Merge branch 'maint'
[org-mode.git] / lisp / org.el
blob687b5f51fb8e933be5dd2962d70b50a5aa429db9
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 t)
83 (require 'org-macs)
84 (require 'org-compat)
86 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
87 ;; some places -- e.g. see the macro org-with-limited-levels.
89 ;; In Org buffers, the value of `outline-regexp' is that of
90 ;; `org-outline-regexp'. The only function still directly relying on
91 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
92 ;; job when `orgstruct-mode' is active.
93 (defvar org-outline-regexp "\\*+ "
94 "Regexp to match Org headlines.")
96 (defvar org-outline-regexp-bol "^\\*+ "
97 "Regexp to match Org headlines.
98 This is similar to `org-outline-regexp' but additionally makes
99 sure that we are at the beginning of the line.")
101 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
102 "Matches an headline, putting stars and text into groups.
103 Stars are put in group 1 and the trimmed body in group 2.")
105 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
106 (when (fboundp 'defvaralias)
107 (unless (boundp 'calendar-view-holidays-initially-flag)
108 (defvaralias 'calendar-view-holidays-initially-flag
109 'view-calendar-holidays-initially))
110 (unless (boundp 'calendar-view-diary-initially-flag)
111 (defvaralias 'calendar-view-diary-initially-flag
112 'view-diary-entries-initially))
113 (unless (boundp 'diary-fancy-buffer)
114 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
116 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
117 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
118 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
119 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
120 (declare-function org-at-clock-log-p "org-clock" ())
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
123 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function orgtbl-mode "org-table" (&optional arg))
127 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
128 (declare-function org-beamer-mode "org-beamer" ())
129 (declare-function org-table-edit-field "org-table" (arg))
130 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
131 (declare-function org-id-get-create "org-id" (&optional force))
132 (declare-function org-id-find-id-file "org-id" (id))
133 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
134 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (autoload 'org-element-at-point "org-element")
141 (autoload 'org-element-type "org-element")
143 (declare-function org-element-at-point "org-element" (&optional keep-trail))
144 (declare-function org-element-type "org-element" (element))
145 (declare-function org-element-context "org-element" (&optional element))
146 (declare-function org-element-contents "org-element" (element))
147 (declare-function org-element-property "org-element" (property element))
148 (declare-function org-element-put-property "org-element"
149 (element property value))
150 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
151 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
152 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
153 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
154 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
156 ;; load languages based on value of `org-babel-load-languages'
157 (defvar org-babel-load-languages)
159 ;;;###autoload
160 (defun org-babel-do-load-languages (sym value)
161 "Load the languages defined in `org-babel-load-languages'."
162 (set-default sym value)
163 (mapc (lambda (pair)
164 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
165 (if active
166 (progn
167 (require (intern (concat "ob-" lang))))
168 (progn
169 (funcall 'fmakunbound
170 (intern (concat "org-babel-execute:" lang)))
171 (funcall 'fmakunbound
172 (intern (concat "org-babel-expand-body:" lang)))))))
173 org-babel-load-languages))
175 (defcustom org-babel-load-languages '((emacs-lisp . t))
176 "Languages which can be evaluated in Org-mode buffers.
177 This list can be used to load support for any of the languages
178 below, note that each language will depend on a different set of
179 system executables and/or Emacs modes. When a language is
180 \"loaded\", then code blocks in that language can be evaluated
181 with `org-babel-execute-src-block' bound by default to C-c
182 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
183 be set to remove code block evaluation from the C-c C-c
184 keybinding. By default only Emacs Lisp (which has no
185 requirements) is loaded."
186 :group 'org-babel
187 :set 'org-babel-do-load-languages
188 :version "24.1"
189 :type '(alist :tag "Babel Languages"
190 :key-type
191 (choice
192 (const :tag "Awk" awk)
193 (const :tag "C" C)
194 (const :tag "R" R)
195 (const :tag "Asymptote" asymptote)
196 (const :tag "Calc" calc)
197 (const :tag "Clojure" clojure)
198 (const :tag "CSS" css)
199 (const :tag "Ditaa" ditaa)
200 (const :tag "Dot" dot)
201 (const :tag "Emacs Lisp" emacs-lisp)
202 (const :tag "Fortran" fortran)
203 (const :tag "Gnuplot" gnuplot)
204 (const :tag "Haskell" haskell)
205 (const :tag "IO" io)
206 (const :tag "Java" java)
207 (const :tag "Javascript" js)
208 (const :tag "LaTeX" latex)
209 (const :tag "Ledger" ledger)
210 (const :tag "Lilypond" lilypond)
211 (const :tag "Lisp" lisp)
212 (const :tag "Makefile" makefile)
213 (const :tag "Maxima" maxima)
214 (const :tag "Matlab" matlab)
215 (const :tag "Mscgen" mscgen)
216 (const :tag "Ocaml" ocaml)
217 (const :tag "Octave" octave)
218 (const :tag "Org" org)
219 (const :tag "Perl" perl)
220 (const :tag "Pico Lisp" picolisp)
221 (const :tag "PlantUML" plantuml)
222 (const :tag "Python" python)
223 (const :tag "Ruby" ruby)
224 (const :tag "Sass" sass)
225 (const :tag "Scala" scala)
226 (const :tag "Scheme" scheme)
227 (const :tag "Screen" screen)
228 (const :tag "Shell Script" sh)
229 (const :tag "Shen" shen)
230 (const :tag "Sql" sql)
231 (const :tag "Sqlite" sqlite))
232 :value-type (boolean :tag "Activate" :value t)))
234 ;;;; Customization variables
235 (defcustom org-clone-delete-id nil
236 "Remove ID property of clones of a subtree.
237 When non-nil, clones of a subtree don't inherit the ID property.
238 Otherwise they inherit the ID property with a new unique
239 identifier."
240 :type 'boolean
241 :version "24.1"
242 :group 'org-id)
244 ;;; Version
245 (org-check-version)
247 ;;;###autoload
248 (defun org-version (&optional here full message)
249 "Show the org-mode version in the echo area.
250 With prefix argument HERE, insert it at point.
251 When FULL is non-nil, use a verbose version string.
252 When MESSAGE is non-nil, display a message with the version."
253 (interactive "P")
254 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
255 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
256 (load-suffixes (list ".el"))
257 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
258 (org-trash (or
259 (and (fboundp 'org-release) (fboundp 'org-git-version))
260 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
261 (load-suffixes save-load-suffixes)
262 (org-version (org-release))
263 (git-version (org-git-version))
264 (version (format "Org-mode version %s (%s @ %s)"
265 org-version
266 git-version
267 (if org-install-dir
268 (if (string= org-dir org-install-dir)
269 org-install-dir
270 (concat "mixed installation! " org-install-dir " and " org-dir))
271 "org-loaddefs.el can not be found!")))
272 (_version (if full version org-version)))
273 (if (org-called-interactively-p 'interactive)
274 (if here
275 (insert version)
276 (message version))
277 (if message (message _version))
278 _version)))
280 (defconst org-version (org-version))
282 ;;; Compatibility constants
284 ;;; The custom variables
286 (defgroup org nil
287 "Outline-based notes management and organizer."
288 :tag "Org"
289 :group 'outlines
290 :group 'calendar)
292 (defcustom org-mode-hook nil
293 "Mode hook for Org-mode, run after the mode was turned on."
294 :group 'org
295 :type 'hook)
297 (defcustom org-load-hook nil
298 "Hook that is run after org.el has been loaded."
299 :group 'org
300 :type 'hook)
302 (defcustom org-log-buffer-setup-hook nil
303 "Hook that is run after an Org log buffer is created."
304 :group 'org
305 :version "24.1"
306 :type 'hook)
308 (defvar org-modules) ; defined below
309 (defvar org-modules-loaded nil
310 "Have the modules been loaded already?")
312 (defun org-load-modules-maybe (&optional force)
313 "Load all extensions listed in `org-modules'."
314 (when (or force (not org-modules-loaded))
315 (mapc (lambda (ext)
316 (condition-case nil (require ext)
317 (error (message "Problems while trying to load feature `%s'" ext))))
318 org-modules)
319 (setq org-modules-loaded t)))
321 (defun org-set-modules (var value)
322 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
323 (set var value)
324 (when (featurep 'org)
325 (org-load-modules-maybe 'force)))
327 (when (org-bound-and-true-p org-modules)
328 (let ((a (member 'org-infojs org-modules)))
329 (and a (setcar a 'org-jsinfo))))
331 (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)
332 "Modules that should always be loaded together with org.el.
333 If a description starts with <C>, the file is not part of Emacs
334 and loading it will require that you have downloaded and properly installed
335 the org-mode distribution.
337 You can also use this system to load external packages (i.e. neither Org
338 core modules, nor modules from the CONTRIB directory). Just add symbols
339 to the end of the list. If the package is called org-xyz.el, then you need
340 to add the symbol `xyz', and the package must have a call to
342 (provide 'org-xyz)"
343 :group 'org
344 :set 'org-set-modules
345 :type
346 '(set :greedy t
347 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
348 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
349 (const :tag " crypt: Encryption of subtrees" org-crypt)
350 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
351 (const :tag " docview: Links to doc-view buffers" org-docview)
352 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
353 (const :tag " id: Global IDs for identifying entries" org-id)
354 (const :tag " info: Links to Info nodes" org-info)
355 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
356 (const :tag " habit: Track your consistency with habits" org-habit)
357 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
358 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
359 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
360 (const :tag " mew Links to Mew folders/messages" org-mew)
361 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
362 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
363 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
364 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
365 (const :tag " vm: Links to VM folders/messages" org-vm)
366 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
367 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
368 (const :tag " mouse: Additional mouse support" org-mouse)
369 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
371 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
372 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
373 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
374 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
375 (const :tag "C collector: Collect properties into tables" org-collector)
376 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
377 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
378 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
379 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
380 (const :tag "C eval: Include command output as text" org-eval)
381 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
382 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
383 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
384 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
385 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
387 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
389 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
390 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
391 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
392 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
393 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
394 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
395 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
396 (const :tag "C mtags: Support for muse-like tags" org-mtags)
397 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
398 (const :tag "C registry: A registry for Org-mode links" org-registry)
399 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
400 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
401 (const :tag "C secretary: Team management with org-mode" org-secretary)
402 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
403 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
404 (const :tag "C track: Keep up with Org-mode development" org-track)
405 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
406 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
407 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
409 (defcustom org-support-shift-select nil
410 "Non-nil means make shift-cursor commands select text when possible.
412 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
413 start selecting a region, or enlarge regions started in this way.
414 In Org-mode, in special contexts, these same keys are used for
415 other purposes, important enough to compete with shift selection.
416 Org tries to balance these needs by supporting `shift-select-mode'
417 outside these special contexts, under control of this variable.
419 The default of this variable is nil, to avoid confusing behavior. Shifted
420 cursor keys will then execute Org commands in the following contexts:
421 - on a headline, changing TODO state (left/right) and priority (up/down)
422 - on a time stamp, changing the time
423 - in a plain list item, changing the bullet type
424 - in a property definition line, switching between allowed values
425 - in the BEGIN line of a clock table (changing the time block).
426 Outside these contexts, the commands will throw an error.
428 When this variable is t and the cursor is not in a special
429 context, Org-mode will support shift-selection for making and
430 enlarging regions. To make this more effective, the bullet
431 cycling will no longer happen anywhere in an item line, but only
432 if the cursor is exactly on the bullet.
434 If you set this variable to the symbol `always', then the keys
435 will not be special in headlines, property lines, and item lines,
436 to make shift selection work there as well. If this is what you
437 want, you can use the following alternative commands: `C-c C-t'
438 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
439 can be used to switch TODO sets, `C-c -' to cycle item bullet
440 types, and properties can be edited by hand or in column view.
442 However, when the cursor is on a timestamp, shift-cursor commands
443 will still edit the time stamp - this is just too good to give up.
445 XEmacs user should have this variable set to nil, because
446 `shift-select-mode' is in Emacs 23 or later only."
447 :group 'org
448 :type '(choice
449 (const :tag "Never" nil)
450 (const :tag "When outside special context" t)
451 (const :tag "Everywhere except timestamps" always)))
453 (defcustom org-loop-over-headlines-in-active-region nil
454 "Shall some commands act upon headlines in the active region?
456 When set to `t', some commands will be performed in all headlines
457 within the active region.
459 When set to `start-level', some commands will be performed in all
460 headlines within the active region, provided that these headlines
461 are of the same level than the first one.
463 When set to a string, those commands will be performed on the
464 matching headlines within the active region. Such string must be
465 a tags/property/todo match as it is used in the agenda tags view.
467 The list of commands is: `org-schedule', `org-deadline',
468 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
469 `org-archive-to-archive-sibling'. The archiving commands skip
470 already archived entries."
471 :type '(choice (const :tag "Don't loop" nil)
472 (const :tag "All headlines in active region" t)
473 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
474 (string :tag "Tags/Property/Todo matcher"))
475 :version "24.1"
476 :group 'org-todo
477 :group 'org-archive)
479 (defgroup org-startup nil
480 "Options concerning startup of Org-mode."
481 :tag "Org Startup"
482 :group 'org)
484 (defcustom org-startup-folded t
485 "Non-nil means entering Org-mode will switch to OVERVIEW.
486 This can also be configured on a per-file basis by adding one of
487 the following lines anywhere in the buffer:
489 #+STARTUP: fold (or `overview', this is equivalent)
490 #+STARTUP: nofold (or `showall', this is equivalent)
491 #+STARTUP: content
492 #+STARTUP: showeverything"
493 :group 'org-startup
494 :type '(choice
495 (const :tag "nofold: show all" nil)
496 (const :tag "fold: overview" t)
497 (const :tag "content: all headlines" content)
498 (const :tag "show everything, even drawers" showeverything)))
500 (defcustom org-startup-truncated t
501 "Non-nil means entering Org-mode will set `truncate-lines'.
502 This is useful since some lines containing links can be very long and
503 uninteresting. Also tables look terrible when wrapped."
504 :group 'org-startup
505 :type 'boolean)
507 (defcustom org-startup-indented nil
508 "Non-nil means turn on `org-indent-mode' on startup.
509 This can also be configured on a per-file basis by adding one of
510 the following lines anywhere in the buffer:
512 #+STARTUP: indent
513 #+STARTUP: noindent"
514 :group 'org-structure
515 :type '(choice
516 (const :tag "Not" nil)
517 (const :tag "Globally (slow on startup in large files)" t)))
519 (defcustom org-use-sub-superscripts t
520 "Non-nil means interpret \"_\" and \"^\" for export.
521 When this option is turned on, you can use TeX-like syntax for sub- and
522 superscripts. Several characters after \"_\" or \"^\" will be
523 considered as a single item - so grouping with {} is normally not
524 needed. For example, the following things will be parsed as single
525 sub- or superscripts.
527 10^24 or 10^tau several digits will be considered 1 item.
528 10^-12 or 10^-tau a leading sign with digits or a word
529 x^2-y^3 will be read as x^2 - y^3, because items are
530 terminated by almost any nonword/nondigit char.
531 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
533 Still, ambiguity is possible - so when in doubt use {} to enclose the
534 sub/superscript. If you set this variable to the symbol `{}',
535 the braces are *required* in order to trigger interpretations as
536 sub/superscript. This can be helpful in documents that need \"_\"
537 frequently in plain text.
539 Not all export backends support this, but HTML does.
541 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
542 :group 'org-startup
543 :group 'org-export-translation
544 :version "24.1"
545 :type '(choice
546 (const :tag "Always interpret" t)
547 (const :tag "Only with braces" {})
548 (const :tag "Never interpret" nil)))
550 (if (fboundp 'defvaralias)
551 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
554 (defcustom org-startup-with-beamer-mode nil
555 "Non-nil means turn on `org-beamer-mode' on startup.
556 This can also be configured on a per-file basis by adding one of
557 the following lines anywhere in the buffer:
559 #+STARTUP: beamer"
560 :group 'org-startup
561 :version "24.1"
562 :type 'boolean)
564 (defcustom org-startup-align-all-tables nil
565 "Non-nil means align all tables when visiting a file.
566 This is useful when the column width in tables is forced with <N> cookies
567 in table fields. Such tables will look correct only after the first re-align.
568 This can also be configured on a per-file basis by adding one of
569 the following lines anywhere in the buffer:
570 #+STARTUP: align
571 #+STARTUP: noalign"
572 :group 'org-startup
573 :type 'boolean)
575 (defcustom org-startup-with-inline-images nil
576 "Non-nil means show inline images when loading a new Org file.
577 This can also be configured on a per-file basis by adding one of
578 the following lines anywhere in the buffer:
579 #+STARTUP: inlineimages
580 #+STARTUP: noinlineimages"
581 :group 'org-startup
582 :version "24.1"
583 :type 'boolean)
585 (defcustom org-insert-mode-line-in-empty-file nil
586 "Non-nil means insert the first line setting Org-mode in empty files.
587 When the function `org-mode' is called interactively in an empty file, this
588 normally means that the file name does not automatically trigger Org-mode.
589 To ensure that the file will always be in Org-mode in the future, a
590 line enforcing Org-mode will be inserted into the buffer, if this option
591 has been set."
592 :group 'org-startup
593 :type 'boolean)
595 (defcustom org-replace-disputed-keys nil
596 "Non-nil means use alternative key bindings for some keys.
597 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
598 These keys are also used by other packages like shift-selection-mode'
599 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
600 If you want to use Org-mode together with one of these other modes,
601 or more generally if you would like to move some Org-mode commands to
602 other keys, set this variable and configure the keys with the variable
603 `org-disputed-keys'.
605 This option is only relevant at load-time of Org-mode, and must be set
606 *before* org.el is loaded. Changing it requires a restart of Emacs to
607 become effective."
608 :group 'org-startup
609 :type 'boolean)
611 (defcustom org-use-extra-keys nil
612 "Non-nil means use extra key sequence definitions for certain commands.
613 This happens automatically if you run XEmacs or if `window-system'
614 is nil. This variable lets you do the same manually. You must
615 set it before loading org.
617 Example: on Carbon Emacs 22 running graphically, with an external
618 keyboard on a Powerbook, the default way of setting M-left might
619 not work for either Alt or ESC. Setting this variable will make
620 it work for ESC."
621 :group 'org-startup
622 :type 'boolean)
624 (if (fboundp 'defvaralias)
625 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
627 (defcustom org-disputed-keys
628 '(([(shift up)] . [(meta p)])
629 ([(shift down)] . [(meta n)])
630 ([(shift left)] . [(meta -)])
631 ([(shift right)] . [(meta +)])
632 ([(control shift right)] . [(meta shift +)])
633 ([(control shift left)] . [(meta shift -)]))
634 "Keys for which Org-mode and other modes compete.
635 This is an alist, cars are the default keys, second element specifies
636 the alternative to use when `org-replace-disputed-keys' is t.
638 Keys can be specified in any syntax supported by `define-key'.
639 The value of this option takes effect only at Org-mode's startup,
640 therefore you'll have to restart Emacs to apply it after changing."
641 :group 'org-startup
642 :type 'alist)
644 (defun org-key (key)
645 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
646 Or return the original if not disputed.
647 Also apply the translations defined in `org-xemacs-key-equivalents'."
648 (when org-replace-disputed-keys
649 (let* ((nkey (key-description key))
650 (x (org-find-if (lambda (x)
651 (equal (key-description (car x)) nkey))
652 org-disputed-keys)))
653 (setq key (if x (cdr x) key))))
654 (when (featurep 'xemacs)
655 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
656 key)
658 (defun org-find-if (predicate seq)
659 (catch 'exit
660 (while seq
661 (if (funcall predicate (car seq))
662 (throw 'exit (car seq))
663 (pop seq)))))
665 (defun org-defkey (keymap key def)
666 "Define a key, possibly translated, as returned by `org-key'."
667 (define-key keymap (org-key key) def))
669 (defcustom org-ellipsis nil
670 "The ellipsis to use in the Org-mode outline.
671 When nil, just use the standard three dots. When a string, use that instead,
672 When a face, use the standard 3 dots, but with the specified face.
673 The change affects only Org-mode (which will then use its own display table).
674 Changing this requires executing `M-x org-mode' in a buffer to become
675 effective."
676 :group 'org-startup
677 :type '(choice (const :tag "Default" nil)
678 (face :tag "Face" :value org-warning)
679 (string :tag "String" :value "...#")))
681 (defvar org-display-table nil
682 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
684 (defgroup org-keywords nil
685 "Keywords in Org-mode."
686 :tag "Org Keywords"
687 :group 'org)
689 (defcustom org-deadline-string "DEADLINE:"
690 "String to mark deadline entries.
691 A deadline is this string, followed by a time stamp. Should be a word,
692 terminated by a colon. You can insert a schedule keyword and
693 a timestamp with \\[org-deadline].
694 Changes become only effective after restarting Emacs."
695 :group 'org-keywords
696 :type 'string)
698 (defcustom org-scheduled-string "SCHEDULED:"
699 "String to mark scheduled TODO entries.
700 A schedule is this string, followed by a time stamp. Should be a word,
701 terminated by a colon. You can insert a schedule keyword and
702 a timestamp with \\[org-schedule].
703 Changes become only effective after restarting Emacs."
704 :group 'org-keywords
705 :type 'string)
707 (defcustom org-closed-string "CLOSED:"
708 "String used as the prefix for timestamps logging closing a TODO entry."
709 :group 'org-keywords
710 :type 'string)
712 (defcustom org-clock-string "CLOCK:"
713 "String used as prefix for timestamps clocking work hours on an item."
714 :group 'org-keywords
715 :type 'string)
717 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
718 org-scheduled-string "\\|"
719 org-deadline-string "\\|"
720 org-closed-string "\\|"
721 org-clock-string "\\)")
722 "Matches a line with planning or clock info.")
724 (defcustom org-comment-string "COMMENT"
725 "Entries starting with this keyword will never be exported.
726 An entry can be toggled between COMMENT and normal with
727 \\[org-toggle-comment].
728 Changes become only effective after restarting Emacs."
729 :group 'org-keywords
730 :type 'string)
732 (defcustom org-quote-string "QUOTE"
733 "Entries starting with this keyword will be exported in fixed-width font.
734 Quoting applies only to the text in the entry following the headline, and does
735 not extend beyond the next headline, even if that is lower level.
736 An entry can be toggled between QUOTE and normal with
737 \\[org-toggle-fixed-width-section]."
738 :group 'org-keywords
739 :type 'string)
741 (defconst org-repeat-re
742 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
743 "Regular expression for specifying repeated events.
744 After a match, group 1 contains the repeat expression.")
746 (defgroup org-structure nil
747 "Options concerning the general structure of Org-mode files."
748 :tag "Org Structure"
749 :group 'org)
751 (defgroup org-reveal-location nil
752 "Options about how to make context of a location visible."
753 :tag "Org Reveal Location"
754 :group 'org-structure)
756 (defconst org-context-choice
757 '(choice
758 (const :tag "Always" t)
759 (const :tag "Never" nil)
760 (repeat :greedy t :tag "Individual contexts"
761 (cons
762 (choice :tag "Context"
763 (const agenda)
764 (const org-goto)
765 (const occur-tree)
766 (const tags-tree)
767 (const link-search)
768 (const mark-goto)
769 (const bookmark-jump)
770 (const isearch)
771 (const default))
772 (boolean))))
773 "Contexts for the reveal options.")
775 (defcustom org-show-hierarchy-above '((default . t))
776 "Non-nil means show full hierarchy when revealing a location.
777 Org-mode often shows locations in an org-mode file which might have
778 been invisible before. When this is set, the hierarchy of headings
779 above the exposed location is shown.
780 Turning this off for example for sparse trees makes them very compact.
781 Instead of t, this can also be an alist specifying this option for different
782 contexts. Valid contexts are
783 agenda when exposing an entry from the agenda
784 org-goto when using the command `org-goto' on key C-c C-j
785 occur-tree when using the command `org-occur' on key C-c /
786 tags-tree when constructing a sparse tree based on tags matches
787 link-search when exposing search matches associated with a link
788 mark-goto when exposing the jump goal of a mark
789 bookmark-jump when exposing a bookmark location
790 isearch when exiting from an incremental search
791 default default for all contexts not set explicitly"
792 :group 'org-reveal-location
793 :type org-context-choice)
795 (defcustom org-show-following-heading '((default . nil))
796 "Non-nil means show following heading when revealing a location.
797 Org-mode often shows locations in an org-mode file which might have
798 been invisible before. When this is set, the heading following the
799 match is shown.
800 Turning this off for example for sparse trees makes them very compact,
801 but makes it harder to edit the location of the match. In such a case,
802 use the command \\[org-reveal] to show more context.
803 Instead of t, this can also be an alist specifying this option for different
804 contexts. See `org-show-hierarchy-above' for valid contexts."
805 :group 'org-reveal-location
806 :type org-context-choice)
808 (defcustom org-show-siblings '((default . nil) (isearch t))
809 "Non-nil means show all sibling heading when revealing a location.
810 Org-mode often shows locations in an org-mode file which might have
811 been invisible before. When this is set, the sibling of the current entry
812 heading are all made visible. If `org-show-hierarchy-above' is t,
813 the same happens on each level of the hierarchy above the current entry.
815 By default this is on for the isearch context, off for all other contexts.
816 Turning this off for example for sparse trees makes them very compact,
817 but makes it harder to edit the location of the match. In such a case,
818 use the command \\[org-reveal] to show more context.
819 Instead of t, this can also be an alist specifying this option for different
820 contexts. See `org-show-hierarchy-above' for valid contexts."
821 :group 'org-reveal-location
822 :type org-context-choice)
824 (defcustom org-show-entry-below '((default . nil))
825 "Non-nil means show the entry below a headline when revealing a location.
826 Org-mode often shows locations in an org-mode file which might have
827 been invisible before. When this is set, the text below the headline that is
828 exposed is also shown.
830 By default this is off for all contexts.
831 Instead of t, this can also be an alist specifying this option for different
832 contexts. See `org-show-hierarchy-above' for valid contexts."
833 :group 'org-reveal-location
834 :type org-context-choice)
836 (defcustom org-indirect-buffer-display 'other-window
837 "How should indirect tree buffers be displayed?
838 This applies to indirect buffers created with the commands
839 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
840 Valid values are:
841 current-window Display in the current window
842 other-window Just display in another window.
843 dedicated-frame Create one new frame, and re-use it each time.
844 new-frame Make a new frame each time. Note that in this case
845 previously-made indirect buffers are kept, and you need to
846 kill these buffers yourself."
847 :group 'org-structure
848 :group 'org-agenda-windows
849 :type '(choice
850 (const :tag "In current window" current-window)
851 (const :tag "In current frame, other window" other-window)
852 (const :tag "Each time a new frame" new-frame)
853 (const :tag "One dedicated frame" dedicated-frame)))
855 (defcustom org-use-speed-commands nil
856 "Non-nil means activate single letter commands at beginning of a headline.
857 This may also be a function to test for appropriate locations where speed
858 commands should be active."
859 :group 'org-structure
860 :type '(choice
861 (const :tag "Never" nil)
862 (const :tag "At beginning of headline stars" t)
863 (function)))
865 (defcustom org-speed-commands-user nil
866 "Alist of additional speed commands.
867 This list will be checked before `org-speed-commands-default'
868 when the variable `org-use-speed-commands' is non-nil
869 and when the cursor is at the beginning of a headline.
870 The car if each entry is a string with a single letter, which must
871 be assigned to `self-insert-command' in the global map.
872 The cdr is either a command to be called interactively, a function
873 to be called, or a form to be evaluated.
874 An entry that is just a list with a single string will be interpreted
875 as a descriptive headline that will be added when listing the speed
876 commands in the Help buffer using the `?' speed command."
877 :group 'org-structure
878 :type '(repeat :value ("k" . ignore)
879 (choice :value ("k" . ignore)
880 (list :tag "Descriptive Headline" (string :tag "Headline"))
881 (cons :tag "Letter and Command"
882 (string :tag "Command letter")
883 (choice
884 (function)
885 (sexp))))))
887 (defgroup org-cycle nil
888 "Options concerning visibility cycling in Org-mode."
889 :tag "Org Cycle"
890 :group 'org-structure)
892 (defcustom org-cycle-skip-children-state-if-no-children t
893 "Non-nil means skip CHILDREN state in entries that don't have any."
894 :group 'org-cycle
895 :type 'boolean)
897 (defcustom org-cycle-max-level nil
898 "Maximum level which should still be subject to visibility cycling.
899 Levels higher than this will, for cycling, be treated as text, not a headline.
900 When `org-odd-levels-only' is set, a value of N in this variable actually
901 means 2N-1 stars as the limiting headline.
902 When nil, cycle all levels.
903 Note that the limiting level of cycling is also influenced by
904 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
905 `org-inlinetask-min-level' is, cycling will be limited to levels one less
906 than its value."
907 :group 'org-cycle
908 :type '(choice
909 (const :tag "No limit" nil)
910 (integer :tag "Maximum level")))
912 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
913 "Names of drawers. Drawers are not opened by cycling on the headline above.
914 Drawers only open with a TAB on the drawer line itself. A drawer looks like
915 this:
916 :DRAWERNAME:
917 .....
918 :END:
919 The drawer \"PROPERTIES\" is special for capturing properties through
920 the property API.
922 Drawers can be defined on the per-file basis with a line like:
924 #+DRAWERS: HIDDEN STATE PROPERTIES"
925 :group 'org-structure
926 :group 'org-cycle
927 :type '(repeat (string :tag "Drawer Name")))
929 (defcustom org-hide-block-startup nil
930 "Non-nil means entering Org-mode will fold all blocks.
931 This can also be set in on a per-file basis with
933 #+STARTUP: hideblocks
934 #+STARTUP: showblocks"
935 :group 'org-startup
936 :group 'org-cycle
937 :type 'boolean)
939 (defcustom org-cycle-global-at-bob nil
940 "Cycle globally if cursor is at beginning of buffer and not at a headline.
941 This makes it possible to do global cycling without having to use S-TAB or
942 \\[universal-argument] TAB. For this special case to work, the first line
943 of the buffer must not be a headline -- it may be empty or some other text.
944 When used in this way, `org-cycle-hook' is disabled temporarily to make
945 sure the cursor stays at the beginning of the buffer. When this option is
946 nil, don't do anything special at the beginning of the buffer."
947 :group 'org-cycle
948 :type 'boolean)
950 (defcustom org-cycle-level-after-item/entry-creation t
951 "Non-nil means cycle entry level or item indentation in new empty entries.
953 When the cursor is at the end of an empty headline, i.e with only stars
954 and maybe a TODO keyword, TAB will then switch the entry to become a child,
955 and then all possible ancestor states, before returning to the original state.
956 This makes data entry extremely fast: M-RET to create a new headline,
957 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
959 When the cursor is at the end of an empty plain list item, one TAB will
960 make it a subitem, two or more tabs will back up to make this an item
961 higher up in the item hierarchy."
962 :group 'org-cycle
963 :type 'boolean)
965 (defcustom org-cycle-emulate-tab t
966 "Where should `org-cycle' emulate TAB.
967 nil Never
968 white Only in completely white lines
969 whitestart Only at the beginning of lines, before the first non-white char
970 t Everywhere except in headlines
971 exc-hl-bol Everywhere except at the start of a headline
972 If TAB is used in a place where it does not emulate TAB, the current subtree
973 visibility is cycled."
974 :group 'org-cycle
975 :type '(choice (const :tag "Never" nil)
976 (const :tag "Only in completely white lines" white)
977 (const :tag "Before first char in a line" whitestart)
978 (const :tag "Everywhere except in headlines" t)
979 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
982 (defcustom org-cycle-separator-lines 2
983 "Number of empty lines needed to keep an empty line between collapsed trees.
984 If you leave an empty line between the end of a subtree and the following
985 headline, this empty line is hidden when the subtree is folded.
986 Org-mode will leave (exactly) one empty line visible if the number of
987 empty lines is equal or larger to the number given in this variable.
988 So the default 2 means at least 2 empty lines after the end of a subtree
989 are needed to produce free space between a collapsed subtree and the
990 following headline.
992 If the number is negative, and the number of empty lines is at least -N,
993 all empty lines are shown.
995 Special case: when 0, never leave empty lines in collapsed view."
996 :group 'org-cycle
997 :type 'integer)
998 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1000 (defcustom org-pre-cycle-hook nil
1001 "Hook that is run before visibility cycling is happening.
1002 The function(s) in this hook must accept a single argument which indicates
1003 the new state that will be set right after running this hook. The
1004 argument is a symbol. Before a global state change, it can have the values
1005 `overview', `content', or `all'. Before a local state change, it can have
1006 the values `folded', `children', or `subtree'."
1007 :group 'org-cycle
1008 :type 'hook)
1010 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1011 org-cycle-hide-drawers
1012 org-cycle-hide-inline-tasks
1013 org-cycle-show-empty-lines
1014 org-optimize-window-after-visibility-change)
1015 "Hook that is run after `org-cycle' has changed the buffer visibility.
1016 The function(s) in this hook must accept a single argument which indicates
1017 the new state that was set by the most recent `org-cycle' command. The
1018 argument is a symbol. After a global state change, it can have the values
1019 `overview', `contents', or `all'. After a local state change, it can have
1020 the values `folded', `children', or `subtree'."
1021 :group 'org-cycle
1022 :type 'hook)
1024 (defgroup org-edit-structure nil
1025 "Options concerning structure editing in Org-mode."
1026 :tag "Org Edit Structure"
1027 :group 'org-structure)
1029 (defcustom org-odd-levels-only nil
1030 "Non-nil means skip even levels and only use odd levels for the outline.
1031 This has the effect that two stars are being added/taken away in
1032 promotion/demotion commands. It also influences how levels are
1033 handled by the exporters.
1034 Changing it requires restart of `font-lock-mode' to become effective
1035 for fontification also in regions already fontified.
1036 You may also set this on a per-file basis by adding one of the following
1037 lines to the buffer:
1039 #+STARTUP: odd
1040 #+STARTUP: oddeven"
1041 :group 'org-edit-structure
1042 :group 'org-appearance
1043 :type 'boolean)
1045 (defcustom org-adapt-indentation t
1046 "Non-nil means adapt indentation to outline node level.
1048 When this variable is set, Org assumes that you write outlines by
1049 indenting text in each node to align with the headline (after the stars).
1050 The following issues are influenced by this variable:
1052 - When this is set and the *entire* text in an entry is indented, the
1053 indentation is increased by one space in a demotion command, and
1054 decreased by one in a promotion command. If any line in the entry
1055 body starts with text at column 0, indentation is not changed at all.
1057 - Property drawers and planning information is inserted indented when
1058 this variable s set. When nil, they will not be indented.
1060 - TAB indents a line relative to context. The lines below a headline
1061 will be indented when this variable is set.
1063 Note that this is all about true indentation, by adding and removing
1064 space characters. See also `org-indent.el' which does level-dependent
1065 indentation in a virtual way, i.e. at display time in Emacs."
1066 :group 'org-edit-structure
1067 :type 'boolean)
1069 (defcustom org-special-ctrl-a/e nil
1070 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1072 When t, `C-a' will bring back the cursor to the beginning of the
1073 headline text, i.e. after the stars and after a possible TODO
1074 keyword. In an item, this will be the position after bullet and
1075 check-box, if any. When the cursor is already at that position,
1076 another `C-a' will bring it to the beginning of the line.
1078 `C-e' will jump to the end of the headline, ignoring the presence
1079 of tags in the headline. A second `C-e' will then jump to the
1080 true end of the line, after any tags. This also means that, when
1081 this variable is non-nil, `C-e' also will never jump beyond the
1082 end of the heading of a folded section, i.e. not after the
1083 ellipses.
1085 When set to the symbol `reversed', the first `C-a' or `C-e' works
1086 normally, going to the true line boundary first. Only a directly
1087 following, identical keypress will bring the cursor to the
1088 special positions.
1090 This may also be a cons cell where the behavior for `C-a' and
1091 `C-e' is set separately."
1092 :group 'org-edit-structure
1093 :type '(choice
1094 (const :tag "off" nil)
1095 (const :tag "on: after stars/bullet and before tags first" t)
1096 (const :tag "reversed: true line boundary first" reversed)
1097 (cons :tag "Set C-a and C-e separately"
1098 (choice :tag "Special C-a"
1099 (const :tag "off" nil)
1100 (const :tag "on: after stars/bullet first" t)
1101 (const :tag "reversed: before stars/bullet first" reversed))
1102 (choice :tag "Special C-e"
1103 (const :tag "off" nil)
1104 (const :tag "on: before tags first" t)
1105 (const :tag "reversed: after tags first" reversed)))))
1106 (if (fboundp 'defvaralias)
1107 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1109 (defcustom org-special-ctrl-k nil
1110 "Non-nil means `C-k' will behave specially in headlines.
1111 When nil, `C-k' will call the default `kill-line' command.
1112 When t, the following will happen while the cursor is in the headline:
1114 - When the cursor is at the beginning of a headline, kill the entire
1115 line and possible the folded subtree below the line.
1116 - When in the middle of the headline text, kill the headline up to the tags.
1117 - When after the headline text, kill the tags."
1118 :group 'org-edit-structure
1119 :type 'boolean)
1121 (defcustom org-ctrl-k-protect-subtree nil
1122 "Non-nil means, do not delete a hidden subtree with C-k.
1123 When set to the symbol `error', simply throw an error when C-k is
1124 used to kill (part-of) a headline that has hidden text behind it.
1125 Any other non-nil value will result in a query to the user, if it is
1126 OK to kill that hidden subtree. When nil, kill without remorse."
1127 :group 'org-edit-structure
1128 :version "24.1"
1129 :type '(choice
1130 (const :tag "Do not protect hidden subtrees" nil)
1131 (const :tag "Protect hidden subtrees with a security query" t)
1132 (const :tag "Never kill a hidden subtree with C-k" error)))
1134 (defcustom org-catch-invisible-edits nil
1135 "Check if in invisible region before inserting or deleting a character.
1136 Valid values are:
1138 nil Do not check, so just do invisible edits.
1139 error Throw an error and do nothing.
1140 show Make point visible, and do the requested edit.
1141 show-and-error Make point visible, then throw an error and abort the edit.
1142 smart Make point visible, and do insertion/deletion if it is
1143 adjacent to visible text and the change feels predictable.
1144 Never delete a previously invisible character or add in the
1145 middle or right after an invisible region. Basically, this
1146 allows insertion and backward-delete right before ellipses.
1147 FIXME: maybe in this case we should not even show?"
1148 :group 'org-edit-structure
1149 :version "24.1"
1150 :type '(choice
1151 (const :tag "Do not check" nil)
1152 (const :tag "Throw error when trying to edit" error)
1153 (const :tag "Unhide, but do not do the edit" show-and-error)
1154 (const :tag "Show invisible part and do the edit" show)
1155 (const :tag "Be smart and do the right thing" smart)))
1157 (defcustom org-yank-folded-subtrees t
1158 "Non-nil means when yanking subtrees, fold them.
1159 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1160 it starts with a heading and all other headings in it are either children
1161 or siblings, then fold all the subtrees. However, do this only if no
1162 text after the yank would be swallowed into a folded tree by this action."
1163 :group 'org-edit-structure
1164 :type 'boolean)
1166 (defcustom org-yank-adjusted-subtrees nil
1167 "Non-nil means when yanking subtrees, adjust the level.
1168 With this setting, `org-paste-subtree' is used to insert the subtree, see
1169 this function for details."
1170 :group 'org-edit-structure
1171 :type 'boolean)
1173 (defcustom org-M-RET-may-split-line '((default . t))
1174 "Non-nil means M-RET will split the line at the cursor position.
1175 When nil, it will go to the end of the line before making a
1176 new line.
1177 You may also set this option in a different way for different
1178 contexts. Valid contexts are:
1180 headline when creating a new headline
1181 item when creating a new item
1182 table in a table field
1183 default the value to be used for all contexts not explicitly
1184 customized"
1185 :group 'org-structure
1186 :group 'org-table
1187 :type '(choice
1188 (const :tag "Always" t)
1189 (const :tag "Never" nil)
1190 (repeat :greedy t :tag "Individual contexts"
1191 (cons
1192 (choice :tag "Context"
1193 (const headline)
1194 (const item)
1195 (const table)
1196 (const default))
1197 (boolean)))))
1200 (defcustom org-insert-heading-respect-content nil
1201 "Non-nil means insert new headings after the current subtree.
1202 When nil, the new heading is created directly after the current line.
1203 The commands \\[org-insert-heading-respect-content] and
1204 \\[org-insert-todo-heading-respect-content] turn this variable on
1205 for the duration of the command."
1206 :group 'org-structure
1207 :type 'boolean)
1209 (defcustom org-blank-before-new-entry '((heading . auto)
1210 (plain-list-item . auto))
1211 "Should `org-insert-heading' leave a blank line before new heading/item?
1212 The value is an alist, with `heading' and `plain-list-item' as CAR,
1213 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1214 which case Org will look at the surrounding headings/items and try to
1215 make an intelligent decision whether to insert a blank line or not.
1217 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1218 set, the setting here is ignored and no empty line is inserted, to avoid
1219 breaking the list structure."
1220 :group 'org-edit-structure
1221 :type '(list
1222 (cons (const heading)
1223 (choice (const :tag "Never" nil)
1224 (const :tag "Always" t)
1225 (const :tag "Auto" auto)))
1226 (cons (const plain-list-item)
1227 (choice (const :tag "Never" nil)
1228 (const :tag "Always" t)
1229 (const :tag "Auto" auto)))))
1231 (defcustom org-insert-heading-hook nil
1232 "Hook being run after inserting a new heading."
1233 :group 'org-edit-structure
1234 :type 'hook)
1236 (defcustom org-enable-fixed-width-editor t
1237 "Non-nil means lines starting with \":\" are treated as fixed-width.
1238 This currently only means they are never auto-wrapped.
1239 When nil, such lines will be treated like ordinary lines.
1240 See also the QUOTE keyword."
1241 :group 'org-edit-structure
1242 :type 'boolean)
1244 (defcustom org-goto-auto-isearch t
1245 "Non-nil means typing characters in `org-goto' starts incremental search.
1246 When nil, you can use these keybindings to navigate the buffer:
1248 q Quit the org-goto interface
1249 n Go to the next visible heading
1250 p Go to the previous visible heading
1251 f Go one heading forward on same level
1252 b Go one heading backward on same level
1253 u Go one heading up"
1254 :group 'org-edit-structure
1255 :type 'boolean)
1257 (defgroup org-sparse-trees nil
1258 "Options concerning sparse trees in Org-mode."
1259 :tag "Org Sparse Trees"
1260 :group 'org-structure)
1262 (defcustom org-highlight-sparse-tree-matches t
1263 "Non-nil means highlight all matches that define a sparse tree.
1264 The highlights will automatically disappear the next time the buffer is
1265 changed by an edit command."
1266 :group 'org-sparse-trees
1267 :type 'boolean)
1269 (defcustom org-remove-highlights-with-change t
1270 "Non-nil means any change to the buffer will remove temporary highlights.
1271 Such highlights are created by `org-occur' and `org-clock-display'.
1272 When nil, `C-c C-c needs to be used to get rid of the highlights.
1273 The highlights created by `org-preview-latex-fragment' always need
1274 `C-c C-c' to be removed."
1275 :group 'org-sparse-trees
1276 :group 'org-time
1277 :type 'boolean)
1280 (defcustom org-occur-hook '(org-first-headline-recenter)
1281 "Hook that is run after `org-occur' has constructed a sparse tree.
1282 This can be used to recenter the window to show as much of the structure
1283 as possible."
1284 :group 'org-sparse-trees
1285 :type 'hook)
1287 (defgroup org-imenu-and-speedbar nil
1288 "Options concerning imenu and speedbar in Org-mode."
1289 :tag "Org Imenu and Speedbar"
1290 :group 'org-structure)
1292 (defcustom org-imenu-depth 2
1293 "The maximum level for Imenu access to Org-mode headlines.
1294 This also applied for speedbar access."
1295 :group 'org-imenu-and-speedbar
1296 :type 'integer)
1298 (defgroup org-table nil
1299 "Options concerning tables in Org-mode."
1300 :tag "Org Table"
1301 :group 'org)
1303 (defcustom org-enable-table-editor 'optimized
1304 "Non-nil means lines starting with \"|\" are handled by the table editor.
1305 When nil, such lines will be treated like ordinary lines.
1307 When equal to the symbol `optimized', the table editor will be optimized to
1308 do the following:
1309 - Automatic overwrite mode in front of whitespace in table fields.
1310 This makes the structure of the table stay in tact as long as the edited
1311 field does not exceed the column width.
1312 - Minimize the number of realigns. Normally, the table is aligned each time
1313 TAB or RET are pressed to move to another field. With optimization this
1314 happens only if changes to a field might have changed the column width.
1315 Optimization requires replacing the functions `self-insert-command',
1316 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1317 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1318 very good at guessing when a re-align will be necessary, but you can always
1319 force one with \\[org-ctrl-c-ctrl-c].
1321 If you would like to use the optimized version in Org-mode, but the
1322 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1324 This variable can be used to turn on and off the table editor during a session,
1325 but in order to toggle optimization, a restart is required.
1327 See also the variable `org-table-auto-blank-field'."
1328 :group 'org-table
1329 :type '(choice
1330 (const :tag "off" nil)
1331 (const :tag "on" t)
1332 (const :tag "on, optimized" optimized)))
1334 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1335 (version<= emacs-version "24.1"))
1336 "Non-nil means cluster self-insert commands for undo when possible.
1337 If this is set, then, like in the Emacs command loop, 20 consecutive
1338 characters will be undone together.
1339 This is configurable, because there is some impact on typing performance."
1340 :group 'org-table
1341 :type 'boolean)
1343 (defcustom org-table-tab-recognizes-table.el t
1344 "Non-nil means TAB will automatically notice a table.el table.
1345 When it sees such a table, it moves point into it and - if necessary -
1346 calls `table-recognize-table'."
1347 :group 'org-table-editing
1348 :type 'boolean)
1350 (defgroup org-link nil
1351 "Options concerning links in Org-mode."
1352 :tag "Org Link"
1353 :group 'org)
1355 (defvar org-link-abbrev-alist-local nil
1356 "Buffer-local version of `org-link-abbrev-alist', which see.
1357 The value of this is taken from the #+LINK lines.")
1358 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1360 (defcustom org-link-abbrev-alist nil
1361 "Alist of link abbreviations.
1362 The car of each element is a string, to be replaced at the start of a link.
1363 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1364 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1366 [[linkkey:tag][description]]
1368 The 'linkkey' must be a word word, starting with a letter, followed
1369 by letters, numbers, '-' or '_'.
1371 If REPLACE is a string, the tag will simply be appended to create the link.
1372 If the string contains \"%s\", the tag will be inserted there. If the string
1373 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1374 at that point (see the function `url-hexify-string'). If the string contains
1375 the specifier \"%(my-function)\", then the custom function `my-function' will
1376 be invoked: this function takes the tag as its only argument and must return
1377 a string.
1379 REPLACE may also be a function that will be called with the tag as the
1380 only argument to create the link, which should be returned as a string.
1382 See the manual for examples."
1383 :group 'org-link
1384 :type '(repeat
1385 (cons
1386 (string :tag "Protocol")
1387 (choice
1388 (string :tag "Format")
1389 (function)))))
1391 (defcustom org-descriptive-links t
1392 "Non-nil means Org will display descriptive links.
1393 E.g. [[http://orgmode.org][Org website]] will be displayed as
1394 \"Org Website\", hiding the link itself and just displaying its
1395 description. When set to `nil', Org will display the full links
1396 literally.
1398 You can interactively set the value of this variable by calling
1399 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1400 :group 'org-link
1401 :type 'boolean)
1403 (defcustom org-link-file-path-type 'adaptive
1404 "How the path name in file links should be stored.
1405 Valid values are:
1407 relative Relative to the current directory, i.e. the directory of the file
1408 into which the link is being inserted.
1409 absolute Absolute path, if possible with ~ for home directory.
1410 noabbrev Absolute path, no abbreviation of home directory.
1411 adaptive Use relative path for files in the current directory and sub-
1412 directories of it. For other files, use an absolute path."
1413 :group 'org-link
1414 :type '(choice
1415 (const relative)
1416 (const absolute)
1417 (const noabbrev)
1418 (const adaptive)))
1420 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1421 "Types of links that should be activated in Org-mode files.
1422 This is a list of symbols, each leading to the activation of a certain link
1423 type. In principle, it does not hurt to turn on most link types - there may
1424 be a small gain when turning off unused link types. The types are:
1426 bracket The recommended [[link][description]] or [[link]] links with hiding.
1427 angle Links in angular brackets that may contain whitespace like
1428 <bbdb:Carsten Dominik>.
1429 plain Plain links in normal text, no whitespace, like http://google.com.
1430 radio Text that is matched by a radio target, see manual for details.
1431 tag Tag settings in a headline (link to tag search).
1432 date Time stamps (link to calendar).
1433 footnote Footnote labels.
1435 Changing this variable requires a restart of Emacs to become effective."
1436 :group 'org-link
1437 :type '(set :greedy t
1438 (const :tag "Double bracket links" bracket)
1439 (const :tag "Angular bracket links" angle)
1440 (const :tag "Plain text links" plain)
1441 (const :tag "Radio target matches" radio)
1442 (const :tag "Tags" tag)
1443 (const :tag "Timestamps" date)
1444 (const :tag "Footnotes" footnote)))
1446 (defcustom org-make-link-description-function nil
1447 "Function to use for generating link descriptions from links.
1448 When nil, the link location will be used. This function must take
1449 two parameters: the first one is the link, the second one is the
1450 description generated by `org-insert-link'. The function should
1451 return the description to use."
1452 :group 'org-link
1453 :type 'function)
1455 (defgroup org-link-store nil
1456 "Options concerning storing links in Org-mode."
1457 :tag "Org Store Link"
1458 :group 'org-link)
1460 (defcustom org-url-hexify-p t
1461 "When non-nil, hexify URL when creating a link."
1462 :type 'boolean
1463 :version "24.3"
1464 :group 'org-link-store)
1466 (defcustom org-email-link-description-format "Email %c: %.30s"
1467 "Format of the description part of a link to an email or usenet message.
1468 The following %-escapes will be replaced by corresponding information:
1470 %F full \"From\" field
1471 %f name, taken from \"From\" field, address if no name
1472 %T full \"To\" field
1473 %t first name in \"To\" field, address if no name
1474 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1475 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1476 %s subject
1477 %d date
1478 %m message-id.
1480 You may use normal field width specification between the % and the letter.
1481 This is for example useful to limit the length of the subject.
1483 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1484 :group 'org-link-store
1485 :type 'string)
1487 (defcustom org-from-is-user-regexp
1488 (let (r1 r2)
1489 (when (and user-mail-address (not (string= user-mail-address "")))
1490 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1491 (when (and user-full-name (not (string= user-full-name "")))
1492 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1493 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1494 "Regexp matched against the \"From:\" header of an email or usenet message.
1495 It should match if the message is from the user him/herself."
1496 :group 'org-link-store
1497 :type 'regexp)
1499 (defcustom org-context-in-file-links t
1500 "Non-nil means file links from `org-store-link' contain context.
1501 A search string will be added to the file name with :: as separator and
1502 used to find the context when the link is activated by the command
1503 `org-open-at-point'. When this option is t, the entire active region
1504 will be placed in the search string of the file link. If set to a
1505 positive integer, only the first n lines of context will be stored.
1507 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1508 negates this setting for the duration of the command."
1509 :group 'org-link-store
1510 :type '(choice boolean integer))
1512 (defcustom org-keep-stored-link-after-insertion nil
1513 "Non-nil means keep link in list for entire session.
1515 The command `org-store-link' adds a link pointing to the current
1516 location to an internal list. These links accumulate during a session.
1517 The command `org-insert-link' can be used to insert links into any
1518 Org-mode file (offering completion for all stored links). When this
1519 option is nil, every link which has been inserted once using \\[org-insert-link]
1520 will be removed from the list, to make completing the unused links
1521 more efficient."
1522 :group 'org-link-store
1523 :type 'boolean)
1525 (defgroup org-link-follow nil
1526 "Options concerning following links in Org-mode."
1527 :tag "Org Follow Link"
1528 :group 'org-link)
1530 (defcustom org-link-translation-function nil
1531 "Function to translate links with different syntax to Org syntax.
1532 This can be used to translate links created for example by the Planner
1533 or emacs-wiki packages to Org syntax.
1534 The function must accept two parameters, a TYPE containing the link
1535 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1536 which is everything after the link protocol. It should return a cons
1537 with possibly modified values of type and path.
1538 Org contains a function for this, so if you set this variable to
1539 `org-translate-link-from-planner', you should be able follow many
1540 links created by planner."
1541 :group 'org-link-follow
1542 :type 'function)
1544 (defcustom org-follow-link-hook nil
1545 "Hook that is run after a link has been followed."
1546 :group 'org-link-follow
1547 :type 'hook)
1549 (defcustom org-tab-follows-link nil
1550 "Non-nil means on links TAB will follow the link.
1551 Needs to be set before org.el is loaded.
1552 This really should not be used, it does not make sense, and the
1553 implementation is bad."
1554 :group 'org-link-follow
1555 :type 'boolean)
1557 (defcustom org-return-follows-link nil
1558 "Non-nil means on links RET will follow the link."
1559 :group 'org-link-follow
1560 :type 'boolean)
1562 (defcustom org-mouse-1-follows-link
1563 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1564 "Non-nil means mouse-1 on a link will follow the link.
1565 A longer mouse click will still set point. Does not work on XEmacs.
1566 Needs to be set before org.el is loaded."
1567 :group 'org-link-follow
1568 :type 'boolean)
1570 (defcustom org-mark-ring-length 4
1571 "Number of different positions to be recorded in the ring.
1572 Changing this requires a restart of Emacs to work correctly."
1573 :group 'org-link-follow
1574 :type 'integer)
1576 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1577 "Non-nil means internal links in Org files must exactly match a headline.
1578 When nil, the link search tries to match a phrase with all words
1579 in the search text."
1580 :group 'org-link-follow
1581 :version "24.1"
1582 :type '(choice
1583 (const :tag "Use fuzzy text search" nil)
1584 (const :tag "Match only exact headline" t)
1585 (const :tag "Match exact headline or query to create it"
1586 query-to-create)))
1588 (defcustom org-link-frame-setup
1589 '((vm . vm-visit-folder-other-frame)
1590 (vm-imap . vm-visit-imap-folder-other-frame)
1591 (gnus . org-gnus-no-new-news)
1592 (file . find-file-other-window)
1593 (wl . wl-other-frame))
1594 "Setup the frame configuration for following links.
1595 When following a link with Emacs, it may often be useful to display
1596 this link in another window or frame. This variable can be used to
1597 set this up for the different types of links.
1598 For VM, use any of
1599 `vm-visit-folder'
1600 `vm-visit-folder-other-window'
1601 `vm-visit-folder-other-frame'
1602 For Gnus, use any of
1603 `gnus'
1604 `gnus-other-frame'
1605 `org-gnus-no-new-news'
1606 For FILE, use any of
1607 `find-file'
1608 `find-file-other-window'
1609 `find-file-other-frame'
1610 For Wanderlust use any of
1611 `wl'
1612 `wl-other-frame'
1613 For the calendar, use the variable `calendar-setup'.
1614 For BBDB, it is currently only possible to display the matches in
1615 another window."
1616 :group 'org-link-follow
1617 :type '(list
1618 (cons (const vm)
1619 (choice
1620 (const vm-visit-folder)
1621 (const vm-visit-folder-other-window)
1622 (const vm-visit-folder-other-frame)))
1623 (cons (const gnus)
1624 (choice
1625 (const gnus)
1626 (const gnus-other-frame)
1627 (const org-gnus-no-new-news)))
1628 (cons (const file)
1629 (choice
1630 (const find-file)
1631 (const find-file-other-window)
1632 (const find-file-other-frame)))
1633 (cons (const wl)
1634 (choice
1635 (const wl)
1636 (const wl-other-frame)))))
1638 (defcustom org-display-internal-link-with-indirect-buffer nil
1639 "Non-nil means use indirect buffer to display infile links.
1640 Activating internal links (from one location in a file to another location
1641 in the same file) normally just jumps to the location. When the link is
1642 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1643 is displayed in
1644 another window. When this option is set, the other window actually displays
1645 an indirect buffer clone of the current buffer, to avoid any visibility
1646 changes to the current buffer."
1647 :group 'org-link-follow
1648 :type 'boolean)
1650 (defcustom org-open-non-existing-files nil
1651 "Non-nil means `org-open-file' will open non-existing files.
1652 When nil, an error will be generated.
1653 This variable applies only to external applications because they
1654 might choke on non-existing files. If the link is to a file that
1655 will be opened in Emacs, the variable is ignored."
1656 :group 'org-link-follow
1657 :type 'boolean)
1659 (defcustom org-open-directory-means-index-dot-org nil
1660 "Non-nil means a link to a directory really means to index.org.
1661 When nil, following a directory link will run dired or open a finder/explorer
1662 window on that directory."
1663 :group 'org-link-follow
1664 :type 'boolean)
1666 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1667 "Function and arguments to call for following mailto links.
1668 This is a list with the first element being a Lisp function, and the
1669 remaining elements being arguments to the function. In string arguments,
1670 %a will be replaced by the address, and %s will be replaced by the subject
1671 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1672 :group 'org-link-follow
1673 :type '(choice
1674 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1675 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1676 (const :tag "message-mail" (message-mail "%a" "%s"))
1677 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1679 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1680 "Non-nil means ask for confirmation before executing shell links.
1681 Shell links can be dangerous: just think about a link
1683 [[shell:rm -rf ~/*][Google Search]]
1685 This link would show up in your Org-mode document as \"Google Search\",
1686 but really it would remove your entire home directory.
1687 Therefore we advise against setting this variable to nil.
1688 Just change it to `y-or-n-p' if you want to confirm with a
1689 single keystroke rather than having to type \"yes\"."
1690 :group 'org-link-follow
1691 :type '(choice
1692 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1693 (const :tag "with y-or-n (faster)" y-or-n-p)
1694 (const :tag "no confirmation (dangerous)" nil)))
1695 (put 'org-confirm-shell-link-function
1696 'safe-local-variable
1697 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1699 (defcustom org-confirm-shell-link-not-regexp ""
1700 "A regexp to skip confirmation for shell links."
1701 :group 'org-link-follow
1702 :version "24.1"
1703 :type 'regexp)
1705 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1706 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1707 Elisp links can be dangerous: just think about a link
1709 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1711 This link would show up in your Org-mode document as \"Google Search\",
1712 but really it would remove your entire home directory.
1713 Therefore we advise against setting this variable to nil.
1714 Just change it to `y-or-n-p' if you want to confirm with a
1715 single keystroke rather than having to type \"yes\"."
1716 :group 'org-link-follow
1717 :type '(choice
1718 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1719 (const :tag "with y-or-n (faster)" y-or-n-p)
1720 (const :tag "no confirmation (dangerous)" nil)))
1721 (put 'org-confirm-shell-link-function
1722 'safe-local-variable
1723 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1725 (defcustom org-confirm-elisp-link-not-regexp ""
1726 "A regexp to skip confirmation for Elisp links."
1727 :group 'org-link-follow
1728 :version "24.1"
1729 :type 'regexp)
1731 (defconst org-file-apps-defaults-gnu
1732 '((remote . emacs)
1733 (system . mailcap)
1734 (t . mailcap))
1735 "Default file applications on a UNIX or GNU/Linux system.
1736 See `org-file-apps'.")
1738 (defconst org-file-apps-defaults-macosx
1739 '((remote . emacs)
1740 (t . "open %s")
1741 (system . "open %s")
1742 ("ps.gz" . "gv %s")
1743 ("eps.gz" . "gv %s")
1744 ("dvi" . "xdvi %s")
1745 ("fig" . "xfig %s"))
1746 "Default file applications on a MacOS X system.
1747 The system \"open\" is known as a default, but we use X11 applications
1748 for some files for which the OS does not have a good default.
1749 See `org-file-apps'.")
1751 (defconst org-file-apps-defaults-windowsnt
1752 (list
1753 '(remote . emacs)
1754 (cons t
1755 (list (if (featurep 'xemacs)
1756 'mswindows-shell-execute
1757 'w32-shell-execute)
1758 "open" 'file))
1759 (cons 'system
1760 (list (if (featurep 'xemacs)
1761 'mswindows-shell-execute
1762 'w32-shell-execute)
1763 "open" 'file)))
1764 "Default file applications on a Windows NT system.
1765 The system \"open\" is used for most files.
1766 See `org-file-apps'.")
1768 (defcustom org-file-apps
1770 (auto-mode . emacs)
1771 ("\\.mm\\'" . default)
1772 ("\\.x?html?\\'" . default)
1773 ("\\.pdf\\'" . default)
1775 "External applications for opening `file:path' items in a document.
1776 Org-mode uses system defaults for different file types, but
1777 you can use this variable to set the application for a given file
1778 extension. The entries in this list are cons cells where the car identifies
1779 files and the cdr the corresponding command. Possible values for the
1780 file identifier are
1781 \"string\" A string as a file identifier can be interpreted in different
1782 ways, depending on its contents:
1784 - Alphanumeric characters only:
1785 Match links with this file extension.
1786 Example: (\"pdf\" . \"evince %s\")
1787 to open PDFs with evince.
1789 - Regular expression: Match links where the
1790 filename matches the regexp. If you want to
1791 use groups here, use shy groups.
1793 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1794 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1795 to open *.html and *.xhtml with firefox.
1797 - Regular expression which contains (non-shy) groups:
1798 Match links where the whole link, including \"::\", and
1799 anything after that, matches the regexp.
1800 In a custom command string, %1, %2, etc. are replaced with
1801 the parts of the link that were matched by the groups.
1802 For backwards compatibility, if a command string is given
1803 that does not use any of the group matches, this case is
1804 handled identically to the second one (i.e. match against
1805 file name only).
1806 In a custom lisp form, you can access the group matches with
1807 (match-string n link).
1809 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1810 to open [[file:document.pdf::5]] with evince at page 5.
1812 `directory' Matches a directory
1813 `remote' Matches a remote file, accessible through tramp or efs.
1814 Remote files most likely should be visited through Emacs
1815 because external applications cannot handle such paths.
1816 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1817 so all files Emacs knows how to handle. Using this with
1818 command `emacs' will open most files in Emacs. Beware that this
1819 will also open html files inside Emacs, unless you add
1820 (\"html\" . default) to the list as well.
1821 t Default for files not matched by any of the other options.
1822 `system' The system command to open files, like `open' on Windows
1823 and Mac OS X, and mailcap under GNU/Linux. This is the command
1824 that will be selected if you call `C-c C-o' with a double
1825 \\[universal-argument] \\[universal-argument] prefix.
1827 Possible values for the command are:
1828 `emacs' The file will be visited by the current Emacs process.
1829 `default' Use the default application for this file type, which is the
1830 association for t in the list, most likely in the system-specific
1831 part.
1832 This can be used to overrule an unwanted setting in the
1833 system-specific variable.
1834 `system' Use the system command for opening files, like \"open\".
1835 This command is specified by the entry whose car is `system'.
1836 Most likely, the system-specific version of this variable
1837 does define this command, but you can overrule/replace it
1838 here.
1839 string A command to be executed by a shell; %s will be replaced
1840 by the path to the file.
1841 sexp A Lisp form which will be evaluated. The file path will
1842 be available in the Lisp variable `file'.
1843 For more examples, see the system specific constants
1844 `org-file-apps-defaults-macosx'
1845 `org-file-apps-defaults-windowsnt'
1846 `org-file-apps-defaults-gnu'."
1847 :group 'org-link-follow
1848 :type '(repeat
1849 (cons (choice :value ""
1850 (string :tag "Extension")
1851 (const :tag "System command to open files" system)
1852 (const :tag "Default for unrecognized files" t)
1853 (const :tag "Remote file" remote)
1854 (const :tag "Links to a directory" directory)
1855 (const :tag "Any files that have Emacs modes"
1856 auto-mode))
1857 (choice :value ""
1858 (const :tag "Visit with Emacs" emacs)
1859 (const :tag "Use default" default)
1860 (const :tag "Use the system command" system)
1861 (string :tag "Command")
1862 (sexp :tag "Lisp form")))))
1864 (defcustom org-doi-server-url "http://dx.doi.org/"
1865 "The URL of the DOI server."
1866 :type 'string
1867 :version "24.3"
1868 :group 'org-link-follow)
1870 (defgroup org-refile nil
1871 "Options concerning refiling entries in Org-mode."
1872 :tag "Org Refile"
1873 :group 'org)
1875 (defcustom org-directory "~/org"
1876 "Directory with org files.
1877 This is just a default location to look for Org files. There is no need
1878 at all to put your files into this directory. It is only used in the
1879 following situations:
1881 1. When a capture template specifies a target file that is not an
1882 absolute path. The path will then be interpreted relative to
1883 `org-directory'
1884 2. When a capture note is filed away in an interactive way (when exiting the
1885 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1886 with `org-directory' as the default path."
1887 :group 'org-refile
1888 :group 'org-remember
1889 :group 'org-capture
1890 :type 'directory)
1892 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1893 "Default target for storing notes.
1894 Used as a fall back file for org-remember.el and org-capture.el, for
1895 templates that do not specify a target file."
1896 :group 'org-refile
1897 :group 'org-remember
1898 :group 'org-capture
1899 :type '(choice
1900 (const :tag "Default from remember-data-file" nil)
1901 file))
1903 (defcustom org-goto-interface 'outline
1904 "The default interface to be used for `org-goto'.
1905 Allowed values are:
1906 outline The interface shows an outline of the relevant file
1907 and the correct heading is found by moving through
1908 the outline or by searching with incremental search.
1909 outline-path-completion Headlines in the current buffer are offered via
1910 completion. This is the interface also used by
1911 the refile command."
1912 :group 'org-refile
1913 :type '(choice
1914 (const :tag "Outline" outline)
1915 (const :tag "Outline-path-completion" outline-path-completion)))
1917 (defcustom org-goto-max-level 5
1918 "Maximum target level when running `org-goto' with refile interface."
1919 :group 'org-refile
1920 :type 'integer)
1922 (defcustom org-reverse-note-order nil
1923 "Non-nil means store new notes at the beginning of a file or entry.
1924 When nil, new notes will be filed to the end of a file or entry.
1925 This can also be a list with cons cells of regular expressions that
1926 are matched against file names, and values."
1927 :group 'org-remember
1928 :group 'org-capture
1929 :group 'org-refile
1930 :type '(choice
1931 (const :tag "Reverse always" t)
1932 (const :tag "Reverse never" nil)
1933 (repeat :tag "By file name regexp"
1934 (cons regexp boolean))))
1936 (defcustom org-log-refile nil
1937 "Information to record when a task is refiled.
1939 Possible values are:
1941 nil Don't add anything
1942 time Add a time stamp to the task
1943 note Prompt for a note and add it with template `org-log-note-headings'
1945 This option can also be set with on a per-file-basis with
1947 #+STARTUP: nologrefile
1948 #+STARTUP: logrefile
1949 #+STARTUP: lognoterefile
1951 You can have local logging settings for a subtree by setting the LOGGING
1952 property to one or more of these keywords.
1954 When bulk-refiling from the agenda, the value `note' is forbidden and
1955 will temporarily be changed to `time'."
1956 :group 'org-refile
1957 :group 'org-progress
1958 :version "24.1"
1959 :type '(choice
1960 (const :tag "No logging" nil)
1961 (const :tag "Record timestamp" time)
1962 (const :tag "Record timestamp with note." note)))
1964 (defcustom org-refile-targets nil
1965 "Targets for refiling entries with \\[org-refile].
1966 This is a list of cons cells. Each cell contains:
1967 - a specification of the files to be considered, either a list of files,
1968 or a symbol whose function or variable value will be used to retrieve
1969 a file name or a list of file names. If you use `org-agenda-files' for
1970 that, all agenda files will be scanned for targets. Nil means consider
1971 headings in the current buffer.
1972 - A specification of how to find candidate refile targets. This may be
1973 any of:
1974 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1975 This tag has to be present in all target headlines, inheritance will
1976 not be considered.
1977 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1978 todo keyword.
1979 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1980 headlines that are refiling targets.
1981 - a cons cell (:level . N). Any headline of level N is considered a target.
1982 Note that, when `org-odd-levels-only' is set, level corresponds to
1983 order in hierarchy, not to the number of stars.
1984 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1985 Note that, when `org-odd-levels-only' is set, level corresponds to
1986 order in hierarchy, not to the number of stars.
1988 Each element of this list generates a set of possible targets.
1989 The union of these sets is presented (with completion) to
1990 the user by `org-refile'.
1992 You can set the variable `org-refile-target-verify-function' to a function
1993 to verify each headline found by the simple criteria above.
1995 When this variable is nil, all top-level headlines in the current buffer
1996 are used, equivalent to the value `((nil . (:level . 1))'."
1997 :group 'org-refile
1998 :type '(repeat
1999 (cons
2000 (choice :value org-agenda-files
2001 (const :tag "All agenda files" org-agenda-files)
2002 (const :tag "Current buffer" nil)
2003 (function) (variable) (file))
2004 (choice :tag "Identify target headline by"
2005 (cons :tag "Specific tag" (const :value :tag) (string))
2006 (cons :tag "TODO keyword" (const :value :todo) (string))
2007 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2008 (cons :tag "Level number" (const :value :level) (integer))
2009 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2011 (defcustom org-refile-target-verify-function nil
2012 "Function to verify if the headline at point should be a refile target.
2013 The function will be called without arguments, with point at the
2014 beginning of the headline. It should return t and leave point
2015 where it is if the headline is a valid target for refiling.
2017 If the target should not be selected, the function must return nil.
2018 In addition to this, it may move point to a place from where the search
2019 should be continued. For example, the function may decide that the entire
2020 subtree of the current entry should be excluded and move point to the end
2021 of the subtree."
2022 :group 'org-refile
2023 :type 'function)
2025 (defcustom org-refile-use-cache nil
2026 "Non-nil means cache refile targets to speed up the process.
2027 The cache for a particular file will be updated automatically when
2028 the buffer has been killed, or when any of the marker used for flagging
2029 refile targets no longer points at a live buffer.
2030 If you have added new entries to a buffer that might themselves be targets,
2031 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2032 find that easier, `C-u C-u C-u C-c C-w'."
2033 :group 'org-refile
2034 :version "24.1"
2035 :type 'boolean)
2037 (defcustom org-refile-use-outline-path nil
2038 "Non-nil means provide refile targets as paths.
2039 So a level 3 headline will be available as level1/level2/level3.
2041 When the value is `file', also include the file name (without directory)
2042 into the path. In this case, you can also stop the completion after
2043 the file name, to get entries inserted as top level in the file.
2045 When `full-file-path', include the full file path."
2046 :group 'org-refile
2047 :type '(choice
2048 (const :tag "Not" nil)
2049 (const :tag "Yes" t)
2050 (const :tag "Start with file name" file)
2051 (const :tag "Start with full file path" full-file-path)))
2053 (defcustom org-outline-path-complete-in-steps t
2054 "Non-nil means complete the outline path in hierarchical steps.
2055 When Org-mode uses the refile interface to select an outline path
2056 \(see variable `org-refile-use-outline-path'), the completion of
2057 the path can be done is a single go, or if can be done in steps down
2058 the headline hierarchy. Going in steps is probably the best if you
2059 do not use a special completion package like `ido' or `icicles'.
2060 However, when using these packages, going in one step can be very
2061 fast, while still showing the whole path to the entry."
2062 :group 'org-refile
2063 :type 'boolean)
2065 (defcustom org-refile-allow-creating-parent-nodes nil
2066 "Non-nil means allow to create new nodes as refile targets.
2067 New nodes are then created by adding \"/new node name\" to the completion
2068 of an existing node. When the value of this variable is `confirm',
2069 new node creation must be confirmed by the user (recommended)
2070 When nil, the completion must match an existing entry.
2072 Note that, if the new heading is not seen by the criteria
2073 listed in `org-refile-targets', multiple instances of the same
2074 heading would be created by trying again to file under the new
2075 heading."
2076 :group 'org-refile
2077 :type '(choice
2078 (const :tag "Never" nil)
2079 (const :tag "Always" t)
2080 (const :tag "Prompt for confirmation" confirm)))
2082 (defcustom org-refile-active-region-within-subtree nil
2083 "Non-nil means also refile active region within a subtree.
2085 By default `org-refile' doesn't allow refiling regions if they
2086 don't contain a set of subtrees, but it might be convenient to
2087 do so sometimes: in that case, the first line of the region is
2088 converted to a headline before refiling."
2089 :group 'org-refile
2090 :version "24.1"
2091 :type 'boolean)
2093 (defgroup org-todo nil
2094 "Options concerning TODO items in Org-mode."
2095 :tag "Org TODO"
2096 :group 'org)
2098 (defgroup org-progress nil
2099 "Options concerning Progress logging in Org-mode."
2100 :tag "Org Progress"
2101 :group 'org-time)
2103 (defvar org-todo-interpretation-widgets
2104 '((:tag "Sequence (cycling hits every state)" sequence)
2105 (:tag "Type (cycling directly to DONE)" type))
2106 "The available interpretation symbols for customizing `org-todo-keywords'.
2107 Interested libraries should add to this list.")
2109 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2110 "List of TODO entry keyword sequences and their interpretation.
2111 \\<org-mode-map>This is a list of sequences.
2113 Each sequence starts with a symbol, either `sequence' or `type',
2114 indicating if the keywords should be interpreted as a sequence of
2115 action steps, or as different types of TODO items. The first
2116 keywords are states requiring action - these states will select a headline
2117 for inclusion into the global TODO list Org-mode produces. If one of
2118 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2119 signify that no further action is necessary. If \"|\" is not found,
2120 the last keyword is treated as the only DONE state of the sequence.
2122 The command \\[org-todo] cycles an entry through these states, and one
2123 additional state where no keyword is present. For details about this
2124 cycling, see the manual.
2126 TODO keywords and interpretation can also be set on a per-file basis with
2127 the special #+SEQ_TODO and #+TYP_TODO lines.
2129 Each keyword can optionally specify a character for fast state selection
2130 \(in combination with the variable `org-use-fast-todo-selection')
2131 and specifiers for state change logging, using the same syntax that
2132 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2133 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2134 indicates to record a time stamp each time this state is selected.
2136 Each keyword may also specify if a timestamp or a note should be
2137 recorded when entering or leaving the state, by adding additional
2138 characters in the parenthesis after the keyword. This looks like this:
2139 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2140 record only the time of the state change. With X and Y being either
2141 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2142 Y when leaving the state if and only if the *target* state does not
2143 define X. You may omit any of the fast-selection key or X or /Y,
2144 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2146 For backward compatibility, this variable may also be just a list
2147 of keywords. In this case the interpretation (sequence or type) will be
2148 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2149 :group 'org-todo
2150 :group 'org-keywords
2151 :type '(choice
2152 (repeat :tag "Old syntax, just keywords"
2153 (string :tag "Keyword"))
2154 (repeat :tag "New syntax"
2155 (cons
2156 (choice
2157 :tag "Interpretation"
2158 ;;Quick and dirty way to see
2159 ;;`org-todo-interpretations'. This takes the
2160 ;;place of item arguments
2161 :convert-widget
2162 (lambda (widget)
2163 (widget-put widget
2164 :args (mapcar
2165 #'(lambda (x)
2166 (widget-convert
2167 (cons 'const x)))
2168 org-todo-interpretation-widgets))
2169 widget))
2170 (repeat
2171 (string :tag "Keyword"))))))
2173 (defvar org-todo-keywords-1 nil
2174 "All TODO and DONE keywords active in a buffer.")
2175 (make-variable-buffer-local 'org-todo-keywords-1)
2176 (defvar org-todo-keywords-for-agenda nil)
2177 (defvar org-done-keywords-for-agenda nil)
2178 (defvar org-drawers-for-agenda nil)
2179 (defvar org-todo-keyword-alist-for-agenda nil)
2180 (defvar org-tag-alist-for-agenda nil)
2181 (defvar org-agenda-contributing-files nil)
2182 (defvar org-not-done-keywords nil)
2183 (make-variable-buffer-local 'org-not-done-keywords)
2184 (defvar org-done-keywords nil)
2185 (make-variable-buffer-local 'org-done-keywords)
2186 (defvar org-todo-heads nil)
2187 (make-variable-buffer-local 'org-todo-heads)
2188 (defvar org-todo-sets nil)
2189 (make-variable-buffer-local 'org-todo-sets)
2190 (defvar org-todo-log-states nil)
2191 (make-variable-buffer-local 'org-todo-log-states)
2192 (defvar org-todo-kwd-alist nil)
2193 (make-variable-buffer-local 'org-todo-kwd-alist)
2194 (defvar org-todo-key-alist nil)
2195 (make-variable-buffer-local 'org-todo-key-alist)
2196 (defvar org-todo-key-trigger nil)
2197 (make-variable-buffer-local 'org-todo-key-trigger)
2199 (defcustom org-todo-interpretation 'sequence
2200 "Controls how TODO keywords are interpreted.
2201 This variable is in principle obsolete and is only used for
2202 backward compatibility, if the interpretation of todo keywords is
2203 not given already in `org-todo-keywords'. See that variable for
2204 more information."
2205 :group 'org-todo
2206 :group 'org-keywords
2207 :type '(choice (const sequence)
2208 (const type)))
2210 (defcustom org-use-fast-todo-selection t
2211 "Non-nil means use the fast todo selection scheme with C-c C-t.
2212 This variable describes if and under what circumstances the cycling
2213 mechanism for TODO keywords will be replaced by a single-key, direct
2214 selection scheme.
2216 When nil, fast selection is never used.
2218 When the symbol `prefix', it will be used when `org-todo' is called
2219 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2220 `C-u t' in an agenda buffer.
2222 When t, fast selection is used by default. In this case, the prefix
2223 argument forces cycling instead.
2225 In all cases, the special interface is only used if access keys have
2226 actually been assigned by the user, i.e. if keywords in the configuration
2227 are followed by a letter in parenthesis, like TODO(t)."
2228 :group 'org-todo
2229 :type '(choice
2230 (const :tag "Never" nil)
2231 (const :tag "By default" t)
2232 (const :tag "Only with C-u C-c C-t" prefix)))
2234 (defcustom org-provide-todo-statistics t
2235 "Non-nil means update todo statistics after insert and toggle.
2236 ALL-HEADLINES means update todo statistics by including headlines
2237 with no TODO keyword as well, counting them as not done.
2238 A list of TODO keywords means the same, but skip keywords that are
2239 not in this list.
2241 When this is set, todo statistics is updated in the parent of the
2242 current entry each time a todo state is changed."
2243 :group 'org-todo
2244 :type '(choice
2245 (const :tag "Yes, only for TODO entries" t)
2246 (const :tag "Yes, including all entries" 'all-headlines)
2247 (repeat :tag "Yes, for TODOs in this list"
2248 (string :tag "TODO keyword"))
2249 (other :tag "No TODO statistics" nil)))
2251 (defcustom org-hierarchical-todo-statistics t
2252 "Non-nil means TODO statistics covers just direct children.
2253 When nil, all entries in the subtree are considered.
2254 This has only an effect if `org-provide-todo-statistics' is set.
2255 To set this to nil for only a single subtree, use a COOKIE_DATA
2256 property and include the word \"recursive\" into the value."
2257 :group 'org-todo
2258 :type 'boolean)
2260 (defcustom org-after-todo-state-change-hook nil
2261 "Hook which is run after the state of a TODO item was changed.
2262 The new state (a string with a TODO keyword, or nil) is available in the
2263 Lisp variable `org-state'."
2264 :group 'org-todo
2265 :type 'hook)
2267 (defvar org-blocker-hook nil
2268 "Hook for functions that are allowed to block a state change.
2270 Functions in this hook should not modify the buffer.
2271 Each function gets as its single argument a property list,
2272 see `org-trigger-hook' for more information about this list.
2274 If any of the functions in this hook returns nil, the state change
2275 is blocked.")
2277 (defvar org-trigger-hook nil
2278 "Hook for functions that are triggered by a state change.
2280 Each function gets as its single argument a property list with at
2281 least the following elements:
2283 (:type type-of-change :position pos-at-entry-start
2284 :from old-state :to new-state)
2286 Depending on the type, more properties may be present.
2288 This mechanism is currently implemented for:
2290 TODO state changes
2291 ------------------
2292 :type todo-state-change
2293 :from previous state (keyword as a string), or nil, or a symbol
2294 'todo' or 'done', to indicate the general type of state.
2295 :to new state, like in :from")
2297 (defcustom org-enforce-todo-dependencies nil
2298 "Non-nil means undone TODO entries will block switching the parent to DONE.
2299 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2300 be blocked if any prior sibling is not yet done.
2301 Finally, if the parent is blocked because of ordered siblings of its own,
2302 the child will also be blocked."
2303 :set (lambda (var val)
2304 (set var val)
2305 (if val
2306 (add-hook 'org-blocker-hook
2307 'org-block-todo-from-children-or-siblings-or-parent)
2308 (remove-hook 'org-blocker-hook
2309 'org-block-todo-from-children-or-siblings-or-parent)))
2310 :group 'org-todo
2311 :type 'boolean)
2313 (defcustom org-enforce-todo-checkbox-dependencies nil
2314 "Non-nil means unchecked boxes will block switching the parent to DONE.
2315 When this is nil, checkboxes have no influence on switching TODO states.
2316 When non-nil, you first need to check off all check boxes before the TODO
2317 entry can be switched to DONE.
2318 This variable needs to be set before org.el is loaded, and you need to
2319 restart Emacs after a change to make the change effective. The only way
2320 to change is while Emacs is running is through the customize interface."
2321 :set (lambda (var val)
2322 (set var val)
2323 (if val
2324 (add-hook 'org-blocker-hook
2325 'org-block-todo-from-checkboxes)
2326 (remove-hook 'org-blocker-hook
2327 'org-block-todo-from-checkboxes)))
2328 :group 'org-todo
2329 :type 'boolean)
2331 (defcustom org-treat-insert-todo-heading-as-state-change nil
2332 "Non-nil means inserting a TODO heading is treated as state change.
2333 So when the command \\[org-insert-todo-heading] is used, state change
2334 logging will apply if appropriate. When nil, the new TODO item will
2335 be inserted directly, and no logging will take place."
2336 :group 'org-todo
2337 :type 'boolean)
2339 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2340 "Non-nil means switching TODO states with S-cursor counts as state change.
2341 This is the default behavior. However, setting this to nil allows a
2342 convenient way to select a TODO state and bypass any logging associated
2343 with that."
2344 :group 'org-todo
2345 :type 'boolean)
2347 (defcustom org-todo-state-tags-triggers nil
2348 "Tag changes that should be triggered by TODO state changes.
2349 This is a list. Each entry is
2351 (state-change (tag . flag) .......)
2353 State-change can be a string with a state, and empty string to indicate the
2354 state that has no TODO keyword, or it can be one of the symbols `todo'
2355 or `done', meaning any not-done or done state, respectively."
2356 :group 'org-todo
2357 :group 'org-tags
2358 :type '(repeat
2359 (cons (choice :tag "When changing to"
2360 (const :tag "Not-done state" todo)
2361 (const :tag "Done state" done)
2362 (string :tag "State"))
2363 (repeat
2364 (cons :tag "Tag action"
2365 (string :tag "Tag")
2366 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2368 (defcustom org-log-done nil
2369 "Information to record when a task moves to the DONE state.
2371 Possible values are:
2373 nil Don't add anything, just change the keyword
2374 time Add a time stamp to the task
2375 note Prompt for a note and add it with template `org-log-note-headings'
2377 This option can also be set with on a per-file-basis with
2379 #+STARTUP: nologdone
2380 #+STARTUP: logdone
2381 #+STARTUP: lognotedone
2383 You can have local logging settings for a subtree by setting the LOGGING
2384 property to one or more of these keywords."
2385 :group 'org-todo
2386 :group 'org-progress
2387 :type '(choice
2388 (const :tag "No logging" nil)
2389 (const :tag "Record CLOSED timestamp" time)
2390 (const :tag "Record CLOSED timestamp with note." note)))
2392 ;; Normalize old uses of org-log-done.
2393 (cond
2394 ((eq org-log-done t) (setq org-log-done 'time))
2395 ((and (listp org-log-done) (memq 'done org-log-done))
2396 (setq org-log-done 'note)))
2398 (defcustom org-log-reschedule nil
2399 "Information to record when the scheduling date of a tasks is modified.
2401 Possible values are:
2403 nil Don't add anything, just change the date
2404 time Add a time stamp to the task
2405 note Prompt for a note and add it with template `org-log-note-headings'
2407 This option can also be set with on a per-file-basis with
2409 #+STARTUP: nologreschedule
2410 #+STARTUP: logreschedule
2411 #+STARTUP: lognotereschedule"
2412 :group 'org-todo
2413 :group 'org-progress
2414 :type '(choice
2415 (const :tag "No logging" nil)
2416 (const :tag "Record timestamp" time)
2417 (const :tag "Record timestamp with note." note)))
2419 (defcustom org-log-redeadline nil
2420 "Information to record when the deadline date of a tasks is modified.
2422 Possible values are:
2424 nil Don't add anything, just change the date
2425 time Add a time stamp to the task
2426 note Prompt for a note and add it with template `org-log-note-headings'
2428 This option can also be set with on a per-file-basis with
2430 #+STARTUP: nologredeadline
2431 #+STARTUP: logredeadline
2432 #+STARTUP: lognoteredeadline
2434 You can have local logging settings for a subtree by setting the LOGGING
2435 property to one or more of these keywords."
2436 :group 'org-todo
2437 :group 'org-progress
2438 :type '(choice
2439 (const :tag "No logging" nil)
2440 (const :tag "Record timestamp" time)
2441 (const :tag "Record timestamp with note." note)))
2443 (defcustom org-log-note-clock-out nil
2444 "Non-nil means record a note when clocking out of an item.
2445 This can also be configured on a per-file basis by adding one of
2446 the following lines anywhere in the buffer:
2448 #+STARTUP: lognoteclock-out
2449 #+STARTUP: nolognoteclock-out"
2450 :group 'org-todo
2451 :group 'org-progress
2452 :type 'boolean)
2454 (defcustom org-log-done-with-time t
2455 "Non-nil means the CLOSED time stamp will contain date and time.
2456 When nil, only the date will be recorded."
2457 :group 'org-progress
2458 :type 'boolean)
2460 (defcustom org-log-note-headings
2461 '((done . "CLOSING NOTE %t")
2462 (state . "State %-12s from %-12S %t")
2463 (note . "Note taken on %t")
2464 (reschedule . "Rescheduled from %S on %t")
2465 (delschedule . "Not scheduled, was %S on %t")
2466 (redeadline . "New deadline from %S on %t")
2467 (deldeadline . "Removed deadline, was %S on %t")
2468 (refile . "Refiled on %t")
2469 (clock-out . ""))
2470 "Headings for notes added to entries.
2471 The value is an alist, with the car being a symbol indicating the note
2472 context, and the cdr is the heading to be used. The heading may also be the
2473 empty string.
2474 %t in the heading will be replaced by a time stamp.
2475 %T will be an active time stamp instead the default inactive one
2476 %d will be replaced by a short-format time stamp.
2477 %D will be replaced by an active short-format time stamp.
2478 %s will be replaced by the new TODO state, in double quotes.
2479 %S will be replaced by the old TODO state, in double quotes.
2480 %u will be replaced by the user name.
2481 %U will be replaced by the full user name.
2483 In fact, it is not a good idea to change the `state' entry, because
2484 agenda log mode depends on the format of these entries."
2485 :group 'org-todo
2486 :group 'org-progress
2487 :type '(list :greedy t
2488 (cons (const :tag "Heading when closing an item" done) string)
2489 (cons (const :tag
2490 "Heading when changing todo state (todo sequence only)"
2491 state) string)
2492 (cons (const :tag "Heading when just taking a note" note) string)
2493 (cons (const :tag "Heading when clocking out" clock-out) string)
2494 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2495 (cons (const :tag "Heading when rescheduling" reschedule) string)
2496 (cons (const :tag "Heading when changing deadline" redeadline) string)
2497 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2498 (cons (const :tag "Heading when refiling" refile) string)))
2500 (unless (assq 'note org-log-note-headings)
2501 (push '(note . "%t") org-log-note-headings))
2503 (defcustom org-log-into-drawer nil
2504 "Non-nil means insert state change notes and time stamps into a drawer.
2505 When nil, state changes notes will be inserted after the headline and
2506 any scheduling and clock lines, but not inside a drawer.
2508 The value of this variable should be the name of the drawer to use.
2509 LOGBOOK is proposed as the default drawer for this purpose, you can
2510 also set this to a string to define the drawer of your choice.
2512 A value of t is also allowed, representing \"LOGBOOK\".
2514 A value of t or nil can also be set with on a per-file-basis with
2516 #+STARTUP: logdrawer
2517 #+STARTUP: nologdrawer
2519 If this variable is set, `org-log-state-notes-insert-after-drawers'
2520 will be ignored.
2522 You can set the property LOG_INTO_DRAWER to overrule this setting for
2523 a subtree."
2524 :group 'org-todo
2525 :group 'org-progress
2526 :type '(choice
2527 (const :tag "Not into a drawer" nil)
2528 (const :tag "LOGBOOK" t)
2529 (string :tag "Other")))
2531 (if (fboundp 'defvaralias)
2532 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2534 (defun org-log-into-drawer ()
2535 "Return the value of `org-log-into-drawer', but let properties overrule.
2536 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2537 used instead of the default value."
2538 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2539 (cond
2540 ((not p) org-log-into-drawer)
2541 ((equal p "nil") nil)
2542 ((equal p "t") "LOGBOOK")
2543 (t p))))
2545 (defcustom org-log-state-notes-insert-after-drawers nil
2546 "Non-nil means insert state change notes after any drawers in entry.
2547 Only the drawers that *immediately* follow the headline and the
2548 deadline/scheduled line are skipped.
2549 When nil, insert notes right after the heading and perhaps the line
2550 with deadline/scheduling if present.
2552 This variable will have no effect if `org-log-into-drawer' is
2553 set."
2554 :group 'org-todo
2555 :group 'org-progress
2556 :type 'boolean)
2558 (defcustom org-log-states-order-reversed t
2559 "Non-nil means the latest state note will be directly after heading.
2560 When nil, the state change notes will be ordered according to time.
2562 This option can also be set with on a per-file-basis with
2564 #+STARTUP: logstatesreversed
2565 #+STARTUP: nologstatesreversed"
2566 :group 'org-todo
2567 :group 'org-progress
2568 :type 'boolean)
2570 (defcustom org-todo-repeat-to-state nil
2571 "The TODO state to which a repeater should return the repeating task.
2572 By default this is the first task in a TODO sequence, or the previous state
2573 in a TODO_TYP set. But you can specify another task here.
2574 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2575 :group 'org-todo
2576 :version "24.1"
2577 :type '(choice (const :tag "Head of sequence" nil)
2578 (string :tag "Specific state")))
2580 (defcustom org-log-repeat 'time
2581 "Non-nil means record moving through the DONE state when triggering repeat.
2582 An auto-repeating task is immediately switched back to TODO when
2583 marked DONE. If you are not logging state changes (by adding \"@\"
2584 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2585 record a closing note, there will be no record of the task moving
2586 through DONE. This variable forces taking a note anyway.
2588 nil Don't force a record
2589 time Record a time stamp
2590 note Prompt for a note and add it with template `org-log-note-headings'
2592 This option can also be set with on a per-file-basis with
2594 #+STARTUP: nologrepeat
2595 #+STARTUP: logrepeat
2596 #+STARTUP: lognoterepeat
2598 You can have local logging settings for a subtree by setting the LOGGING
2599 property to one or more of these keywords."
2600 :group 'org-todo
2601 :group 'org-progress
2602 :type '(choice
2603 (const :tag "Don't force a record" nil)
2604 (const :tag "Force recording the DONE state" time)
2605 (const :tag "Force recording a note with the DONE state" note)))
2608 (defgroup org-priorities nil
2609 "Priorities in Org-mode."
2610 :tag "Org Priorities"
2611 :group 'org-todo)
2613 (defcustom org-enable-priority-commands t
2614 "Non-nil means priority commands are active.
2615 When nil, these commands will be disabled, so that you never accidentally
2616 set a priority."
2617 :group 'org-priorities
2618 :type 'boolean)
2620 (defcustom org-highest-priority ?A
2621 "The highest priority of TODO items. A character like ?A, ?B etc.
2622 Must have a smaller ASCII number than `org-lowest-priority'."
2623 :group 'org-priorities
2624 :type 'character)
2626 (defcustom org-lowest-priority ?C
2627 "The lowest priority of TODO items. A character like ?A, ?B etc.
2628 Must have a larger ASCII number than `org-highest-priority'."
2629 :group 'org-priorities
2630 :type 'character)
2632 (defcustom org-default-priority ?B
2633 "The default priority of TODO items.
2634 This is the priority an item gets if no explicit priority is given.
2635 When starting to cycle on an empty priority the first step in the cycle
2636 depends on `org-priority-start-cycle-with-default'. The resulting first
2637 step priority must not exceed the range from `org-highest-priority' to
2638 `org-lowest-priority' which means that `org-default-priority' has to be
2639 in this range exclusive or inclusive the range boundaries. Else the
2640 first step refuses to set the default and the second will fall back
2641 to (depending on the command used) the highest or lowest priority."
2642 :group 'org-priorities
2643 :type 'character)
2645 (defcustom org-priority-start-cycle-with-default t
2646 "Non-nil means start with default priority when starting to cycle.
2647 When this is nil, the first step in the cycle will be (depending on the
2648 command used) one higher or lower than the default priority.
2649 See also `org-default-priority'."
2650 :group 'org-priorities
2651 :type 'boolean)
2653 (defcustom org-get-priority-function nil
2654 "Function to extract the priority from a string.
2655 The string is normally the headline. If this is nil Org computes the
2656 priority from the priority cookie like [#A] in the headline. It returns
2657 an integer, increasing by 1000 for each priority level.
2658 The user can set a different function here, which should take a string
2659 as an argument and return the numeric priority."
2660 :group 'org-priorities
2661 :version "24.1"
2662 :type 'function)
2664 (defgroup org-time nil
2665 "Options concerning time stamps and deadlines in Org-mode."
2666 :tag "Org Time"
2667 :group 'org)
2669 (defcustom org-insert-labeled-timestamps-at-point nil
2670 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2671 When nil, these labeled time stamps are forces into the second line of an
2672 entry, just after the headline. When scheduling from the global TODO list,
2673 the time stamp will always be forced into the second line."
2674 :group 'org-time
2675 :type 'boolean)
2677 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2678 "Formats for `format-time-string' which are used for time stamps.
2679 It is not recommended to change this constant.")
2681 (defcustom org-time-stamp-rounding-minutes '(0 5)
2682 "Number of minutes to round time stamps to.
2683 These are two values, the first applies when first creating a time stamp.
2684 The second applies when changing it with the commands `S-up' and `S-down'.
2685 When changing the time stamp, this means that it will change in steps
2686 of N minutes, as given by the second value.
2688 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2689 numbers should be factors of 60, so for example 5, 10, 15.
2691 When this is larger than 1, you can still force an exact time stamp by using
2692 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2693 and by using a prefix arg to `S-up/down' to specify the exact number
2694 of minutes to shift."
2695 :group 'org-time
2696 :get #'(lambda (var) ; Make sure both elements are there
2697 (if (integerp (default-value var))
2698 (list (default-value var) 5)
2699 (default-value var)))
2700 :type '(list
2701 (integer :tag "when inserting times")
2702 (integer :tag "when modifying times")))
2704 ;; Normalize old customizations of this variable.
2705 (when (integerp org-time-stamp-rounding-minutes)
2706 (setq org-time-stamp-rounding-minutes
2707 (list org-time-stamp-rounding-minutes
2708 org-time-stamp-rounding-minutes)))
2710 (defcustom org-display-custom-times nil
2711 "Non-nil means overlay custom formats over all time stamps.
2712 The formats are defined through the variable `org-time-stamp-custom-formats'.
2713 To turn this on on a per-file basis, insert anywhere in the file:
2714 #+STARTUP: customtime"
2715 :group 'org-time
2716 :set 'set-default
2717 :type 'sexp)
2718 (make-variable-buffer-local 'org-display-custom-times)
2720 (defcustom org-time-stamp-custom-formats
2721 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2722 "Custom formats for time stamps. See `format-time-string' for the syntax.
2723 These are overlaid over the default ISO format if the variable
2724 `org-display-custom-times' is set. Time like %H:%M should be at the
2725 end of the second format. The custom formats are also honored by export
2726 commands, if custom time display is turned on at the time of export."
2727 :group 'org-time
2728 :type 'sexp)
2730 (defun org-time-stamp-format (&optional long inactive)
2731 "Get the right format for a time string."
2732 (let ((f (if long (cdr org-time-stamp-formats)
2733 (car org-time-stamp-formats))))
2734 (if inactive
2735 (concat "[" (substring f 1 -1) "]")
2736 f)))
2738 (defcustom org-time-clocksum-format
2739 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2740 "The format string used when creating CLOCKSUM lines.
2741 This is also used when Org mode generates a time duration.
2743 The value can be a single format string containing two
2744 %-sequences, which will be filled with the number of hours and
2745 minutes in that order.
2747 Alternatively, the value can be a plist associating any of the
2748 keys :years, :months, :weeks, :days, :hours or :minutes with
2749 format strings. The time duration is formatted using only the
2750 time components that are needed and concatenating the results.
2751 If a time unit in absent, it falls back to the next smallest
2752 unit.
2754 The keys :require-years, :require-months, :require-days,
2755 :require-weeks, :require-hours, :require-minutes are also
2756 meaningful. A non-nil value for these keys indicates that the
2757 corresponding time component should always be included, even if
2758 its value is 0.
2761 For example,
2763 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2764 :require-minutes t)
2766 means durations longer than a day will be expressed in days,
2767 hours and minutes, and durations less than a day will always be
2768 expressed in hours and minutes (even for durations less than an
2769 hour).
2771 The value
2773 \(:days \"%dd\" :minutes \"%dm\")
2775 means durations longer than a day will be expressed in days and
2776 minutes, and durations less than a day will be expressed entirely
2777 in minutes (even for durations longer than an hour)."
2778 :group 'org-time
2779 :group 'org-clock
2780 :version "24.3"
2781 :type '(choice (string :tag "Format string")
2782 (set :tag "Plist"
2783 (group :inline t (const :tag "Years" :years)
2784 (string :tag "Format string"))
2785 (group :inline t
2786 (const :tag "Always show years" :require-years)
2787 (const t))
2788 (group :inline t (const :tag "Months" :months)
2789 (string :tag "Format string"))
2790 (group :inline t
2791 (const :tag "Always show months" :require-months)
2792 (const t))
2793 (group :inline t (const :tag "Weeks" :weeks)
2794 (string :tag "Format string"))
2795 (group :inline t
2796 (const :tag "Always show weeks" :require-weeks)
2797 (const t))
2798 (group :inline t (const :tag "Days" :days)
2799 (string :tag "Format string"))
2800 (group :inline t
2801 (const :tag "Always show days" :require-days)
2802 (const t))
2803 (group :inline t (const :tag "Hours" :hours)
2804 (string :tag "Format string"))
2805 (group :inline t
2806 (const :tag "Always show hours" :require-hours)
2807 (const t))
2808 (group :inline t (const :tag "Minutes" :minutes)
2809 (string :tag "Format string"))
2810 (group :inline t
2811 (const :tag "Always show minutes" :require-minutes)
2812 (const t)))))
2814 (defcustom org-time-clocksum-use-fractional nil
2815 "When non-nil, \\[org-clock-display] uses fractional times.
2816 See `org-time-clocksum-format' for more on time clock formats."
2817 :group 'org-time
2818 :group 'org-clock
2819 :version "24.3"
2820 :type 'boolean)
2822 (defcustom org-time-clocksum-use-effort-durations t
2823 "When non-nil, \\[org-clock-display] uses effort durations.
2824 E.g. by default, one day is considered to be a 8 hours effort,
2825 so a task that has been clocked for 16 hours will be displayed
2826 as during 2 days in the clock display or in the clocktable.
2828 See `org-effort-durations' on how to set effort durations
2829 and `org-time-clocksum-format' for more on time clock formats."
2830 :group 'org-time
2831 :group 'org-clock
2832 :version "24.3"
2833 :type 'boolean)
2835 (defcustom org-time-clocksum-fractional-format "%.2f"
2836 "The format string used when creating CLOCKSUM lines,
2837 or when Org mode generates a time duration, if
2838 `org-time-clocksum-use-fractional' is enabled.
2840 The value can be a single format string containing one
2841 %-sequence, which will be filled with the number of hours as
2842 a float.
2844 Alternatively, the value can be a plist associating any of the
2845 keys :years, :months, :weeks, :days, :hours or :minutes with
2846 a format string. The time duration is formatted using the
2847 largest time unit which gives a non-zero integer part. If all
2848 specified formats have zero integer part, the smallest time unit
2849 is used."
2850 :group 'org-time
2851 :type '(choice (string :tag "Format string")
2852 (set (group :inline t (const :tag "Years" :years)
2853 (string :tag "Format string"))
2854 (group :inline t (const :tag "Months" :months)
2855 (string :tag "Format string"))
2856 (group :inline t (const :tag "Weeks" :weeks)
2857 (string :tag "Format string"))
2858 (group :inline t (const :tag "Days" :days)
2859 (string :tag "Format string"))
2860 (group :inline t (const :tag "Hours" :hours)
2861 (string :tag "Format string"))
2862 (group :inline t (const :tag "Minutes" :minutes)
2863 (string :tag "Format string")))))
2865 (defcustom org-deadline-warning-days 14
2866 "No. of days before expiration during which a deadline becomes active.
2867 This variable governs the display in sparse trees and in the agenda.
2868 When 0 or negative, it means use this number (the absolute value of it)
2869 even if a deadline has a different individual lead time specified.
2871 Custom commands can set this variable in the options section."
2872 :group 'org-time
2873 :group 'org-agenda-daily/weekly
2874 :type 'integer)
2876 (defcustom org-read-date-prefer-future t
2877 "Non-nil means assume future for incomplete date input from user.
2878 This affects the following situations:
2879 1. The user gives a month but not a year.
2880 For example, if it is April and you enter \"feb 2\", this will be read
2881 as Feb 2, *next* year. \"May 5\", however, will be this year.
2882 2. The user gives a day, but no month.
2883 For example, if today is the 15th, and you enter \"3\", Org-mode will
2884 read this as the third of *next* month. However, if you enter \"17\",
2885 it will be considered as *this* month.
2887 If you set this variable to the symbol `time', then also the following
2888 will work:
2890 3. If the user gives a time.
2891 If the time is before now, it will be interpreted as tomorrow.
2893 Currently none of this works for ISO week specifications.
2895 When this option is nil, the current day, month and year will always be
2896 used as defaults.
2898 See also `org-agenda-jump-prefer-future'."
2899 :group 'org-time
2900 :type '(choice
2901 (const :tag "Never" nil)
2902 (const :tag "Check month and day" t)
2903 (const :tag "Check month, day, and time" time)))
2905 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2906 "Should the agenda jump command prefer the future for incomplete dates?
2907 The default is to do the same as configured in `org-read-date-prefer-future'.
2908 But you can also set a deviating value here.
2909 This may t or nil, or the symbol `org-read-date-prefer-future'."
2910 :group 'org-agenda
2911 :group 'org-time
2912 :version "24.1"
2913 :type '(choice
2914 (const :tag "Use org-read-date-prefer-future"
2915 org-read-date-prefer-future)
2916 (const :tag "Never" nil)
2917 (const :tag "Always" t)))
2919 (defcustom org-read-date-force-compatible-dates t
2920 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2922 Depending on the system Emacs is running on, certain dates cannot
2923 be represented with the type used internally to represent time.
2924 Dates between 1970-1-1 and 2038-1-1 can always be represented
2925 correctly. Some systems allow for earlier dates, some for later,
2926 some for both. One way to find out it to insert any date into an
2927 Org buffer, putting the cursor on the year and hitting S-up and
2928 S-down to test the range.
2930 When this variable is set to t, the date/time prompt will not let
2931 you specify dates outside the 1970-2037 range, so it is certain that
2932 these dates will work in whatever version of Emacs you are
2933 running, and also that you can move a file from one Emacs implementation
2934 to another. WHenever Org is forcing the year for you, it will display
2935 a message and beep.
2937 When this variable is nil, Org will check if the date is
2938 representable in the specific Emacs implementation you are using.
2939 If not, it will force a year, usually the current year, and beep
2940 to remind you. Currently this setting is not recommended because
2941 the likelihood that you will open your Org files in an Emacs that
2942 has limited date range is not negligible.
2944 A workaround for this problem is to use diary sexp dates for time
2945 stamps outside of this range."
2946 :group 'org-time
2947 :version "24.1"
2948 :type 'boolean)
2950 (defcustom org-read-date-display-live t
2951 "Non-nil means display current interpretation of date prompt live.
2952 This display will be in an overlay, in the minibuffer."
2953 :group 'org-time
2954 :type 'boolean)
2956 (defcustom org-read-date-popup-calendar t
2957 "Non-nil means pop up a calendar when prompting for a date.
2958 In the calendar, the date can be selected with mouse-1. However, the
2959 minibuffer will also be active, and you can simply enter the date as well.
2960 When nil, only the minibuffer will be available."
2961 :group 'org-time
2962 :type 'boolean)
2963 (if (fboundp 'defvaralias)
2964 (defvaralias 'org-popup-calendar-for-date-prompt
2965 'org-read-date-popup-calendar))
2967 (defcustom org-read-date-minibuffer-setup-hook nil
2968 "Hook to be used to set up keys for the date/time interface.
2969 Add key definitions to `minibuffer-local-map', which will be a temporary
2970 copy."
2971 :group 'org-time
2972 :type 'hook)
2974 (defcustom org-extend-today-until 0
2975 "The hour when your day really ends. Must be an integer.
2976 This has influence for the following applications:
2977 - When switching the agenda to \"today\". It it is still earlier than
2978 the time given here, the day recognized as TODAY is actually yesterday.
2979 - When a date is read from the user and it is still before the time given
2980 here, the current date and time will be assumed to be yesterday, 23:59.
2981 Also, timestamps inserted in capture templates follow this rule.
2983 IMPORTANT: This is a feature whose implementation is and likely will
2984 remain incomplete. Really, it is only here because past midnight seems to
2985 be the favorite working time of John Wiegley :-)"
2986 :group 'org-time
2987 :type 'integer)
2989 (defcustom org-use-effective-time nil
2990 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2991 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2992 \"effective time\" of any timestamps between midnight and 8am will be
2993 23:59 of the previous day."
2994 :group 'org-time
2995 :version "24.1"
2996 :type 'boolean)
2998 (defcustom org-use-last-clock-out-time-as-effective-time nil
2999 "When non-nil, use the last clock out time for `org-todo'.
3000 Note that this option has precedence over the combined use of
3001 `org-use-effective-time' and `org-extend-today-until'."
3002 :group 'org-time
3003 ;; :version "24.3"
3004 :type 'boolean)
3006 (defcustom org-edit-timestamp-down-means-later nil
3007 "Non-nil means S-down will increase the time in a time stamp.
3008 When nil, S-up will increase."
3009 :group 'org-time
3010 :type 'boolean)
3012 (defcustom org-calendar-follow-timestamp-change t
3013 "Non-nil means make the calendar window follow timestamp changes.
3014 When a timestamp is modified and the calendar window is visible, it will be
3015 moved to the new date."
3016 :group 'org-time
3017 :type 'boolean)
3019 (defgroup org-tags nil
3020 "Options concerning tags in Org-mode."
3021 :tag "Org Tags"
3022 :group 'org)
3024 (defcustom org-tag-alist nil
3025 "List of tags allowed in Org-mode files.
3026 When this list is nil, Org-mode will base TAG input on what is already in the
3027 buffer.
3028 The value of this variable is an alist, the car of each entry must be a
3029 keyword as a string, the cdr may be a character that is used to select
3030 that tag through the fast-tag-selection interface.
3031 See the manual for details."
3032 :group 'org-tags
3033 :type '(repeat
3034 (choice
3035 (cons (string :tag "Tag name")
3036 (character :tag "Access char"))
3037 (list :tag "Start radio group"
3038 (const :startgroup)
3039 (option (string :tag "Group description")))
3040 (list :tag "End radio group"
3041 (const :endgroup)
3042 (option (string :tag "Group description")))
3043 (const :tag "New line" (:newline)))))
3045 (defcustom org-tag-persistent-alist nil
3046 "List of tags that will always appear in all Org-mode files.
3047 This is in addition to any in buffer settings or customizations
3048 of `org-tag-alist'.
3049 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3050 The value of this variable is an alist, the car of each entry must be a
3051 keyword as a string, the cdr may be a character that is used to select
3052 that tag through the fast-tag-selection interface.
3053 See the manual for details.
3054 To disable these tags on a per-file basis, insert anywhere in the file:
3055 #+STARTUP: noptag"
3056 :group 'org-tags
3057 :type '(repeat
3058 (choice
3059 (cons (string :tag "Tag name")
3060 (character :tag "Access char"))
3061 (const :tag "Start radio group" (:startgroup))
3062 (const :tag "End radio group" (:endgroup))
3063 (const :tag "New line" (:newline)))))
3065 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3066 "If non-nil, always offer completion for all tags of all agenda files.
3067 Instead of customizing this variable directly, you might want to
3068 set it locally for capture buffers, because there no list of
3069 tags in that file can be created dynamically (there are none).
3071 (add-hook 'org-capture-mode-hook
3072 (lambda ()
3073 (set (make-local-variable
3074 'org-complete-tags-always-offer-all-agenda-tags)
3075 t)))"
3076 :group 'org-tags
3077 :version "24.1"
3078 :type 'boolean)
3080 (defvar org-file-tags nil
3081 "List of tags that can be inherited by all entries in the file.
3082 The tags will be inherited if the variable `org-use-tag-inheritance'
3083 says they should be.
3084 This variable is populated from #+FILETAGS lines.")
3086 (defcustom org-use-fast-tag-selection 'auto
3087 "Non-nil means use fast tag selection scheme.
3088 This is a special interface to select and deselect tags with single keys.
3089 When nil, fast selection is never used.
3090 When the symbol `auto', fast selection is used if and only if selection
3091 characters for tags have been configured, either through the variable
3092 `org-tag-alist' or through a #+TAGS line in the buffer.
3093 When t, fast selection is always used and selection keys are assigned
3094 automatically if necessary."
3095 :group 'org-tags
3096 :type '(choice
3097 (const :tag "Always" t)
3098 (const :tag "Never" nil)
3099 (const :tag "When selection characters are configured" 'auto)))
3101 (defcustom org-fast-tag-selection-single-key nil
3102 "Non-nil means fast tag selection exits after first change.
3103 When nil, you have to press RET to exit it.
3104 During fast tag selection, you can toggle this flag with `C-c'.
3105 This variable can also have the value `expert'. In this case, the window
3106 displaying the tags menu is not even shown, until you press C-c again."
3107 :group 'org-tags
3108 :type '(choice
3109 (const :tag "No" nil)
3110 (const :tag "Yes" t)
3111 (const :tag "Expert" expert)))
3113 (defvar org-fast-tag-selection-include-todo nil
3114 "Non-nil means fast tags selection interface will also offer TODO states.
3115 This is an undocumented feature, you should not rely on it.")
3117 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3118 "The column to which tags should be indented in a headline.
3119 If this number is positive, it specifies the column. If it is negative,
3120 it means that the tags should be flushright to that column. For example,
3121 -80 works well for a normal 80 character screen.
3122 When 0, place tags directly after headline text, with only one space in
3123 between."
3124 :group 'org-tags
3125 :type 'integer)
3127 (defcustom org-auto-align-tags t
3128 "Non-nil keeps tags aligned when modifying headlines.
3129 Some operations (i.e. demoting) change the length of a headline and
3130 therefore shift the tags around. With this option turned on, after
3131 each such operation the tags are again aligned to `org-tags-column'."
3132 :group 'org-tags
3133 :type 'boolean)
3135 (defcustom org-use-tag-inheritance t
3136 "Non-nil means tags in levels apply also for sublevels.
3137 When nil, only the tags directly given in a specific line apply there.
3138 This may also be a list of tags that should be inherited, or a regexp that
3139 matches tags that should be inherited. Additional control is possible
3140 with the variable `org-tags-exclude-from-inheritance' which gives an
3141 explicit list of tags to be excluded from inheritance, even if the value of
3142 `org-use-tag-inheritance' would select it for inheritance.
3144 If this option is t, a match early-on in a tree can lead to a large
3145 number of matches in the subtree when constructing the agenda or creating
3146 a sparse tree. If you only want to see the first match in a tree during
3147 a search, check out the variable `org-tags-match-list-sublevels'."
3148 :group 'org-tags
3149 :type '(choice
3150 (const :tag "Not" nil)
3151 (const :tag "Always" t)
3152 (repeat :tag "Specific tags" (string :tag "Tag"))
3153 (regexp :tag "Tags matched by regexp")))
3155 (defcustom org-tags-exclude-from-inheritance nil
3156 "List of tags that should never be inherited.
3157 This is a way to exclude a few tags from inheritance. For way to do
3158 the opposite, to actively allow inheritance for selected tags,
3159 see the variable `org-use-tag-inheritance'."
3160 :group 'org-tags
3161 :type '(repeat (string :tag "Tag")))
3163 (defun org-tag-inherit-p (tag)
3164 "Check if TAG is one that should be inherited."
3165 (cond
3166 ((member tag org-tags-exclude-from-inheritance) nil)
3167 ((eq org-use-tag-inheritance t) t)
3168 ((not org-use-tag-inheritance) nil)
3169 ((stringp org-use-tag-inheritance)
3170 (string-match org-use-tag-inheritance tag))
3171 ((listp org-use-tag-inheritance)
3172 (member tag org-use-tag-inheritance))
3173 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3175 (defcustom org-tags-match-list-sublevels t
3176 "Non-nil means list also sublevels of headlines matching a search.
3177 This variable applies to tags/property searches, and also to stuck
3178 projects because this search is based on a tags match as well.
3180 When set to the symbol `indented', sublevels are indented with
3181 leading dots.
3183 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3184 the sublevels of a headline matching a tag search often also match
3185 the same search. Listing all of them can create very long lists.
3186 Setting this variable to nil causes subtrees of a match to be skipped.
3188 This variable is semi-obsolete and probably should always be true. It
3189 is better to limit inheritance to certain tags using the variables
3190 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3191 :group 'org-tags
3192 :type '(choice
3193 (const :tag "No, don't list them" nil)
3194 (const :tag "Yes, do list them" t)
3195 (const :tag "List them, indented with leading dots" indented)))
3197 (defcustom org-tags-sort-function nil
3198 "When set, tags are sorted using this function as a comparator."
3199 :group 'org-tags
3200 :type '(choice
3201 (const :tag "No sorting" nil)
3202 (const :tag "Alphabetical" string<)
3203 (const :tag "Reverse alphabetical" string>)
3204 (function :tag "Custom function" nil)))
3206 (defvar org-tags-history nil
3207 "History of minibuffer reads for tags.")
3208 (defvar org-last-tags-completion-table nil
3209 "The last used completion table for tags.")
3210 (defvar org-after-tags-change-hook nil
3211 "Hook that is run after the tags in a line have changed.")
3213 (defgroup org-properties nil
3214 "Options concerning properties in Org-mode."
3215 :tag "Org Properties"
3216 :group 'org)
3218 (defcustom org-property-format "%-10s %s"
3219 "How property key/value pairs should be formatted by `indent-line'.
3220 When `indent-line' hits a property definition, it will format the line
3221 according to this format, mainly to make sure that the values are
3222 lined-up with respect to each other."
3223 :group 'org-properties
3224 :type 'string)
3226 (defcustom org-properties-postprocess-alist nil
3227 "Alist of properties and functions to adjust inserted values.
3228 Elements of this alist must be of the form
3230 ([string] [function])
3232 where [string] must be a property name and [function] must be a
3233 lambda expression: this lambda expression must take one argument,
3234 the value to adjust, and return the new value as a string.
3236 For example, this element will allow the property \"Remaining\"
3237 to be updated wrt the relation between the \"Effort\" property
3238 and the clock summary:
3240 ((\"Remaining\" (lambda(value)
3241 (let ((clocksum (org-clock-sum-current-item))
3242 (effort (org-duration-string-to-minutes
3243 (org-entry-get (point) \"Effort\"))))
3244 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3245 :group 'org-properties
3246 :version "24.1"
3247 :type '(alist :key-type (string :tag "Property")
3248 :value-type (function :tag "Function")))
3250 (defcustom org-use-property-inheritance nil
3251 "Non-nil means properties apply also for sublevels.
3253 This setting is chiefly used during property searches. Turning it on can
3254 cause significant overhead when doing a search, which is why it is not
3255 on by default.
3257 When nil, only the properties directly given in the current entry count.
3258 When t, every property is inherited. The value may also be a list of
3259 properties that should have inheritance, or a regular expression matching
3260 properties that should be inherited.
3262 However, note that some special properties use inheritance under special
3263 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3264 and the properties ending in \"_ALL\" when they are used as descriptor
3265 for valid values of a property.
3267 Note for programmers:
3268 When querying an entry with `org-entry-get', you can control if inheritance
3269 should be used. By default, `org-entry-get' looks only at the local
3270 properties. You can request inheritance by setting the inherit argument
3271 to t (to force inheritance) or to `selective' (to respect the setting
3272 in this variable)."
3273 :group 'org-properties
3274 :type '(choice
3275 (const :tag "Not" nil)
3276 (const :tag "Always" t)
3277 (repeat :tag "Specific properties" (string :tag "Property"))
3278 (regexp :tag "Properties matched by regexp")))
3280 (defun org-property-inherit-p (property)
3281 "Check if PROPERTY is one that should be inherited."
3282 (cond
3283 ((eq org-use-property-inheritance t) t)
3284 ((not org-use-property-inheritance) nil)
3285 ((stringp org-use-property-inheritance)
3286 (string-match org-use-property-inheritance property))
3287 ((listp org-use-property-inheritance)
3288 (member property org-use-property-inheritance))
3289 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3291 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3292 "The default column format, if no other format has been defined.
3293 This variable can be set on the per-file basis by inserting a line
3295 #+COLUMNS: %25ITEM ....."
3296 :group 'org-properties
3297 :type 'string)
3299 (defcustom org-columns-ellipses ".."
3300 "The ellipses to be used when a field in column view is truncated.
3301 When this is the empty string, as many characters as possible are shown,
3302 but then there will be no visual indication that the field has been truncated.
3303 When this is a string of length N, the last N characters of a truncated
3304 field are replaced by this string. If the column is narrower than the
3305 ellipses string, only part of the ellipses string will be shown."
3306 :group 'org-properties
3307 :type 'string)
3309 (defcustom org-columns-modify-value-for-display-function nil
3310 "Function that modifies values for display in column view.
3311 For example, it can be used to cut out a certain part from a time stamp.
3312 The function must take 2 arguments:
3314 column-title The title of the column (*not* the property name)
3315 value The value that should be modified.
3317 The function should return the value that should be displayed,
3318 or nil if the normal value should be used."
3319 :group 'org-properties
3320 :type 'function)
3322 (defcustom org-effort-property "Effort"
3323 "The property that is being used to keep track of effort estimates.
3324 Effort estimates given in this property need to have the format H:MM."
3325 :group 'org-properties
3326 :group 'org-progress
3327 :type '(string :tag "Property"))
3329 (defconst org-global-properties-fixed
3330 '(("VISIBILITY_ALL" . "folded children content all")
3331 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3332 "List of property/value pairs that can be inherited by any entry.
3334 These are fixed values, for the preset properties. The user variable
3335 that can be used to add to this list is `org-global-properties'.
3337 The entries in this list are cons cells where the car is a property
3338 name and cdr is a string with the value. If the value represents
3339 multiple items like an \"_ALL\" property, separate the items by
3340 spaces.")
3342 (defcustom org-global-properties nil
3343 "List of property/value pairs that can be inherited by any entry.
3345 This list will be combined with the constant `org-global-properties-fixed'.
3347 The entries in this list are cons cells where the car is a property
3348 name and cdr is a string with the value.
3350 You can set buffer-local values for the same purpose in the variable
3351 `org-file-properties' this by adding lines like
3353 #+PROPERTY: NAME VALUE"
3354 :group 'org-properties
3355 :type '(repeat
3356 (cons (string :tag "Property")
3357 (string :tag "Value"))))
3359 (defvar org-file-properties nil
3360 "List of property/value pairs that can be inherited by any entry.
3361 Valid for the current buffer.
3362 This variable is populated from #+PROPERTY lines.")
3363 (make-variable-buffer-local 'org-file-properties)
3365 (defgroup org-agenda nil
3366 "Options concerning agenda views in Org-mode."
3367 :tag "Org Agenda"
3368 :group 'org)
3370 (defvar org-category nil
3371 "Variable used by org files to set a category for agenda display.
3372 Such files should use a file variable to set it, for example
3374 # -*- mode: org; org-category: \"ELisp\"
3376 or contain a special line
3378 #+CATEGORY: ELisp
3380 If the file does not specify a category, then file's base name
3381 is used instead.")
3382 (make-variable-buffer-local 'org-category)
3383 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3385 (defcustom org-agenda-files nil
3386 "The files to be used for agenda display.
3387 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3388 \\[org-remove-file]. You can also use customize to edit the list.
3390 If an entry is a directory, all files in that directory that are matched by
3391 `org-agenda-file-regexp' will be part of the file list.
3393 If the value of the variable is not a list but a single file name, then
3394 the list of agenda files is actually stored and maintained in that file, one
3395 agenda file per line. In this file paths can be given relative to
3396 `org-directory'. Tilde expansion and environment variable substitution
3397 are also made."
3398 :group 'org-agenda
3399 :type '(choice
3400 (repeat :tag "List of files and directories" file)
3401 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3403 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3404 "Regular expression to match files for `org-agenda-files'.
3405 If any element in the list in that variable contains a directory instead
3406 of a normal file, all files in that directory that are matched by this
3407 regular expression will be included."
3408 :group 'org-agenda
3409 :type 'regexp)
3411 (defcustom org-agenda-text-search-extra-files nil
3412 "List of extra files to be searched by text search commands.
3413 These files will be search in addition to the agenda files by the
3414 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3415 Note that these files will only be searched for text search commands,
3416 not for the other agenda views like todo lists, tag searches or the weekly
3417 agenda. This variable is intended to list notes and possibly archive files
3418 that should also be searched by these two commands.
3419 In fact, if the first element in the list is the symbol `agenda-archives',
3420 than all archive files of all agenda files will be added to the search
3421 scope."
3422 :group 'org-agenda
3423 :type '(set :greedy t
3424 (const :tag "Agenda Archives" agenda-archives)
3425 (repeat :inline t (file))))
3427 (if (fboundp 'defvaralias)
3428 (defvaralias 'org-agenda-multi-occur-extra-files
3429 'org-agenda-text-search-extra-files))
3431 (defcustom org-agenda-skip-unavailable-files nil
3432 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3433 A nil value means to remove them, after a query, from the list."
3434 :group 'org-agenda
3435 :type 'boolean)
3437 (defcustom org-calendar-to-agenda-key [?c]
3438 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3439 The command `org-calendar-goto-agenda' will be bound to this key. The
3440 default is the character `c' because then `c' can be used to switch back and
3441 forth between agenda and calendar."
3442 :group 'org-agenda
3443 :type 'sexp)
3445 (defcustom org-calendar-insert-diary-entry-key [?i]
3446 "The key to be installed in `calendar-mode-map' for adding diary entries.
3447 This option is irrelevant until `org-agenda-diary-file' has been configured
3448 to point to an Org-mode file. When that is the case, the command
3449 `org-agenda-diary-entry' will be bound to the key given here, by default
3450 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3451 if you want to continue doing this, you need to change this to a different
3452 key."
3453 :group 'org-agenda
3454 :type 'sexp)
3456 (defcustom org-agenda-diary-file 'diary-file
3457 "File to which to add new entries with the `i' key in agenda and calendar.
3458 When this is the symbol `diary-file', the functionality in the Emacs
3459 calendar will be used to add entries to the `diary-file'. But when this
3460 points to a file, `org-agenda-diary-entry' will be used instead."
3461 :group 'org-agenda
3462 :type '(choice
3463 (const :tag "The standard Emacs diary file" diary-file)
3464 (file :tag "Special Org file diary entries")))
3466 (eval-after-load "calendar"
3467 '(progn
3468 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3469 'org-calendar-goto-agenda)
3470 (add-hook 'calendar-mode-hook
3471 (lambda ()
3472 (unless (eq org-agenda-diary-file 'diary-file)
3473 (define-key calendar-mode-map
3474 org-calendar-insert-diary-entry-key
3475 'org-agenda-diary-entry))))))
3477 (defgroup org-latex nil
3478 "Options for embedding LaTeX code into Org-mode."
3479 :tag "Org LaTeX"
3480 :group 'org)
3482 (defcustom org-format-latex-options
3483 '(:foreground default :background default :scale 1.0
3484 :html-foreground "Black" :html-background "Transparent"
3485 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3486 "Options for creating images from LaTeX fragments.
3487 This is a property list with the following properties:
3488 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3489 `default' means use the foreground of the default face.
3490 `auto' means use the foreground from the text face.
3491 :background the background color, or \"Transparent\".
3492 `default' means use the background of the default face.
3493 `auto' means use the background from the text face.
3494 :scale a scaling factor for the size of the images, to get more pixels
3495 :html-foreground, :html-background, :html-scale
3496 the same numbers for HTML export.
3497 :matchers a list indicating which matchers should be used to
3498 find LaTeX fragments. Valid members of this list are:
3499 \"begin\" find environments
3500 \"$1\" find single characters surrounded by $.$
3501 \"$\" find math expressions surrounded by $...$
3502 \"$$\" find math expressions surrounded by $$....$$
3503 \"\\(\" find math expressions surrounded by \\(...\\)
3504 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3505 :group 'org-latex
3506 :type 'plist)
3508 (defcustom org-format-latex-signal-error t
3509 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3510 When nil, just push out a message."
3511 :group 'org-latex
3512 :version "24.1"
3513 :type 'boolean)
3515 (defcustom org-latex-to-mathml-jar-file nil
3516 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3517 Use this to specify additional executable file say a jar file.
3519 When using MathToWeb as the converter, specify the full-path to
3520 your mathtoweb.jar file."
3521 :group 'org-latex
3522 :version "24.1"
3523 :type '(choice
3524 (const :tag "None" nil)
3525 (file :tag "JAR file" :must-match t)))
3527 (defcustom org-latex-to-mathml-convert-command nil
3528 "Command to convert LaTeX fragments to MathML.
3529 Replace format-specifiers in the command as noted below and use
3530 `shell-command' to convert LaTeX to MathML.
3531 %j: Executable file in fully expanded form as specified by
3532 `org-latex-to-mathml-jar-file'.
3533 %I: Input LaTeX file in fully expanded form
3534 %o: Output MathML file
3535 This command is used by `org-create-math-formula'.
3537 When using MathToWeb as the converter, set this to
3538 \"java -jar %j -unicode -force -df %o %I\"."
3539 :group 'org-latex
3540 :version "24.1"
3541 :type '(choice
3542 (const :tag "None" nil)
3543 (string :tag "\nShell command")))
3545 (defcustom org-latex-create-formula-image-program 'dvipng
3546 "Program to convert LaTeX fragments with.
3548 dvipng Process the LaTeX fragments to dvi file, then convert
3549 dvi files to png files using dvipng.
3550 This will also include processing of non-math environments.
3551 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3552 to convert pdf files to png files"
3553 :group 'org-latex
3554 :version "24.1"
3555 :type '(choice
3556 (const :tag "dvipng" dvipng)
3557 (const :tag "imagemagick" imagemagick)))
3559 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3560 "Path to store latex preview images.
3561 A relative path here creates many directories relative to the
3562 processed org files paths. An absolute path puts all preview
3563 images at the same place."
3564 :group 'org-latex
3565 :version "24.3"
3566 :type 'string)
3568 (defun org-format-latex-mathml-available-p ()
3569 "Return t if `org-latex-to-mathml-convert-command' is usable."
3570 (save-match-data
3571 (when (and (boundp 'org-latex-to-mathml-convert-command)
3572 org-latex-to-mathml-convert-command)
3573 (let ((executable (car (split-string
3574 org-latex-to-mathml-convert-command))))
3575 (when (executable-find executable)
3576 (if (string-match
3577 "%j" org-latex-to-mathml-convert-command)
3578 (file-readable-p org-latex-to-mathml-jar-file)
3579 t))))))
3581 (defcustom org-format-latex-header "\\documentclass{article}
3582 \\usepackage[usenames]{color}
3583 \\usepackage{amsmath}
3584 \\usepackage[mathscr]{eucal}
3585 \\pagestyle{empty} % do not remove
3586 \[PACKAGES]
3587 \[DEFAULT-PACKAGES]
3588 % The settings below are copied from fullpage.sty
3589 \\setlength{\\textwidth}{\\paperwidth}
3590 \\addtolength{\\textwidth}{-3cm}
3591 \\setlength{\\oddsidemargin}{1.5cm}
3592 \\addtolength{\\oddsidemargin}{-2.54cm}
3593 \\setlength{\\evensidemargin}{\\oddsidemargin}
3594 \\setlength{\\textheight}{\\paperheight}
3595 \\addtolength{\\textheight}{-\\headheight}
3596 \\addtolength{\\textheight}{-\\headsep}
3597 \\addtolength{\\textheight}{-\\footskip}
3598 \\addtolength{\\textheight}{-3cm}
3599 \\setlength{\\topmargin}{1.5cm}
3600 \\addtolength{\\topmargin}{-2.54cm}"
3601 "The document header used for processing LaTeX fragments.
3602 It is imperative that this header make sure that no page number
3603 appears on the page. The package defined in the variables
3604 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3605 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3606 will be appended."
3607 :group 'org-latex
3608 :type 'string)
3610 (defvar org-format-latex-header-extra nil)
3612 (defun org-set-packages-alist (var val)
3613 "Set the packages alist and make sure it has 3 elements per entry."
3614 (set var (mapcar (lambda (x)
3615 (if (and (consp x) (= (length x) 2))
3616 (list (car x) (nth 1 x) t)
3618 val)))
3620 (defun org-get-packages-alist (var)
3622 "Get the packages alist and make sure it has 3 elements per entry."
3623 (mapcar (lambda (x)
3624 (if (and (consp x) (= (length x) 2))
3625 (list (car x) (nth 1 x) t)
3627 (default-value var)))
3629 ;; The following variables are defined here because is it also used
3630 ;; when formatting latex fragments. Originally it was part of the
3631 ;; LaTeX exporter, which is why the name includes "export".
3632 (defcustom org-export-latex-default-packages-alist
3633 '(("AUTO" "inputenc" t)
3634 ("T1" "fontenc" t)
3635 ("" "fixltx2e" nil)
3636 ("" "graphicx" t)
3637 ("" "longtable" nil)
3638 ("" "float" nil)
3639 ("" "wrapfig" nil)
3640 ("" "soul" t)
3641 ("" "textcomp" t)
3642 ("" "marvosym" t)
3643 ("" "wasysym" t)
3644 ("" "latexsym" t)
3645 ("" "amssymb" t)
3646 ("" "hyperref" nil)
3647 "\\tolerance=1000"
3649 "Alist of default packages to be inserted in the header.
3650 Change this only if one of the packages here causes an incompatibility
3651 with another package you are using.
3652 The packages in this list are needed by one part or another of Org-mode
3653 to function properly.
3655 - inputenc, fontenc: for basic font and character selection
3656 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3657 for interpreting the entities in `org-entities'. You can skip some of these
3658 packages if you don't use any of the symbols in it.
3659 - graphicx: for including images
3660 - float, wrapfig: for figure placement
3661 - longtable: for long tables
3662 - hyperref: for cross references
3664 Therefore you should not modify this variable unless you know what you
3665 are doing. The one reason to change it anyway is that you might be loading
3666 some other package that conflicts with one of the default packages.
3667 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3668 If SNIPPET-FLAG is t, the package also needs to be included when
3669 compiling LaTeX snippets into images for inclusion into HTML."
3670 :group 'org-export-latex
3671 :set 'org-set-packages-alist
3672 :get 'org-get-packages-alist
3673 :version "24.1"
3674 :type '(repeat
3675 (choice
3676 (list :tag "options/package pair"
3677 (string :tag "options")
3678 (string :tag "package")
3679 (boolean :tag "Snippet"))
3680 (string :tag "A line of LaTeX"))))
3682 (defcustom org-export-latex-packages-alist nil
3683 "Alist of packages to be inserted in every LaTeX header.
3684 These will be inserted after `org-export-latex-default-packages-alist'.
3685 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3686 SNIPPET-FLAG, when t, indicates that this package is also needed when
3687 turning LaTeX snippets into images for inclusion into HTML.
3688 Make sure that you only list packages here which:
3689 - you want in every file
3690 - do not conflict with the default packages in
3691 `org-export-latex-default-packages-alist'
3692 - do not conflict with the setup in `org-format-latex-header'."
3693 :group 'org-export-latex
3694 :set 'org-set-packages-alist
3695 :get 'org-get-packages-alist
3696 :type '(repeat
3697 (choice
3698 (list :tag "options/package pair"
3699 (string :tag "options")
3700 (string :tag "package")
3701 (boolean :tag "Snippet"))
3702 (string :tag "A line of LaTeX"))))
3705 (defgroup org-appearance nil
3706 "Settings for Org-mode appearance."
3707 :tag "Org Appearance"
3708 :group 'org)
3710 (defcustom org-level-color-stars-only nil
3711 "Non-nil means fontify only the stars in each headline.
3712 When nil, the entire headline is fontified.
3713 Changing it requires restart of `font-lock-mode' to become effective
3714 also in regions already fontified."
3715 :group 'org-appearance
3716 :type 'boolean)
3718 (defcustom org-hide-leading-stars nil
3719 "Non-nil means hide the first N-1 stars in a headline.
3720 This works by using the face `org-hide' for these stars. This
3721 face is white for a light background, and black for a dark
3722 background. You may have to customize the face `org-hide' to
3723 make this work.
3724 Changing it requires restart of `font-lock-mode' to become effective
3725 also in regions already fontified.
3726 You may also set this on a per-file basis by adding one of the following
3727 lines to the buffer:
3729 #+STARTUP: hidestars
3730 #+STARTUP: showstars"
3731 :group 'org-appearance
3732 :type 'boolean)
3734 (defcustom org-hidden-keywords nil
3735 "List of symbols corresponding to keywords to be hidden the org buffer.
3736 For example, a value '(title) for this list will make the document's title
3737 appear in the buffer without the initial #+TITLE: keyword."
3738 :group 'org-appearance
3739 :version "24.1"
3740 :type '(set (const :tag "#+AUTHOR" author)
3741 (const :tag "#+DATE" date)
3742 (const :tag "#+EMAIL" email)
3743 (const :tag "#+TITLE" title)))
3745 (defcustom org-custom-properties nil
3746 "List of properties (as strings) with a special meaning.
3747 The default use of these custom properties is to let the user
3748 hide them with `org-toggle-custom-properties-visibility'."
3749 :group 'org-properties
3750 :group 'org-appearance
3751 :version "24.3"
3752 :type '(repeat (string :tag "Property Name")))
3754 (defcustom org-fontify-done-headline nil
3755 "Non-nil means change the face of a headline if it is marked DONE.
3756 Normally, only the TODO/DONE keyword indicates the state of a headline.
3757 When this is non-nil, the headline after the keyword is set to the
3758 `org-headline-done' as an additional indication."
3759 :group 'org-appearance
3760 :type 'boolean)
3762 (defcustom org-fontify-emphasized-text t
3763 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3764 Changing this variable requires a restart of Emacs to take effect."
3765 :group 'org-appearance
3766 :type 'boolean)
3768 (defcustom org-fontify-whole-heading-line nil
3769 "Non-nil means fontify the whole line for headings.
3770 This is useful when setting a background color for the
3771 org-level-* faces."
3772 :group 'org-appearance
3773 :type 'boolean)
3775 (defcustom org-highlight-latex-fragments-and-specials nil
3776 "Non-nil means fontify what is treated specially by the exporters."
3777 :group 'org-appearance
3778 :type 'boolean)
3780 (defcustom org-hide-emphasis-markers nil
3781 "Non-nil mean font-lock should hide the emphasis marker characters."
3782 :group 'org-appearance
3783 :type 'boolean)
3785 (defcustom org-pretty-entities nil
3786 "Non-nil means show entities as UTF8 characters.
3787 When nil, the \\name form remains in the buffer."
3788 :group 'org-appearance
3789 :version "24.1"
3790 :type 'boolean)
3792 (defcustom org-pretty-entities-include-sub-superscripts t
3793 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3794 :group 'org-appearance
3795 :version "24.1"
3796 :type 'boolean)
3798 (defvar org-emph-re nil
3799 "Regular expression for matching emphasis.
3800 After a match, the match groups contain these elements:
3801 0 The match of the full regular expression, including the characters
3802 before and after the proper match
3803 1 The character before the proper match, or empty at beginning of line
3804 2 The proper match, including the leading and trailing markers
3805 3 The leading marker like * or /, indicating the type of highlighting
3806 4 The text between the emphasis markers, not including the markers
3807 5 The character after the match, empty at the end of a line")
3808 (defvar org-verbatim-re nil
3809 "Regular expression for matching verbatim text.")
3810 (defvar org-emphasis-regexp-components) ; defined just below
3811 (defvar org-emphasis-alist) ; defined just below
3812 (defun org-set-emph-re (var val)
3813 "Set variable and compute the emphasis regular expression."
3814 (set var val)
3815 (when (and (boundp 'org-emphasis-alist)
3816 (boundp 'org-emphasis-regexp-components)
3817 org-emphasis-alist org-emphasis-regexp-components)
3818 (let* ((e org-emphasis-regexp-components)
3819 (pre (car e))
3820 (post (nth 1 e))
3821 (border (nth 2 e))
3822 (body (nth 3 e))
3823 (nl (nth 4 e))
3824 (body1 (concat body "*?"))
3825 (markers (mapconcat 'car org-emphasis-alist ""))
3826 (vmarkers (mapconcat
3827 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3828 org-emphasis-alist "")))
3829 ;; make sure special characters appear at the right position in the class
3830 (if (string-match "\\^" markers)
3831 (setq markers (concat (replace-match "" t t markers) "^")))
3832 (if (string-match "-" markers)
3833 (setq markers (concat (replace-match "" t t markers) "-")))
3834 (if (string-match "\\^" vmarkers)
3835 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3836 (if (string-match "-" vmarkers)
3837 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3838 (if (> nl 0)
3839 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3840 (int-to-string nl) "\\}")))
3841 ;; Make the regexp
3842 (setq org-emph-re
3843 (concat "\\([" pre "]\\|^\\)"
3844 "\\("
3845 "\\([" markers "]\\)"
3846 "\\("
3847 "[^" border "]\\|"
3848 "[^" border "]"
3849 body1
3850 "[^" border "]"
3851 "\\)"
3852 "\\3\\)"
3853 "\\([" post "]\\|$\\)"))
3854 (setq org-verbatim-re
3855 (concat "\\([" pre "]\\|^\\)"
3856 "\\("
3857 "\\([" vmarkers "]\\)"
3858 "\\("
3859 "[^" border "]\\|"
3860 "[^" border "]"
3861 body1
3862 "[^" border "]"
3863 "\\)"
3864 "\\3\\)"
3865 "\\([" post "]\\|$\\)")))))
3867 (defcustom org-emphasis-regexp-components
3868 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3869 "Components used to build the regular expression for emphasis.
3870 This is a list with five entries. Terminology: In an emphasis string
3871 like \" *strong word* \", we call the initial space PREMATCH, the final
3872 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3873 and \"trong wor\" is the body. The different components in this variable
3874 specify what is allowed/forbidden in each part:
3876 pre Chars allowed as prematch. Beginning of line will be allowed too.
3877 post Chars allowed as postmatch. End of line will be allowed too.
3878 border The chars *forbidden* as border characters.
3879 body-regexp A regexp like \".\" to match a body character. Don't use
3880 non-shy groups here, and don't allow newline here.
3881 newline The maximum number of newlines allowed in an emphasis exp.
3883 Use customize to modify this, or restart Emacs after changing it."
3884 :group 'org-appearance
3885 :set 'org-set-emph-re
3886 :type '(list
3887 (sexp :tag "Allowed chars in pre ")
3888 (sexp :tag "Allowed chars in post ")
3889 (sexp :tag "Forbidden chars in border ")
3890 (sexp :tag "Regexp for body ")
3891 (integer :tag "number of newlines allowed")
3892 (option (boolean :tag "Please ignore this button"))))
3894 (defcustom org-emphasis-alist
3895 `(("*" bold "<b>" "</b>")
3896 ("/" italic "<i>" "</i>")
3897 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3898 ("=" org-code "<code>" "</code>" verbatim)
3899 ("~" org-verbatim "<code>" "</code>" verbatim)
3900 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3901 "<del>" "</del>")
3903 "Special syntax for emphasized text.
3904 Text starting and ending with a special character will be emphasized, for
3905 example *bold*, _underlined_ and /italic/. This variable sets the marker
3906 characters, the face to be used by font-lock for highlighting in Org-mode
3907 Emacs buffers, and the HTML tags to be used for this.
3908 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3909 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3910 Use customize to modify this, or restart Emacs after changing it."
3911 :group 'org-appearance
3912 :set 'org-set-emph-re
3913 :type '(repeat
3914 (list
3915 (string :tag "Marker character")
3916 (choice
3917 (face :tag "Font-lock-face")
3918 (plist :tag "Face property list"))
3919 (string :tag "HTML start tag")
3920 (string :tag "HTML end tag")
3921 (option (const verbatim)))))
3923 (defvar org-syntax-table
3924 (let ((st (make-syntax-table)))
3925 (mapc (lambda(c) (modify-syntax-entry
3926 (string-to-char (car c)) "w p" st))
3927 org-emphasis-alist)
3928 st))
3930 (defvar org-protecting-blocks
3931 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3932 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3933 This is needed for font-lock setup.")
3935 ;;; Miscellaneous options
3937 (defgroup org-completion nil
3938 "Completion in Org-mode."
3939 :tag "Org Completion"
3940 :group 'org)
3942 (defcustom org-completion-use-ido nil
3943 "Non-nil means use ido completion wherever possible.
3944 Note that `ido-mode' must be active for this variable to be relevant.
3945 If you decide to turn this variable on, you might well want to turn off
3946 `org-outline-path-complete-in-steps'.
3947 See also `org-completion-use-iswitchb'."
3948 :group 'org-completion
3949 :type 'boolean)
3951 (defcustom org-completion-use-iswitchb nil
3952 "Non-nil means use iswitchb completion wherever possible.
3953 Note that `iswitchb-mode' must be active for this variable to be relevant.
3954 If you decide to turn this variable on, you might well want to turn off
3955 `org-outline-path-complete-in-steps'.
3956 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3957 :group 'org-completion
3958 :type 'boolean)
3960 (defcustom org-completion-fallback-command 'hippie-expand
3961 "The expansion command called by \\[pcomplete] in normal context.
3962 Normal means, no org-mode-specific context."
3963 :group 'org-completion
3964 :type 'function)
3966 ;;; Functions and variables from their packages
3967 ;; Declared here to avoid compiler warnings
3969 ;; XEmacs only
3970 (defvar outline-mode-menu-heading)
3971 (defvar outline-mode-menu-show)
3972 (defvar outline-mode-menu-hide)
3973 (defvar zmacs-regions) ; XEmacs regions
3975 ;; Emacs only
3976 (defvar mark-active)
3978 ;; Various packages
3979 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3980 (declare-function calendar-forward-day "cal-move" (arg))
3981 (declare-function calendar-goto-date "cal-move" (date))
3982 (declare-function calendar-goto-today "cal-move" ())
3983 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3984 (defvar calc-embedded-close-formula)
3985 (defvar calc-embedded-open-formula)
3986 (declare-function cdlatex-tab "ext:cdlatex" ())
3987 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3988 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3989 (defvar font-lock-unfontify-region-function)
3990 (declare-function iswitchb-read-buffer "iswitchb"
3991 (prompt &optional default require-match start matches-set))
3992 (defvar iswitchb-temp-buflist)
3993 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3994 (defvar org-agenda-tags-todo-honor-ignore-options)
3995 (declare-function org-agenda-skip "org-agenda" ())
3996 (declare-function
3997 org-agenda-format-item "org-agenda"
3998 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3999 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4000 (declare-function org-agenda-change-all-lines "org-agenda"
4001 (newhead hdmarker &optional fixface just-this))
4002 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4003 (declare-function org-agenda-maybe-redo "org-agenda" ())
4004 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4005 (beg end))
4006 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4007 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4008 "org-agenda" (&optional end))
4009 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4010 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4011 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4012 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4013 (declare-function org-indent-mode "org-indent" (&optional arg))
4014 (declare-function parse-time-string "parse-time" (string))
4015 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4016 (declare-function org-export-latex-fix-inputenc "org-latex" ())
4017 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4018 (defvar remember-data-file)
4019 (defvar texmathp-why)
4020 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4021 (declare-function table--at-cell-p "table" (position &optional object at-column))
4023 (defvar org-latex-regexps)
4025 ;;; Autoload and prepare some org modules
4027 ;; Some table stuff that needs to be defined here, because it is used
4028 ;; by the functions setting up org-mode or checking for table context.
4030 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4031 "Detect an org-type or table-type table.")
4032 (defconst org-table-line-regexp "^[ \t]*|"
4033 "Detect an org-type table line.")
4034 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4035 "Detect an org-type table line.")
4036 (defconst org-table-hline-regexp "^[ \t]*|-"
4037 "Detect an org-type table hline.")
4038 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4039 "Detect a table-type table hline.")
4040 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4041 "Detect the first line outside a table when searching from within it.
4042 This works for both table types.")
4044 ;; Autoload the functions in org-table.el that are needed by functions here.
4046 (eval-and-compile
4047 (org-autoload "org-table"
4048 '(org-table-begin org-table-blank-field org-table-end)))
4050 ;;;###autoload
4051 (defun turn-on-orgtbl ()
4052 "Unconditionally turn on `orgtbl-mode'."
4053 (require 'org-table)
4054 (orgtbl-mode 1))
4056 (defun org-at-table-p (&optional table-type)
4057 "Return t if the cursor is inside an org-type table.
4058 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4059 (if org-enable-table-editor
4060 (save-excursion
4061 (beginning-of-line 1)
4062 (looking-at (if table-type org-table-any-line-regexp
4063 org-table-line-regexp)))
4064 nil))
4065 (defsubst org-table-p () (org-at-table-p))
4067 (defun org-at-table.el-p ()
4068 "Return t if and only if we are at a table.el table."
4069 (and (org-at-table-p 'any)
4070 (save-excursion
4071 (goto-char (org-table-begin 'any))
4072 (looking-at org-table1-hline-regexp))))
4073 (defun org-table-recognize-table.el ()
4074 "If there is a table.el table nearby, recognize it and move into it."
4075 (if org-table-tab-recognizes-table.el
4076 (if (org-at-table.el-p)
4077 (progn
4078 (beginning-of-line 1)
4079 (if (looking-at org-table-dataline-regexp)
4081 (if (looking-at org-table1-hline-regexp)
4082 (progn
4083 (beginning-of-line 2)
4084 (if (looking-at org-table-any-border-regexp)
4085 (beginning-of-line -1)))))
4086 (if (re-search-forward "|" (org-table-end t) t)
4087 (progn
4088 (require 'table)
4089 (if (table--at-cell-p (point))
4091 (message "recognizing table.el table...")
4092 (table-recognize-table)
4093 (message "recognizing table.el table...done")))
4094 (error "This should not happen"))
4096 nil)
4097 nil))
4099 (defun org-at-table-hline-p ()
4100 "Return t if the cursor is inside a hline in a table."
4101 (if org-enable-table-editor
4102 (save-excursion
4103 (beginning-of-line 1)
4104 (looking-at org-table-hline-regexp))
4105 nil))
4107 (defvar org-table-clean-did-remove-column nil)
4109 (defun org-table-map-tables (function &optional quietly)
4110 "Apply FUNCTION to the start of all tables in the buffer."
4111 (save-excursion
4112 (save-restriction
4113 (widen)
4114 (goto-char (point-min))
4115 (while (re-search-forward org-table-any-line-regexp nil t)
4116 (unless quietly
4117 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4118 (beginning-of-line 1)
4119 (when (and (looking-at org-table-line-regexp)
4120 ;; Exclude tables in src/example/verbatim/clocktable blocks
4121 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4122 (save-excursion (funcall function))
4123 (or (looking-at org-table-line-regexp)
4124 (forward-char 1)))
4125 (re-search-forward org-table-any-border-regexp nil 1))))
4126 (unless quietly (message "Mapping tables: done")))
4128 ;; Declare and autoload functions from org-exp.el & Co
4130 (declare-function org-default-export-plist "org-exp")
4131 (declare-function org-infile-export-plist "org-exp")
4132 (declare-function org-get-current-options "org-exp")
4134 ;; Declare and autoload functions from org-agenda.el
4136 (eval-and-compile
4137 (org-autoload "org-agenda"
4138 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4140 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4141 (declare-function org-clock-update-mode-line "org-clock" ())
4142 (declare-function org-resolve-clocks "org-clock"
4143 (&optional also-non-dangling-p prompt last-valid))
4144 (defvar org-clock-start-time)
4145 (defvar org-clock-marker (make-marker)
4146 "Marker recording the last clock-in.")
4147 (defvar org-clock-hd-marker (make-marker)
4148 "Marker recording the last clock-in, but the headline position.")
4149 (defvar org-clock-heading ""
4150 "The heading of the current clock entry.")
4151 (defun org-clock-is-active ()
4152 "Return non-nil if clock is currently running.
4153 The return value is actually the clock marker."
4154 (marker-buffer org-clock-marker))
4156 (eval-and-compile
4157 (org-autoload "org-clock" '(org-clock-remove-overlays
4158 org-clock-update-time-maybe
4159 org-clocktable-shift)))
4161 (defun org-check-running-clock ()
4162 "Check if the current buffer contains the running clock.
4163 If yes, offer to stop it and to save the buffer with the changes."
4164 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4165 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4166 (buffer-name))))
4167 (org-clock-out)
4168 (when (y-or-n-p "Save changed buffer?")
4169 (save-buffer))))
4171 (defun org-clocktable-try-shift (dir n)
4172 "Check if this line starts a clock table, if yes, shift the time block."
4173 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4174 (org-clocktable-shift dir n)))
4176 ;;;###autoload
4177 (defun org-clock-persistence-insinuate ()
4178 "Set up hooks for clock persistence."
4179 (require 'org-clock)
4180 (add-hook 'org-mode-hook 'org-clock-load)
4181 (add-hook 'kill-emacs-hook 'org-clock-save))
4183 ;; Define the variable already here, to make sure we have it.
4184 (defvar org-indent-mode nil
4185 "Non-nil if Org-Indent mode is enabled.
4186 Use the command `org-indent-mode' to change this variable.")
4188 ;; Autoload archiving code
4189 ;; The stuff that is needed for cycling and tags has to be defined here.
4191 (defgroup org-archive nil
4192 "Options concerning archiving in Org-mode."
4193 :tag "Org Archive"
4194 :group 'org-structure)
4196 (defcustom org-archive-location "%s_archive::"
4197 "The location where subtrees should be archived.
4199 The value of this variable is a string, consisting of two parts,
4200 separated by a double-colon. The first part is a filename and
4201 the second part is a headline.
4203 When the filename is omitted, archiving happens in the same file.
4204 %s in the filename will be replaced by the current file
4205 name (without the directory part). Archiving to a different file
4206 is useful to keep archived entries from contributing to the
4207 Org-mode Agenda.
4209 The archived entries will be filed as subtrees of the specified
4210 headline. When the headline is omitted, the subtrees are simply
4211 filed away at the end of the file, as top-level entries. Also in
4212 the heading you can use %s to represent the file name, this can be
4213 useful when using the same archive for a number of different files.
4215 Here are a few examples:
4216 \"%s_archive::\"
4217 If the current file is Projects.org, archive in file
4218 Projects.org_archive, as top-level trees. This is the default.
4220 \"::* Archived Tasks\"
4221 Archive in the current file, under the top-level headline
4222 \"* Archived Tasks\".
4224 \"~/org/archive.org::\"
4225 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4227 \"~/org/archive.org::* From %s\"
4228 Archive in file ~/org/archive.org (absolute path), under headlines
4229 \"From FILENAME\" where file name is the current file name.
4231 \"~/org/datetree.org::datetree/* Finished Tasks\"
4232 The \"datetree/\" string is special, signifying to archive
4233 items to the datetree. Items are placed in either the CLOSED
4234 date of the item, or the current date if there is no CLOSED date.
4235 The heading will be a subentry to the current date. There doesn't
4236 need to be a heading, but there always needs to be a slash after
4237 datetree. For example, to store archived items directly in the
4238 datetree, use \"~/org/datetree.org::datetree/\".
4240 \"basement::** Finished Tasks\"
4241 Archive in file ./basement (relative path), as level 3 trees
4242 below the level 2 heading \"** Finished Tasks\".
4244 You may set this option on a per-file basis by adding to the buffer a
4245 line like
4247 #+ARCHIVE: basement::** Finished Tasks
4249 You may also define it locally for a subtree by setting an ARCHIVE property
4250 in the entry. If such a property is found in an entry, or anywhere up
4251 the hierarchy, it will be used."
4252 :group 'org-archive
4253 :type 'string)
4255 (defcustom org-archive-tag "ARCHIVE"
4256 "The tag that marks a subtree as archived.
4257 An archived subtree does not open during visibility cycling, and does
4258 not contribute to the agenda listings.
4259 After changing this, font-lock must be restarted in the relevant buffers to
4260 get the proper fontification."
4261 :group 'org-archive
4262 :group 'org-keywords
4263 :type 'string)
4265 (defcustom org-agenda-skip-archived-trees t
4266 "Non-nil means the agenda will skip any items located in archived trees.
4267 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4268 variable is no longer recommended, you should leave it at the value t.
4269 Instead, use the key `v' to cycle the archives-mode in the agenda."
4270 :group 'org-archive
4271 :group 'org-agenda-skip
4272 :type 'boolean)
4274 (defcustom org-columns-skip-archived-trees t
4275 "Non-nil means ignore archived trees when creating column view."
4276 :group 'org-archive
4277 :group 'org-properties
4278 :type 'boolean)
4280 (defcustom org-cycle-open-archived-trees nil
4281 "Non-nil means `org-cycle' will open archived trees.
4282 An archived tree is a tree marked with the tag ARCHIVE.
4283 When nil, archived trees will stay folded. You can still open them with
4284 normal outline commands like `show-all', but not with the cycling commands."
4285 :group 'org-archive
4286 :group 'org-cycle
4287 :type 'boolean)
4289 (defcustom org-sparse-tree-open-archived-trees nil
4290 "Non-nil means sparse tree construction shows matches in archived trees.
4291 When nil, matches in these trees are highlighted, but the trees are kept in
4292 collapsed state."
4293 :group 'org-archive
4294 :group 'org-sparse-trees
4295 :type 'boolean)
4297 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4298 "The default date type when building a sparse tree.
4299 When this is nil, a date is a scheduled or a deadline timestamp.
4300 Otherwise, these types are allowed:
4302 all: all timestamps
4303 active: only active timestamps (<...>)
4304 inactive: only inactive timestamps (<...)
4305 scheduled: only scheduled timestamps
4306 deadline: only deadline timestamps"
4307 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4308 (const :tag "All timestamps" all)
4309 (const :tag "Only active timestamps" active)
4310 (const :tag "Only inactive timestamps" inactive)
4311 (const :tag "Only scheduled timestamps" scheduled)
4312 (const :tag "Only deadline timestamps" deadline))
4313 :version "24.3"
4314 :group 'org-sparse-trees)
4316 (defun org-cycle-hide-archived-subtrees (state)
4317 "Re-hide all archived subtrees after a visibility state change."
4318 (when (and (not org-cycle-open-archived-trees)
4319 (not (memq state '(overview folded))))
4320 (save-excursion
4321 (let* ((globalp (memq state '(contents all)))
4322 (beg (if globalp (point-min) (point)))
4323 (end (if globalp (point-max) (org-end-of-subtree t))))
4324 (org-hide-archived-subtrees beg end)
4325 (goto-char beg)
4326 (if (looking-at (concat ".*:" org-archive-tag ":"))
4327 (message "%s" (substitute-command-keys
4328 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4330 (defun org-force-cycle-archived ()
4331 "Cycle subtree even if it is archived."
4332 (interactive)
4333 (setq this-command 'org-cycle)
4334 (let ((org-cycle-open-archived-trees t))
4335 (call-interactively 'org-cycle)))
4337 (defun org-hide-archived-subtrees (beg end)
4338 "Re-hide all archived subtrees after a visibility state change."
4339 (save-excursion
4340 (let* ((re (concat ":" org-archive-tag ":")))
4341 (goto-char beg)
4342 (while (re-search-forward re end t)
4343 (when (org-at-heading-p)
4344 (org-flag-subtree t)
4345 (org-end-of-subtree t))))))
4347 (declare-function outline-end-of-heading "outline" ())
4348 (declare-function outline-flag-region "outline" (from to flag))
4349 (defun org-flag-subtree (flag)
4350 (save-excursion
4351 (org-back-to-heading t)
4352 (outline-end-of-heading)
4353 (outline-flag-region (point)
4354 (progn (org-end-of-subtree t) (point))
4355 flag)))
4357 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4359 (eval-and-compile
4360 (org-autoload "org-archive"
4361 '(org-add-archive-files)))
4363 ;; Autoload Column View Code
4365 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4366 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4367 (declare-function org-columns-compute "org-colview" (property))
4369 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4370 '(org-columns-number-to-string
4371 org-columns-get-format-and-top-level
4372 org-columns-compute
4373 org-columns-remove-overlays))
4375 ;; Autoload ID code
4377 (declare-function org-id-store-link "org-id")
4378 (declare-function org-id-locations-load "org-id")
4379 (declare-function org-id-locations-save "org-id")
4380 (defvar org-id-track-globally)
4381 (org-autoload "org-id"
4382 '(org-id-new
4383 org-id-copy
4384 org-id-get-with-outline-path-completion
4385 org-id-get-with-outline-drilling))
4387 ;;; Variables for pre-computed regular expressions, all buffer local
4389 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4390 "Matches first line of a hidden block.")
4391 (make-variable-buffer-local 'org-drawer-regexp)
4392 (defvar org-todo-regexp nil
4393 "Matches any of the TODO state keywords.")
4394 (make-variable-buffer-local 'org-todo-regexp)
4395 (defvar org-not-done-regexp nil
4396 "Matches any of the TODO state keywords except the last one.")
4397 (make-variable-buffer-local 'org-not-done-regexp)
4398 (defvar org-not-done-heading-regexp nil
4399 "Matches a TODO headline that is not done.")
4400 (make-variable-buffer-local 'org-not-done-regexp)
4401 (defvar org-todo-line-regexp nil
4402 "Matches a headline and puts TODO state into group 2 if present.")
4403 (make-variable-buffer-local 'org-todo-line-regexp)
4404 (defvar org-complex-heading-regexp nil
4405 "Matches a headline and puts everything into groups:
4406 group 1: the stars
4407 group 2: The todo keyword, maybe
4408 group 3: Priority cookie
4409 group 4: True headline
4410 group 5: Tags")
4411 (make-variable-buffer-local 'org-complex-heading-regexp)
4412 (defvar org-complex-heading-regexp-format nil
4413 "Printf format to make regexp to match an exact headline.
4414 This regexp will match the headline of any node which has the
4415 exact headline text that is put into the format, but may have any
4416 TODO state, priority and tags.")
4417 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4418 (defvar org-todo-line-tags-regexp nil
4419 "Matches a headline and puts TODO state into group 2 if present.
4420 Also put tags into group 4 if tags are present.")
4421 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4422 (defvar org-ds-keyword-length 12
4423 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4424 (make-variable-buffer-local 'org-ds-keyword-length)
4425 (defvar org-deadline-regexp nil
4426 "Matches the DEADLINE keyword.")
4427 (make-variable-buffer-local 'org-deadline-regexp)
4428 (defvar org-deadline-time-regexp nil
4429 "Matches the DEADLINE keyword together with a time stamp.")
4430 (make-variable-buffer-local 'org-deadline-time-regexp)
4431 (defvar org-deadline-line-regexp nil
4432 "Matches the DEADLINE keyword and the rest of the line.")
4433 (make-variable-buffer-local 'org-deadline-line-regexp)
4434 (defvar org-scheduled-regexp nil
4435 "Matches the SCHEDULED keyword.")
4436 (make-variable-buffer-local 'org-scheduled-regexp)
4437 (defvar org-scheduled-time-regexp nil
4438 "Matches the SCHEDULED keyword together with a time stamp.")
4439 (make-variable-buffer-local 'org-scheduled-time-regexp)
4440 (defvar org-closed-time-regexp nil
4441 "Matches the CLOSED keyword together with a time stamp.")
4442 (make-variable-buffer-local 'org-closed-time-regexp)
4444 (defvar org-keyword-time-regexp nil
4445 "Matches any of the 4 keywords, together with the time stamp.")
4446 (make-variable-buffer-local 'org-keyword-time-regexp)
4447 (defvar org-keyword-time-not-clock-regexp nil
4448 "Matches any of the 3 keywords, together with the time stamp.")
4449 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4450 (defvar org-maybe-keyword-time-regexp nil
4451 "Matches a timestamp, possibly preceded by a keyword.")
4452 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4453 (defvar org-all-time-keywords nil
4454 "List of time keywords.")
4455 (make-variable-buffer-local 'org-all-time-keywords)
4457 (defconst org-plain-time-of-day-regexp
4458 (concat
4459 "\\(\\<[012]?[0-9]"
4460 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4461 "\\(--?"
4462 "\\(\\<[012]?[0-9]"
4463 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4464 "\\)?")
4465 "Regular expression to match a plain time or time range.
4466 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4467 groups carry important information:
4468 0 the full match
4469 1 the first time, range or not
4470 8 the second time, if it is a range.")
4472 (defconst org-plain-time-extension-regexp
4473 (concat
4474 "\\(\\<[012]?[0-9]"
4475 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4476 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4477 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4478 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4479 groups carry important information:
4480 0 the full match
4481 7 hours of duration
4482 9 minutes of duration")
4484 (defconst org-stamp-time-of-day-regexp
4485 (concat
4486 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4487 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4488 "\\(--?"
4489 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4490 "Regular expression to match a timestamp time or time range.
4491 After a match, the following groups carry important information:
4492 0 the full match
4493 1 date plus weekday, for back referencing to make sure both times are on the same day
4494 2 the first time, range or not
4495 4 the second time, if it is a range.")
4497 (defconst org-startup-options
4498 '(("fold" org-startup-folded t)
4499 ("overview" org-startup-folded t)
4500 ("nofold" org-startup-folded nil)
4501 ("showall" org-startup-folded nil)
4502 ("showeverything" org-startup-folded showeverything)
4503 ("content" org-startup-folded content)
4504 ("indent" org-startup-indented t)
4505 ("noindent" org-startup-indented nil)
4506 ("hidestars" org-hide-leading-stars t)
4507 ("showstars" org-hide-leading-stars nil)
4508 ("odd" org-odd-levels-only t)
4509 ("oddeven" org-odd-levels-only nil)
4510 ("align" org-startup-align-all-tables t)
4511 ("noalign" org-startup-align-all-tables nil)
4512 ("inlineimages" org-startup-with-inline-images t)
4513 ("noinlineimages" org-startup-with-inline-images nil)
4514 ("customtime" org-display-custom-times t)
4515 ("logdone" org-log-done time)
4516 ("lognotedone" org-log-done note)
4517 ("nologdone" org-log-done nil)
4518 ("lognoteclock-out" org-log-note-clock-out t)
4519 ("nolognoteclock-out" org-log-note-clock-out nil)
4520 ("logrepeat" org-log-repeat state)
4521 ("lognoterepeat" org-log-repeat note)
4522 ("logdrawer" org-log-into-drawer t)
4523 ("nologdrawer" org-log-into-drawer nil)
4524 ("logstatesreversed" org-log-states-order-reversed t)
4525 ("nologstatesreversed" org-log-states-order-reversed nil)
4526 ("nologrepeat" org-log-repeat nil)
4527 ("logreschedule" org-log-reschedule time)
4528 ("lognotereschedule" org-log-reschedule note)
4529 ("nologreschedule" org-log-reschedule nil)
4530 ("logredeadline" org-log-redeadline time)
4531 ("lognoteredeadline" org-log-redeadline note)
4532 ("nologredeadline" org-log-redeadline nil)
4533 ("logrefile" org-log-refile time)
4534 ("lognoterefile" org-log-refile note)
4535 ("nologrefile" org-log-refile nil)
4536 ("fninline" org-footnote-define-inline t)
4537 ("nofninline" org-footnote-define-inline nil)
4538 ("fnlocal" org-footnote-section nil)
4539 ("fnauto" org-footnote-auto-label t)
4540 ("fnprompt" org-footnote-auto-label nil)
4541 ("fnconfirm" org-footnote-auto-label confirm)
4542 ("fnplain" org-footnote-auto-label plain)
4543 ("fnadjust" org-footnote-auto-adjust t)
4544 ("nofnadjust" org-footnote-auto-adjust nil)
4545 ("constcgs" constants-unit-system cgs)
4546 ("constSI" constants-unit-system SI)
4547 ("noptag" org-tag-persistent-alist nil)
4548 ("hideblocks" org-hide-block-startup t)
4549 ("nohideblocks" org-hide-block-startup nil)
4550 ("beamer" org-startup-with-beamer-mode t)
4551 ("entitiespretty" org-pretty-entities t)
4552 ("entitiesplain" org-pretty-entities nil))
4553 "Variable associated with STARTUP options for org-mode.
4554 Each element is a list of three items: the startup options (as written
4555 in the #+STARTUP line), the corresponding variable, and the value to set
4556 this variable to if the option is found. An optional forth element PUSH
4557 means to push this value onto the list in the variable.")
4559 (defun org-update-property-plist (key val props)
4560 "Update PROPS with KEY and VAL."
4561 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4562 (key (if appending (substring key 0 (- (length key) 1)) key))
4563 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4564 (previous (cdr (assoc key props))))
4565 (if appending
4566 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4567 (cons (cons key val) remainder))))
4569 (defconst org-block-regexp
4570 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4571 "Regular expression for hiding blocks.")
4572 (defconst org-heading-keyword-regexp-format
4573 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4574 "Printf format for a regexp matching an headline with some keyword.
4575 This regexp will match the headline of any node which has the
4576 exact keyword that is put into the format. The keyword isn't in
4577 any group by default, but the stars and the body are.")
4578 (defconst org-heading-keyword-maybe-regexp-format
4579 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4580 "Printf format for a regexp matching an headline, possibly with some keyword.
4581 This regexp can match any headline with the specified keyword, or
4582 without a keyword. The keyword isn't in any group by default,
4583 but the stars and the body are.")
4585 (defun org-set-regexps-and-options ()
4586 "Precompute regular expressions for current buffer."
4587 (when (derived-mode-p 'org-mode)
4588 (org-set-local 'org-todo-kwd-alist nil)
4589 (org-set-local 'org-todo-key-alist nil)
4590 (org-set-local 'org-todo-key-trigger nil)
4591 (org-set-local 'org-todo-keywords-1 nil)
4592 (org-set-local 'org-done-keywords nil)
4593 (org-set-local 'org-todo-heads nil)
4594 (org-set-local 'org-todo-sets nil)
4595 (org-set-local 'org-todo-log-states nil)
4596 (org-set-local 'org-file-properties nil)
4597 (org-set-local 'org-file-tags nil)
4598 (let ((re (org-make-options-regexp
4599 '("CATEGORY" "TODO" "COLUMNS"
4600 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4601 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4602 "OPTIONS")
4603 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4604 (splitre "[ \t]+")
4605 (scripts org-use-sub-superscripts)
4606 kwds kws0 kwsa key log value cat arch tags const links hw dws
4607 tail sep kws1 prio props ftags drawers beamer-p
4608 ext-setup-or-nil setup-contents (start 0))
4609 (save-excursion
4610 (save-restriction
4611 (widen)
4612 (goto-char (point-min))
4613 (while (or (and ext-setup-or-nil
4614 (string-match re ext-setup-or-nil start)
4615 (setq start (match-end 0)))
4616 (and (setq ext-setup-or-nil nil start 0)
4617 (re-search-forward re nil t)))
4618 (setq key (upcase (match-string 1 ext-setup-or-nil))
4619 value (org-match-string-no-properties 2 ext-setup-or-nil))
4620 (if (stringp value) (setq value (org-trim value)))
4621 (cond
4622 ((equal key "CATEGORY")
4623 (setq cat value))
4624 ((member key '("SEQ_TODO" "TODO"))
4625 (push (cons 'sequence (org-split-string value splitre)) kwds))
4626 ((equal key "TYP_TODO")
4627 (push (cons 'type (org-split-string value splitre)) kwds))
4628 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4629 ;; general TODO-like setup
4630 (push (cons (intern (downcase (match-string 1 key)))
4631 (org-split-string value splitre)) kwds))
4632 ((equal key "TAGS")
4633 (setq tags (append tags (if tags '("\\n") nil)
4634 (org-split-string value splitre))))
4635 ((equal key "COLUMNS")
4636 (org-set-local 'org-columns-default-format value))
4637 ((equal key "LINK")
4638 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4639 (push (cons (match-string 1 value)
4640 (org-trim (match-string 2 value)))
4641 links)))
4642 ((equal key "PRIORITIES")
4643 (setq prio (org-split-string value " +")))
4644 ((equal key "PROPERTY")
4645 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4646 (setq props (org-update-property-plist (match-string 1 value)
4647 (match-string 2 value)
4648 props))))
4649 ((equal key "FILETAGS")
4650 (when (string-match "\\S-" value)
4651 (setq ftags
4652 (append
4653 ftags
4654 (apply 'append
4655 (mapcar (lambda (x) (org-split-string x ":"))
4656 (org-split-string value)))))))
4657 ((equal key "DRAWERS")
4658 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4659 ((equal key "CONSTANTS")
4660 (setq const (append const (org-split-string value splitre))))
4661 ((equal key "STARTUP")
4662 (let ((opts (org-split-string value splitre))
4663 l var val)
4664 (while (setq l (pop opts))
4665 (when (setq l (assoc l org-startup-options))
4666 (setq var (nth 1 l) val (nth 2 l))
4667 (if (not (nth 3 l))
4668 (set (make-local-variable var) val)
4669 (if (not (listp (symbol-value var)))
4670 (set (make-local-variable var) nil))
4671 (set (make-local-variable var) (symbol-value var))
4672 (add-to-list var val))))))
4673 ((equal key "ARCHIVE")
4674 (setq arch value)
4675 (remove-text-properties 0 (length arch)
4676 '(face t fontified t) arch))
4677 ((equal key "LATEX_CLASS")
4678 (setq beamer-p (equal value "beamer")))
4679 ((equal key "OPTIONS")
4680 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4681 (setq scripts (read (match-string 2 value)))))
4682 ((equal key "SETUPFILE")
4683 (setq setup-contents (org-file-contents
4684 (expand-file-name
4685 (org-remove-double-quotes value))
4686 'noerror))
4687 (if (not ext-setup-or-nil)
4688 (setq ext-setup-or-nil setup-contents start 0)
4689 (setq ext-setup-or-nil
4690 (concat (substring ext-setup-or-nil 0 start)
4691 "\n" setup-contents "\n"
4692 (substring ext-setup-or-nil start)))))))
4693 ;; search for property blocks
4694 (goto-char (point-min))
4695 (while (re-search-forward org-block-regexp nil t)
4696 (when (equal "PROPERTY" (upcase (match-string 1)))
4697 (setq value (replace-regexp-in-string
4698 "[\n\r]" " " (match-string 4)))
4699 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4700 (setq props (org-update-property-plist (match-string 1 value)
4701 (match-string 2 value)
4702 props)))))))
4703 (org-set-local 'org-use-sub-superscripts scripts)
4704 (when cat
4705 (org-set-local 'org-category (intern cat))
4706 (push (cons "CATEGORY" cat) props))
4707 (when prio
4708 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4709 (setq prio (mapcar 'string-to-char prio))
4710 (org-set-local 'org-highest-priority (nth 0 prio))
4711 (org-set-local 'org-lowest-priority (nth 1 prio))
4712 (org-set-local 'org-default-priority (nth 2 prio)))
4713 (and props (org-set-local 'org-file-properties (nreverse props)))
4714 (and ftags (org-set-local 'org-file-tags
4715 (mapcar 'org-add-prop-inherited ftags)))
4716 (and drawers (org-set-local 'org-drawers drawers))
4717 (and arch (org-set-local 'org-archive-location arch))
4718 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4719 ;; Process the TODO keywords
4720 (unless kwds
4721 ;; Use the global values as if they had been given locally.
4722 (setq kwds (default-value 'org-todo-keywords))
4723 (if (stringp (car kwds))
4724 (setq kwds (list (cons org-todo-interpretation
4725 (default-value 'org-todo-keywords)))))
4726 (setq kwds (reverse kwds)))
4727 (setq kwds (nreverse kwds))
4728 (let (inter kws kw)
4729 (while (setq kws (pop kwds))
4730 (let ((kws (or
4731 (run-hook-with-args-until-success
4732 'org-todo-setup-filter-hook kws)
4733 kws)))
4734 (setq inter (pop kws) sep (member "|" kws)
4735 kws0 (delete "|" (copy-sequence kws))
4736 kwsa nil
4737 kws1 (mapcar
4738 (lambda (x)
4739 ;; 1 2
4740 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4741 (progn
4742 (setq kw (match-string 1 x)
4743 key (and (match-end 2) (match-string 2 x))
4744 log (org-extract-log-state-settings x))
4745 (push (cons kw (and key (string-to-char key))) kwsa)
4746 (and log (push log org-todo-log-states))
4748 (error "Invalid TODO keyword %s" x)))
4749 kws0)
4750 kwsa (if kwsa (append '((:startgroup))
4751 (nreverse kwsa)
4752 '((:endgroup))))
4753 hw (car kws1)
4754 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4755 tail (list inter hw (car dws) (org-last dws))))
4756 (add-to-list 'org-todo-heads hw 'append)
4757 (push kws1 org-todo-sets)
4758 (setq org-done-keywords (append org-done-keywords dws nil))
4759 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4760 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4761 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4762 (setq org-todo-sets (nreverse org-todo-sets)
4763 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4764 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4765 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4766 ;; Process the constants
4767 (when const
4768 (let (e cst)
4769 (while (setq e (pop const))
4770 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4771 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4772 (setq org-table-formula-constants-local cst)))
4774 ;; Process the tags.
4775 (when tags
4776 (let (e tgs)
4777 (while (setq e (pop tags))
4778 (cond
4779 ((equal e "{") (push '(:startgroup) tgs))
4780 ((equal e "}") (push '(:endgroup) tgs))
4781 ((equal e "\\n") (push '(:newline) tgs))
4782 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4783 (push (cons (match-string 1 e)
4784 (string-to-char (match-string 2 e)))
4785 tgs))
4786 (t (push (list e) tgs))))
4787 (org-set-local 'org-tag-alist nil)
4788 (while (setq e (pop tgs))
4789 (or (and (stringp (car e))
4790 (assoc (car e) org-tag-alist))
4791 (push e org-tag-alist)))))
4793 ;; Compute the regular expressions and other local variables.
4794 ;; Using `org-outline-regexp-bol' would complicate them much,
4795 ;; because of the fixed white space at the end of that string.
4796 (if (not org-done-keywords)
4797 (setq org-done-keywords (and org-todo-keywords-1
4798 (list (org-last org-todo-keywords-1)))))
4799 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4800 (length org-scheduled-string)
4801 (length org-clock-string)
4802 (length org-closed-string)))
4803 org-drawer-regexp
4804 (concat "^[ \t]*:\\("
4805 (mapconcat 'regexp-quote org-drawers "\\|")
4806 "\\):[ \t]*$")
4807 org-not-done-keywords
4808 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4809 org-todo-regexp
4810 (concat "\\("
4811 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4812 "\\)")
4813 org-not-done-regexp
4814 (concat "\\("
4815 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4816 "\\)")
4817 org-not-done-heading-regexp
4818 (format org-heading-keyword-regexp-format org-not-done-regexp)
4819 org-todo-line-regexp
4820 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4821 org-complex-heading-regexp
4822 (concat "^\\(\\*+\\)"
4823 "\\(?: +" org-todo-regexp "\\)?"
4824 "\\(?: +\\(\\[#.\\]\\)\\)?"
4825 "\\(?: +\\(.*?\\)\\)??"
4826 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4827 "[ \t]*$")
4828 org-complex-heading-regexp-format
4829 (concat "^\\(\\*+\\)"
4830 "\\(?: +" org-todo-regexp "\\)?"
4831 "\\(?: +\\(\\[#.\\]\\)\\)?"
4832 "\\(?: +"
4833 ;; Stats cookies can be stuck to body.
4834 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4835 "\\(%s\\)"
4836 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4837 "\\)"
4838 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4839 "[ \t]*$")
4840 org-todo-line-tags-regexp
4841 (concat "^\\(\\*+\\)"
4842 "\\(?: +" org-todo-regexp "\\)?"
4843 "\\(?: +\\(.*?\\)\\)??"
4844 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4845 "[ \t]*$")
4846 org-deadline-regexp (concat "\\<" org-deadline-string)
4847 org-deadline-time-regexp
4848 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4849 org-deadline-line-regexp
4850 (concat "\\<\\(" org-deadline-string "\\).*")
4851 org-scheduled-regexp
4852 (concat "\\<" org-scheduled-string)
4853 org-scheduled-time-regexp
4854 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4855 org-closed-time-regexp
4856 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4857 org-keyword-time-regexp
4858 (concat "\\<\\(" org-scheduled-string
4859 "\\|" org-deadline-string
4860 "\\|" org-closed-string
4861 "\\|" org-clock-string "\\)"
4862 " *[[<]\\([^]>]+\\)[]>]")
4863 org-keyword-time-not-clock-regexp
4864 (concat "\\<\\(" org-scheduled-string
4865 "\\|" org-deadline-string
4866 "\\|" org-closed-string
4867 "\\)"
4868 " *[[<]\\([^]>]+\\)[]>]")
4869 org-maybe-keyword-time-regexp
4870 (concat "\\(\\<\\(" org-scheduled-string
4871 "\\|" org-deadline-string
4872 "\\|" org-closed-string
4873 "\\|" org-clock-string "\\)\\)?"
4874 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4875 org-all-time-keywords
4876 (mapcar (lambda (w) (substring w 0 -1))
4877 (list org-scheduled-string org-deadline-string
4878 org-clock-string org-closed-string))
4880 (org-compute-latex-and-specials-regexp)
4881 (org-set-font-lock-defaults))))
4883 (defun org-file-contents (file &optional noerror)
4884 "Return the contents of FILE, as a string."
4885 (if (or (not file)
4886 (not (file-readable-p file)))
4887 (if noerror
4888 (progn
4889 (message "Cannot read file \"%s\"" file)
4890 (ding) (sit-for 2)
4892 (error "Cannot read file \"%s\"" file))
4893 (with-temp-buffer
4894 (insert-file-contents file)
4895 (buffer-string))))
4897 (defun org-extract-log-state-settings (x)
4898 "Extract the log state setting from a TODO keyword string.
4899 This will extract info from a string like \"WAIT(w@/!)\"."
4900 (let (kw key log1 log2)
4901 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4902 (setq kw (match-string 1 x)
4903 key (and (match-end 2) (match-string 2 x))
4904 log1 (and (match-end 3) (match-string 3 x))
4905 log2 (and (match-end 4) (match-string 4 x)))
4906 (and (or log1 log2)
4907 (list kw
4908 (and log1 (if (equal log1 "!") 'time 'note))
4909 (and log2 (if (equal log2 "!") 'time 'note)))))))
4911 (defun org-remove-keyword-keys (list)
4912 "Remove a pair of parenthesis at the end of each string in LIST."
4913 (mapcar (lambda (x)
4914 (if (string-match "(.*)$" x)
4915 (substring x 0 (match-beginning 0))
4917 list))
4919 (defun org-assign-fast-keys (alist)
4920 "Assign fast keys to a keyword-key alist.
4921 Respect keys that are already there."
4922 (let (new e (alt ?0))
4923 (while (setq e (pop alist))
4924 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4925 (cdr e)) ;; Key already assigned.
4926 (push e new)
4927 (let ((clist (string-to-list (downcase (car e))))
4928 (used (append new alist)))
4929 (when (= (car clist) ?@)
4930 (pop clist))
4931 (while (and clist (rassoc (car clist) used))
4932 (pop clist))
4933 (unless clist
4934 (while (rassoc alt used)
4935 (incf alt)))
4936 (push (cons (car e) (or (car clist) alt)) new))))
4937 (nreverse new)))
4939 ;;; Some variables used in various places
4941 (defvar org-window-configuration nil
4942 "Used in various places to store a window configuration.")
4943 (defvar org-selected-window nil
4944 "Used in various places to store a window configuration.")
4945 (defvar org-finish-function nil
4946 "Function to be called when `C-c C-c' is used.
4947 This is for getting out of special buffers like capture.")
4950 ;; FIXME: Occasionally check by commenting these, to make sure
4951 ;; no other functions uses these, forgetting to let-bind them.
4952 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4953 (defvar org-last-state)
4954 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4956 ;; Defined somewhere in this file, but used before definition.
4957 (defvar org-entities) ;; defined in org-entities.el
4958 (defvar org-struct-menu)
4959 (defvar org-org-menu)
4960 (defvar org-tbl-menu)
4962 ;;;; Define the Org-mode
4964 ;; We use a before-change function to check if a table might need
4965 ;; an update.
4966 (defvar org-table-may-need-update t
4967 "Indicates that a table might need an update.
4968 This variable is set by `org-before-change-function'.
4969 `org-table-align' sets it back to nil.")
4970 (defun org-before-change-function (beg end)
4971 "Every change indicates that a table might need an update."
4972 (setq org-table-may-need-update t))
4973 (defvar org-mode-map)
4974 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4975 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4976 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4977 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4978 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4979 (defvar org-table-buffer-is-an nil)
4981 (defvar bidi-paragraph-direction)
4982 (defvar buffer-face-mode-face)
4984 (require 'outline)
4985 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4986 (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"))
4987 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4989 ;; Other stuff we need.
4990 (require 'time-date)
4991 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4992 (require 'easymenu)
4993 (require 'overlay)
4995 ;; (require 'org-macs) moved higher up in the file before it is first used
4996 (require 'org-entities)
4997 ;; (require 'org-compat) moved higher up in the file before it is first used
4998 (require 'org-faces)
4999 (require 'org-list)
5000 (require 'org-pcomplete)
5001 (require 'org-src)
5002 (require 'org-footnote)
5004 ;; babel
5005 (require 'ob)
5007 ;;;###autoload
5008 (define-derived-mode org-mode outline-mode "Org"
5009 "Outline-based notes management and organizer, alias
5010 \"Carsten's outline-mode for keeping track of everything.\"
5012 Org-mode develops organizational tasks around a NOTES file which
5013 contains information about projects as plain text. Org-mode is
5014 implemented on top of outline-mode, which is ideal to keep the content
5015 of large files well structured. It supports ToDo items, deadlines and
5016 time stamps, which magically appear in the diary listing of the Emacs
5017 calendar. Tables are easily created with a built-in table editor.
5018 Plain text URL-like links connect to websites, emails (VM), Usenet
5019 messages (Gnus), BBDB entries, and any files related to the project.
5020 For printing and sharing of notes, an Org-mode file (or a part of it)
5021 can be exported as a structured ASCII or HTML file.
5023 The following commands are available:
5025 \\{org-mode-map}"
5027 ;; Get rid of Outline menus, they are not needed
5028 ;; Need to do this here because define-derived-mode sets up
5029 ;; the keymap so late. Still, it is a waste to call this each time
5030 ;; we switch another buffer into org-mode.
5031 (if (featurep 'xemacs)
5032 (when (boundp 'outline-mode-menu-heading)
5033 ;; Assume this is Greg's port, it uses easymenu
5034 (easy-menu-remove outline-mode-menu-heading)
5035 (easy-menu-remove outline-mode-menu-show)
5036 (easy-menu-remove outline-mode-menu-hide))
5037 (define-key org-mode-map [menu-bar headings] 'undefined)
5038 (define-key org-mode-map [menu-bar hide] 'undefined)
5039 (define-key org-mode-map [menu-bar show] 'undefined))
5041 (org-load-modules-maybe)
5042 (easy-menu-add org-org-menu)
5043 (easy-menu-add org-tbl-menu)
5044 (org-install-agenda-files-menu)
5045 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5046 (add-to-invisibility-spec '(org-cwidth))
5047 (add-to-invisibility-spec '(org-hide-block . t))
5048 (when (featurep 'xemacs)
5049 (org-set-local 'line-move-ignore-invisible t))
5050 (org-set-local 'outline-regexp org-outline-regexp)
5051 (org-set-local 'outline-level 'org-outline-level)
5052 (setq bidi-paragraph-direction 'left-to-right)
5053 (when (and org-ellipsis
5054 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5055 (fboundp 'make-glyph-code))
5056 (unless org-display-table
5057 (setq org-display-table (make-display-table)))
5058 (set-display-table-slot
5059 org-display-table 4
5060 (vconcat (mapcar
5061 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5062 org-ellipsis)))
5063 (if (stringp org-ellipsis) org-ellipsis "..."))))
5064 (setq buffer-display-table org-display-table))
5065 (org-set-regexps-and-options)
5066 (when (and org-tag-faces (not org-tags-special-faces-re))
5067 ;; tag faces set outside customize.... force initialization.
5068 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5069 ;; Calc embedded
5070 (org-set-local 'calc-embedded-open-mode "# ")
5071 (modify-syntax-entry ?@ "w")
5072 (modify-syntax-entry ?\" "\"")
5073 (if org-startup-truncated (setq truncate-lines t))
5074 (org-set-local 'font-lock-unfontify-region-function
5075 'org-unfontify-region)
5076 ;; Activate before-change-function
5077 (org-set-local 'org-table-may-need-update t)
5078 (org-add-hook 'before-change-functions 'org-before-change-function nil
5079 'local)
5080 ;; Check for running clock before killing a buffer
5081 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5082 ;; Initialize macros templates.
5083 (org-macro-initialize-templates)
5084 ;; Initialize radio targets.
5085 (org-update-radio-target-regexp)
5086 ;; Indentation.
5087 (org-set-local 'indent-line-function 'org-indent-line)
5088 (org-set-local 'indent-region-function 'org-indent-region)
5089 ;; Filling and auto-filling.
5090 (org-setup-filling)
5091 ;; Comments.
5092 (org-setup-comments-handling)
5093 ;; Beginning/end of defun
5094 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5095 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5096 ;; Next error for sparse trees
5097 (org-set-local 'next-error-function 'org-occur-next-match)
5098 ;; Make sure dependence stuff works reliably, even for users who set it
5099 ;; too late :-(
5100 (if org-enforce-todo-dependencies
5101 (add-hook 'org-blocker-hook
5102 'org-block-todo-from-children-or-siblings-or-parent)
5103 (remove-hook 'org-blocker-hook
5104 'org-block-todo-from-children-or-siblings-or-parent))
5105 (if org-enforce-todo-checkbox-dependencies
5106 (add-hook 'org-blocker-hook
5107 'org-block-todo-from-checkboxes)
5108 (remove-hook 'org-blocker-hook
5109 'org-block-todo-from-checkboxes))
5111 ;; Align options lines
5112 (org-set-local
5113 'align-mode-rules-list
5114 '((org-in-buffer-settings
5115 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5116 (modes . '(org-mode)))))
5118 ;; Imenu
5119 (org-set-local 'imenu-create-index-function
5120 'org-imenu-get-tree)
5122 ;; Make isearch reveal context
5123 (if (or (featurep 'xemacs)
5124 (not (boundp 'outline-isearch-open-invisible-function)))
5125 ;; Emacs 21 and XEmacs make use of the hook
5126 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5127 ;; Emacs 22 deals with this through a special variable
5128 (org-set-local 'outline-isearch-open-invisible-function
5129 (lambda (&rest ignore) (org-show-context 'isearch))))
5131 ;; Turn on org-beamer-mode?
5132 (and org-startup-with-beamer-mode (org-beamer-mode))
5134 ;; Setup the pcomplete hooks
5135 (set (make-local-variable 'pcomplete-command-completion-function)
5136 'org-pcomplete-initial)
5137 (set (make-local-variable 'pcomplete-command-name-function)
5138 'org-command-at-point)
5139 (set (make-local-variable 'pcomplete-default-completion-function)
5140 'ignore)
5141 (set (make-local-variable 'pcomplete-parse-arguments-function)
5142 'org-parse-arguments)
5143 (set (make-local-variable 'pcomplete-termination-string) "")
5144 (when (>= emacs-major-version 23)
5145 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5147 ;; If empty file that did not turn on org-mode automatically, make it to.
5148 (if (and org-insert-mode-line-in-empty-file
5149 (org-called-interactively-p 'any)
5150 (= (point-min) (point-max)))
5151 (insert "# -*- mode: org -*-\n\n"))
5152 (unless org-inhibit-startup
5153 (when org-startup-align-all-tables
5154 (let ((bmp (buffer-modified-p)))
5155 (org-table-map-tables 'org-table-align 'quietly)
5156 (set-buffer-modified-p bmp)))
5157 (when org-startup-with-inline-images
5158 (org-display-inline-images))
5159 (when org-startup-indented
5160 (require 'org-indent)
5161 (org-indent-mode 1))
5162 (unless org-inhibit-startup-visibility-stuff
5163 (org-set-startup-visibility)))
5164 ;; Try to set org-hide correctly
5165 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5167 (when (fboundp 'abbrev-table-put)
5168 (abbrev-table-put org-mode-abbrev-table
5169 :parents (list text-mode-abbrev-table)))
5171 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5174 (defun org-find-invisible-foreground ()
5175 (let ((candidates (remove
5176 "unspecified-bg"
5177 (nconc
5178 (list (face-background 'default)
5179 (face-background 'org-default))
5180 (mapcar
5181 (lambda (alist)
5182 (when (boundp alist)
5183 (cdr (assoc 'background-color (symbol-value alist)))))
5184 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5185 (list (face-foreground 'org-hide))))))
5186 (car (remove nil candidates))))
5188 (defun org-current-time (&optional rounding-minutes)
5189 "Current time, possibly rounded to ROUNDING-MINUTES.
5190 When ROUNDING-MINUTES is not an integer, fall back on the car of
5191 `org-time-stamp-rounding-minutes'."
5192 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5193 (car org-time-stamp-rounding-minutes)))
5194 (time (decode-time)))
5195 (if (> r 1)
5196 (apply 'encode-time
5197 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5198 (nthcdr 2 time)))
5199 (current-time))))
5201 (defun org-today ()
5202 "Return today date, considering `org-extend-today-until'."
5203 (time-to-days
5204 (time-subtract (current-time)
5205 (list 0 (* 3600 org-extend-today-until) 0))))
5207 ;;;; Font-Lock stuff, including the activators
5209 (defvar org-mouse-map (make-sparse-keymap))
5210 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5211 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5212 (when org-mouse-1-follows-link
5213 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5214 (when org-tab-follows-link
5215 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5216 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5218 (require 'font-lock)
5220 (defconst org-non-link-chars "]\t\n\r<>")
5221 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5222 "shell" "elisp" "doi" "message"))
5223 (defvar org-link-types-re nil
5224 "Matches a link that has a url-like prefix like \"http:\"")
5225 (defvar org-link-re-with-space nil
5226 "Matches a link with spaces, optional angular brackets around it.")
5227 (defvar org-link-re-with-space2 nil
5228 "Matches a link with spaces, optional angular brackets around it.")
5229 (defvar org-link-re-with-space3 nil
5230 "Matches a link with spaces, only for internal part in bracket links.")
5231 (defvar org-angle-link-re nil
5232 "Matches link with angular brackets, spaces are allowed.")
5233 (defvar org-plain-link-re nil
5234 "Matches plain link, without spaces.")
5235 (defvar org-bracket-link-regexp nil
5236 "Matches a link in double brackets.")
5237 (defvar org-bracket-link-analytic-regexp nil
5238 "Regular expression used to analyze links.
5239 Here is what the match groups contain after a match:
5240 1: http:
5241 2: http
5242 3: path
5243 4: [desc]
5244 5: desc")
5245 (defvar org-bracket-link-analytic-regexp++ nil
5246 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5247 (defvar org-any-link-re nil
5248 "Regular expression matching any link.")
5250 (defcustom org-match-sexp-depth 3
5251 "Number of stacked braces for sub/superscript matching.
5252 This has to be set before loading org.el to be effective."
5253 :group 'org-export-translation ; ??????????????????????????/
5254 :type 'integer)
5256 (defun org-create-multibrace-regexp (left right n)
5257 "Create a regular expression which will match a balanced sexp.
5258 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5259 as single character strings.
5260 The regexp returned will match the entire expression including the
5261 delimiters. It will also define a single group which contains the
5262 match except for the outermost delimiters. The maximum depth of
5263 stacked delimiters is N. Escaping delimiters is not possible."
5264 (let* ((nothing (concat "[^" left right "]*?"))
5265 (or "\\|")
5266 (re nothing)
5267 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5268 (while (> n 1)
5269 (setq n (1- n)
5270 re (concat re or next)
5271 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5272 (concat left "\\(" re "\\)" right)))
5274 (defvar org-match-substring-regexp
5275 (concat
5276 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5277 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5278 "\\|"
5279 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5280 "\\|"
5281 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5282 "The regular expression matching a sub- or superscript.")
5284 (defvar org-match-substring-with-braces-regexp
5285 (concat
5286 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5287 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5288 "\\)")
5289 "The regular expression matching a sub- or superscript, forcing braces.")
5291 (defun org-make-link-regexps ()
5292 "Update the link regular expressions.
5293 This should be called after the variable `org-link-types' has changed."
5294 (setq org-link-types-re
5295 (concat
5296 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5297 org-link-re-with-space
5298 (concat
5299 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5300 "\\([^" org-non-link-chars " ]"
5301 "[^" org-non-link-chars "]*"
5302 "[^" org-non-link-chars " ]\\)>?")
5303 org-link-re-with-space2
5304 (concat
5305 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5306 "\\([^" org-non-link-chars " ]"
5307 "[^\t\n\r]*"
5308 "[^" org-non-link-chars " ]\\)>?")
5309 org-link-re-with-space3
5310 (concat
5311 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5312 "\\([^" org-non-link-chars " ]"
5313 "[^\t\n\r]*\\)")
5314 org-angle-link-re
5315 (concat
5316 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5317 "\\([^" org-non-link-chars " ]"
5318 "[^" org-non-link-chars "]*"
5319 "\\)>")
5320 org-plain-link-re
5321 (concat
5322 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5323 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5324 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5325 org-bracket-link-regexp
5326 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5327 org-bracket-link-analytic-regexp
5328 (concat
5329 "\\[\\["
5330 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5331 "\\([^]]+\\)"
5332 "\\]"
5333 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5334 "\\]")
5335 org-bracket-link-analytic-regexp++
5336 (concat
5337 "\\[\\["
5338 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5339 "\\([^]]+\\)"
5340 "\\]"
5341 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5342 "\\]")
5343 org-any-link-re
5344 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5345 org-angle-link-re "\\)\\|\\("
5346 org-plain-link-re "\\)")))
5348 (org-make-link-regexps)
5350 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5351 "Regular expression for fast time stamp matching.")
5352 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5353 "Regular expression for fast time stamp matching.")
5354 (defconst org-ts-regexp0
5355 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5356 "Regular expression matching time strings for analysis.
5357 This one does not require the space after the date, so it can be used
5358 on a string that terminates immediately after the date.")
5359 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5360 "Regular expression matching time strings for analysis.")
5361 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5362 "Regular expression matching time stamps, with groups.")
5363 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5364 "Regular expression matching time stamps (also [..]), with groups.")
5365 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5366 "Regular expression matching a time stamp range.")
5367 (defconst org-tr-regexp-both
5368 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5369 "Regular expression matching a time stamp range.")
5370 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5371 org-ts-regexp "\\)?")
5372 "Regular expression matching a time stamp or time stamp range.")
5373 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5374 org-ts-regexp-both "\\)?")
5375 "Regular expression matching a time stamp or time stamp range.
5376 The time stamps may be either active or inactive.")
5378 (defvar org-emph-face nil)
5380 (defun org-do-emphasis-faces (limit)
5381 "Run through the buffer and add overlays to emphasized strings."
5382 (let (rtn a)
5383 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5384 (if (not (= (char-after (match-beginning 3))
5385 (char-after (match-beginning 4))))
5386 (progn
5387 (setq rtn t)
5388 (setq a (assoc (match-string 3) org-emphasis-alist))
5389 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5390 'face
5391 (nth 1 a))
5392 (and (nth 4 a)
5393 (org-remove-flyspell-overlays-in
5394 (match-beginning 0) (match-end 0)))
5395 (add-text-properties (match-beginning 2) (match-end 2)
5396 '(font-lock-multiline t org-emphasis t))
5397 (when org-hide-emphasis-markers
5398 (add-text-properties (match-end 4) (match-beginning 5)
5399 '(invisible org-link))
5400 (add-text-properties (match-beginning 3) (match-end 3)
5401 '(invisible org-link)))))
5402 (backward-char 1))
5403 rtn))
5405 (defun org-emphasize (&optional char)
5406 "Insert or change an emphasis, i.e. a font like bold or italic.
5407 If there is an active region, change that region to a new emphasis.
5408 If there is no region, just insert the marker characters and position
5409 the cursor between them.
5410 CHAR should be either the marker character, or the first character of the
5411 HTML tag associated with that emphasis. If CHAR is a space, the means
5412 to remove the emphasis of the selected region.
5413 If char is not given (for example in an interactive call) it
5414 will be prompted for."
5415 (interactive)
5416 (let ((eal org-emphasis-alist) e det
5417 (erc org-emphasis-regexp-components)
5418 (prompt "")
5419 (string "") beg end move tag c s)
5420 (if (org-region-active-p)
5421 (setq beg (region-beginning) end (region-end)
5422 string (buffer-substring beg end))
5423 (setq move t))
5425 (while (setq e (pop eal))
5426 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5427 c (aref tag 0))
5428 (push (cons c (string-to-char (car e))) det)
5429 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5430 (substring tag 1)))))
5431 (setq det (nreverse det))
5432 (unless char
5433 (message "%s" (concat "Emphasis marker or tag:" prompt))
5434 (setq char (read-char-exclusive)))
5435 (setq char (or (cdr (assoc char det)) char))
5436 (if (equal char ?\ )
5437 (setq s "" move nil)
5438 (unless (assoc (char-to-string char) org-emphasis-alist)
5439 (error "No such emphasis marker: \"%c\"" char))
5440 (setq s (char-to-string char)))
5441 (while (and (> (length string) 1)
5442 (equal (substring string 0 1) (substring string -1))
5443 (assoc (substring string 0 1) org-emphasis-alist))
5444 (setq string (substring string 1 -1)))
5445 (setq string (concat s string s))
5446 (if beg (delete-region beg end))
5447 (unless (or (bolp)
5448 (string-match (concat "[" (nth 0 erc) "\n]")
5449 (char-to-string (char-before (point)))))
5450 (insert " "))
5451 (unless (or (eobp)
5452 (string-match (concat "[" (nth 1 erc) "\n]")
5453 (char-to-string (char-after (point)))))
5454 (insert " ") (backward-char 1))
5455 (insert string)
5456 (and move (backward-char 1))))
5458 (defconst org-nonsticky-props
5459 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5461 (defsubst org-rear-nonsticky-at (pos)
5462 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5464 (defun org-activate-plain-links (limit)
5465 "Run through the buffer and add overlays to links."
5466 (catch 'exit
5467 (let (f hl)
5468 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5469 (not (org-in-src-block-p)))
5470 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5471 (setq f (get-text-property (match-beginning 0) 'face))
5472 (setq hl (org-match-string-no-properties 0))
5473 (if (or (eq f 'org-tag)
5474 (and (listp f) (memq 'org-tag f)))
5476 (add-text-properties (match-beginning 0) (match-end 0)
5477 (list 'mouse-face 'highlight
5478 'face 'org-link
5479 'htmlize-link `(:uri ,hl)
5480 'keymap org-mouse-map))
5481 (org-rear-nonsticky-at (match-end 0)))
5482 t))))
5484 (defun org-activate-code (limit)
5485 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5486 (progn
5487 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5488 (remove-text-properties (match-beginning 0) (match-end 0)
5489 '(display t invisible t intangible t))
5490 t)))
5492 (defcustom org-src-fontify-natively nil
5493 "When non-nil, fontify code in code blocks."
5494 :type 'boolean
5495 :version "24.1"
5496 :group 'org-appearance
5497 :group 'org-babel)
5499 (defcustom org-allow-promoting-top-level-subtree nil
5500 "When non-nil, allow promoting a top level subtree.
5501 The leading star of the top level headline will be replaced
5502 by a #."
5503 :type 'boolean
5504 :version "24.1"
5505 :group 'org-appearance)
5507 (defun org-fontify-meta-lines-and-blocks (limit)
5508 (condition-case nil
5509 (org-fontify-meta-lines-and-blocks-1 limit)
5510 (error (message "org-mode fontification error"))))
5512 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5513 "Fontify #+ lines and blocks, in the correct ways."
5514 (let ((case-fold-search t))
5515 (if (re-search-forward
5516 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5517 limit t)
5518 (let ((beg (match-beginning 0))
5519 (block-start (match-end 0))
5520 (block-end nil)
5521 (lang (match-string 7))
5522 (beg1 (line-beginning-position 2))
5523 (dc1 (downcase (match-string 2)))
5524 (dc3 (downcase (match-string 3)))
5525 end end1 quoting block-type ovl)
5526 (cond
5527 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5528 ;; a single line of backend-specific content
5529 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5530 (remove-text-properties (match-beginning 0) (match-end 0)
5531 '(display t invisible t intangible t))
5532 (add-text-properties (match-beginning 1) (match-end 3)
5533 '(font-lock-fontified t face org-meta-line))
5534 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5535 '(font-lock-fontified t face org-block))
5536 ; for backend-specific code
5538 ((and (match-end 4) (equal dc3 "+begin"))
5539 ;; Truly a block
5540 (setq block-type (downcase (match-string 5))
5541 quoting (member block-type org-protecting-blocks))
5542 (when (re-search-forward
5543 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5544 nil t) ;; on purpose, we look further than LIMIT
5545 (setq end (min (point-max) (match-end 0))
5546 end1 (min (point-max) (1- (match-beginning 0))))
5547 (setq block-end (match-beginning 0))
5548 (when quoting
5549 (remove-text-properties beg end
5550 '(display t invisible t intangible t)))
5551 (add-text-properties
5552 beg end
5553 '(font-lock-fontified t font-lock-multiline t))
5554 (add-text-properties beg beg1 '(face org-meta-line))
5555 (add-text-properties end1 (min (point-max) (1+ end))
5556 '(face org-meta-line)) ; for end_src
5557 (cond
5558 ((and lang (not (string= lang "")) org-src-fontify-natively)
5559 (org-src-font-lock-fontify-block lang block-start block-end)
5560 ;; remove old background overlays
5561 (mapc (lambda (ov)
5562 (if (eq (overlay-get ov 'face) 'org-block-background)
5563 (delete-overlay ov)))
5564 (overlays-at (/ (+ beg1 block-end) 2)))
5565 ;; add a background overlay
5566 (setq ovl (make-overlay beg1 block-end))
5567 (overlay-put ovl 'face 'org-block-background)
5568 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5569 (quoting
5570 (add-text-properties beg1 (min (point-max) (1+ end1))
5571 '(face org-block))) ; end of source block
5572 ((not org-fontify-quote-and-verse-blocks))
5573 ((string= block-type "quote")
5574 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5575 ((string= block-type "verse")
5576 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5577 (add-text-properties beg beg1 '(face org-block-begin-line))
5578 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5579 '(face org-block-end-line))
5581 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5582 (add-text-properties
5583 beg (match-end 3)
5584 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5585 '(font-lock-fontified t invisible t)
5586 '(font-lock-fontified t face org-document-info-keyword)))
5587 (add-text-properties
5588 (match-beginning 6) (1+ (match-end 6))
5589 (if (string-equal dc1 "+title:")
5590 '(font-lock-fontified t face org-document-title)
5591 '(font-lock-fontified t face org-document-info))))
5592 ((or (equal dc1 "+results")
5593 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5594 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5595 "+call:" "+header:" "+headers:" "+name:"))
5596 (and (match-end 4) (equal dc3 "+attr")))
5597 (add-text-properties
5598 beg (match-end 0)
5599 '(font-lock-fontified t face org-meta-line))
5601 ((member dc3 '(" " ""))
5602 (add-text-properties
5603 beg (match-end 0)
5604 '(font-lock-fontified t face font-lock-comment-face)))
5605 ((not (member (char-after beg) '(?\ ?\t)))
5606 ;; just any other in-buffer setting, but not indented
5607 (add-text-properties
5608 beg (match-end 0)
5609 '(font-lock-fontified t face org-meta-line))
5611 (t nil))))))
5613 (defun org-activate-angle-links (limit)
5614 "Run through the buffer and add overlays to links."
5615 (if (and (re-search-forward org-angle-link-re limit t)
5616 (not (org-in-src-block-p)))
5617 (progn
5618 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5619 (add-text-properties (match-beginning 0) (match-end 0)
5620 (list 'mouse-face 'highlight
5621 'keymap org-mouse-map))
5622 (org-rear-nonsticky-at (match-end 0))
5623 t)))
5625 (defun org-activate-footnote-links (limit)
5626 "Run through the buffer and add overlays to footnotes."
5627 (let ((fn (org-footnote-next-reference-or-definition limit)))
5628 (when fn
5629 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5630 (org-remove-flyspell-overlays-in beg end)
5631 (add-text-properties beg end
5632 (list 'mouse-face 'highlight
5633 'keymap org-mouse-map
5634 'help-echo
5635 (if (= (point-at-bol) beg)
5636 "Footnote definition"
5637 "Footnote reference")
5638 'font-lock-fontified t
5639 'font-lock-multiline t
5640 'face 'org-footnote))))))
5642 (defun org-activate-bracket-links (limit)
5643 "Run through the buffer and add overlays to bracketed links."
5644 (if (and (re-search-forward org-bracket-link-regexp limit t)
5645 (not (org-in-src-block-p)))
5646 (let* ((hl (org-match-string-no-properties 1))
5647 (help (concat "LINK: " hl))
5648 ;; FIXME: Above we should remove the escapes. But that
5649 ;; requires another match, protecting match data, a lot
5650 ;; of overhead for font-lock.
5651 (ip (org-maybe-intangible
5652 (list 'invisible 'org-link
5653 'keymap org-mouse-map 'mouse-face 'highlight
5654 'font-lock-multiline t 'help-echo help
5655 'htmlize-link `(:uri ,hl))))
5656 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5657 'font-lock-multiline t 'help-echo help
5658 'htmlize-link `(:uri ,hl))))
5659 ;; We need to remove the invisible property here. Table narrowing
5660 ;; may have made some of this invisible.
5661 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5662 (remove-text-properties (match-beginning 0) (match-end 0)
5663 '(invisible nil))
5664 (if (match-end 3)
5665 (progn
5666 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5667 (org-rear-nonsticky-at (match-beginning 3))
5668 (add-text-properties (match-beginning 3) (match-end 3) vp)
5669 (org-rear-nonsticky-at (match-end 3))
5670 (add-text-properties (match-end 3) (match-end 0) ip)
5671 (org-rear-nonsticky-at (match-end 0)))
5672 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5673 (org-rear-nonsticky-at (match-beginning 1))
5674 (add-text-properties (match-beginning 1) (match-end 1) vp)
5675 (org-rear-nonsticky-at (match-end 1))
5676 (add-text-properties (match-end 1) (match-end 0) ip)
5677 (org-rear-nonsticky-at (match-end 0)))
5678 t)))
5680 (defun org-activate-dates (limit)
5681 "Run through the buffer and add overlays to dates."
5682 (if (re-search-forward org-tsr-regexp-both limit t)
5683 (progn
5684 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5685 (add-text-properties (match-beginning 0) (match-end 0)
5686 (list 'mouse-face 'highlight
5687 'keymap org-mouse-map))
5688 (org-rear-nonsticky-at (match-end 0))
5689 (when org-display-custom-times
5690 (if (match-end 3)
5691 (org-display-custom-time (match-beginning 3) (match-end 3)))
5692 (org-display-custom-time (match-beginning 1) (match-end 1)))
5693 t)))
5695 (defvar org-target-link-regexp nil
5696 "Regular expression matching radio targets in plain text.")
5697 (make-variable-buffer-local 'org-target-link-regexp)
5698 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5699 "Regular expression matching a link target.")
5700 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5701 "Regular expression matching a radio target.")
5702 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5703 "Regular expression matching any target.")
5705 (defun org-activate-target-links (limit)
5706 "Run through the buffer and add overlays to target matches."
5707 (when org-target-link-regexp
5708 (let ((case-fold-search t))
5709 (if (re-search-forward org-target-link-regexp limit t)
5710 (progn
5711 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5712 (add-text-properties (match-beginning 0) (match-end 0)
5713 (list 'mouse-face 'highlight
5714 'keymap org-mouse-map
5715 'help-echo "Radio target link"
5716 'org-linked-text t))
5717 (org-rear-nonsticky-at (match-end 0))
5718 t)))))
5720 (defun org-update-radio-target-regexp ()
5721 "Find all radio targets in this file and update the regular expression."
5722 (interactive)
5723 (when (memq 'radio org-activate-links)
5724 (setq org-target-link-regexp
5725 (org-make-target-link-regexp (org-all-targets 'radio)))
5726 (org-restart-font-lock)))
5728 (defun org-hide-wide-columns (limit)
5729 (let (s e)
5730 (setq s (text-property-any (point) (or limit (point-max))
5731 'org-cwidth t))
5732 (when s
5733 (setq e (next-single-property-change s 'org-cwidth))
5734 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5735 (goto-char e)
5736 t)))
5738 (defvar org-latex-and-specials-regexp nil
5739 "Regular expression for highlighting export special stuff.")
5740 (defvar org-match-substring-regexp)
5741 (defvar org-match-substring-with-braces-regexp)
5743 ;; This should be with the exporter code, but we also use if for font-locking
5744 (defconst org-export-html-special-string-regexps
5745 '(("\\\\-" . "&shy;")
5746 ("---\\([^-]\\)" . "&mdash;\\1")
5747 ("--\\([^-]\\)" . "&ndash;\\1")
5748 ("\\.\\.\\." . "&hellip;"))
5749 "Regular expressions for special string conversion.")
5752 (defun org-compute-latex-and-specials-regexp ()
5753 "Compute regular expression for stuff treated specially by exporters."
5754 (if (not org-highlight-latex-fragments-and-specials)
5755 (org-set-local 'org-latex-and-specials-regexp nil)
5756 (require 'org-exp)
5757 (let*
5758 ((matchers (plist-get org-format-latex-options :matchers))
5759 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5760 org-latex-regexps)))
5761 (org-export-allow-BIND nil)
5762 (options (org-combine-plists (org-default-export-plist)
5763 (org-infile-export-plist)))
5764 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5765 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5766 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5767 (org-export-html-expand (plist-get options :expand-quoted-html))
5768 (org-export-with-special-strings (plist-get options :special-strings))
5769 (re-sub
5770 (cond
5771 ((equal org-export-with-sub-superscripts '{})
5772 (list org-match-substring-with-braces-regexp))
5773 (org-export-with-sub-superscripts
5774 (list org-match-substring-regexp))))
5775 (re-latex
5776 (if org-export-with-LaTeX-fragments
5777 (mapcar (lambda (x) (nth 1 x)) latexs)))
5778 (re-macros
5779 (if org-export-with-TeX-macros
5780 (list (concat "\\\\"
5781 (regexp-opt
5782 (append
5784 (delq nil
5785 (mapcar 'car-safe
5786 (append org-entities-user
5787 org-entities)))
5788 (if (boundp 'org-latex-entities)
5789 (mapcar (lambda (x)
5790 (or (car-safe x) x))
5791 org-latex-entities)
5792 nil))
5793 'words))) ; FIXME
5795 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5796 (re-special (if org-export-with-special-strings
5797 (mapcar (lambda (x) (car x))
5798 org-export-html-special-string-regexps)))
5799 (re-rest
5800 (delq nil
5801 (list
5802 (if org-export-html-expand "@<[^>\n]+>")
5803 ))))
5804 (org-set-local
5805 'org-latex-and-specials-regexp
5806 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5807 re-rest) "\\|")))))
5809 (defun org-do-latex-and-special-faces (limit)
5810 "Run through the buffer and add overlays to links."
5811 (when org-latex-and-specials-regexp
5812 (let (rtn d)
5813 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5814 limit t))
5815 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5816 'face))
5817 '(org-code org-verbatim underline)))
5818 (progn
5819 (setq rtn t
5820 d (cond ((member (char-after (1+ (match-beginning 0)))
5821 '(?_ ?^)) 1)
5822 (t 0)))
5823 (font-lock-prepend-text-property
5824 (+ d (match-beginning 0)) (match-end 0)
5825 'face 'org-latex-and-export-specials)
5826 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5827 '(font-lock-multiline t)))))
5828 rtn)))
5830 (defun org-restart-font-lock ()
5831 "Restart `font-lock-mode', to force refontification."
5832 (when (and (boundp 'font-lock-mode) font-lock-mode)
5833 (font-lock-mode -1)
5834 (font-lock-mode 1)))
5836 (defun org-all-targets (&optional radio)
5837 "Return a list of all targets in this file.
5838 When optional argument RADIO is non-nil, only find radio
5839 targets."
5840 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5841 (save-excursion
5842 (goto-char (point-min))
5843 (while (re-search-forward re nil t)
5844 ;; Make sure point is really within the object.
5845 (backward-char)
5846 (let ((obj (org-element-context)))
5847 (when (memq (org-element-type obj) '(radio-target target))
5848 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5849 rtn)))
5851 (defun org-make-target-link-regexp (targets)
5852 "Make regular expression matching all strings in TARGETS.
5853 The regular expression finds the targets also if there is a line break
5854 between words."
5855 (and targets
5856 (concat
5857 "\\<\\("
5858 (mapconcat
5859 (lambda (x)
5860 (setq x (regexp-quote x))
5861 (while (string-match " +" x)
5862 (setq x (replace-match "\\s-+" t t x)))
5864 targets
5865 "\\|")
5866 "\\)\\>")))
5868 (defun org-activate-tags (limit)
5869 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5870 (progn
5871 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5872 (add-text-properties (match-beginning 1) (match-end 1)
5873 (list 'mouse-face 'highlight
5874 'keymap org-mouse-map))
5875 (org-rear-nonsticky-at (match-end 1))
5876 t)))
5878 (defun org-outline-level ()
5879 "Compute the outline level of the heading at point.
5880 If this is called at a normal headline, the level is the number of stars.
5881 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5882 (save-excursion
5883 (if (not (condition-case nil
5884 (org-back-to-heading t)
5885 (error nil)))
5887 (looking-at org-outline-regexp)
5888 (1- (- (match-end 0) (match-beginning 0))))))
5890 (defvar org-font-lock-keywords nil)
5892 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5893 "Regular expression matching a property line.")
5895 (defvar org-font-lock-hook nil
5896 "Functions to be called for special font lock stuff.")
5898 (defvar org-font-lock-set-keywords-hook nil
5899 "Functions that can manipulate `org-font-lock-extra-keywords'.
5900 This is called after `org-font-lock-extra-keywords' is defined, but before
5901 it is installed to be used by font lock. This can be useful if something
5902 needs to be inserted at a specific position in the font-lock sequence.")
5904 (defun org-font-lock-hook (limit)
5905 "Run `org-font-lock-hook' within LIMIT."
5906 (run-hook-with-args 'org-font-lock-hook limit))
5908 (defun org-set-font-lock-defaults ()
5909 "Set font lock defaults for the current buffer."
5910 (let* ((em org-fontify-emphasized-text)
5911 (lk org-activate-links)
5912 (org-font-lock-extra-keywords
5913 (list
5914 ;; Call the hook
5915 '(org-font-lock-hook)
5916 ;; Headlines
5917 `(,(if org-fontify-whole-heading-line
5918 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5919 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5920 (1 (org-get-level-face 1))
5921 (2 (org-get-level-face 2))
5922 (3 (org-get-level-face 3)))
5923 ;; Table lines
5924 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5925 (1 'org-table t))
5926 ;; Table internals
5927 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5928 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5929 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5930 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5931 ;; Drawers
5932 (list org-drawer-regexp '(0 'org-special-keyword t))
5933 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5934 ;; Properties
5935 (list org-property-re
5936 '(1 'org-special-keyword t)
5937 '(3 'org-property-value t))
5938 ;; Links
5939 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5940 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5941 (if (memq 'plain lk) '(org-activate-plain-links))
5942 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5943 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5944 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5945 (if (memq 'footnote lk) '(org-activate-footnote-links))
5946 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5947 '(org-hide-wide-columns (0 nil append))
5948 ;; TODO keyword
5949 (list (format org-heading-keyword-regexp-format
5950 org-todo-regexp)
5951 '(2 (org-get-todo-face 2) t))
5952 ;; DONE
5953 (if org-fontify-done-headline
5954 (list (format org-heading-keyword-regexp-format
5955 (concat
5956 "\\(?:"
5957 (mapconcat 'regexp-quote org-done-keywords "\\|")
5958 "\\)"))
5959 '(2 'org-headline-done t))
5960 nil)
5961 ;; Priorities
5962 '(org-font-lock-add-priority-faces)
5963 ;; Tags
5964 '(org-font-lock-add-tag-faces)
5965 ;; Special keywords
5966 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5967 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5968 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5969 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5970 ;; Emphasis
5971 (if em
5972 (if (featurep 'xemacs)
5973 '(org-do-emphasis-faces (0 nil append))
5974 '(org-do-emphasis-faces)))
5975 ;; Checkboxes
5976 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5977 1 'org-checkbox prepend)
5978 (if (cdr (assq 'checkbox org-list-automatic-rules))
5979 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5980 (0 (org-get-checkbox-statistics-face) t)))
5981 ;; Description list items
5982 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5983 1 'org-list-dt prepend)
5984 ;; ARCHIVEd headings
5985 (list (concat
5986 org-outline-regexp-bol
5987 "\\(.*:" org-archive-tag ":.*\\)")
5988 '(1 'org-archived prepend))
5989 ;; Specials
5990 '(org-do-latex-and-special-faces)
5991 '(org-fontify-entities)
5992 '(org-raise-scripts)
5993 ;; Code
5994 '(org-activate-code (1 'org-code t))
5995 ;; COMMENT
5996 (list (format org-heading-keyword-regexp-format
5997 (concat "\\("
5998 org-comment-string "\\|" org-quote-string
5999 "\\)"))
6000 '(2 'org-special-keyword t))
6001 ;; Blocks and meta lines
6002 '(org-fontify-meta-lines-and-blocks)
6004 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6005 (run-hooks 'org-font-lock-set-keywords-hook)
6006 ;; Now set the full font-lock-keywords
6007 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6008 (org-set-local 'font-lock-defaults
6009 '(org-font-lock-keywords t nil nil backward-paragraph))
6010 (kill-local-variable 'font-lock-keywords) nil))
6012 (defun org-toggle-pretty-entities ()
6013 "Toggle the composition display of entities as UTF8 characters."
6014 (interactive)
6015 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6016 (org-restart-font-lock)
6017 (if org-pretty-entities
6018 (message "Entities are displayed as UTF8 characters")
6019 (save-restriction
6020 (widen)
6021 (org-decompose-region (point-min) (point-max))
6022 (message "Entities are displayed plain"))))
6024 (defvar org-custom-properties-overlays nil
6025 "List of overlays used for custom properties.")
6026 (make-variable-buffer-local 'org-custom-properties-overlays)
6028 (defun org-toggle-custom-properties-visibility ()
6029 "Display or hide properties in `org-custom-properties'."
6030 (interactive)
6031 (if org-custom-properties-overlays
6032 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6033 (setq org-custom-properties-overlays nil))
6034 (unless (not org-custom-properties)
6035 (save-excursion
6036 (save-restriction
6037 (widen)
6038 (goto-char (point-min))
6039 (while (re-search-forward org-property-re nil t)
6040 (mapc (lambda(p)
6041 (when (equal p (substring (match-string 1) 1 -1))
6042 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6043 (overlay-put o 'invisible t)
6044 (overlay-put o 'org-custom-property t)
6045 (push o org-custom-properties-overlays))))
6046 org-custom-properties)))))))
6048 (defun org-fontify-entities (limit)
6049 "Find an entity to fontify."
6050 (let (ee)
6051 (when org-pretty-entities
6052 (catch 'match
6053 (while (re-search-forward
6054 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6055 limit t)
6056 (if (and (not (org-in-indented-comment-line))
6057 (setq ee (org-entity-get (match-string 1)))
6058 (= (length (nth 6 ee)) 1))
6059 (let*
6060 ((end (if (equal (match-string 2) "{}")
6061 (match-end 2)
6062 (match-end 1))))
6063 (add-text-properties
6064 (match-beginning 0) end
6065 (list 'font-lock-fontified t))
6066 (compose-region (match-beginning 0) end
6067 (nth 6 ee) nil)
6068 (backward-char 1)
6069 (throw 'match t))))
6070 nil))))
6072 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6073 "Fontify string S like in Org-mode."
6074 (with-temp-buffer
6075 (insert s)
6076 (let ((org-odd-levels-only odd-levels))
6077 (org-mode)
6078 (font-lock-fontify-buffer)
6079 (buffer-string))))
6081 (defvar org-m nil)
6082 (defvar org-l nil)
6083 (defvar org-f nil)
6084 (defun org-get-level-face (n)
6085 "Get the right face for match N in font-lock matching of headlines."
6086 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6087 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6088 (if org-cycle-level-faces
6089 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6090 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6091 (cond
6092 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6093 ((eq n 2) org-f)
6094 (t (if org-level-color-stars-only nil org-f))))
6097 (defun org-get-todo-face (kwd)
6098 "Get the right face for a TODO keyword KWD.
6099 If KWD is a number, get the corresponding match group."
6100 (if (numberp kwd) (setq kwd (match-string kwd)))
6101 (or (org-face-from-face-or-color
6102 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6103 (and (member kwd org-done-keywords) 'org-done)
6104 'org-todo))
6106 (defun org-face-from-face-or-color (context inherit face-or-color)
6107 "Create a face list that inherits INHERIT, but sets the foreground color.
6108 When FACE-OR-COLOR is not a string, just return it."
6109 (if (stringp face-or-color)
6110 (list :inherit inherit
6111 (cdr (assoc context org-faces-easy-properties))
6112 face-or-color)
6113 face-or-color))
6115 (defun org-font-lock-add-tag-faces (limit)
6116 "Add the special tag faces."
6117 (when (and org-tag-faces org-tags-special-faces-re)
6118 (while (re-search-forward org-tags-special-faces-re limit t)
6119 (add-text-properties (match-beginning 1) (match-end 1)
6120 (list 'face (org-get-tag-face 1)
6121 'font-lock-fontified t))
6122 (backward-char 1))))
6124 (defun org-font-lock-add-priority-faces (limit)
6125 "Add the special priority faces."
6126 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6127 (when (save-match-data (org-at-heading-p))
6128 (add-text-properties
6129 (match-beginning 0) (match-end 0)
6130 (list 'face (or (org-face-from-face-or-color
6131 'priority 'org-priority
6132 (cdr (assoc (char-after (match-beginning 1))
6133 org-priority-faces)))
6134 'org-priority)
6135 'font-lock-fontified t)))))
6137 (defun org-get-tag-face (kwd)
6138 "Get the right face for a TODO keyword KWD.
6139 If KWD is a number, get the corresponding match group."
6140 (if (numberp kwd) (setq kwd (match-string kwd)))
6141 (or (org-face-from-face-or-color
6142 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6143 'org-tag))
6145 (defun org-unfontify-region (beg end &optional maybe_loudly)
6146 "Remove fontification and activation overlays from links."
6147 (font-lock-default-unfontify-region beg end)
6148 (let* ((buffer-undo-list t)
6149 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6150 (inhibit-modification-hooks t)
6151 deactivate-mark buffer-file-name buffer-file-truename)
6152 (org-decompose-region beg end)
6153 (remove-text-properties beg end
6154 '(mouse-face t keymap t org-linked-text t
6155 invisible t intangible t
6156 org-no-flyspell t org-emphasis t))
6157 (org-remove-font-lock-display-properties beg end)))
6159 (defconst org-script-display '(((raise -0.3) (height 0.7))
6160 ((raise 0.3) (height 0.7))
6161 ((raise -0.5))
6162 ((raise 0.5)))
6163 "Display properties for showing superscripts and subscripts.")
6165 (defun org-remove-font-lock-display-properties (beg end)
6166 "Remove specific display properties that have been added by font lock.
6167 The will remove the raise properties that are used to show superscripts
6168 and subscripts."
6169 (let (next prop)
6170 (while (< beg end)
6171 (setq next (next-single-property-change beg 'display nil end)
6172 prop (get-text-property beg 'display))
6173 (if (member prop org-script-display)
6174 (put-text-property beg next 'display nil))
6175 (setq beg next))))
6177 (defun org-raise-scripts (limit)
6178 "Add raise properties to sub/superscripts."
6179 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6180 (if (re-search-forward
6181 (if (eq org-use-sub-superscripts t)
6182 org-match-substring-regexp
6183 org-match-substring-with-braces-regexp)
6184 limit t)
6185 (let* ((pos (point)) table-p comment-p
6186 (mpos (match-beginning 3))
6187 (emph-p (get-text-property mpos 'org-emphasis))
6188 (link-p (get-text-property mpos 'mouse-face))
6189 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6190 (goto-char (point-at-bol))
6191 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6192 comment-p (org-looking-at-p "[ \t]*#"))
6193 (goto-char pos)
6194 ;; FIXME: Should we go back one character here, for a_b^c
6195 ;; (goto-char (1- pos)) ;????????????????????
6196 (if (or comment-p emph-p link-p keyw-p)
6198 (put-text-property (match-beginning 3) (match-end 0)
6199 'display
6200 (if (equal (char-after (match-beginning 2)) ?^)
6201 (nth (if table-p 3 1) org-script-display)
6202 (nth (if table-p 2 0) org-script-display)))
6203 (add-text-properties (match-beginning 2) (match-end 2)
6204 (list 'invisible t
6205 'org-dwidth t 'org-dwidth-n 1))
6206 (if (and (eq (char-after (match-beginning 3)) ?{)
6207 (eq (char-before (match-end 3)) ?}))
6208 (progn
6209 (add-text-properties
6210 (match-beginning 3) (1+ (match-beginning 3))
6211 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6212 (add-text-properties
6213 (1- (match-end 3)) (match-end 3)
6214 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6215 t)))))
6217 ;;;; Visibility cycling, including org-goto and indirect buffer
6219 ;;; Cycling
6221 (defvar org-cycle-global-status nil)
6222 (make-variable-buffer-local 'org-cycle-global-status)
6223 (defvar org-cycle-subtree-status nil)
6224 (make-variable-buffer-local 'org-cycle-subtree-status)
6226 (defvar org-inlinetask-min-level)
6228 ;;;###autoload
6229 (defun org-cycle (&optional arg)
6230 "TAB-action and visibility cycling for Org-mode.
6232 This is the command invoked in Org-mode by the TAB key. Its main purpose
6233 is outline visibility cycling, but it also invokes other actions
6234 in special contexts.
6236 - When this function is called with a prefix argument, rotate the entire
6237 buffer through 3 states (global cycling)
6238 1. OVERVIEW: Show only top-level headlines.
6239 2. CONTENTS: Show all headlines of all levels, but no body text.
6240 3. SHOW ALL: Show everything.
6241 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6242 determined by the variable `org-startup-folded', and by any VISIBILITY
6243 properties in the buffer.
6244 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6245 including any drawers.
6247 - When inside a table, re-align the table and move to the next field.
6249 - When point is at the beginning of a headline, rotate the subtree started
6250 by this line through 3 different states (local cycling)
6251 1. FOLDED: Only the main headline is shown.
6252 2. CHILDREN: The main headline and the direct children are shown.
6253 From this state, you can move to one of the children
6254 and zoom in further.
6255 3. SUBTREE: Show the entire subtree, including body text.
6256 If there is no subtree, switch directly from CHILDREN to FOLDED.
6258 - When point is at the beginning of an empty headline and the variable
6259 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6260 of the headline by demoting and promoting it to likely levels. This
6261 speeds up creation document structure by pressing TAB once or several
6262 times right after creating a new headline.
6264 - When there is a numeric prefix, go up to a heading with level ARG, do
6265 a `show-subtree' and return to the previous cursor position. If ARG
6266 is negative, go up that many levels.
6268 - When point is not at the beginning of a headline, execute the global
6269 binding for TAB, which is re-indenting the line. See the option
6270 `org-cycle-emulate-tab' for details.
6272 - Special case: if point is at the beginning of the buffer and there is
6273 no headline in line 1, this function will act as if called with prefix arg
6274 (C-u TAB, same as S-TAB) also when called without prefix arg.
6275 But only if also the variable `org-cycle-global-at-bob' is t."
6276 (interactive "P")
6277 (org-load-modules-maybe)
6278 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6279 (and org-cycle-level-after-item/entry-creation
6280 (or (org-cycle-level)
6281 (org-cycle-item-indentation))))
6282 (let* (message-log-max ; Don't populate the *Messages* buffer
6283 (limit-level
6284 (or org-cycle-max-level
6285 (and (boundp 'org-inlinetask-min-level)
6286 org-inlinetask-min-level
6287 (1- org-inlinetask-min-level))))
6288 (nstars (and limit-level
6289 (if org-odd-levels-only
6290 (and limit-level (1- (* limit-level 2)))
6291 limit-level)))
6292 (org-outline-regexp
6293 (if (not (derived-mode-p 'org-mode))
6294 outline-regexp
6295 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6296 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6297 (not (looking-at org-outline-regexp))))
6298 (org-cycle-hook
6299 (if bob-special
6300 (delq 'org-optimize-window-after-visibility-change
6301 (copy-sequence org-cycle-hook))
6302 org-cycle-hook))
6303 (pos (point)))
6305 (if (or bob-special (equal arg '(4)))
6306 ;; special case: use global cycling
6307 (setq arg t))
6309 (cond
6311 ((equal arg '(16))
6312 (setq last-command 'dummy)
6313 (org-set-startup-visibility)
6314 (message "Startup visibility, plus VISIBILITY properties"))
6316 ((equal arg '(64))
6317 (show-all)
6318 (message "Entire buffer visible, including drawers"))
6320 ;; Table: enter it or move to the next field.
6321 ((org-at-table-p 'any)
6322 (if (org-at-table.el-p)
6323 (message "Use C-c ' to edit table.el tables")
6324 (if arg (org-table-edit-field t)
6325 (org-table-justify-field-maybe)
6326 (call-interactively 'org-table-next-field))))
6328 ((run-hook-with-args-until-success
6329 'org-tab-after-check-for-table-hook))
6331 ;; Global cycling: delegate to `org-cycle-internal-global'.
6332 ((eq arg t) (org-cycle-internal-global))
6334 ;; Drawers: delegate to `org-flag-drawer'.
6335 ((and org-drawers org-drawer-regexp
6336 (save-excursion
6337 (beginning-of-line 1)
6338 (looking-at org-drawer-regexp)))
6339 (org-flag-drawer ; toggle block visibility
6340 (not (get-char-property (match-end 0) 'invisible))))
6342 ;; Show-subtree, ARG levels up from here.
6343 ((integerp arg)
6344 (save-excursion
6345 (org-back-to-heading)
6346 (outline-up-heading (if (< arg 0) (- arg)
6347 (- (funcall outline-level) arg)))
6348 (org-show-subtree)))
6350 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6351 ((and (featurep 'org-inlinetask)
6352 (org-inlinetask-at-task-p)
6353 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6354 (org-inlinetask-toggle-visibility))
6356 ((org-try-cdlatex-tab))
6358 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6359 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6360 (save-excursion (beginning-of-line 1)
6361 (looking-at org-outline-regexp)))
6362 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6363 (org-cycle-internal-local))
6365 ;; From there: TAB emulation and template completion.
6366 (buffer-read-only (org-back-to-heading))
6368 ((run-hook-with-args-until-success
6369 'org-tab-after-check-for-cycling-hook))
6371 ((org-try-structure-completion))
6373 ((run-hook-with-args-until-success
6374 'org-tab-before-tab-emulation-hook))
6376 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6377 (or (not (bolp))
6378 (not (looking-at org-outline-regexp))))
6379 (call-interactively (global-key-binding "\t")))
6381 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6382 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6383 (or (and (eq org-cycle-emulate-tab 'white)
6384 (= (match-end 0) (point-at-eol)))
6385 (and (eq org-cycle-emulate-tab 'whitestart)
6386 (>= (match-end 0) pos))))
6388 (eq org-cycle-emulate-tab t))
6389 (call-interactively (global-key-binding "\t")))
6391 (t (save-excursion
6392 (org-back-to-heading)
6393 (org-cycle)))))))
6395 (defun org-cycle-internal-global ()
6396 "Do the global cycling action."
6397 ;; Hack to avoid display of messages for .org attachments in Gnus
6398 (let (message-log-max ; Don't populate the *Messages* buffer
6399 (ga (string-match "\\*fontification" (buffer-name))))
6400 (cond
6401 ((and (eq last-command this-command)
6402 (eq org-cycle-global-status 'overview))
6403 ;; We just created the overview - now do table of contents
6404 ;; This can be slow in very large buffers, so indicate action
6405 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6406 (unless ga (message "CONTENTS..."))
6407 (org-content)
6408 (unless ga (message "CONTENTS...done"))
6409 (setq org-cycle-global-status 'contents)
6410 (run-hook-with-args 'org-cycle-hook 'contents))
6412 ((and (eq last-command this-command)
6413 (eq org-cycle-global-status 'contents))
6414 ;; We just showed the table of contents - now show everything
6415 (run-hook-with-args 'org-pre-cycle-hook 'all)
6416 (show-all)
6417 (unless ga (message "SHOW ALL"))
6418 (setq org-cycle-global-status 'all)
6419 (run-hook-with-args 'org-cycle-hook 'all))
6422 ;; Default action: go to overview
6423 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6424 (org-overview)
6425 (unless ga (message "OVERVIEW"))
6426 (setq org-cycle-global-status 'overview)
6427 (run-hook-with-args 'org-cycle-hook 'overview)))))
6429 (defun org-cycle-internal-local ()
6430 "Do the local cycling action."
6431 (let (message-log-max ; Don't populate the *Messages* buffer
6432 (goal-column 0) eoh eol eos has-children children-skipped struct)
6433 ;; First, determine end of headline (EOH), end of subtree or item
6434 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6435 (save-excursion
6436 (if (org-at-item-p)
6437 (progn
6438 (beginning-of-line)
6439 (setq struct (org-list-struct))
6440 (setq eoh (point-at-eol))
6441 (setq eos (org-list-get-item-end-before-blank (point) struct))
6442 (setq has-children (org-list-has-child-p (point) struct)))
6443 (org-back-to-heading)
6444 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6445 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6446 (setq has-children
6447 (or (save-excursion
6448 (let ((level (funcall outline-level)))
6449 (outline-next-heading)
6450 (and (org-at-heading-p t)
6451 (> (funcall outline-level) level))))
6452 (save-excursion
6453 (org-list-search-forward (org-item-beginning-re) eos t)))))
6454 ;; Determine end invisible part of buffer (EOL)
6455 (beginning-of-line 2)
6456 ;; XEmacs doesn't have `next-single-char-property-change'
6457 (if (featurep 'xemacs)
6458 (while (and (not (eobp)) ;; this is like `next-line'
6459 (get-char-property (1- (point)) 'invisible))
6460 (beginning-of-line 2))
6461 (while (and (not (eobp)) ;; this is like `next-line'
6462 (get-char-property (1- (point)) 'invisible))
6463 (goto-char (next-single-char-property-change (point) 'invisible))
6464 (and (eolp) (beginning-of-line 2))))
6465 (setq eol (point)))
6466 ;; Find out what to do next and set `this-command'
6467 (cond
6468 ((= eos eoh)
6469 ;; Nothing is hidden behind this heading
6470 (unless (org-before-first-heading-p)
6471 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6472 (message "EMPTY ENTRY")
6473 (setq org-cycle-subtree-status nil)
6474 (save-excursion
6475 (goto-char eos)
6476 (outline-next-heading)
6477 (if (outline-invisible-p) (org-flag-heading nil))))
6478 ((and (or (>= eol eos)
6479 (not (string-match "\\S-" (buffer-substring eol eos))))
6480 (or has-children
6481 (not (setq children-skipped
6482 org-cycle-skip-children-state-if-no-children))))
6483 ;; Entire subtree is hidden in one line: children view
6484 (unless (org-before-first-heading-p)
6485 (run-hook-with-args 'org-pre-cycle-hook 'children))
6486 (if (org-at-item-p)
6487 (org-list-set-item-visibility (point-at-bol) struct 'children)
6488 (org-show-entry)
6489 (org-with-limited-levels (show-children))
6490 ;; FIXME: This slows down the func way too much.
6491 ;; How keep drawers hidden in subtree anyway?
6492 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6493 ;; (org-cycle-hide-drawers 'subtree))
6495 ;; Fold every list in subtree to top-level items.
6496 (when (eq org-cycle-include-plain-lists 'integrate)
6497 (save-excursion
6498 (org-back-to-heading)
6499 (while (org-list-search-forward (org-item-beginning-re) eos t)
6500 (beginning-of-line 1)
6501 (let* ((struct (org-list-struct))
6502 (prevs (org-list-prevs-alist struct))
6503 (end (org-list-get-bottom-point struct)))
6504 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6505 (org-list-get-all-items (point) struct prevs))
6506 (goto-char end))))))
6507 (message "CHILDREN")
6508 (save-excursion
6509 (goto-char eos)
6510 (outline-next-heading)
6511 (if (outline-invisible-p) (org-flag-heading nil)))
6512 (setq org-cycle-subtree-status 'children)
6513 (unless (org-before-first-heading-p)
6514 (run-hook-with-args 'org-cycle-hook 'children)))
6515 ((or children-skipped
6516 (and (eq last-command this-command)
6517 (eq org-cycle-subtree-status 'children)))
6518 ;; We just showed the children, or no children are there,
6519 ;; now show everything.
6520 (unless (org-before-first-heading-p)
6521 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6522 (outline-flag-region eoh eos nil)
6523 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6524 (setq org-cycle-subtree-status 'subtree)
6525 (unless (org-before-first-heading-p)
6526 (run-hook-with-args 'org-cycle-hook 'subtree)))
6528 ;; Default action: hide the subtree.
6529 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6530 (outline-flag-region eoh eos t)
6531 (message "FOLDED")
6532 (setq org-cycle-subtree-status 'folded)
6533 (unless (org-before-first-heading-p)
6534 (run-hook-with-args 'org-cycle-hook 'folded))))))
6536 ;;;###autoload
6537 (defun org-global-cycle (&optional arg)
6538 "Cycle the global visibility. For details see `org-cycle'.
6539 With \\[universal-argument] prefix arg, switch to startup visibility.
6540 With a numeric prefix, show all headlines up to that level."
6541 (interactive "P")
6542 (let ((org-cycle-include-plain-lists
6543 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6544 (cond
6545 ((integerp arg)
6546 (show-all)
6547 (hide-sublevels arg)
6548 (setq org-cycle-global-status 'contents))
6549 ((equal arg '(4))
6550 (org-set-startup-visibility)
6551 (message "Startup visibility, plus VISIBILITY properties."))
6553 (org-cycle '(4))))))
6555 (defun org-set-startup-visibility ()
6556 "Set the visibility required by startup options and properties."
6557 (cond
6558 ((eq org-startup-folded t)
6559 (org-cycle '(4)))
6560 ((eq org-startup-folded 'content)
6561 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6562 (org-cycle '(4)) (org-cycle '(4)))))
6563 (unless (eq org-startup-folded 'showeverything)
6564 (if org-hide-block-startup (org-hide-block-all))
6565 (org-set-visibility-according-to-property 'no-cleanup)
6566 (org-cycle-hide-archived-subtrees 'all)
6567 (org-cycle-hide-drawers 'all)
6568 (org-cycle-show-empty-lines t)))
6570 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6571 "Switch subtree visibilities according to :VISIBILITY: property."
6572 (interactive)
6573 (let (org-show-entry-below state)
6574 (save-excursion
6575 (goto-char (point-min))
6576 (while (re-search-forward
6577 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6578 nil t)
6579 (setq state (match-string 1))
6580 (save-excursion
6581 (org-back-to-heading t)
6582 (hide-subtree)
6583 (org-reveal)
6584 (cond
6585 ((equal state '("fold" "folded"))
6586 (hide-subtree))
6587 ((equal state "children")
6588 (org-show-hidden-entry)
6589 (show-children))
6590 ((equal state "content")
6591 (save-excursion
6592 (save-restriction
6593 (org-narrow-to-subtree)
6594 (org-content))))
6595 ((member state '("all" "showall"))
6596 (show-subtree)))))
6597 (unless no-cleanup
6598 (org-cycle-hide-archived-subtrees 'all)
6599 (org-cycle-hide-drawers 'all)
6600 (org-cycle-show-empty-lines 'all)))))
6602 ;; This function uses outline-regexp instead of the more fundamental
6603 ;; org-outline-regexp so that org-cycle-global works outside of Org
6604 ;; buffers, where outline-regexp is needed.
6605 (defun org-overview ()
6606 "Switch to overview mode, showing only top-level headlines.
6607 Really, this shows all headlines with level equal or greater than the level
6608 of the first headline in the buffer. This is important, because if the
6609 first headline is not level one, then (hide-sublevels 1) gives confusing
6610 results."
6611 (interactive)
6612 (let ((level (save-excursion
6613 (goto-char (point-min))
6614 (if (re-search-forward (concat "^" outline-regexp) nil t)
6615 (progn
6616 (goto-char (match-beginning 0))
6617 (funcall outline-level))))))
6618 (and level (hide-sublevels level))))
6620 (defun org-content (&optional arg)
6621 "Show all headlines in the buffer, like a table of contents.
6622 With numerical argument N, show content up to level N."
6623 (interactive "P")
6624 (save-excursion
6625 ;; Visit all headings and show their offspring
6626 (and (integerp arg) (org-overview))
6627 (goto-char (point-max))
6628 (catch 'exit
6629 (while (and (progn (condition-case nil
6630 (outline-previous-visible-heading 1)
6631 (error (goto-char (point-min))))
6633 (looking-at org-outline-regexp))
6634 (if (integerp arg)
6635 (show-children (1- arg))
6636 (show-branches))
6637 (if (bobp) (throw 'exit nil))))))
6640 (defun org-optimize-window-after-visibility-change (state)
6641 "Adjust the window after a change in outline visibility.
6642 This function is the default value of the hook `org-cycle-hook'."
6643 (when (get-buffer-window (current-buffer))
6644 (cond
6645 ((eq state 'content) nil)
6646 ((eq state 'all) nil)
6647 ((eq state 'folded) nil)
6648 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6649 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6651 (defun org-remove-empty-overlays-at (pos)
6652 "Remove outline overlays that do not contain non-white stuff."
6653 (mapc
6654 (lambda (o)
6655 (and (eq 'outline (overlay-get o 'invisible))
6656 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6657 (overlay-end o))))
6658 (delete-overlay o)))
6659 (overlays-at pos)))
6661 (defun org-clean-visibility-after-subtree-move ()
6662 "Fix visibility issues after moving a subtree."
6663 ;; First, find a reasonable region to look at:
6664 ;; Start two siblings above, end three below
6665 (let* ((beg (save-excursion
6666 (and (org-get-last-sibling)
6667 (org-get-last-sibling))
6668 (point)))
6669 (end (save-excursion
6670 (and (org-get-next-sibling)
6671 (org-get-next-sibling)
6672 (org-get-next-sibling))
6673 (if (org-at-heading-p)
6674 (point-at-eol)
6675 (point))))
6676 (level (looking-at "\\*+"))
6677 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6678 (save-excursion
6679 (save-restriction
6680 (narrow-to-region beg end)
6681 (when re
6682 ;; Properly fold already folded siblings
6683 (goto-char (point-min))
6684 (while (re-search-forward re nil t)
6685 (if (and (not (outline-invisible-p))
6686 (save-excursion
6687 (goto-char (point-at-eol)) (outline-invisible-p)))
6688 (hide-entry))))
6689 (org-cycle-show-empty-lines 'overview)
6690 (org-cycle-hide-drawers 'overview)))))
6692 (defun org-cycle-show-empty-lines (state)
6693 "Show empty lines above all visible headlines.
6694 The region to be covered depends on STATE when called through
6695 `org-cycle-hook'. Lisp program can use t for STATE to get the
6696 entire buffer covered. Note that an empty line is only shown if there
6697 are at least `org-cycle-separator-lines' empty lines before the headline."
6698 (when (not (= org-cycle-separator-lines 0))
6699 (save-excursion
6700 (let* ((n (abs org-cycle-separator-lines))
6701 (re (cond
6702 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6703 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6704 (t (let ((ns (number-to-string (- n 2))))
6705 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6706 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6707 beg end b e)
6708 (cond
6709 ((memq state '(overview contents t))
6710 (setq beg (point-min) end (point-max)))
6711 ((memq state '(children folded))
6712 (setq beg (point) end (progn (org-end-of-subtree t t)
6713 (beginning-of-line 2)
6714 (point)))))
6715 (when beg
6716 (goto-char beg)
6717 (while (re-search-forward re end t)
6718 (unless (get-char-property (match-end 1) 'invisible)
6719 (setq e (match-end 1))
6720 (if (< org-cycle-separator-lines 0)
6721 (setq b (save-excursion
6722 (goto-char (match-beginning 0))
6723 (org-back-over-empty-lines)
6724 (if (save-excursion
6725 (goto-char (max (point-min) (1- (point))))
6726 (org-at-heading-p))
6727 (1- (point))
6728 (point))))
6729 (setq b (match-beginning 1)))
6730 (outline-flag-region b e nil)))))))
6731 ;; Never hide empty lines at the end of the file.
6732 (save-excursion
6733 (goto-char (point-max))
6734 (outline-previous-heading)
6735 (outline-end-of-heading)
6736 (if (and (looking-at "[ \t\n]+")
6737 (= (match-end 0) (point-max)))
6738 (outline-flag-region (point) (match-end 0) nil))))
6740 (defun org-show-empty-lines-in-parent ()
6741 "Move to the parent and re-show empty lines before visible headlines."
6742 (save-excursion
6743 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6744 (org-cycle-show-empty-lines context))))
6746 (defun org-files-list ()
6747 "Return `org-agenda-files' list, plus all open org-mode files.
6748 This is useful for operations that need to scan all of a user's
6749 open and agenda-wise Org files."
6750 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6751 (dolist (buf (buffer-list))
6752 (with-current-buffer buf
6753 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6754 (let ((file (expand-file-name (buffer-file-name))))
6755 (unless (member file files)
6756 (push file files))))))
6757 files))
6759 (defsubst org-entry-beginning-position ()
6760 "Return the beginning position of the current entry."
6761 (save-excursion (outline-back-to-heading t) (point)))
6763 (defsubst org-entry-end-position ()
6764 "Return the end position of the current entry."
6765 (save-excursion (outline-next-heading) (point)))
6767 (defun org-cycle-hide-drawers (state)
6768 "Re-hide all drawers after a visibility state change."
6769 (when (and (derived-mode-p 'org-mode)
6770 (not (memq state '(overview folded contents))))
6771 (save-excursion
6772 (let* ((globalp (memq state '(contents all)))
6773 (beg (if globalp (point-min) (point)))
6774 (end (if globalp (point-max)
6775 (if (eq state 'children)
6776 (save-excursion (outline-next-heading) (point))
6777 (org-end-of-subtree t)))))
6778 (goto-char beg)
6779 (while (re-search-forward org-drawer-regexp end t)
6780 (org-flag-drawer t))))))
6782 (defun org-cycle-hide-inline-tasks (state)
6783 "Re-hide inline task when switching to 'contents visibility state."
6784 (when (and (eq state 'contents)
6785 (boundp 'org-inlinetask-min-level)
6786 org-inlinetask-min-level)
6787 (hide-sublevels (1- org-inlinetask-min-level))))
6789 (defun org-flag-drawer (flag)
6790 "When FLAG is non-nil, hide the drawer we are within.
6791 Otherwise make it visible."
6792 (save-excursion
6793 (beginning-of-line 1)
6794 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6795 (let ((b (match-end 0)))
6796 (if (re-search-forward
6797 "^[ \t]*:END:"
6798 (save-excursion (outline-next-heading) (point)) t)
6799 (outline-flag-region b (point-at-eol) flag)
6800 (error ":END: line missing at position %s" b))))))
6802 (defun org-subtree-end-visible-p ()
6803 "Is the end of the current subtree visible?"
6804 (pos-visible-in-window-p
6805 (save-excursion (org-end-of-subtree t) (point))))
6807 (defun org-first-headline-recenter (&optional N)
6808 "Move cursor to the first headline and recenter the headline.
6809 Optional argument N means put the headline into the Nth line of the window."
6810 (goto-char (point-min))
6811 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6812 (beginning-of-line)
6813 (recenter (prefix-numeric-value N))))
6815 ;;; Saving and restoring visibility
6817 (defun org-outline-overlay-data (&optional use-markers)
6818 "Return a list of the locations of all outline overlays.
6819 These are overlays with the `invisible' property value `outline'.
6820 The return value is a list of cons cells, with start and stop
6821 positions for each overlay.
6822 If USE-MARKERS is set, return the positions as markers."
6823 (let (beg end)
6824 (save-excursion
6825 (save-restriction
6826 (widen)
6827 (delq nil
6828 (mapcar (lambda (o)
6829 (when (eq (overlay-get o 'invisible) 'outline)
6830 (setq beg (overlay-start o)
6831 end (overlay-end o))
6832 (and beg end (> end beg)
6833 (if use-markers
6834 (cons (move-marker (make-marker) beg)
6835 (move-marker (make-marker) end))
6836 (cons beg end)))))
6837 (overlays-in (point-min) (point-max))))))))
6839 (defun org-set-outline-overlay-data (data)
6840 "Create visibility overlays for all positions in DATA.
6841 DATA should have been made by `org-outline-overlay-data'."
6842 (let (o)
6843 (save-excursion
6844 (save-restriction
6845 (widen)
6846 (show-all)
6847 (mapc (lambda (c)
6848 (outline-flag-region (car c) (cdr c) t))
6849 data)))))
6851 ;;; Folding of blocks
6853 (defvar org-hide-block-overlays nil
6854 "Overlays hiding blocks.")
6855 (make-variable-buffer-local 'org-hide-block-overlays)
6857 (defun org-block-map (function &optional start end)
6858 "Call FUNCTION at the head of all source blocks in the current buffer.
6859 Optional arguments START and END can be used to limit the range."
6860 (let ((start (or start (point-min)))
6861 (end (or end (point-max))))
6862 (save-excursion
6863 (goto-char start)
6864 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6865 (save-excursion
6866 (save-match-data
6867 (goto-char (match-beginning 0))
6868 (funcall function)))))))
6870 (defun org-hide-block-toggle-all ()
6871 "Toggle the visibility of all blocks in the current buffer."
6872 (org-block-map #'org-hide-block-toggle))
6874 (defun org-hide-block-all ()
6875 "Fold all blocks in the current buffer."
6876 (interactive)
6877 (org-show-block-all)
6878 (org-block-map #'org-hide-block-toggle-maybe))
6880 (defun org-show-block-all ()
6881 "Unfold all blocks in the current buffer."
6882 (interactive)
6883 (mapc 'delete-overlay org-hide-block-overlays)
6884 (setq org-hide-block-overlays nil))
6886 (defun org-hide-block-toggle-maybe ()
6887 "Toggle visibility of block at point."
6888 (interactive)
6889 (let ((case-fold-search t))
6890 (if (save-excursion
6891 (beginning-of-line 1)
6892 (looking-at org-block-regexp))
6893 (progn (org-hide-block-toggle)
6894 t) ;; to signal that we took action
6895 nil))) ;; to signal that we did not
6897 (defun org-hide-block-toggle (&optional force)
6898 "Toggle the visibility of the current block."
6899 (interactive)
6900 (save-excursion
6901 (beginning-of-line)
6902 (if (re-search-forward org-block-regexp nil t)
6903 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6904 (end (match-end 0)) ;; end of entire body
6906 (if (memq t (mapcar (lambda (overlay)
6907 (eq (overlay-get overlay 'invisible)
6908 'org-hide-block))
6909 (overlays-at start)))
6910 (if (or (not force) (eq force 'off))
6911 (mapc (lambda (ov)
6912 (when (member ov org-hide-block-overlays)
6913 (setq org-hide-block-overlays
6914 (delq ov org-hide-block-overlays)))
6915 (when (eq (overlay-get ov 'invisible)
6916 'org-hide-block)
6917 (delete-overlay ov)))
6918 (overlays-at start)))
6919 (setq ov (make-overlay start end))
6920 (overlay-put ov 'invisible 'org-hide-block)
6921 ;; make the block accessible to isearch
6922 (overlay-put
6923 ov 'isearch-open-invisible
6924 (lambda (ov)
6925 (when (member ov org-hide-block-overlays)
6926 (setq org-hide-block-overlays
6927 (delq ov org-hide-block-overlays)))
6928 (when (eq (overlay-get ov 'invisible)
6929 'org-hide-block)
6930 (delete-overlay ov))))
6931 (push ov org-hide-block-overlays)))
6932 (error "Not looking at a source block"))))
6934 ;; org-tab-after-check-for-cycling-hook
6935 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6936 ;; Remove overlays when changing major mode
6937 (add-hook 'org-mode-hook
6938 (lambda () (org-add-hook 'change-major-mode-hook
6939 'org-show-block-all 'append 'local)))
6941 ;;; Org-goto
6943 (defvar org-goto-window-configuration nil)
6944 (defvar org-goto-marker nil)
6945 (defvar org-goto-map)
6946 (defun org-goto-map ()
6947 "Set the keymap `org-goto'."
6948 (setq org-goto-map
6949 (let ((map (make-sparse-keymap)))
6950 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6951 mouse-drag-region universal-argument org-occur))
6952 cmd)
6953 (while (setq cmd (pop cmds))
6954 (substitute-key-definition cmd cmd map global-map)))
6955 (suppress-keymap map)
6956 (org-defkey map "\C-m" 'org-goto-ret)
6957 (org-defkey map [(return)] 'org-goto-ret)
6958 (org-defkey map [(left)] 'org-goto-left)
6959 (org-defkey map [(right)] 'org-goto-right)
6960 (org-defkey map [(control ?g)] 'org-goto-quit)
6961 (org-defkey map "\C-i" 'org-cycle)
6962 (org-defkey map [(tab)] 'org-cycle)
6963 (org-defkey map [(down)] 'outline-next-visible-heading)
6964 (org-defkey map [(up)] 'outline-previous-visible-heading)
6965 (if org-goto-auto-isearch
6966 (if (fboundp 'define-key-after)
6967 (define-key-after map [t] 'org-goto-local-auto-isearch)
6968 nil)
6969 (org-defkey map "q" 'org-goto-quit)
6970 (org-defkey map "n" 'outline-next-visible-heading)
6971 (org-defkey map "p" 'outline-previous-visible-heading)
6972 (org-defkey map "f" 'outline-forward-same-level)
6973 (org-defkey map "b" 'outline-backward-same-level)
6974 (org-defkey map "u" 'outline-up-heading))
6975 (org-defkey map "/" 'org-occur)
6976 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6977 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6978 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6979 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6980 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6981 map)))
6983 (defconst org-goto-help
6984 "Browse buffer copy, to find location or copy text.%s
6985 RET=jump to location C-g=quit and return to previous location
6986 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6988 (defvar org-goto-start-pos) ; dynamically scoped parameter
6990 ;; FIXME: Docstring does not mention both interfaces
6991 (defun org-goto (&optional alternative-interface)
6992 "Look up a different location in the current file, keeping current visibility.
6994 When you want look-up or go to a different location in a
6995 document, the fastest way is often to fold the entire buffer and
6996 then dive into the tree. This method has the disadvantage, that
6997 the previous location will be folded, which may not be what you
6998 want.
7000 This command works around this by showing a copy of the current
7001 buffer in an indirect buffer, in overview mode. You can dive
7002 into the tree in that copy, use org-occur and incremental search
7003 to find a location. When pressing RET or `Q', the command
7004 returns to the original buffer in which the visibility is still
7005 unchanged. After RET it will also jump to the location selected
7006 in the indirect buffer and expose the headline hierarchy above.
7008 With a prefix argument, use the alternative interface: e.g. if
7009 `org-goto-interface' is 'outline use 'outline-path-completion."
7010 (interactive "P")
7011 (org-goto-map)
7012 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7013 (org-refile-use-outline-path t)
7014 (org-refile-target-verify-function nil)
7015 (interface
7016 (if (not alternative-interface)
7017 org-goto-interface
7018 (if (eq org-goto-interface 'outline)
7019 'outline-path-completion
7020 'outline)))
7021 (org-goto-start-pos (point))
7022 (selected-point
7023 (if (eq interface 'outline)
7024 (car (org-get-location (current-buffer) org-goto-help))
7025 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7026 (org-refile-check-position pa)
7027 (nth 3 pa)))))
7028 (if selected-point
7029 (progn
7030 (org-mark-ring-push org-goto-start-pos)
7031 (goto-char selected-point)
7032 (if (or (outline-invisible-p) (org-invisible-p2))
7033 (org-show-context 'org-goto)))
7034 (message "Quit"))))
7036 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7037 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7038 (defvar org-goto-local-auto-isearch-map) ; defined below
7040 (defun org-get-location (buf help)
7041 "Let the user select a location in the Org-mode buffer BUF.
7042 This function uses a recursive edit. It returns the selected position
7043 or nil."
7044 (org-no-popups
7045 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7046 (isearch-hide-immediately nil)
7047 (isearch-search-fun-function
7048 (lambda () 'org-goto-local-search-headings))
7049 (org-goto-selected-point org-goto-exit-command))
7050 (save-excursion
7051 (save-window-excursion
7052 (delete-other-windows)
7053 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7054 (org-pop-to-buffer-same-window
7055 (condition-case nil
7056 (make-indirect-buffer (current-buffer) "*org-goto*")
7057 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7058 (with-output-to-temp-buffer "*Org Help*"
7059 (princ (format help (if org-goto-auto-isearch
7060 " Just type for auto-isearch."
7061 " n/p/f/b/u to navigate, q to quit."))))
7062 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7063 (setq buffer-read-only nil)
7064 (let ((org-startup-truncated t)
7065 (org-startup-folded nil)
7066 (org-startup-align-all-tables nil))
7067 (org-mode)
7068 (org-overview))
7069 (setq buffer-read-only t)
7070 (if (and (boundp 'org-goto-start-pos)
7071 (integer-or-marker-p org-goto-start-pos))
7072 (let ((org-show-hierarchy-above t)
7073 (org-show-siblings t)
7074 (org-show-following-heading t))
7075 (goto-char org-goto-start-pos)
7076 (and (outline-invisible-p) (org-show-context)))
7077 (goto-char (point-min)))
7078 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7079 (message "Select location and press RET")
7080 (use-local-map org-goto-map)
7081 (recursive-edit)))
7082 (kill-buffer "*org-goto*")
7083 (cons org-goto-selected-point org-goto-exit-command))))
7085 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7086 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7087 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7088 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7090 (defun org-goto-local-search-headings (string bound noerror)
7091 "Search and make sure that any matches are in headlines."
7092 (catch 'return
7093 (while (if isearch-forward
7094 (search-forward string bound noerror)
7095 (search-backward string bound noerror))
7096 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7097 (and (member :headline context)
7098 (not (member :tags context))))
7099 (throw 'return (point))))))
7101 (defun org-goto-local-auto-isearch ()
7102 "Start isearch."
7103 (interactive)
7104 (goto-char (point-min))
7105 (let ((keys (this-command-keys)))
7106 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7107 (isearch-mode t)
7108 (isearch-process-search-char (string-to-char keys)))))
7110 (defun org-goto-ret (&optional arg)
7111 "Finish `org-goto' by going to the new location."
7112 (interactive "P")
7113 (setq org-goto-selected-point (point)
7114 org-goto-exit-command 'return)
7115 (throw 'exit nil))
7117 (defun org-goto-left ()
7118 "Finish `org-goto' by going to the new location."
7119 (interactive)
7120 (if (org-at-heading-p)
7121 (progn
7122 (beginning-of-line 1)
7123 (setq org-goto-selected-point (point)
7124 org-goto-exit-command 'left)
7125 (throw 'exit nil))
7126 (error "Not on a heading")))
7128 (defun org-goto-right ()
7129 "Finish `org-goto' by going to the new location."
7130 (interactive)
7131 (if (org-at-heading-p)
7132 (progn
7133 (setq org-goto-selected-point (point)
7134 org-goto-exit-command 'right)
7135 (throw 'exit nil))
7136 (error "Not on a heading")))
7138 (defun org-goto-quit ()
7139 "Finish `org-goto' without cursor motion."
7140 (interactive)
7141 (setq org-goto-selected-point nil)
7142 (setq org-goto-exit-command 'quit)
7143 (throw 'exit nil))
7145 ;;; Indirect buffer display of subtrees
7147 (defvar org-indirect-dedicated-frame nil
7148 "This is the frame being used for indirect tree display.")
7149 (defvar org-last-indirect-buffer nil)
7151 (defun org-tree-to-indirect-buffer (&optional arg)
7152 "Create indirect buffer and narrow it to current subtree.
7153 With a numerical prefix ARG, go up to this level and then take that tree.
7154 If ARG is negative, go up that many levels.
7156 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7157 indirect buffer previously made with this command, to avoid proliferation of
7158 indirect buffers. However, when you call the command with a \
7159 \\[universal-argument] prefix, or
7160 when `org-indirect-buffer-display' is `new-frame', the last buffer
7161 is kept so that you can work with several indirect buffers at the same time.
7162 If `org-indirect-buffer-display' is `dedicated-frame', the \
7163 \\[universal-argument] prefix also
7164 requests that a new frame be made for the new buffer, so that the dedicated
7165 frame is not changed."
7166 (interactive "P")
7167 (let ((cbuf (current-buffer))
7168 (cwin (selected-window))
7169 (pos (point))
7170 beg end level heading ibuf)
7171 (save-excursion
7172 (org-back-to-heading t)
7173 (when (numberp arg)
7174 (setq level (org-outline-level))
7175 (if (< arg 0) (setq arg (+ level arg)))
7176 (while (> (setq level (org-outline-level)) arg)
7177 (org-up-heading-safe)))
7178 (setq beg (point)
7179 heading (org-get-heading))
7180 (org-end-of-subtree t t)
7181 (if (org-at-heading-p) (backward-char 1))
7182 (setq end (point)))
7183 (if (and (buffer-live-p org-last-indirect-buffer)
7184 (not (eq org-indirect-buffer-display 'new-frame))
7185 (not arg))
7186 (kill-buffer org-last-indirect-buffer))
7187 (setq ibuf (org-get-indirect-buffer cbuf)
7188 org-last-indirect-buffer ibuf)
7189 (cond
7190 ((or (eq org-indirect-buffer-display 'new-frame)
7191 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7192 (select-frame (make-frame))
7193 (delete-other-windows)
7194 (org-pop-to-buffer-same-window ibuf)
7195 (org-set-frame-title heading))
7196 ((eq org-indirect-buffer-display 'dedicated-frame)
7197 (raise-frame
7198 (select-frame (or (and org-indirect-dedicated-frame
7199 (frame-live-p org-indirect-dedicated-frame)
7200 org-indirect-dedicated-frame)
7201 (setq org-indirect-dedicated-frame (make-frame)))))
7202 (delete-other-windows)
7203 (org-pop-to-buffer-same-window ibuf)
7204 (org-set-frame-title (concat "Indirect: " heading)))
7205 ((eq org-indirect-buffer-display 'current-window)
7206 (org-pop-to-buffer-same-window ibuf))
7207 ((eq org-indirect-buffer-display 'other-window)
7208 (pop-to-buffer ibuf))
7209 (t (error "Invalid value")))
7210 (if (featurep 'xemacs)
7211 (save-excursion (org-mode) (turn-on-font-lock)))
7212 (narrow-to-region beg end)
7213 (show-all)
7214 (goto-char pos)
7215 (run-hook-with-args 'org-cycle-hook 'all)
7216 (and (window-live-p cwin) (select-window cwin))))
7218 (defun org-get-indirect-buffer (&optional buffer)
7219 (setq buffer (or buffer (current-buffer)))
7220 (let ((n 1) (base (buffer-name buffer)) bname)
7221 (while (buffer-live-p
7222 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7223 (setq n (1+ n)))
7224 (condition-case nil
7225 (make-indirect-buffer buffer bname 'clone)
7226 (error (make-indirect-buffer buffer bname)))))
7228 (defun org-set-frame-title (title)
7229 "Set the title of the current frame to the string TITLE."
7230 ;; FIXME: how to name a single frame in XEmacs???
7231 (unless (featurep 'xemacs)
7232 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7234 ;;;; Structure editing
7236 ;;; Inserting headlines
7238 (defun org-previous-line-empty-p ()
7239 (save-excursion
7240 (and (not (bobp))
7241 (or (beginning-of-line 0) t)
7242 (save-match-data
7243 (looking-at "[ \t]*$")))))
7245 (defun org-insert-heading (&optional force-heading invisible-ok)
7246 "Insert a new heading or item with same depth at point.
7247 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7248 If point is at the beginning of a headline, insert a sibling before the
7249 current headline. If point is not at the beginning, split the line,
7250 create the new headline with the text in the current line after point
7251 \(but see also the variable `org-M-RET-may-split-line').
7253 With a double prefix arg, force the heading to be inserted at the
7254 end of the parent subtree.
7256 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7257 This is important for non-interactive uses of the command."
7258 (interactive "P")
7259 (if (or (= (buffer-size) 0)
7260 (and (not (save-excursion
7261 (and (ignore-errors (org-back-to-heading invisible-ok))
7262 (org-at-heading-p))))
7263 (or force-heading (not (org-in-item-p)))))
7264 (progn
7265 (insert "\n* ")
7266 (run-hooks 'org-insert-heading-hook))
7267 (when (or force-heading (not (org-insert-item)))
7268 (let* ((empty-line-p nil)
7269 (level nil)
7270 (on-heading (org-at-heading-p))
7271 (head (save-excursion
7272 (condition-case nil
7273 (progn
7274 (org-back-to-heading invisible-ok)
7275 (when (and (not on-heading)
7276 (featurep 'org-inlinetask)
7277 (integerp org-inlinetask-min-level)
7278 (>= (length (match-string 0))
7279 org-inlinetask-min-level))
7280 ;; Find a heading level before the inline task
7281 (while (and (setq level (org-up-heading-safe))
7282 (>= level org-inlinetask-min-level)))
7283 (if (org-at-heading-p)
7284 (org-back-to-heading invisible-ok)
7285 (error "This should not happen")))
7286 (setq empty-line-p (org-previous-line-empty-p))
7287 (match-string 0))
7288 (error "*"))))
7289 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7290 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7291 pos hide-previous previous-pos)
7292 (cond
7293 ((and (org-at-heading-p) (bolp)
7294 (or (bobp)
7295 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7296 ;; insert before the current line
7297 (open-line (if blank 2 1)))
7298 ((and (bolp)
7299 (not org-insert-heading-respect-content)
7300 (or (bobp)
7301 (save-excursion
7302 (backward-char 1) (not (outline-invisible-p)))))
7303 ;; insert right here
7304 nil)
7306 ;; somewhere in the line
7307 (save-excursion
7308 (setq previous-pos (point-at-bol))
7309 (end-of-line)
7310 (setq hide-previous (outline-invisible-p)))
7311 (and org-insert-heading-respect-content (org-show-subtree))
7312 (let ((split
7313 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7314 (save-excursion
7315 (let ((p (point)))
7316 (goto-char (point-at-bol))
7317 (and (looking-at org-complex-heading-regexp)
7318 (match-beginning 4)
7319 (> p (match-beginning 4)))))))
7320 tags pos)
7321 (cond
7322 (org-insert-heading-respect-content
7323 (if (not (equal force-heading '(16)))
7324 (org-end-of-subtree nil t)
7325 (org-up-heading-safe)
7326 (org-end-of-subtree nil t))
7327 (when (featurep 'org-inlinetask)
7328 (while (and (not (eobp))
7329 (looking-at "\\(\\*+\\)[ \t]+")
7330 (>= (length (match-string 1))
7331 org-inlinetask-min-level))
7332 (org-end-of-subtree nil t)))
7333 (or (bolp) (newline))
7334 (or (org-previous-line-empty-p)
7335 (and blank (newline)))
7336 (open-line 1))
7337 ((org-at-heading-p)
7338 (when hide-previous
7339 (show-children)
7340 (org-show-entry))
7341 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7342 (setq tags (and (match-end 2) (match-string 2)))
7343 (and (match-end 1)
7344 (delete-region (match-beginning 1) (match-end 1)))
7345 (setq pos (point-at-bol))
7346 (or split (end-of-line 1))
7347 (delete-horizontal-space)
7348 (if (string-match "\\`\\*+\\'"
7349 (buffer-substring (point-at-bol) (point)))
7350 (insert " "))
7351 (newline (if blank 2 1))
7352 (when tags
7353 (save-excursion
7354 (goto-char pos)
7355 (end-of-line 1)
7356 (insert " " tags)
7357 (org-set-tags nil 'align))))
7359 (or split (end-of-line 1))
7360 (newline (if blank 2 1)))))))
7361 (insert head) (just-one-space)
7362 (setq pos (point))
7363 (end-of-line 1)
7364 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7365 (when (and org-insert-heading-respect-content hide-previous)
7366 (save-excursion
7367 (goto-char previous-pos)
7368 (hide-subtree)))
7369 (run-hooks 'org-insert-heading-hook)))))
7371 (defun org-get-heading (&optional no-tags no-todo)
7372 "Return the heading of the current entry, without the stars.
7373 When NO-TAGS is non-nil, don't include tags.
7374 When NO-TODO is non-nil, don't include TODO keywords."
7375 (save-excursion
7376 (org-back-to-heading t)
7377 (cond
7378 ((and no-tags no-todo)
7379 (looking-at org-complex-heading-regexp)
7380 (match-string 4))
7381 (no-tags
7382 (looking-at (concat org-outline-regexp
7383 "\\(.*?\\)"
7384 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7385 (match-string 1))
7386 (no-todo
7387 (looking-at org-todo-line-regexp)
7388 (match-string 3))
7389 (t (looking-at org-heading-regexp)
7390 (match-string 2)))))
7392 (defun org-heading-components ()
7393 "Return the components of the current heading.
7394 This is a list with the following elements:
7395 - the level as an integer
7396 - the reduced level, different if `org-odd-levels-only' is set.
7397 - the TODO keyword, or nil
7398 - the priority character, like ?A, or nil if no priority is given
7399 - the headline text itself, or the tags string if no headline text
7400 - the tags string, or nil."
7401 (save-excursion
7402 (org-back-to-heading t)
7403 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7404 (list (length (match-string 1))
7405 (org-reduced-level (length (match-string 1)))
7406 (org-match-string-no-properties 2)
7407 (and (match-end 3) (aref (match-string 3) 2))
7408 (org-match-string-no-properties 4)
7409 (org-match-string-no-properties 5)))))
7411 (defun org-get-entry ()
7412 "Get the entry text, after heading, entire subtree."
7413 (save-excursion
7414 (org-back-to-heading t)
7415 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7417 (defun org-insert-heading-after-current ()
7418 "Insert a new heading with same level as current, after current subtree."
7419 (interactive)
7420 (org-back-to-heading)
7421 (org-insert-heading)
7422 (org-move-subtree-down)
7423 (end-of-line 1))
7425 (defun org-insert-heading-respect-content ()
7426 (interactive)
7427 (let ((org-insert-heading-respect-content t))
7428 (org-insert-heading t)))
7430 (defun org-insert-todo-heading-respect-content (&optional force-state)
7431 (interactive "P")
7432 (let ((org-insert-heading-respect-content t))
7433 (org-insert-todo-heading force-state t)))
7435 (defun org-insert-todo-heading (arg &optional force-heading)
7436 "Insert a new heading with the same level and TODO state as current heading.
7437 If the heading has no TODO state, or if the state is DONE, use the first
7438 state (TODO by default). Also one prefix arg, force first state. With two
7439 prefix args, force inserting at the end of the parent subtree."
7440 (interactive "P")
7441 (when (or force-heading (not (org-insert-item 'checkbox)))
7442 (org-insert-heading (or (and (equal arg '(16)) '(16))
7443 force-heading))
7444 (save-excursion
7445 (org-back-to-heading)
7446 (outline-previous-heading)
7447 (looking-at org-todo-line-regexp))
7448 (let*
7449 ((new-mark-x
7450 (if (or arg
7451 (not (match-beginning 2))
7452 (member (match-string 2) org-done-keywords))
7453 (car org-todo-keywords-1)
7454 (match-string 2)))
7455 (new-mark
7457 (run-hook-with-args-until-success
7458 'org-todo-get-default-hook new-mark-x nil)
7459 new-mark-x)))
7460 (beginning-of-line 1)
7461 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7462 (if org-treat-insert-todo-heading-as-state-change
7463 (org-todo new-mark)
7464 (insert new-mark " "))))
7465 (when org-provide-todo-statistics
7466 (org-update-parent-todo-statistics))))
7468 (defun org-insert-subheading (arg)
7469 "Insert a new subheading and demote it.
7470 Works for outline headings and for plain lists alike."
7471 (interactive "P")
7472 (org-insert-heading arg)
7473 (cond
7474 ((org-at-heading-p) (org-do-demote))
7475 ((org-at-item-p) (org-indent-item))))
7477 (defun org-insert-todo-subheading (arg)
7478 "Insert a new subheading with TODO keyword or checkbox and demote it.
7479 Works for outline headings and for plain lists alike."
7480 (interactive "P")
7481 (org-insert-todo-heading arg)
7482 (cond
7483 ((org-at-heading-p) (org-do-demote))
7484 ((org-at-item-p) (org-indent-item))))
7486 ;;; Promotion and Demotion
7488 (defvar org-after-demote-entry-hook nil
7489 "Hook run after an entry has been demoted.
7490 The cursor will be at the beginning of the entry.
7491 When a subtree is being demoted, the hook will be called for each node.")
7493 (defvar org-after-promote-entry-hook nil
7494 "Hook run after an entry has been promoted.
7495 The cursor will be at the beginning of the entry.
7496 When a subtree is being promoted, the hook will be called for each node.")
7498 (defun org-promote-subtree ()
7499 "Promote the entire subtree.
7500 See also `org-promote'."
7501 (interactive)
7502 (save-excursion
7503 (org-with-limited-levels (org-map-tree 'org-promote)))
7504 (org-fix-position-after-promote))
7506 (defun org-demote-subtree ()
7507 "Demote the entire subtree. See `org-demote'.
7508 See also `org-promote'."
7509 (interactive)
7510 (save-excursion
7511 (org-with-limited-levels (org-map-tree 'org-demote)))
7512 (org-fix-position-after-promote))
7515 (defun org-do-promote ()
7516 "Promote the current heading higher up the tree.
7517 If the region is active in `transient-mark-mode', promote all headings
7518 in the region."
7519 (interactive)
7520 (save-excursion
7521 (if (org-region-active-p)
7522 (org-map-region 'org-promote (region-beginning) (region-end))
7523 (org-promote)))
7524 (org-fix-position-after-promote))
7526 (defun org-do-demote ()
7527 "Demote the current heading lower down the tree.
7528 If the region is active in `transient-mark-mode', demote all headings
7529 in the region."
7530 (interactive)
7531 (save-excursion
7532 (if (org-region-active-p)
7533 (org-map-region 'org-demote (region-beginning) (region-end))
7534 (org-demote)))
7535 (org-fix-position-after-promote))
7537 (defun org-fix-position-after-promote ()
7538 "Make sure that after pro/demotion cursor position is right."
7539 (let ((pos (point)))
7540 (when (save-excursion
7541 (beginning-of-line 1)
7542 (looking-at org-todo-line-regexp)
7543 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7544 (cond ((eobp) (insert " "))
7545 ((eolp) (insert " "))
7546 ((equal (char-after) ?\ ) (forward-char 1))))))
7548 (defun org-current-level ()
7549 "Return the level of the current entry, or nil if before the first headline.
7550 The level is the number of stars at the beginning of the headline."
7551 (save-excursion
7552 (org-with-limited-levels
7553 (if (ignore-errors (org-back-to-heading t))
7554 (funcall outline-level)))))
7556 (defun org-get-previous-line-level ()
7557 "Return the outline depth of the last headline before the current line.
7558 Returns 0 for the first headline in the buffer, and nil if before the
7559 first headline."
7560 (let ((current-level (org-current-level))
7561 (prev-level (when (> (line-number-at-pos) 1)
7562 (save-excursion
7563 (beginning-of-line 0)
7564 (org-current-level)))))
7565 (cond ((null current-level) nil) ; Before first headline
7566 ((null prev-level) 0) ; At first headline
7567 (prev-level))))
7569 (defun org-reduced-level (l)
7570 "Compute the effective level of a heading.
7571 This takes into account the setting of `org-odd-levels-only'."
7572 (cond
7573 ((zerop l) 0)
7574 (org-odd-levels-only (1+ (floor (/ l 2))))
7575 (t l)))
7577 (defun org-level-increment ()
7578 "Return the number of stars that will be added or removed at a
7579 time to headlines when structure editing, based on the value of
7580 `org-odd-levels-only'."
7581 (if org-odd-levels-only 2 1))
7583 (defun org-get-valid-level (level &optional change)
7584 "Rectify a level change under the influence of `org-odd-levels-only'
7585 LEVEL is a current level, CHANGE is by how much the level should be
7586 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7587 even level numbers will become the next higher odd number."
7588 (if org-odd-levels-only
7589 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7590 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7591 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7592 (max 1 (+ level (or change 0)))))
7594 (if (boundp 'define-obsolete-function-alias)
7595 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7596 (define-obsolete-function-alias 'org-get-legal-level
7597 'org-get-valid-level)
7598 (define-obsolete-function-alias 'org-get-legal-level
7599 'org-get-valid-level "23.1")))
7601 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7602 ;; ̀org-with-limited-levels'
7603 (defun org-promote ()
7604 "Promote the current heading higher up the tree.
7605 If the region is active in `transient-mark-mode', promote all headings
7606 in the region."
7607 (org-back-to-heading t)
7608 (let* ((level (save-match-data (funcall outline-level)))
7609 (after-change-functions (remove 'flyspell-after-change-function
7610 after-change-functions))
7611 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7612 (diff (abs (- level (length up-head) -1))))
7613 (cond ((and (= level 1) org-called-with-limited-levels
7614 org-allow-promoting-top-level-subtree)
7615 (replace-match "# " nil t))
7616 ((= level 1)
7617 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7618 (t (replace-match up-head nil t)))
7619 ;; Fixup tag positioning
7620 (unless (= level 1)
7621 (and org-auto-align-tags (org-set-tags nil t))
7622 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7623 (run-hooks 'org-after-promote-entry-hook)))
7625 (defun org-demote ()
7626 "Demote the current heading lower down the tree.
7627 If the region is active in `transient-mark-mode', demote all headings
7628 in the region."
7629 (org-back-to-heading t)
7630 (let* ((level (save-match-data (funcall outline-level)))
7631 (after-change-functions (remove 'flyspell-after-change-function
7632 after-change-functions))
7633 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7634 (diff (abs (- level (length down-head) -1))))
7635 (replace-match down-head nil t)
7636 ;; Fixup tag positioning
7637 (and org-auto-align-tags (org-set-tags nil t))
7638 (if org-adapt-indentation (org-fixup-indentation diff))
7639 (run-hooks 'org-after-demote-entry-hook)))
7641 (defun org-cycle-level ()
7642 "Cycle the level of an empty headline through possible states.
7643 This goes first to child, then to parent, level, then up the hierarchy.
7644 After top level, it switches back to sibling level."
7645 (interactive)
7646 (let ((org-adapt-indentation nil))
7647 (when (org-point-at-end-of-empty-headline)
7648 (setq this-command 'org-cycle-level) ; Only needed for caching
7649 (let ((cur-level (org-current-level))
7650 (prev-level (org-get-previous-line-level)))
7651 (cond
7652 ;; If first headline in file, promote to top-level.
7653 ((= prev-level 0)
7654 (loop repeat (/ (- cur-level 1) (org-level-increment))
7655 do (org-do-promote)))
7656 ;; If same level as prev, demote one.
7657 ((= prev-level cur-level)
7658 (org-do-demote))
7659 ;; If parent is top-level, promote to top level if not already.
7660 ((= prev-level 1)
7661 (loop repeat (/ (- cur-level 1) (org-level-increment))
7662 do (org-do-promote)))
7663 ;; If top-level, return to prev-level.
7664 ((= cur-level 1)
7665 (loop repeat (/ (- prev-level 1) (org-level-increment))
7666 do (org-do-demote)))
7667 ;; If less than prev-level, promote one.
7668 ((< cur-level prev-level)
7669 (org-do-promote))
7670 ;; If deeper than prev-level, promote until higher than
7671 ;; prev-level.
7672 ((> cur-level prev-level)
7673 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7674 do (org-do-promote))))
7675 t))))
7677 (defun org-map-tree (fun)
7678 "Call FUN for every heading underneath the current one."
7679 (org-back-to-heading)
7680 (let ((level (funcall outline-level)))
7681 (save-excursion
7682 (funcall fun)
7683 (while (and (progn
7684 (outline-next-heading)
7685 (> (funcall outline-level) level))
7686 (not (eobp)))
7687 (funcall fun)))))
7689 (defun org-map-region (fun beg end)
7690 "Call FUN for every heading between BEG and END."
7691 (let ((org-ignore-region t))
7692 (save-excursion
7693 (setq end (copy-marker end))
7694 (goto-char beg)
7695 (if (and (re-search-forward org-outline-regexp-bol nil t)
7696 (< (point) end))
7697 (funcall fun))
7698 (while (and (progn
7699 (outline-next-heading)
7700 (< (point) end))
7701 (not (eobp)))
7702 (funcall fun)))))
7704 (defvar org-property-end-re) ; silence byte-compiler
7705 (defun org-fixup-indentation (diff)
7706 "Change the indentation in the current entry by DIFF.
7707 However, if any line in the current entry has no indentation, or if it
7708 would end up with no indentation after the change, nothing at all is done."
7709 (save-excursion
7710 (let ((end (save-excursion (outline-next-heading)
7711 (point-marker)))
7712 (prohibit (if (> diff 0)
7713 "^\\S-"
7714 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7715 col)
7716 (unless (save-excursion (end-of-line 1)
7717 (re-search-forward prohibit end t))
7718 (while (and (< (point) end)
7719 (re-search-forward "^[ \t]+" end t))
7720 (goto-char (match-end 0))
7721 (setq col (current-column))
7722 (if (< diff 0) (replace-match ""))
7723 (org-indent-to-column (+ diff col))))
7724 (move-marker end nil))))
7726 (defun org-convert-to-odd-levels ()
7727 "Convert an org-mode file with all levels allowed to one with odd levels.
7728 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7729 level 5 etc."
7730 (interactive)
7731 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7732 (let ((outline-level 'org-outline-level)
7733 (org-odd-levels-only nil) n)
7734 (save-excursion
7735 (goto-char (point-min))
7736 (while (re-search-forward "^\\*\\*+ " nil t)
7737 (setq n (- (length (match-string 0)) 2))
7738 (while (>= (setq n (1- n)) 0)
7739 (org-demote))
7740 (end-of-line 1))))))
7742 (defun org-convert-to-oddeven-levels ()
7743 "Convert an org-mode file with only odd levels to one with odd/even levels.
7744 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7745 file contains a section with an even level, conversion would
7746 destroy the structure of the file. An error is signaled in this
7747 case."
7748 (interactive)
7749 (goto-char (point-min))
7750 ;; First check if there are no even levels
7751 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7752 (org-show-context t)
7753 (error "Not all levels are odd in this file. Conversion not possible"))
7754 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7755 (let ((outline-regexp org-outline-regexp)
7756 (outline-level 'org-outline-level)
7757 (org-odd-levels-only nil) n)
7758 (save-excursion
7759 (goto-char (point-min))
7760 (while (re-search-forward "^\\*\\*+ " nil t)
7761 (setq n (/ (1- (length (match-string 0))) 2))
7762 (while (>= (setq n (1- n)) 0)
7763 (org-promote))
7764 (end-of-line 1))))))
7766 (defun org-tr-level (n)
7767 "Make N odd if required."
7768 (if org-odd-levels-only (1+ (/ n 2)) n))
7770 ;;; Vertical tree motion, cutting and pasting of subtrees
7772 (defun org-move-subtree-up (&optional arg)
7773 "Move the current subtree up past ARG headlines of the same level."
7774 (interactive "p")
7775 (org-move-subtree-down (- (prefix-numeric-value arg))))
7777 (defun org-move-subtree-down (&optional arg)
7778 "Move the current subtree down past ARG headlines of the same level."
7779 (interactive "p")
7780 (setq arg (prefix-numeric-value arg))
7781 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7782 'org-get-last-sibling))
7783 (ins-point (make-marker))
7784 (cnt (abs arg))
7785 (col (current-column))
7786 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7787 ;; Select the tree
7788 (org-back-to-heading)
7789 (setq beg0 (point))
7790 (save-excursion
7791 (setq ne-beg (org-back-over-empty-lines))
7792 (setq beg (point)))
7793 (save-match-data
7794 (save-excursion (outline-end-of-heading)
7795 (setq folded (outline-invisible-p)))
7796 (outline-end-of-subtree))
7797 (outline-next-heading)
7798 (setq ne-end (org-back-over-empty-lines))
7799 (setq end (point))
7800 (goto-char beg0)
7801 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7802 ;; include less whitespace
7803 (save-excursion
7804 (goto-char beg)
7805 (forward-line (- ne-beg ne-end))
7806 (setq beg (point))))
7807 ;; Find insertion point, with error handling
7808 (while (> cnt 0)
7809 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7810 (progn (goto-char beg0)
7811 (error "Cannot move past superior level or buffer limit")))
7812 (setq cnt (1- cnt)))
7813 (if (> arg 0)
7814 ;; Moving forward - still need to move over subtree
7815 (progn (org-end-of-subtree t t)
7816 (save-excursion
7817 (org-back-over-empty-lines)
7818 (or (bolp) (newline)))))
7819 (setq ne-ins (org-back-over-empty-lines))
7820 (move-marker ins-point (point))
7821 (setq txt (buffer-substring beg end))
7822 (org-save-markers-in-region beg end)
7823 (delete-region beg end)
7824 (org-remove-empty-overlays-at beg)
7825 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7826 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7827 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7828 (let ((bbb (point)))
7829 (insert-before-markers txt)
7830 (org-reinstall-markers-in-region bbb)
7831 (move-marker ins-point bbb))
7832 (or (bolp) (insert "\n"))
7833 (setq ins-end (point))
7834 (goto-char ins-point)
7835 (org-skip-whitespace)
7836 (when (and (< arg 0)
7837 (org-first-sibling-p)
7838 (> ne-ins ne-beg))
7839 ;; Move whitespace back to beginning
7840 (save-excursion
7841 (goto-char ins-end)
7842 (let ((kill-whole-line t))
7843 (kill-line (- ne-ins ne-beg)) (point)))
7844 (insert (make-string (- ne-ins ne-beg) ?\n)))
7845 (move-marker ins-point nil)
7846 (if folded
7847 (hide-subtree)
7848 (org-show-entry)
7849 (show-children)
7850 (org-cycle-hide-drawers 'children))
7851 (org-clean-visibility-after-subtree-move)
7852 ;; move back to the initial column we were at
7853 (move-to-column col)))
7855 (defvar org-subtree-clip ""
7856 "Clipboard for cut and paste of subtrees.
7857 This is actually only a copy of the kill, because we use the normal kill
7858 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7860 (defvar org-subtree-clip-folded nil
7861 "Was the last copied subtree folded?
7862 This is used to fold the tree back after pasting.")
7864 (defun org-cut-subtree (&optional n)
7865 "Cut the current subtree into the clipboard.
7866 With prefix arg N, cut this many sequential subtrees.
7867 This is a short-hand for marking the subtree and then cutting it."
7868 (interactive "p")
7869 (org-copy-subtree n 'cut))
7871 (defun org-copy-subtree (&optional n cut force-store-markers)
7872 "Cut the current subtree into the clipboard.
7873 With prefix arg N, cut this many sequential subtrees.
7874 This is a short-hand for marking the subtree and then copying it.
7875 If CUT is non-nil, actually cut the subtree.
7876 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7877 of some markers in the region, even if CUT is non-nil. This is
7878 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7879 (interactive "p")
7880 (let (beg end folded (beg0 (point)))
7881 (if (org-called-interactively-p 'any)
7882 (org-back-to-heading nil) ; take what looks like a subtree
7883 (org-back-to-heading t)) ; take what is really there
7884 (setq beg (point))
7885 (skip-chars-forward " \t\r\n")
7886 (save-match-data
7887 (save-excursion (outline-end-of-heading)
7888 (setq folded (outline-invisible-p)))
7889 (condition-case nil
7890 (org-forward-heading-same-level (1- n) t)
7891 (error nil))
7892 (org-end-of-subtree t t))
7893 (setq end (point))
7894 (goto-char beg0)
7895 (when (> end beg)
7896 (setq org-subtree-clip-folded folded)
7897 (when (or cut force-store-markers)
7898 (org-save-markers-in-region beg end))
7899 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7900 (setq org-subtree-clip (current-kill 0))
7901 (message "%s: Subtree(s) with %d characters"
7902 (if cut "Cut" "Copied")
7903 (length org-subtree-clip)))))
7905 (defun org-paste-subtree (&optional level tree for-yank)
7906 "Paste the clipboard as a subtree, with modification of headline level.
7907 The entire subtree is promoted or demoted in order to match a new headline
7908 level.
7910 If the cursor is at the beginning of a headline, the same level as
7911 that headline is used to paste the tree
7913 If not, the new level is derived from the *visible* headings
7914 before and after the insertion point, and taken to be the inferior headline
7915 level of the two. So if the previous visible heading is level 3 and the
7916 next is level 4 (or vice versa), level 4 will be used for insertion.
7917 This makes sure that the subtree remains an independent subtree and does
7918 not swallow low level entries.
7920 You can also force a different level, either by using a numeric prefix
7921 argument, or by inserting the heading marker by hand. For example, if the
7922 cursor is after \"*****\", then the tree will be shifted to level 5.
7924 If optional TREE is given, use this text instead of the kill ring.
7926 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7927 move back over whitespace before inserting, and move point to the end of
7928 the inserted text when done."
7929 (interactive "P")
7930 (setq tree (or tree (and kill-ring (current-kill 0))))
7931 (unless (org-kill-is-subtree-p tree)
7932 (error "%s"
7933 (substitute-command-keys
7934 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7935 (org-with-limited-levels
7936 (let* ((visp (not (outline-invisible-p)))
7937 (txt tree)
7938 (^re_ "\\(\\*+\\)[ \t]*")
7939 (old-level (if (string-match org-outline-regexp-bol txt)
7940 (- (match-end 0) (match-beginning 0) 1)
7941 -1))
7942 (force-level (cond (level (prefix-numeric-value level))
7943 ((and (looking-at "[ \t]*$")
7944 (string-match
7945 "^\\*+$" (buffer-substring
7946 (point-at-bol) (point))))
7947 (- (match-end 1) (match-beginning 1)))
7948 ((and (bolp)
7949 (looking-at org-outline-regexp))
7950 (- (match-end 0) (point) 1))))
7951 (previous-level (save-excursion
7952 (condition-case nil
7953 (progn
7954 (outline-previous-visible-heading 1)
7955 (if (looking-at ^re_)
7956 (- (match-end 0) (match-beginning 0) 1)
7958 (error 1))))
7959 (next-level (save-excursion
7960 (condition-case nil
7961 (progn
7962 (or (looking-at org-outline-regexp)
7963 (outline-next-visible-heading 1))
7964 (if (looking-at ^re_)
7965 (- (match-end 0) (match-beginning 0) 1)
7967 (error 1))))
7968 (new-level (or force-level (max previous-level next-level)))
7969 (shift (if (or (= old-level -1)
7970 (= new-level -1)
7971 (= old-level new-level))
7973 (- new-level old-level)))
7974 (delta (if (> shift 0) -1 1))
7975 (func (if (> shift 0) 'org-demote 'org-promote))
7976 (org-odd-levels-only nil)
7977 beg end newend)
7978 ;; Remove the forced level indicator
7979 (if force-level
7980 (delete-region (point-at-bol) (point)))
7981 ;; Paste
7982 (beginning-of-line (if (bolp) 1 2))
7983 (setq beg (point))
7984 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7985 (insert-before-markers txt)
7986 (unless (string-match "\n\\'" txt) (insert "\n"))
7987 (setq newend (point))
7988 (org-reinstall-markers-in-region beg)
7989 (setq end (point))
7990 (goto-char beg)
7991 (skip-chars-forward " \t\n\r")
7992 (setq beg (point))
7993 (if (and (outline-invisible-p) visp)
7994 (save-excursion (outline-show-heading)))
7995 ;; Shift if necessary
7996 (unless (= shift 0)
7997 (save-restriction
7998 (narrow-to-region beg end)
7999 (while (not (= shift 0))
8000 (org-map-region func (point-min) (point-max))
8001 (setq shift (+ delta shift)))
8002 (goto-char (point-min))
8003 (setq newend (point-max))))
8004 (when (or (org-called-interactively-p 'interactive) for-yank)
8005 (message "Clipboard pasted as level %d subtree" new-level))
8006 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8007 kill-ring
8008 (eq org-subtree-clip (current-kill 0))
8009 org-subtree-clip-folded)
8010 ;; The tree was folded before it was killed/copied
8011 (hide-subtree))
8012 (and for-yank (goto-char newend)))))
8014 (defun org-kill-is-subtree-p (&optional txt)
8015 "Check if the current kill is an outline subtree, or a set of trees.
8016 Returns nil if kill does not start with a headline, or if the first
8017 headline level is not the largest headline level in the tree.
8018 So this will actually accept several entries of equal levels as well,
8019 which is OK for `org-paste-subtree'.
8020 If optional TXT is given, check this string instead of the current kill."
8021 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8022 (re (org-get-limited-outline-regexp))
8023 (^re (concat "^" re))
8024 (start-level (and kill
8025 (string-match
8026 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8027 kill)
8028 (- (match-end 2) (match-beginning 2) 1)))
8029 (start (1+ (or (match-beginning 2) -1))))
8030 (if (not start-level)
8031 (progn
8032 nil) ;; does not even start with a heading
8033 (catch 'exit
8034 (while (setq start (string-match ^re kill (1+ start)))
8035 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8036 (throw 'exit nil)))
8037 t))))
8039 (defvar org-markers-to-move nil
8040 "Markers that should be moved with a cut-and-paste operation.
8041 Those markers are stored together with their positions relative to
8042 the start of the region.")
8044 (defun org-save-markers-in-region (beg end)
8045 "Check markers in region.
8046 If these markers are between BEG and END, record their position relative
8047 to BEG, so that after moving the block of text, we can put the markers back
8048 into place.
8049 This function gets called just before an entry or tree gets cut from the
8050 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8051 called immediately, to move the markers with the entries."
8052 (setq org-markers-to-move nil)
8053 (when (featurep 'org-clock)
8054 (org-clock-save-markers-for-cut-and-paste beg end))
8055 (when (featurep 'org-agenda)
8056 (org-agenda-save-markers-for-cut-and-paste beg end)))
8058 (defun org-check-and-save-marker (marker beg end)
8059 "Check if MARKER is between BEG and END.
8060 If yes, remember the marker and the distance to BEG."
8061 (when (and (marker-buffer marker)
8062 (equal (marker-buffer marker) (current-buffer)))
8063 (if (and (>= marker beg) (< marker end))
8064 (push (cons marker (- marker beg)) org-markers-to-move))))
8066 (defun org-reinstall-markers-in-region (beg)
8067 "Move all remembered markers to their position relative to BEG."
8068 (mapc (lambda (x)
8069 (move-marker (car x) (+ beg (cdr x))))
8070 org-markers-to-move)
8071 (setq org-markers-to-move nil))
8073 (defun org-narrow-to-subtree ()
8074 "Narrow buffer to the current subtree."
8075 (interactive)
8076 (save-excursion
8077 (save-match-data
8078 (org-with-limited-levels
8079 (narrow-to-region
8080 (progn (org-back-to-heading t) (point))
8081 (progn (org-end-of-subtree t t)
8082 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8083 (point)))))))
8085 (defun org-narrow-to-block ()
8086 "Narrow buffer to the current block."
8087 (interactive)
8088 (let* ((case-fold-search t)
8089 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8090 "^[ \t]*#\\+end_.*")))
8091 (if blockp
8092 (narrow-to-region (car blockp) (cdr blockp))
8093 (error "Not in a block"))))
8095 (eval-when-compile
8096 (defvar org-property-drawer-re))
8098 (defvar org-property-start-re) ;; defined below
8099 (defun org-clone-subtree-with-time-shift (n &optional shift)
8100 "Clone the task (subtree) at point N times.
8101 The clones will be inserted as siblings.
8103 In interactive use, the user will be prompted for the number of
8104 clones to be produced, and for a time SHIFT, which may be a
8105 repeater as used in time stamps, for example `+3d'.
8107 When a valid repeater is given and the entry contains any time
8108 stamps, the clones will become a sequence in time, with time
8109 stamps in the subtree shifted for each clone produced. If SHIFT
8110 is nil or the empty string, time stamps will be left alone. The
8111 ID property of the original subtree is removed.
8113 If the original subtree did contain time stamps with a repeater,
8114 the following will happen:
8115 - the repeater will be removed in each clone
8116 - an additional clone will be produced, with the current, unshifted
8117 date(s) in the entry.
8118 - the original entry will be placed *after* all the clones, with
8119 repeater intact.
8120 - the start days in the repeater in the original entry will be shifted
8121 to past the last clone.
8122 In this way you can spell out a number of instances of a repeating task,
8123 and still retain the repeater to cover future instances of the task."
8124 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8125 (let (beg end template task idprop
8126 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8127 (drawer-re org-drawer-regexp))
8128 (if (not (and (integerp n) (> n 0)))
8129 (error "Invalid number of replications %s" n))
8130 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8131 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8132 shift)))
8133 (error "Invalid shift specification %s" shift))
8134 (when doshift
8135 (setq shift-n (string-to-number (match-string 1 shift))
8136 shift-what (cdr (assoc (match-string 2 shift)
8137 '(("d" . day) ("w" . week)
8138 ("m" . month) ("y" . year))))))
8139 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8140 (setq nmin 1 nmax n)
8141 (org-back-to-heading t)
8142 (setq beg (point))
8143 (setq idprop (org-entry-get nil "ID"))
8144 (org-end-of-subtree t t)
8145 (or (bolp) (insert "\n"))
8146 (setq end (point))
8147 (setq template (buffer-substring beg end))
8148 (when (and doshift
8149 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8150 (delete-region beg end)
8151 (setq end beg)
8152 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8153 (goto-char end)
8154 (loop for n from nmin to nmax do
8155 ;; prepare clone
8156 (with-temp-buffer
8157 (insert template)
8158 (org-mode)
8159 (goto-char (point-min))
8160 (org-show-subtree)
8161 (and idprop (if org-clone-delete-id
8162 (org-entry-delete nil "ID")
8163 (org-id-get-create t)))
8164 (unless (= n 0)
8165 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8166 (kill-whole-line))
8167 (goto-char (point-min))
8168 (while (re-search-forward drawer-re nil t)
8169 (mapc (lambda (d)
8170 (org-remove-empty-drawer-at d (point))) org-drawers)))
8171 (goto-char (point-min))
8172 (when doshift
8173 (while (re-search-forward org-ts-regexp-both nil t)
8174 (org-timestamp-change (* n shift-n) shift-what))
8175 (unless (= n n-no-remove)
8176 (goto-char (point-min))
8177 (while (re-search-forward org-ts-regexp nil t)
8178 (save-excursion
8179 (goto-char (match-beginning 0))
8180 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8181 (delete-region (match-beginning 1) (match-end 1)))))))
8182 (setq task (buffer-string)))
8183 (insert task))
8184 (goto-char beg)))
8186 ;;; Outline Sorting
8188 (defun org-sort (with-case)
8189 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8190 Optional argument WITH-CASE means sort case-sensitively."
8191 (interactive "P")
8192 (cond
8193 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8194 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8196 (org-call-with-arg 'org-sort-entries with-case))))
8198 (defun org-sort-remove-invisible (s)
8199 (remove-text-properties 0 (length s) org-rm-props s)
8200 (while (string-match org-bracket-link-regexp s)
8201 (setq s (replace-match (if (match-end 2)
8202 (match-string 3 s)
8203 (match-string 1 s)) t t s)))
8206 (defvar org-priority-regexp) ; defined later in the file
8208 (defvar org-after-sorting-entries-or-items-hook nil
8209 "Hook that is run after a bunch of entries or items have been sorted.
8210 When children are sorted, the cursor is in the parent line when this
8211 hook gets called. When a region or a plain list is sorted, the cursor
8212 will be in the first entry of the sorted region/list.")
8214 (defun org-sort-entries
8215 (&optional with-case sorting-type getkey-func compare-func property)
8216 "Sort entries on a certain level of an outline tree.
8217 If there is an active region, the entries in the region are sorted.
8218 Else, if the cursor is before the first entry, sort the top-level items.
8219 Else, the children of the entry at point are sorted.
8221 Sorting can be alphabetically, numerically, by date/time as given by
8222 a time stamp, by a property or by priority.
8224 The command prompts for the sorting type unless it has been given to the
8225 function through the SORTING-TYPE argument, which needs to be a character,
8226 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8227 precise meaning of each character:
8229 n Numerically, by converting the beginning of the entry/item to a number.
8230 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8231 o By order of TODO keywords.
8232 t By date/time, either the first active time stamp in the entry, or, if
8233 none exist, by the first inactive one.
8234 s By the scheduled date/time.
8235 d By deadline date/time.
8236 c By creation time, which is assumed to be the first inactive time stamp
8237 at the beginning of a line.
8238 p By priority according to the cookie.
8239 r By the value of a property.
8241 Capital letters will reverse the sort order.
8243 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8244 called with point at the beginning of the record. It must return either
8245 a string or a number that should serve as the sorting key for that record.
8247 Comparing entries ignores case by default. However, with an optional argument
8248 WITH-CASE, the sorting considers case as well."
8249 (interactive "P")
8250 (let ((case-func (if with-case 'identity 'downcase))
8251 (cmstr
8252 ;; The clock marker is lost when using `sort-subr', let's
8253 ;; store the clocking string.
8254 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8255 (save-excursion
8256 (goto-char org-clock-marker)
8257 (looking-back "^.*") (match-string-no-properties 0))))
8258 start beg end stars re re2
8259 txt what tmp)
8260 ;; Find beginning and end of region to sort
8261 (cond
8262 ((org-region-active-p)
8263 ;; we will sort the region
8264 (setq end (region-end)
8265 what "region")
8266 (goto-char (region-beginning))
8267 (if (not (org-at-heading-p)) (outline-next-heading))
8268 (setq start (point)))
8269 ((or (org-at-heading-p)
8270 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8271 ;; we will sort the children of the current headline
8272 (org-back-to-heading)
8273 (setq start (point)
8274 end (progn (org-end-of-subtree t t)
8275 (or (bolp) (insert "\n"))
8276 (org-back-over-empty-lines)
8277 (point))
8278 what "children")
8279 (goto-char start)
8280 (show-subtree)
8281 (outline-next-heading))
8283 ;; we will sort the top-level entries in this file
8284 (goto-char (point-min))
8285 (or (org-at-heading-p) (outline-next-heading))
8286 (setq start (point))
8287 (goto-char (point-max))
8288 (beginning-of-line 1)
8289 (when (looking-at ".*?\\S-")
8290 ;; File ends in a non-white line
8291 (end-of-line 1)
8292 (insert "\n"))
8293 (setq end (point-max))
8294 (setq what "top-level")
8295 (goto-char start)
8296 (show-all)))
8298 (setq beg (point))
8299 (if (>= beg end) (error "Nothing to sort"))
8301 (looking-at "\\(\\*+\\)")
8302 (setq stars (match-string 1)
8303 re (concat "^" (regexp-quote stars) " +")
8304 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8305 txt (buffer-substring beg end))
8306 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8307 (if (and (not (equal stars "*")) (string-match re2 txt))
8308 (error "Region to sort contains a level above the first entry"))
8310 (unless sorting-type
8311 (message
8312 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8313 [t]ime [s]cheduled [d]eadline [c]reated
8314 A/N/P/R/O/F/T/S/D/C means reversed:"
8315 what)
8316 (setq sorting-type (read-char-exclusive))
8318 (unless getkey-func
8319 (and (= (downcase sorting-type) ?f)
8320 (setq getkey-func
8321 (org-icompleting-read "Sort using function: "
8322 obarray 'fboundp t nil nil))
8323 (setq getkey-func (intern getkey-func))))
8325 (and (= (downcase sorting-type) ?r)
8326 (not property)
8327 (setq property
8328 (org-icompleting-read "Property: "
8329 (mapcar 'list (org-buffer-property-keys t))
8330 nil t))))
8332 (message "Sorting entries...")
8334 (save-restriction
8335 (narrow-to-region start end)
8336 (let ((dcst (downcase sorting-type))
8337 (case-fold-search nil)
8338 (now (current-time)))
8339 (sort-subr
8340 (/= dcst sorting-type)
8341 ;; This function moves to the beginning character of the "record" to
8342 ;; be sorted.
8343 (lambda nil
8344 (if (re-search-forward re nil t)
8345 (goto-char (match-beginning 0))
8346 (goto-char (point-max))))
8347 ;; This function moves to the last character of the "record" being
8348 ;; sorted.
8349 (lambda nil
8350 (save-match-data
8351 (condition-case nil
8352 (outline-forward-same-level 1)
8353 (error
8354 (goto-char (point-max))))))
8355 ;; This function returns the value that gets sorted against.
8356 (lambda nil
8357 (cond
8358 ((= dcst ?n)
8359 (if (looking-at org-complex-heading-regexp)
8360 (string-to-number (match-string 4))
8361 nil))
8362 ((= dcst ?a)
8363 (if (looking-at org-complex-heading-regexp)
8364 (funcall case-func (match-string 4))
8365 nil))
8366 ((= dcst ?t)
8367 (let ((end (save-excursion (outline-next-heading) (point))))
8368 (if (or (re-search-forward org-ts-regexp end t)
8369 (re-search-forward org-ts-regexp-both end t))
8370 (org-time-string-to-seconds (match-string 0))
8371 (org-float-time now))))
8372 ((= dcst ?c)
8373 (let ((end (save-excursion (outline-next-heading) (point))))
8374 (if (re-search-forward
8375 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8376 end t)
8377 (org-time-string-to-seconds (match-string 0))
8378 (org-float-time now))))
8379 ((= dcst ?s)
8380 (let ((end (save-excursion (outline-next-heading) (point))))
8381 (if (re-search-forward org-scheduled-time-regexp end t)
8382 (org-time-string-to-seconds (match-string 1))
8383 (org-float-time now))))
8384 ((= dcst ?d)
8385 (let ((end (save-excursion (outline-next-heading) (point))))
8386 (if (re-search-forward org-deadline-time-regexp end t)
8387 (org-time-string-to-seconds (match-string 1))
8388 (org-float-time now))))
8389 ((= dcst ?p)
8390 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8391 (string-to-char (match-string 2))
8392 org-default-priority))
8393 ((= dcst ?r)
8394 (or (org-entry-get nil property) ""))
8395 ((= dcst ?o)
8396 (if (looking-at org-complex-heading-regexp)
8397 (- 9999 (length (member (match-string 2)
8398 org-todo-keywords-1)))))
8399 ((= dcst ?f)
8400 (if getkey-func
8401 (progn
8402 (setq tmp (funcall getkey-func))
8403 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8404 tmp)
8405 (error "Invalid key function `%s'" getkey-func)))
8406 (t (error "Invalid sorting type `%c'" sorting-type))))
8408 (cond
8409 ((= dcst ?a) 'string<)
8410 ((= dcst ?f) compare-func)
8411 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8412 (run-hooks 'org-after-sorting-entries-or-items-hook)
8413 ;; Reset the clock marker if needed
8414 (when cmstr
8415 (save-excursion
8416 (goto-char start)
8417 (search-forward cmstr nil t)
8418 (move-marker org-clock-marker (point))))
8419 (message "Sorting entries...done")))
8421 (defun org-do-sort (table what &optional with-case sorting-type)
8422 "Sort TABLE of WHAT according to SORTING-TYPE.
8423 The user will be prompted for the SORTING-TYPE if the call to this
8424 function does not specify it. WHAT is only for the prompt, to indicate
8425 what is being sorted. The sorting key will be extracted from
8426 the car of the elements of the table.
8427 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8428 (unless sorting-type
8429 (message
8430 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8431 what)
8432 (setq sorting-type (read-char-exclusive)))
8433 (let ((dcst (downcase sorting-type))
8434 extractfun comparefun)
8435 ;; Define the appropriate functions
8436 (cond
8437 ((= dcst ?n)
8438 (setq extractfun 'string-to-number
8439 comparefun (if (= dcst sorting-type) '< '>)))
8440 ((= dcst ?a)
8441 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8442 (lambda(x) (downcase (org-sort-remove-invisible x))))
8443 comparefun (if (= dcst sorting-type)
8444 'string<
8445 (lambda (a b) (and (not (string< a b))
8446 (not (string= a b)))))))
8447 ((= dcst ?t)
8448 (setq extractfun
8449 (lambda (x)
8450 (if (or (string-match org-ts-regexp x)
8451 (string-match org-ts-regexp-both x))
8452 (org-float-time
8453 (org-time-string-to-time (match-string 0 x)))
8455 comparefun (if (= dcst sorting-type) '< '>)))
8456 (t (error "Invalid sorting type `%c'" sorting-type)))
8458 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8459 table)
8460 (lambda (a b) (funcall comparefun (car a) (car b))))))
8463 ;;; The orgstruct minor mode
8465 ;; Define a minor mode which can be used in other modes in order to
8466 ;; integrate the org-mode structure editing commands.
8468 ;; This is really a hack, because the org-mode structure commands use
8469 ;; keys which normally belong to the major mode. Here is how it
8470 ;; works: The minor mode defines all the keys necessary to operate the
8471 ;; structure commands, but wraps the commands into a function which
8472 ;; tests if the cursor is currently at a headline or a plain list
8473 ;; item. If that is the case, the structure command is used,
8474 ;; temporarily setting many Org-mode variables like regular
8475 ;; expressions for filling etc. However, when any of those keys is
8476 ;; used at a different location, function uses `key-binding' to look
8477 ;; up if the key has an associated command in another currently active
8478 ;; keymap (minor modes, major mode, global), and executes that
8479 ;; command. There might be problems if any of the keys is otherwise
8480 ;; used as a prefix key.
8482 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8483 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8484 ;; addresses this by checking explicitly for both bindings.
8486 (defvar orgstruct-mode-map (make-sparse-keymap)
8487 "Keymap for the minor `orgstruct-mode'.")
8489 (defvar org-local-vars nil
8490 "List of local variables, for use by `orgstruct-mode'.")
8492 ;;;###autoload
8493 (define-minor-mode orgstruct-mode
8494 "Toggle the minor mode `orgstruct-mode'.
8495 This mode is for using Org-mode structure commands in other
8496 modes. The following keys behave as if Org-mode were active, if
8497 the cursor is on a headline, or on a plain list item (both as
8498 defined by Org-mode).
8500 M-up Move entry/item up
8501 M-down Move entry/item down
8502 M-left Promote
8503 M-right Demote
8504 M-S-up Move entry/item up
8505 M-S-down Move entry/item down
8506 M-S-left Promote subtree
8507 M-S-right Demote subtree
8508 M-q Fill paragraph and items like in Org-mode
8509 C-c ^ Sort entries
8510 C-c - Cycle list bullet
8511 TAB Cycle item visibility
8512 M-RET Insert new heading/item
8513 S-M-RET Insert new TODO heading / Checkbox item
8514 C-c C-c Set tags / toggle checkbox"
8515 nil " OrgStruct" nil
8516 (org-load-modules-maybe)
8517 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8519 ;;;###autoload
8520 (defun turn-on-orgstruct ()
8521 "Unconditionally turn on `orgstruct-mode'."
8522 (orgstruct-mode 1))
8524 (defvar org-fb-vars nil)
8525 (make-variable-buffer-local 'org-fb-vars)
8526 (defun orgstruct++-mode (&optional arg)
8527 "Toggle `orgstruct-mode', the enhanced version of it.
8528 In addition to setting orgstruct-mode, this also exports all
8529 indentation and autofilling variables from org-mode into the
8530 buffer. It will also recognize item context in multiline items."
8531 (interactive "P")
8532 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8533 (if (< arg 1)
8534 (progn (orgstruct-mode -1)
8535 (mapc (lambda(v)
8536 (org-set-local (car v)
8537 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8538 org-fb-vars))
8539 (orgstruct-mode 1)
8540 (setq org-fb-vars nil)
8541 (let (var val)
8542 (mapc
8543 (lambda (x)
8544 (when (string-match
8545 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8546 (symbol-name (car x)))
8547 (setq var (car x) val (nth 1 x))
8548 (push (list var `(quote ,(eval var))) org-fb-vars)
8549 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8550 org-local-vars)
8551 (org-set-local 'orgstruct-is-++ t))))
8553 (defvar orgstruct-is-++ nil
8554 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8555 (make-variable-buffer-local 'orgstruct-is-++)
8557 ;;;###autoload
8558 (defun turn-on-orgstruct++ ()
8559 "Unconditionally turn on `orgstruct++-mode'."
8560 (orgstruct++-mode 1))
8562 (defun orgstruct-error ()
8563 "Error when there is no default binding for a structure key."
8564 (interactive)
8565 (error "This key has no function outside structure elements"))
8567 (defun orgstruct-setup ()
8568 "Setup orgstruct keymaps."
8569 (let ((nfunc 0)
8570 (bindings
8571 (list
8572 '([(meta up)] org-metaup)
8573 '([(meta down)] org-metadown)
8574 '([(meta left)] org-metaleft)
8575 '([(meta right)] org-metaright)
8576 '([(meta shift up)] org-shiftmetaup)
8577 '([(meta shift down)] org-shiftmetadown)
8578 '([(meta shift left)] org-shiftmetaleft)
8579 '([(meta shift right)] org-shiftmetaright)
8580 '([?\e (up)] org-metaup)
8581 '([?\e (down)] org-metadown)
8582 '([?\e (left)] org-metaleft)
8583 '([?\e (right)] org-metaright)
8584 '([?\e (shift up)] org-shiftmetaup)
8585 '([?\e (shift down)] org-shiftmetadown)
8586 '([?\e (shift left)] org-shiftmetaleft)
8587 '([?\e (shift right)] org-shiftmetaright)
8588 '([(shift up)] org-shiftup)
8589 '([(shift down)] org-shiftdown)
8590 '([(shift left)] org-shiftleft)
8591 '([(shift right)] org-shiftright)
8592 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8593 '("\M-q" fill-paragraph)
8594 '("\C-c^" org-sort)
8595 '("\C-c-" org-cycle-list-bullet)))
8596 elt key fun cmd)
8597 (while (setq elt (pop bindings))
8598 (setq nfunc (1+ nfunc))
8599 (setq key (org-key (car elt))
8600 fun (nth 1 elt)
8601 cmd (orgstruct-make-binding fun nfunc key))
8602 (org-defkey orgstruct-mode-map key cmd))
8604 ;; Prevent an error for users who forgot to make autoloads
8605 (require 'org-element)
8607 ;; Special treatment needed for TAB and RET
8608 (org-defkey orgstruct-mode-map [(tab)]
8609 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8610 (org-defkey orgstruct-mode-map "\C-i"
8611 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8613 (org-defkey orgstruct-mode-map "\M-\C-m"
8614 (orgstruct-make-binding 'org-insert-heading 105
8615 "\M-\C-m" [(meta return)]))
8616 (org-defkey orgstruct-mode-map [(meta return)]
8617 (orgstruct-make-binding 'org-insert-heading 106
8618 [(meta return)] "\M-\C-m"))
8620 (org-defkey orgstruct-mode-map [(shift meta return)]
8621 (orgstruct-make-binding 'org-insert-todo-heading 107
8622 [(meta return)] "\M-\C-m"))
8624 (org-defkey orgstruct-mode-map "\e\C-m"
8625 (orgstruct-make-binding 'org-insert-heading 108
8626 "\e\C-m" [?\e (return)]))
8627 (org-defkey orgstruct-mode-map [?\e (return)]
8628 (orgstruct-make-binding 'org-insert-heading 109
8629 [?\e (return)] "\e\C-m"))
8630 (org-defkey orgstruct-mode-map [?\e (shift return)]
8631 (orgstruct-make-binding 'org-insert-todo-heading 110
8632 [?\e (return)] "\e\C-m"))
8634 (unless org-local-vars
8635 (setq org-local-vars (org-get-local-variables)))
8639 (defun orgstruct-make-binding (fun n &rest keys)
8640 "Create a function for binding in the structure minor mode.
8641 FUN is the command to call inside a table. N is used to create a unique
8642 command name. KEYS are keys that should be checked in for a command
8643 to execute outside of tables."
8644 (eval
8645 (list 'defun
8646 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8647 '(arg)
8648 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8649 "Outside of structure, run the binding of `"
8650 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8651 "'.")
8652 '(interactive "p")
8653 (list 'if
8654 `(org-context-p 'headline 'item
8655 (and orgstruct-is-++
8656 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8657 'item-body))
8658 (list 'org-run-like-in-org-mode (list 'quote fun))
8659 (list 'let '(orgstruct-mode)
8660 (list 'call-interactively
8661 (append '(or)
8662 (mapcar (lambda (k)
8663 (list 'key-binding k))
8664 keys)
8665 '('orgstruct-error))))))))
8667 (defun org-contextualize-keys (alist contexts)
8668 "Return valid elements in ALIST depending on CONTEXTS.
8670 `org-agenda-custom-commands' or `org-capture-templates' are the
8671 values used for ALIST, and `org-agenda-custom-commands-contexts'
8672 or `org-capture-templates-contexts' are the associated contexts
8673 definitions."
8674 (let ((contexts
8675 ;; normalize contexts
8676 (mapcar
8677 (lambda(c) (cond ((listp (cadr c))
8678 (list (car c) (car c) (cadr c)))
8679 ((string= "" (cadr c))
8680 (list (car c) (car c) (caddr c)))
8681 (t c))) contexts))
8682 (a alist) c r s)
8683 ;; loop over all commands or templates
8684 (while (setq c (pop a))
8685 (let (vrules repl)
8686 (cond
8687 ((not (assoc (car c) contexts))
8688 (push c r))
8689 ((and (assoc (car c) contexts)
8690 (setq vrules (org-contextualize-validate-key
8691 (car c) contexts)))
8692 (mapc (lambda (vr)
8693 (when (not (equal (car vr) (cadr vr)))
8694 (setq repl vr))) vrules)
8695 (if (not repl) (push c r)
8696 (push (cadr repl) s)
8697 (push
8698 (cons (car c)
8699 (cdr (or (assoc (cadr repl) alist)
8700 (error "Undefined key `%s' as contextual replacement for `%s'"
8701 (cadr repl) (car c)))))
8702 r))))))
8703 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8704 (delq
8706 (delete-dups
8707 (mapcar (lambda (x)
8708 (let ((tpl (car x)))
8709 (when (not (delq
8711 (mapcar (lambda(y)
8712 (equal y tpl)) s))) x)))
8713 (reverse r))))))
8715 (defun org-contextualize-validate-key (key contexts)
8716 "Check CONTEXTS for agenda or capture KEY."
8717 (let (r rr res)
8718 (while (setq r (pop contexts))
8719 (mapc
8720 (lambda (rr)
8721 (when
8722 (and (equal key (car r))
8723 (if (functionp rr) (funcall rr)
8724 (or (and (eq (car rr) 'in-file)
8725 (buffer-file-name)
8726 (string-match (cdr rr) (buffer-file-name)))
8727 (and (eq (car rr) 'in-mode)
8728 (string-match (cdr rr) (symbol-name major-mode)))
8729 (when (and (eq (car rr) 'not-in-file)
8730 (buffer-file-name))
8731 (not (string-match (cdr rr) (buffer-file-name))))
8732 (when (eq (car rr) 'not-in-mode)
8733 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8734 (push r res)))
8735 (car (last r))))
8736 (delete-dups (delq nil res))))
8738 (defun org-context-p (&rest contexts)
8739 "Check if local context is any of CONTEXTS.
8740 Possible values in the list of contexts are `table', `headline', and `item'."
8741 (let ((pos (point)))
8742 (goto-char (point-at-bol))
8743 (prog1 (or (and (memq 'table contexts)
8744 (looking-at "[ \t]*|"))
8745 (and (memq 'headline contexts)
8746 (looking-at org-outline-regexp))
8747 (and (memq 'item contexts)
8748 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8749 (and (memq 'item-body contexts)
8750 (org-in-item-p)))
8751 (goto-char pos))))
8753 (defun org-get-local-variables ()
8754 "Return a list of all local variables in an Org mode buffer."
8755 (let (varlist)
8756 (with-current-buffer (get-buffer-create "*Org tmp*")
8757 (erase-buffer)
8758 (org-mode)
8759 (setq varlist (buffer-local-variables)))
8760 (kill-buffer "*Org tmp*")
8761 (delq nil
8762 (mapcar
8763 (lambda (x)
8764 (setq x
8765 (if (symbolp x)
8766 (list x)
8767 (list (car x) (list 'quote (cdr x)))))
8768 (if (string-match
8769 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8770 (symbol-name (car x)))
8771 x nil))
8772 varlist))))
8774 (defun org-clone-local-variables (from-buffer &optional regexp)
8775 "Clone local variables from FROM-BUFFER.
8776 Optional argument REGEXP selects variables to clone."
8777 (mapc
8778 (lambda (pair)
8779 (and (symbolp (car pair))
8780 (or (null regexp)
8781 (string-match regexp (symbol-name (car pair))))
8782 (set (make-local-variable (car pair))
8783 (cdr pair))))
8784 (buffer-local-variables from-buffer)))
8786 ;;;###autoload
8787 (defun org-run-like-in-org-mode (cmd)
8788 "Run a command, pretending that the current buffer is in Org-mode.
8789 This will temporarily bind local variables that are typically bound in
8790 Org-mode to the values they have in Org-mode, and then interactively
8791 call CMD."
8792 (org-load-modules-maybe)
8793 (unless org-local-vars
8794 (setq org-local-vars (org-get-local-variables)))
8795 (eval (list 'let org-local-vars
8796 (list 'call-interactively (list 'quote cmd)))))
8798 ;;;; Archiving
8800 (defun org-get-category (&optional pos force-refresh)
8801 "Get the category applying to position POS."
8802 (save-match-data
8803 (if force-refresh (org-refresh-category-properties))
8804 (let ((pos (or pos (point))))
8805 (or (get-text-property pos 'org-category)
8806 (progn (org-refresh-category-properties)
8807 (get-text-property pos 'org-category))))))
8809 (defun org-refresh-category-properties ()
8810 "Refresh category text properties in the buffer."
8811 (let ((case-fold-search t)
8812 (inhibit-read-only t)
8813 (def-cat (cond
8814 ((null org-category)
8815 (if buffer-file-name
8816 (file-name-sans-extension
8817 (file-name-nondirectory buffer-file-name))
8818 "???"))
8819 ((symbolp org-category) (symbol-name org-category))
8820 (t org-category)))
8821 beg end cat pos optionp)
8822 (org-unmodified
8823 (save-excursion
8824 (save-restriction
8825 (widen)
8826 (goto-char (point-min))
8827 (put-text-property (point) (point-max) 'org-category def-cat)
8828 (while (re-search-forward
8829 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8830 (setq pos (match-end 0)
8831 optionp (equal (char-after (match-beginning 0)) ?#)
8832 cat (org-trim (match-string 2)))
8833 (if optionp
8834 (setq beg (point-at-bol) end (point-max))
8835 (org-back-to-heading t)
8836 (setq beg (point) end (org-end-of-subtree t t)))
8837 (put-text-property beg end 'org-category cat)
8838 (put-text-property beg end 'org-category-position beg)
8839 (goto-char pos)))))))
8841 (defun org-refresh-properties (dprop tprop)
8842 "Refresh buffer text properties.
8843 DPROP is the drawer property and TPROP is the corresponding text
8844 property to set."
8845 (let ((case-fold-search t)
8846 (inhibit-read-only t) p)
8847 (org-unmodified
8848 (save-excursion
8849 (save-restriction
8850 (widen)
8851 (goto-char (point-min))
8852 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8853 (setq p (org-match-string-no-properties 1))
8854 (save-excursion
8855 (org-back-to-heading t)
8856 (put-text-property
8857 (point-at-bol) (point-at-eol) tprop p))))))))
8860 ;;;; Link Stuff
8862 ;;; Link abbreviations
8864 (defun org-link-expand-abbrev (link)
8865 "Apply replacements as defined in `org-link-abbrev-alist'."
8866 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8867 (let* ((key (match-string 1 link))
8868 (as (or (assoc key org-link-abbrev-alist-local)
8869 (assoc key org-link-abbrev-alist)))
8870 (tag (and (match-end 2) (match-string 3 link)))
8871 rpl)
8872 (if (not as)
8873 link
8874 (setq rpl (cdr as))
8875 (cond
8876 ((symbolp rpl) (funcall rpl tag))
8877 ((string-match "%(\\([^)]+\\))" rpl)
8878 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8879 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8880 ((string-match "%h" rpl)
8881 (replace-match (url-hexify-string (or tag "")) t t rpl))
8882 (t (concat rpl tag)))))
8883 link))
8885 ;;; Storing and inserting links
8887 (defvar org-insert-link-history nil
8888 "Minibuffer history for links inserted with `org-insert-link'.")
8890 (defvar org-stored-links nil
8891 "Contains the links stored with `org-store-link'.")
8893 (defvar org-store-link-plist nil
8894 "Plist with info about the most recently link created with `org-store-link'.")
8896 (defvar org-link-protocols nil
8897 "Link protocols added to Org-mode using `org-add-link-type'.")
8899 (defvar org-store-link-functions nil
8900 "List of functions that are called to create and store a link.
8901 Each function will be called in turn until one returns a non-nil
8902 value. Each function should check if it is responsible for creating
8903 this link (for example by looking at the major mode).
8904 If not, it must exit and return nil.
8905 If yes, it should return a non-nil value after a calling
8906 `org-store-link-props' with a list of properties and values.
8907 Special properties are:
8909 :type The link prefix, like \"http\". This must be given.
8910 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8911 This is obligatory as well.
8912 :description Optional default description for the second pair
8913 of brackets in an Org-mode link. The user can still change
8914 this when inserting this link into an Org-mode buffer.
8916 In addition to these, any additional properties can be specified
8917 and then used in capture templates.")
8919 (defun org-add-link-type (type &optional follow export)
8920 "Add TYPE to the list of `org-link-types'.
8921 Re-compute all regular expressions depending on `org-link-types'
8923 FOLLOW and EXPORT are two functions.
8925 FOLLOW should take the link path as the single argument and do whatever
8926 is necessary to follow the link, for example find a file or display
8927 a mail message.
8929 EXPORT should format the link path for export to one of the export formats.
8930 It should be a function accepting three arguments:
8932 path the path of the link, the text after the prefix (like \"http:\")
8933 desc the description of the link, if any, or a description added by
8934 org-export-normalize-links if there is none
8935 format the export format, a symbol like `html' or `latex' or `ascii'..
8937 The function may use the FORMAT information to return different values
8938 depending on the format. The return value will be put literally into
8939 the exported file. If the return value is nil, this means Org should
8940 do what it normally does with links which do not have EXPORT defined.
8942 Org-mode has a built-in default for exporting links. If you are happy with
8943 this default, there is no need to define an export function for the link
8944 type. For a simple example of an export function, see `org-bbdb.el'."
8945 (add-to-list 'org-link-types type t)
8946 (org-make-link-regexps)
8947 (if (assoc type org-link-protocols)
8948 (setcdr (assoc type org-link-protocols) (list follow export))
8949 (push (list type follow export) org-link-protocols)))
8951 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8952 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8954 ;;;###autoload
8955 (defun org-store-link (arg)
8956 "\\<org-mode-map>Store an org-link to the current location.
8957 This link is added to `org-stored-links' and can later be inserted
8958 into an org-buffer with \\[org-insert-link].
8960 For some link types, a prefix arg is interpreted.
8961 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8962 For file links, arg negates `org-context-in-file-links'.
8964 A double prefix arg force skipping storing functions that are not
8965 part of Org's core."
8966 (interactive "P")
8967 (org-load-modules-maybe)
8968 (setq org-store-link-plist nil) ; reset
8969 (org-with-limited-levels
8970 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
8971 (cond
8972 ((and (not (equal arg '(16)))
8973 (setq sfuns
8974 (delq
8975 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
8976 org-store-link-functions))
8977 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
8978 (or (and (cdr sfuns)
8979 (funcall (intern
8980 (completing-read "Which function for creating the link? "
8981 sfunsn t (car sfunsn)))))
8982 (funcall (caar sfuns)))
8983 (setq link (plist-get org-store-link-plist :link)
8984 desc (or (plist-get org-store-link-plist :description) link))))
8985 ((org-src-edit-buffer-p)
8986 (let (label gc)
8987 (while (or (not label)
8988 (save-excursion
8989 (save-restriction
8990 (widen)
8991 (goto-char (point-min))
8992 (re-search-forward
8993 (regexp-quote (format org-coderef-label-format label))
8994 nil t))))
8995 (when label (message "Label exists already") (sit-for 2))
8996 (setq label (read-string "Code line label: " label)))
8997 (end-of-line 1)
8998 (setq link (format org-coderef-label-format label))
8999 (setq gc (- 79 (length link)))
9000 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9001 (insert link)
9002 (setq link (concat "(" label ")") desc nil)))
9004 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9005 ;; We are in the agenda, link to referenced location
9006 (let ((m (or (get-text-property (point) 'org-hd-marker)
9007 (get-text-property (point) 'org-marker))))
9008 (when m
9009 (org-with-point-at m
9010 (setq agenda-link
9011 (if (org-called-interactively-p 'any)
9012 (call-interactively 'org-store-link)
9013 (org-store-link nil)))))))
9015 ((eq major-mode 'calendar-mode)
9016 (let ((cd (calendar-cursor-to-date)))
9017 (setq link
9018 (format-time-string
9019 (car org-time-stamp-formats)
9020 (apply 'encode-time
9021 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9022 nil nil nil))))
9023 (org-store-link-props :type "calendar" :date cd)))
9025 ((eq major-mode 'help-mode)
9026 (setq link (concat "help:" (save-excursion
9027 (goto-char (point-min))
9028 (looking-at "^[^ ]+")
9029 (match-string 0))))
9030 (org-store-link-props :type "help"))
9032 ((eq major-mode 'w3-mode)
9033 (setq cpltxt (if (and (buffer-name)
9034 (not (string-match "Untitled" (buffer-name))))
9035 (buffer-name)
9036 (url-view-url t))
9037 link (url-view-url t))
9038 (org-store-link-props :type "w3" :url (url-view-url t)))
9040 ((setq search (run-hook-with-args-until-success
9041 'org-create-file-search-functions))
9042 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9043 "::" search))
9044 (setq cpltxt (or description link)))
9046 ((eq major-mode 'image-mode)
9047 (setq cpltxt (concat "file:"
9048 (abbreviate-file-name buffer-file-name))
9049 link cpltxt)
9050 (org-store-link-props :type "image" :file buffer-file-name))
9052 ((eq major-mode 'dired-mode)
9053 ;; link to the file in the current line
9054 (let ((file (dired-get-filename nil t)))
9055 (setq file (if file
9056 (abbreviate-file-name
9057 (expand-file-name (dired-get-filename nil t)))
9058 ;; otherwise, no file so use current directory.
9059 default-directory))
9060 (setq cpltxt (concat "file:" file)
9061 link cpltxt)))
9063 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9064 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9065 (cond
9066 ((org-in-regexp "<<\\(.*?\\)>>")
9067 (setq cpltxt
9068 (concat "file:"
9069 (abbreviate-file-name
9070 (buffer-file-name (buffer-base-buffer)))
9071 "::" (match-string 1))
9072 link cpltxt))
9073 ((and (featurep 'org-id)
9074 (or (eq org-id-link-to-org-use-id t)
9075 (and (org-called-interactively-p 'any)
9076 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9077 (and (eq org-id-link-to-org-use-id
9078 'create-if-interactive-and-no-custom-id)
9079 (not custom-id))))
9080 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9081 ;; We can make a link using the ID.
9082 (setq link (condition-case nil
9083 (prog1 (org-id-store-link)
9084 (setq desc (plist-get org-store-link-plist :description)))
9085 (error
9086 ;; probably before first headline, link to file only
9087 (concat "file:"
9088 (abbreviate-file-name
9089 (buffer-file-name (buffer-base-buffer))))))))
9091 ;; Just link to current headline
9092 (setq cpltxt (concat "file:"
9093 (abbreviate-file-name
9094 (buffer-file-name (buffer-base-buffer)))))
9095 ;; Add a context search string
9096 (when (org-xor org-context-in-file-links arg)
9097 (let* ((ee (org-element-at-point))
9098 (et (org-element-type ee))
9099 (ev (plist-get (cadr ee) :value)))
9100 (setq txt (cond
9101 ((org-at-heading-p) nil)
9102 ((eq et 'keyword) ev)
9103 ((org-region-active-p)
9104 (buffer-substring (region-beginning) (region-end)))))
9105 (when (or (null txt) (string-match "\\S-" txt))
9106 (setq cpltxt
9107 (concat cpltxt "::"
9108 (condition-case nil
9109 (org-make-org-heading-search-string txt)
9110 (error "")))
9111 desc (or (and (eq et 'keyword) ev)
9112 (nth 4 (ignore-errors (org-heading-components)))
9113 "NONE")))))
9114 (if (string-match "::\\'" cpltxt)
9115 (setq cpltxt (substring cpltxt 0 -2)))
9116 (setq link cpltxt))))
9118 ((buffer-file-name (buffer-base-buffer))
9119 ;; Just link to this file here.
9120 (setq cpltxt (concat "file:"
9121 (abbreviate-file-name
9122 (buffer-file-name (buffer-base-buffer)))))
9123 ;; Add a context string
9124 (when (org-xor org-context-in-file-links arg)
9125 (setq txt (if (org-region-active-p)
9126 (buffer-substring (region-beginning) (region-end))
9127 (buffer-substring (point-at-bol) (point-at-eol))))
9128 ;; Only use search option if there is some text.
9129 (when (string-match "\\S-" txt)
9130 (setq cpltxt
9131 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9132 desc "NONE")))
9133 (setq link cpltxt))
9135 ((org-called-interactively-p 'interactive)
9136 (user-error "No method for storing a link from this buffer"))
9138 (t (setq link nil)))
9140 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9141 (setq link (or link cpltxt)
9142 desc (or desc cpltxt))
9143 (cond ((equal desc "NONE") (setq desc nil))
9144 ((string-match org-bracket-link-regexp desc)
9145 (setq desc (replace-regexp-in-string
9146 org-bracket-link-regexp
9147 (concat "\\3" (if (equal (length (match-string 0 desc))
9148 (length desc)) "*" "")) desc))))
9150 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9151 (progn
9152 (setq org-stored-links
9153 (cons (list link desc) org-stored-links))
9154 (message "Stored: %s" (or desc link))
9155 (when custom-id
9156 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9157 "::#" custom-id))
9158 (setq org-stored-links
9159 (cons (list link desc) org-stored-links))))
9160 (or agenda-link (and link (org-make-link-string link desc)))))))
9162 (defun org-store-link-props (&rest plist)
9163 "Store link properties, extract names and addresses."
9164 (let (x adr)
9165 (when (setq x (plist-get plist :from))
9166 (setq adr (mail-extract-address-components x))
9167 (setq plist (plist-put plist :fromname (car adr)))
9168 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9169 (when (setq x (plist-get plist :to))
9170 (setq adr (mail-extract-address-components x))
9171 (setq plist (plist-put plist :toname (car adr)))
9172 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9173 (let ((from (plist-get plist :from))
9174 (to (plist-get plist :to)))
9175 (when (and from to org-from-is-user-regexp)
9176 (setq plist
9177 (plist-put plist :fromto
9178 (if (string-match org-from-is-user-regexp from)
9179 (concat "to %t")
9180 (concat "from %f"))))))
9181 (setq org-store-link-plist plist))
9183 (defun org-add-link-props (&rest plist)
9184 "Add these properties to the link property list."
9185 (let (key value)
9186 (while plist
9187 (setq key (pop plist) value (pop plist))
9188 (setq org-store-link-plist
9189 (plist-put org-store-link-plist key value)))))
9191 (defun org-email-link-description (&optional fmt)
9192 "Return the description part of an email link.
9193 This takes information from `org-store-link-plist' and formats it
9194 according to FMT (default from `org-email-link-description-format')."
9195 (setq fmt (or fmt org-email-link-description-format))
9196 (let* ((p org-store-link-plist)
9197 (to (plist-get p :toaddress))
9198 (from (plist-get p :fromaddress))
9199 (table
9200 (list
9201 (cons "%c" (plist-get p :fromto))
9202 (cons "%F" (plist-get p :from))
9203 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9204 (cons "%T" (plist-get p :to))
9205 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9206 (cons "%s" (plist-get p :subject))
9207 (cons "%d" (plist-get p :date))
9208 (cons "%m" (plist-get p :message-id)))))
9209 (when (string-match "%c" fmt)
9210 ;; Check if the user wrote this message
9211 (if (and org-from-is-user-regexp from to
9212 (save-match-data (string-match org-from-is-user-regexp from)))
9213 (setq fmt (replace-match "to %t" t t fmt))
9214 (setq fmt (replace-match "from %f" t t fmt))))
9215 (org-replace-escapes fmt table)))
9217 (defun org-make-org-heading-search-string (&optional string)
9218 "Make search string for the current headline or STRING."
9219 (let ((s (or string
9220 (and (derived-mode-p 'org-mode)
9221 (save-excursion
9222 (org-back-to-heading t)
9223 (plist-get (cadr (org-element-at-point))
9224 :raw-value)))))
9225 (lines org-context-in-file-links))
9226 (or string (setq s (concat "*" s))) ; Add * for headlines
9227 (when (and string (integerp lines) (> lines 0))
9228 (let ((slines (org-split-string s "\n")))
9229 (when (< lines (length slines))
9230 (setq s (mapconcat
9231 'identity
9232 (reverse (nthcdr (- (length slines) lines)
9233 (reverse slines))) "\n")))))
9234 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9236 (defun org-make-link-string (link &optional description)
9237 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9238 (unless (string-match "\\S-" link)
9239 (error "Empty link"))
9240 (when (and description
9241 (stringp description)
9242 (not (string-match "\\S-" description)))
9243 (setq description nil))
9244 (when (stringp description)
9245 ;; Remove brackets from the description, they are fatal.
9246 (while (string-match "\\[" description)
9247 (setq description (replace-match "{" t t description)))
9248 (while (string-match "\\]" description)
9249 (setq description (replace-match "}" t t description))))
9250 (when (equal link description)
9251 ;; No description needed, it is identical
9252 (setq description nil))
9253 (when (and (not description)
9254 (not (string-match (org-image-file-name-regexp) link))
9255 (not (equal link (org-link-escape link))))
9256 (setq description (org-extract-attributes link)))
9257 (setq link
9258 (cond ((string-match (org-image-file-name-regexp) link) link)
9259 ((string-match org-link-types-re link)
9260 (concat (match-string 1 link)
9261 (org-link-escape (substring link (match-end 1)))))
9262 (t (org-link-escape link))))
9263 (concat "[[" link "]"
9264 (if description (concat "[" description "]") "")
9265 "]"))
9267 (defconst org-link-escape-chars
9268 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9269 "List of characters that should be escaped in link.
9270 This is the list that is used for internal purposes.")
9272 (defconst org-link-escape-chars-browser
9273 '(?\ )
9274 "List of escapes for characters that are problematic in links.
9275 This is the list that is used before handing over to the browser.")
9277 (defun org-link-escape (text &optional table merge)
9278 "Return percent escaped representation of TEXT.
9279 TEXT is a string with the text to escape.
9280 Optional argument TABLE is a list with characters that should be
9281 escaped. When nil, `org-link-escape-chars' is used.
9282 If optional argument MERGE is set, merge TABLE into
9283 `org-link-escape-chars'."
9284 (cond
9285 ((and table merge)
9286 (mapc (lambda (defchr)
9287 (unless (member defchr table)
9288 (setq table (cons defchr table)))) org-link-escape-chars))
9289 ((null table)
9290 (setq table org-link-escape-chars)))
9291 (mapconcat
9292 (lambda (char)
9293 (if (or (member char table)
9294 (and (or (< char 32) (= char 37) (> char 126))
9295 org-url-hexify-p))
9296 (mapconcat (lambda (sequence-element)
9297 (format "%%%.2X" sequence-element))
9298 (or (encode-coding-char char 'utf-8)
9299 (error "Unable to percent escape character: %s"
9300 (char-to-string char))) "")
9301 (char-to-string char))) text ""))
9303 (defun org-link-unescape (str)
9304 "Unhex hexified Unicode strings as returned from the JavaScript function
9305 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9306 (unless (and (null str) (string= "" str))
9307 (let ((pos 0) (case-fold-search t) unhexed)
9308 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9309 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9310 (setq str (replace-match unhexed t t str))
9311 (setq pos (+ pos (length unhexed))))))
9312 str)
9314 (defun org-link-unescape-compound (hex)
9315 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9316 Note: this function also decodes single byte encodings like
9317 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9318 (save-match-data
9319 (let* ((bytes (cdr (split-string hex "%")))
9320 (ret "")
9321 (eat 0)
9322 (sum 0))
9323 (while bytes
9324 (let* ((val (string-to-number (pop bytes) 16))
9325 (shift-xor
9326 (if (= 0 eat)
9327 (cond
9328 ((>= val 252) (cons 6 252))
9329 ((>= val 248) (cons 5 248))
9330 ((>= val 240) (cons 4 240))
9331 ((>= val 224) (cons 3 224))
9332 ((>= val 192) (cons 2 192))
9333 (t (cons 0 0)))
9334 (cons 6 128))))
9335 (if (>= val 192) (setq eat (car shift-xor)))
9336 (setq val (logxor val (cdr shift-xor)))
9337 (setq sum (+ (lsh sum (car shift-xor)) val))
9338 (if (> eat 0) (setq eat (- eat 1)))
9339 (cond
9340 ((= 0 eat) ;multi byte
9341 (setq ret (concat ret (org-char-to-string sum)))
9342 (setq sum 0))
9343 ((not bytes) ; single byte(s)
9344 (setq ret (org-link-unescape-single-byte-sequence hex))))
9345 )) ;; end (while bytes
9346 ret )))
9348 (defun org-link-unescape-single-byte-sequence (hex)
9349 "Unhexify hex-encoded single byte character sequences."
9350 (mapconcat (lambda (byte)
9351 (char-to-string (string-to-number byte 16)))
9352 (cdr (split-string hex "%")) ""))
9354 (defun org-xor (a b)
9355 "Exclusive or."
9356 (if a (not b) b))
9358 (defun org-fixup-message-id-for-http (s)
9359 "Replace special characters in a message id, so it can be used in an http query."
9360 (when (string-match "%" s)
9361 (setq s (mapconcat (lambda (c)
9362 (if (eq c ?%)
9363 "%25"
9364 (char-to-string c)))
9365 s "")))
9366 (while (string-match "<" s)
9367 (setq s (replace-match "%3C" t t s)))
9368 (while (string-match ">" s)
9369 (setq s (replace-match "%3E" t t s)))
9370 (while (string-match "@" s)
9371 (setq s (replace-match "%40" t t s)))
9374 (defun org-link-prettify (link)
9375 "Return a human-readable representation of LINK.
9376 The car of LINK must be a raw link the cdr of LINK must be either
9377 a link description or nil."
9378 (let ((desc (or (cadr link) "<no description>")))
9379 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9380 "<" (car link) ">")))
9382 ;;;###autoload
9383 (defun org-insert-link-global ()
9384 "Insert a link like Org-mode does.
9385 This command can be called in any mode to insert a link in Org-mode syntax."
9386 (interactive)
9387 (org-load-modules-maybe)
9388 (org-run-like-in-org-mode 'org-insert-link))
9390 (defun org-insert-all-links (&optional keep)
9391 "Insert all links in `org-stored-links'."
9392 (interactive "P")
9393 (let ((links (copy-sequence org-stored-links)) l)
9394 (while (setq l (if keep (pop links) (pop org-stored-links)))
9395 (insert "- ")
9396 (org-insert-link nil (car l) (cadr l))
9397 (insert "\n"))))
9399 (defun org-link-fontify-links-to-this-file ()
9400 "Fontify links to the current file in `org-stored-links'."
9401 (let ((f (buffer-file-name)) a b)
9402 (setq a (mapcar (lambda(l)
9403 (let ((ll (car l)))
9404 (when (and (string-match "^file:\\(.+\\)::" ll)
9405 (equal f (expand-file-name (match-string 1 ll))))
9406 ll)))
9407 org-stored-links))
9408 (when (featurep 'org-id)
9409 (setq b (mapcar (lambda(l)
9410 (let ((ll (car l)))
9411 (when (and (string-match "^id:\\(.+\\)$" ll)
9412 (equal f (expand-file-name
9413 (or (org-id-find-id-file
9414 (match-string 1 ll)) ""))))
9415 ll)))
9416 org-stored-links)))
9417 (mapcar (lambda(l)
9418 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9419 (delq nil (append a b)))))
9421 (defvar org-link-links-in-this-file nil)
9422 (defun org-insert-link (&optional complete-file link-location default-description)
9423 "Insert a link. At the prompt, enter the link.
9425 Completion can be used to insert any of the link protocol prefixes like
9426 http or ftp in use.
9428 The history can be used to select a link previously stored with
9429 `org-store-link'. When the empty string is entered (i.e. if you just
9430 press RET at the prompt), the link defaults to the most recently
9431 stored link. As SPC triggers completion in the minibuffer, you need to
9432 use M-SPC or C-q SPC to force the insertion of a space character.
9434 You will also be prompted for a description, and if one is given, it will
9435 be displayed in the buffer instead of the link.
9437 If there is already a link at point, this command will allow you to edit link
9438 and description parts.
9440 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9441 be selected using completion. The path to the file will be relative to the
9442 current directory if the file is in the current directory or a subdirectory.
9443 Otherwise, the link will be the absolute path as completed in the minibuffer
9444 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9445 option `org-link-file-path-type'.
9447 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9448 the current directory or below.
9450 With three \\[universal-argument] prefixes, negate the meaning of
9451 `org-keep-stored-link-after-insertion'.
9453 If `org-make-link-description-function' is non-nil, this function will be
9454 called with the link target, and the result will be the default
9455 link description.
9457 If the LINK-LOCATION parameter is non-nil, this value will be
9458 used as the link location instead of reading one interactively.
9460 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9461 be used as the default description."
9462 (interactive "P")
9463 (let* ((wcf (current-window-configuration))
9464 (origbuf (current-buffer))
9465 (region (if (org-region-active-p)
9466 (buffer-substring (region-beginning) (region-end))))
9467 (remove (and region (list (region-beginning) (region-end))))
9468 (desc region)
9469 tmphist ; byte-compile incorrectly complains about this
9470 (link link-location)
9471 (abbrevs org-link-abbrev-alist-local)
9472 entry file all-prefixes auto-desc)
9473 (cond
9474 (link-location) ; specified by arg, just use it.
9475 ((org-in-regexp org-bracket-link-regexp 1)
9476 ;; We do have a link at point, and we are going to edit it.
9477 (setq remove (list (match-beginning 0) (match-end 0)))
9478 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9479 (setq link (read-string "Link: "
9480 (org-link-unescape
9481 (org-match-string-no-properties 1)))))
9482 ((or (org-in-regexp org-angle-link-re)
9483 (org-in-regexp org-plain-link-re))
9484 ;; Convert to bracket link
9485 (setq remove (list (match-beginning 0) (match-end 0))
9486 link (read-string "Link: "
9487 (org-remove-angle-brackets (match-string 0)))))
9488 ((member complete-file '((4) (16)))
9489 ;; Completing read for file names.
9490 (setq link (org-file-complete-link complete-file)))
9492 ;; Read link, with completion for stored links.
9493 (org-link-fontify-links-to-this-file)
9494 (org-switch-to-buffer-other-window "*Org Links*")
9495 (with-current-buffer "*Org Links*"
9496 (erase-buffer)
9497 (insert "Insert a link.
9498 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9499 (when org-stored-links
9500 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9501 (insert (mapconcat 'org-link-prettify
9502 (reverse org-stored-links) "\n")))
9503 (goto-char (point-min)))
9504 (let ((cw (selected-window)))
9505 (select-window (get-buffer-window "*Org Links*" 'visible))
9506 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9507 (unless (pos-visible-in-window-p (point-max))
9508 (org-fit-window-to-buffer))
9509 (and (window-live-p cw) (select-window cw)))
9510 ;; Fake a link history, containing the stored links.
9511 (setq tmphist (append (mapcar 'car org-stored-links)
9512 org-insert-link-history))
9513 (setq all-prefixes (append (mapcar 'car abbrevs)
9514 (mapcar 'car org-link-abbrev-alist)
9515 org-link-types))
9516 (unwind-protect
9517 (progn
9518 (setq link
9519 (org-completing-read
9520 "Link: "
9521 (append
9522 (mapcar (lambda (x) (concat x ":"))
9523 all-prefixes)
9524 (mapcar 'car org-stored-links))
9525 nil nil nil
9526 'tmphist
9527 (caar org-stored-links)))
9528 (if (not (string-match "\\S-" link))
9529 (error "No link selected"))
9530 (mapc (lambda(l)
9531 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9532 org-stored-links)
9533 (if (or (member link all-prefixes)
9534 (and (equal ":" (substring link -1))
9535 (member (substring link 0 -1) all-prefixes)
9536 (setq link (substring link 0 -1))))
9537 (setq link (with-current-buffer origbuf
9538 (org-link-try-special-completion link)))))
9539 (set-window-configuration wcf)
9540 (kill-buffer "*Org Links*"))
9541 (setq entry (assoc link org-stored-links))
9542 (or entry (push link org-insert-link-history))
9543 (setq desc (or desc (nth 1 entry)))))
9545 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9546 (not org-keep-stored-link-after-insertion))
9547 (setq org-stored-links (delq (assoc link org-stored-links)
9548 org-stored-links)))
9550 (if (string-match org-plain-link-re link)
9551 ;; URL-like link, normalize the use of angular brackets.
9552 (setq link (org-remove-angle-brackets link)))
9554 ;; Check if we are linking to the current file with a search
9555 ;; option If yes, simplify the link by using only the search
9556 ;; option.
9557 (when (and buffer-file-name
9558 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9559 (let* ((path (match-string 1 link))
9560 (case-fold-search nil)
9561 (search (match-string 2 link)))
9562 (save-match-data
9563 (if (equal (file-truename buffer-file-name) (file-truename path))
9564 ;; We are linking to this same file, with a search option
9565 (setq link search)))))
9567 ;; Check if we can/should use a relative path. If yes, simplify the link
9568 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9569 (let* ((type (match-string 1 link))
9570 (path (match-string 2 link))
9571 (origpath path)
9572 (case-fold-search nil))
9573 (cond
9574 ((or (eq org-link-file-path-type 'absolute)
9575 (equal complete-file '(16)))
9576 (setq path (abbreviate-file-name (expand-file-name path))))
9577 ((eq org-link-file-path-type 'noabbrev)
9578 (setq path (expand-file-name path)))
9579 ((eq org-link-file-path-type 'relative)
9580 (setq path (file-relative-name path)))
9582 (save-match-data
9583 (if (string-match (concat "^" (regexp-quote
9584 (expand-file-name
9585 (file-name-as-directory
9586 default-directory))))
9587 (expand-file-name path))
9588 ;; We are linking a file with relative path name.
9589 (setq path (substring (expand-file-name path)
9590 (match-end 0)))
9591 (setq path (abbreviate-file-name (expand-file-name path)))))))
9592 (setq link (concat type path))
9593 (if (equal desc origpath)
9594 (setq desc path))))
9596 (if org-make-link-description-function
9597 (setq desc
9598 (or (condition-case nil
9599 (funcall org-make-link-description-function link desc)
9600 (error (progn (message "Can't get link description from `%s'"
9601 (symbol-name org-make-link-description-function))
9602 (sit-for 2) nil)))
9603 (read-string "Description: " default-description)))
9604 (if default-description (setq desc default-description)
9605 (setq desc (or (and auto-desc desc)
9606 (read-string "Description: " desc)))))
9608 (unless (string-match "\\S-" desc) (setq desc nil))
9609 (if remove (apply 'delete-region remove))
9610 (insert (org-make-link-string link desc))))
9612 (defun org-link-try-special-completion (type)
9613 "If there is completion support for link type TYPE, offer it."
9614 (let ((fun (intern (concat "org-" type "-complete-link"))))
9615 (if (functionp fun)
9616 (funcall fun)
9617 (read-string "Link (no completion support): " (concat type ":")))))
9619 (defun org-file-complete-link (&optional arg)
9620 "Create a file link using completion."
9621 (let (file link)
9622 (setq file (org-iread-file-name "File: "))
9623 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9624 (pwd1 (file-name-as-directory (abbreviate-file-name
9625 (expand-file-name ".")))))
9626 (cond
9627 ((equal arg '(16))
9628 (setq link (concat
9629 "file:"
9630 (abbreviate-file-name (expand-file-name file)))))
9631 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9632 (setq link (concat "file:" (match-string 1 file))))
9633 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9634 (expand-file-name file))
9635 (setq link (concat
9636 "file:" (match-string 1 (expand-file-name file)))))
9637 (t (setq link (concat "file:" file)))))
9638 link))
9640 (defun org-iread-file-name (&rest args)
9641 "Read-file-name using `ido-mode' speedup if available.
9642 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9643 See `read-file-name' for a description of parameters."
9644 (org-without-partial-completion
9645 (if (and org-completion-use-ido
9646 (fboundp 'ido-read-file-name)
9647 (boundp 'ido-mode) ido-mode
9648 (listp (second args)))
9649 (let ((ido-enter-matching-directory nil))
9650 (apply 'ido-read-file-name args))
9651 (apply 'read-file-name args))))
9653 (defun org-completing-read (&rest args)
9654 "Completing-read with SPACE being a normal character."
9655 (let ((enable-recursive-minibuffers t)
9656 (minibuffer-local-completion-map
9657 (copy-keymap minibuffer-local-completion-map)))
9658 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9659 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9660 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9661 (apply 'org-icompleting-read args)))
9663 (defun org-completing-read-no-i (&rest args)
9664 (let (org-completion-use-ido org-completion-use-iswitchb)
9665 (apply 'org-completing-read args)))
9667 (defun org-iswitchb-completing-read (prompt choices &rest args)
9668 "Use iswitch as a completing-read replacement to choose from choices.
9669 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9670 from."
9671 (let* ((iswitchb-use-virtual-buffers nil)
9672 (iswitchb-make-buflist-hook
9673 (lambda ()
9674 (setq iswitchb-temp-buflist choices))))
9675 (iswitchb-read-buffer prompt)))
9677 (defun org-icompleting-read (&rest args)
9678 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9679 (org-without-partial-completion
9680 (if (and org-completion-use-ido
9681 (fboundp 'ido-completing-read)
9682 (boundp 'ido-mode) ido-mode
9683 (listp (second args)))
9684 (let ((ido-enter-matching-directory nil))
9685 (apply 'ido-completing-read (concat (car args))
9686 (if (consp (car (nth 1 args)))
9687 (mapcar 'car (nth 1 args))
9688 (nth 1 args))
9689 (cddr args)))
9690 (if (and org-completion-use-iswitchb
9691 (boundp 'iswitchb-mode) iswitchb-mode
9692 (listp (second args)))
9693 (apply 'org-iswitchb-completing-read (concat (car args))
9694 (if (consp (car (nth 1 args)))
9695 (mapcar 'car (nth 1 args))
9696 (nth 1 args))
9697 (cddr args))
9698 (apply 'completing-read args)))))
9700 (defun org-extract-attributes (s)
9701 "Extract the attributes cookie from a string and set as text property."
9702 (let (a attr (start 0) key value)
9703 (save-match-data
9704 (when (string-match "{{\\([^}]+\\)}}$" s)
9705 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9706 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9707 (setq key (match-string 1 a) value (match-string 2 a)
9708 start (match-end 0)
9709 attr (plist-put attr (intern key) value))))
9710 (org-add-props s nil 'org-attr attr))
9713 (defun org-extract-attributes-from-string (tag)
9714 (let (key value attr)
9715 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9716 (setq key (match-string 1 tag) value (match-string 2 tag)
9717 tag (replace-match "" t t tag)
9718 attr (plist-put attr (intern key) value)))
9719 (cons tag attr)))
9721 (defun org-attributes-to-string (plist)
9722 "Format a property list into an HTML attribute list."
9723 (let ((s "") key value)
9724 (while plist
9725 (setq key (pop plist) value (pop plist))
9726 (and value
9727 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9730 ;;; Opening/following a link
9732 (defvar org-link-search-failed nil)
9734 (defvar org-open-link-functions nil
9735 "Hook for functions finding a plain text link.
9736 These functions must take a single argument, the link content.
9737 They will be called for links that look like [[link text][description]]
9738 when LINK TEXT does not have a protocol like \"http:\" and does not look
9739 like a filename (e.g. \"./blue.png\").
9741 These functions will be called *before* Org attempts to resolve the
9742 link by doing text searches in the current buffer - so if you want a
9743 link \"[[target]]\" to still find \"<<target>>\", your function should
9744 handle this as a special case.
9746 When the function does handle the link, it must return a non-nil value.
9747 If it decides that it is not responsible for this link, it must return
9748 nil to indicate that that Org-mode can continue with other options
9749 like exact and fuzzy text search.")
9751 (defun org-next-link ()
9752 "Move forward to the next link.
9753 If the link is in hidden text, expose it."
9754 (interactive)
9755 (when (and org-link-search-failed (eq this-command last-command))
9756 (goto-char (point-min))
9757 (message "Link search wrapped back to beginning of buffer"))
9758 (setq org-link-search-failed nil)
9759 (let* ((pos (point))
9760 (ct (org-context))
9761 (a (assoc :link ct)))
9762 (if a (goto-char (nth 2 a)))
9763 (if (re-search-forward org-any-link-re nil t)
9764 (progn
9765 (goto-char (match-beginning 0))
9766 (if (outline-invisible-p) (org-show-context)))
9767 (goto-char pos)
9768 (setq org-link-search-failed t)
9769 (error "No further link found"))))
9771 (defun org-previous-link ()
9772 "Move backward to the previous link.
9773 If the link is in hidden text, expose it."
9774 (interactive)
9775 (when (and org-link-search-failed (eq this-command last-command))
9776 (goto-char (point-max))
9777 (message "Link search wrapped back to end of buffer"))
9778 (setq org-link-search-failed nil)
9779 (let* ((pos (point))
9780 (ct (org-context))
9781 (a (assoc :link ct)))
9782 (if a (goto-char (nth 1 a)))
9783 (if (re-search-backward org-any-link-re nil t)
9784 (progn
9785 (goto-char (match-beginning 0))
9786 (if (outline-invisible-p) (org-show-context)))
9787 (goto-char pos)
9788 (setq org-link-search-failed t)
9789 (error "No further link found"))))
9791 (defun org-translate-link (s)
9792 "Translate a link string if a translation function has been defined."
9793 (if (and org-link-translation-function
9794 (fboundp org-link-translation-function)
9795 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9796 (progn
9797 (setq s (funcall org-link-translation-function
9798 (match-string 1 s) (match-string 2 s)))
9799 (concat (car s) ":" (cdr s)))
9802 (defun org-translate-link-from-planner (type path)
9803 "Translate a link from Emacs Planner syntax so that Org can follow it.
9804 This is still an experimental function, your mileage may vary."
9805 (cond
9806 ((member type '("http" "https" "news" "ftp"))
9807 ;; standard Internet links are the same.
9808 nil)
9809 ((and (equal type "irc") (string-match "^//" path))
9810 ;; Planner has two / at the beginning of an irc link, we have 1.
9811 ;; We should have zero, actually....
9812 (setq path (substring path 1)))
9813 ((and (equal type "lisp") (string-match "^/" path))
9814 ;; Planner has a slash, we do not.
9815 (setq type "elisp" path (substring path 1)))
9816 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9817 ;; A typical message link. Planner has the id after the final slash,
9818 ;; we separate it with a hash mark
9819 (setq path (concat (match-string 1 path) "#"
9820 (org-remove-angle-brackets (match-string 2 path)))))
9822 (cons type path))
9824 (defun org-find-file-at-mouse (ev)
9825 "Open file link or URL at mouse."
9826 (interactive "e")
9827 (mouse-set-point ev)
9828 (org-open-at-point 'in-emacs))
9830 (defun org-open-at-mouse (ev)
9831 "Open file link or URL at mouse.
9832 See the docstring of `org-open-file' for details."
9833 (interactive "e")
9834 (mouse-set-point ev)
9835 (if (eq major-mode 'org-agenda-mode)
9836 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9837 (org-open-at-point))
9839 (defvar org-window-config-before-follow-link nil
9840 "The window configuration before following a link.
9841 This is saved in case the need arises to restore it.")
9843 (defvar org-open-link-marker (make-marker)
9844 "Marker pointing to the location where `org-open-at-point; was called.")
9846 ;;;###autoload
9847 (defun org-open-at-point-global ()
9848 "Follow a link like Org-mode does.
9849 This command can be called in any mode to follow a link that has
9850 Org-mode syntax."
9851 (interactive)
9852 (org-run-like-in-org-mode 'org-open-at-point))
9854 ;;;###autoload
9855 (defun org-open-link-from-string (s &optional arg reference-buffer)
9856 "Open a link in the string S, as if it was in Org-mode."
9857 (interactive "sLink: \nP")
9858 (let ((reference-buffer (or reference-buffer (current-buffer))))
9859 (with-temp-buffer
9860 (let ((org-inhibit-startup (not reference-buffer)))
9861 (org-mode)
9862 (insert s)
9863 (goto-char (point-min))
9864 (when reference-buffer
9865 (setq org-link-abbrev-alist-local
9866 (with-current-buffer reference-buffer
9867 org-link-abbrev-alist-local)))
9868 (org-open-at-point arg reference-buffer)))))
9870 (defvar org-open-at-point-functions nil
9871 "Hook that is run when following a link at point.
9873 Functions in this hook must return t if they identify and follow
9874 a link at point. If they don't find anything interesting at point,
9875 they must return nil.")
9877 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9878 (defun org-open-at-point (&optional arg reference-buffer)
9879 "Open link at or after point.
9880 If there is no link at point, this function will search forward up to
9881 the end of the current line.
9882 Normally, files will be opened by an appropriate application. If the
9883 optional prefix argument ARG is non-nil, Emacs will visit the file.
9884 With a double prefix argument, try to open outside of Emacs, in the
9885 application the system uses for this file type."
9886 (interactive "P")
9887 ;; if in a code block, then open the block's results
9888 (unless (call-interactively #'org-babel-open-src-block-result)
9889 (org-load-modules-maybe)
9890 (move-marker org-open-link-marker (point))
9891 (setq org-window-config-before-follow-link (current-window-configuration))
9892 (org-remove-occur-highlights nil nil t)
9893 (cond
9894 ((and (org-at-heading-p)
9895 (not (org-at-timestamp-p t))
9896 (not (org-in-regexp
9897 (concat org-plain-link-re "\\|"
9898 org-bracket-link-regexp "\\|"
9899 org-angle-link-re "\\|"
9900 "[ \t]:[^ \t\n]+:[ \t]*$")))
9901 (not (get-text-property (point) 'org-linked-text)))
9902 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9903 (lk0 (car lkall))
9904 (lk (if (stringp lk0) (list lk0) lk0))
9905 (lkend (cdr lkall)))
9906 (mapcar (lambda(l)
9907 (search-forward l nil lkend)
9908 (goto-char (match-beginning 0))
9909 (org-open-at-point))
9910 lk))
9911 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9912 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9913 ((and (org-at-timestamp-p t)
9914 (not (org-in-regexp org-bracket-link-regexp)))
9915 (org-follow-timestamp-link))
9916 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9917 (not (org-in-regexp org-any-link-re)))
9918 (org-footnote-action))
9920 (let (type path link line search (pos (point)))
9921 (catch 'match
9922 (save-excursion
9923 (skip-chars-forward "^]\n\r")
9924 (when (org-in-regexp org-bracket-link-regexp 1)
9925 (setq link (org-extract-attributes
9926 (org-link-unescape (org-match-string-no-properties 1))))
9927 (while (string-match " *\n *" link)
9928 (setq link (replace-match " " t t link)))
9929 (setq link (org-link-expand-abbrev link))
9930 (cond
9931 ((or (file-name-absolute-p link)
9932 (string-match "^\\.\\.?/" link))
9933 (setq type "file" path link))
9934 ((string-match org-link-re-with-space3 link)
9935 (setq type (match-string 1 link) path (match-string 2 link)))
9936 ((string-match "^help:+\\(.+\\)" link)
9937 (setq type "help" path (match-string 1 link)))
9938 (t (setq type "thisfile" path link)))
9939 (throw 'match t)))
9941 (when (get-text-property (point) 'org-linked-text)
9942 (setq type "thisfile"
9943 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9944 (1+ (point)) (point))
9945 path (buffer-substring
9946 (or (previous-single-property-change pos 'org-linked-text)
9947 (point-min))
9948 (or (next-single-property-change pos 'org-linked-text)
9949 (point-max))))
9950 (throw 'match t))
9952 (save-excursion
9953 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9954 (when (or (org-in-regexp org-angle-link-re)
9955 (and plinkpos (goto-char (car plinkpos))
9956 (save-match-data (not (looking-back "\\[\\[")))))
9957 (setq type (match-string 1)
9958 path (org-link-unescape (match-string 2)))
9959 (throw 'match t))))
9960 (save-excursion
9961 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9962 (setq type "tags"
9963 path (match-string 1))
9964 (while (string-match ":" path)
9965 (setq path (replace-match "+" t t path)))
9966 (throw 'match t)))
9967 (when (org-in-regexp "<\\([^><\n]+\\)>")
9968 (setq type "tree-match"
9969 path (match-string 1))
9970 (throw 'match t)))
9971 (unless path
9972 (user-error "No link found"))
9974 ;; switch back to reference buffer
9975 ;; needed when if called in a temporary buffer through
9976 ;; org-open-link-from-string
9977 (with-current-buffer (or reference-buffer (current-buffer))
9979 ;; Remove any trailing spaces in path
9980 (if (string-match " +\\'" path)
9981 (setq path (replace-match "" t t path)))
9982 (if (and org-link-translation-function
9983 (fboundp org-link-translation-function))
9984 ;; Check if we need to translate the link
9985 (let ((tmp (funcall org-link-translation-function type path)))
9986 (setq type (car tmp) path (cdr tmp))))
9988 (cond
9990 ((assoc type org-link-protocols)
9991 (funcall (nth 1 (assoc type org-link-protocols)) path))
9993 ((equal type "help")
9994 (let ((f-or-v (intern path)))
9995 (cond ((fboundp f-or-v)
9996 (describe-function f-or-v))
9997 ((boundp f-or-v)
9998 (describe-variable f-or-v))
9999 (t (error "Not a known function or variable")))))
10001 ((equal type "mailto")
10002 (let ((cmd (car org-link-mailto-program))
10003 (args (cdr org-link-mailto-program)) args1
10004 (address path) (subject "") a)
10005 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10006 (setq address (match-string 1 path)
10007 subject (org-link-escape (match-string 2 path))))
10008 (while args
10009 (cond
10010 ((not (stringp (car args))) (push (pop args) args1))
10011 (t (setq a (pop args))
10012 (if (string-match "%a" a)
10013 (setq a (replace-match address t t a)))
10014 (if (string-match "%s" a)
10015 (setq a (replace-match subject t t a)))
10016 (push a args1))))
10017 (apply cmd (nreverse args1))))
10019 ((member type '("http" "https" "ftp" "news"))
10020 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10021 (org-link-escape
10022 path org-link-escape-chars-browser)
10023 path))))
10025 ((string= type "doi")
10026 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10027 (org-link-escape
10028 path org-link-escape-chars-browser)
10029 path))))
10031 ((member type '("message"))
10032 (browse-url (concat type ":" path)))
10034 ((string= type "tags")
10035 (org-tags-view arg path))
10037 ((string= type "tree-match")
10038 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10040 ((string= type "file")
10041 (if (string-match "::\\([0-9]+\\)\\'" path)
10042 (setq line (string-to-number (match-string 1 path))
10043 path (substring path 0 (match-beginning 0)))
10044 (if (string-match "::\\(.+\\)\\'" path)
10045 (setq search (match-string 1 path)
10046 path (substring path 0 (match-beginning 0)))))
10047 (if (string-match "[*?{]" (file-name-nondirectory path))
10048 (dired path)
10049 (org-open-file path arg line search)))
10051 ((string= type "shell")
10052 (let ((buf (generate-new-buffer "*Org Shell Output"))
10053 (cmd path))
10054 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10055 (string-match org-confirm-shell-link-not-regexp cmd))
10056 (not org-confirm-shell-link-function)
10057 (funcall org-confirm-shell-link-function
10058 (format "Execute \"%s\" in shell? "
10059 (org-add-props cmd nil
10060 'face 'org-warning))))
10061 (progn
10062 (message "Executing %s" cmd)
10063 (shell-command cmd buf)
10064 (if (featurep 'midnight)
10065 (setq clean-buffer-list-kill-buffer-names
10066 (cons buf clean-buffer-list-kill-buffer-names))))
10067 (error "Abort"))))
10069 ((string= type "elisp")
10070 (let ((cmd path))
10071 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10072 (string-match org-confirm-elisp-link-not-regexp cmd))
10073 (not org-confirm-elisp-link-function)
10074 (funcall org-confirm-elisp-link-function
10075 (format "Execute \"%s\" as elisp? "
10076 (org-add-props cmd nil
10077 'face 'org-warning))))
10078 (message "%s => %s" cmd
10079 (if (equal (string-to-char cmd) ?\()
10080 (eval (read cmd))
10081 (call-interactively (read cmd))))
10082 (error "Abort"))))
10084 ((and (string= type "thisfile")
10085 (run-hook-with-args-until-success
10086 'org-open-link-functions path)))
10088 ((string= type "thisfile")
10089 (if arg
10090 (switch-to-buffer-other-window
10091 (org-get-buffer-for-internal-link (current-buffer)))
10092 (org-mark-ring-push))
10093 (let ((cmd `(org-link-search
10094 ,path
10095 ,(cond ((equal arg '(4)) ''occur)
10096 ((equal arg '(16)) ''org-occur))
10097 ,pos)))
10098 (condition-case nil (let ((org-link-search-inhibit-query t))
10099 (eval cmd))
10100 (error (progn (widen) (eval cmd))))))
10102 (t (browse-url-at-point)))))))
10103 (move-marker org-open-link-marker nil)
10104 (run-hook-with-args 'org-follow-link-hook)))
10106 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10107 "Offer links in the current entry and return the selected link.
10108 If there is only one link, return it.
10109 If NTH is an integer, return the NTH link found.
10110 If ZERO is a string, check also this string for a link, and if
10111 there is one, return it."
10112 (with-current-buffer buffer
10113 (save-excursion
10114 (save-restriction
10115 (widen)
10116 (goto-char marker)
10117 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10118 "\\(" org-angle-link-re "\\)\\|"
10119 "\\(" org-plain-link-re "\\)"))
10120 (cnt ?0)
10121 (in-emacs (if (integerp nth) nil nth))
10122 have-zero end links link c)
10123 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10124 (push (match-string 0 zero) links)
10125 (setq cnt (1- cnt) have-zero t))
10126 (save-excursion
10127 (org-back-to-heading t)
10128 (setq end (save-excursion (outline-next-heading) (point)))
10129 (while (re-search-forward re end t)
10130 (push (match-string 0) links))
10131 (setq links (org-uniquify (reverse links))))
10132 (cond
10133 ((null links)
10134 (message "No links"))
10135 ((equal (length links) 1)
10136 (setq link (car links)))
10137 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10138 (setq link (nth (if have-zero nth (1- nth)) links)))
10139 (t ; we have to select a link
10140 (save-excursion
10141 (save-window-excursion
10142 (delete-other-windows)
10143 (with-output-to-temp-buffer "*Select Link*"
10144 (mapc (lambda (l)
10145 (if (not (string-match org-bracket-link-regexp l))
10146 (princ (format "[%c] %s\n" (incf cnt)
10147 (org-remove-angle-brackets l)))
10148 (if (match-end 3)
10149 (princ (format "[%c] %s (%s)\n" (incf cnt)
10150 (match-string 3 l) (match-string 1 l)))
10151 (princ (format "[%c] %s\n" (incf cnt)
10152 (match-string 1 l))))))
10153 links))
10154 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10155 (message "Select link to open, RET to open all:")
10156 (setq c (read-char-exclusive))
10157 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10158 (when (equal c ?q) (error "Abort"))
10159 (if (equal c ?\C-m)
10160 (setq link links)
10161 (setq nth (- c ?0))
10162 (if have-zero (setq nth (1+ nth)))
10163 (unless (and (integerp nth) (>= (length links) nth))
10164 (error "Invalid link selection"))
10165 (setq link (nth (1- nth) links)))))
10166 (cons link end))))))
10168 ;; Add special file links that specify the way of opening
10170 (org-add-link-type "file+sys" 'org-open-file-with-system)
10171 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10172 (defun org-open-file-with-system (path)
10173 "Open file at PATH using the system way of opening it."
10174 (org-open-file path 'system))
10175 (defun org-open-file-with-emacs (path)
10176 "Open file at PATH in Emacs."
10177 (org-open-file path 'emacs))
10178 (defun org-remove-file-link-modifiers ()
10179 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10180 (goto-char (point-min))
10181 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10182 (org-if-unprotected
10183 (replace-match "file:" t t))))
10184 (eval-after-load "org-exp"
10185 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10186 'org-remove-file-link-modifiers))
10188 ;;; File search
10190 (defvar org-create-file-search-functions nil
10191 "List of functions to construct the right search string for a file link.
10192 These functions are called in turn with point at the location to
10193 which the link should point.
10195 A function in the hook should first test if it would like to
10196 handle this file type, for example by checking the `major-mode'
10197 or the file extension. If it decides not to handle this file, it
10198 should just return nil to give other functions a chance. If it
10199 does handle the file, it must return the search string to be used
10200 when following the link. The search string will be part of the
10201 file link, given after a double colon, and `org-open-at-point'
10202 will automatically search for it. If special measures must be
10203 taken to make the search successful, another function should be
10204 added to the companion hook `org-execute-file-search-functions',
10205 which see.
10207 A function in this hook may also use `setq' to set the variable
10208 `description' to provide a suggestion for the descriptive text to
10209 be used for this link when it gets inserted into an Org-mode
10210 buffer with \\[org-insert-link].")
10212 (defvar org-execute-file-search-functions nil
10213 "List of functions to execute a file search triggered by a link.
10215 Functions added to this hook must accept a single argument, the
10216 search string that was part of the file link, the part after the
10217 double colon. The function must first check if it would like to
10218 handle this search, for example by checking the `major-mode' or
10219 the file extension. If it decides not to handle this search, it
10220 should just return nil to give other functions a chance. If it
10221 does handle the search, it must return a non-nil value to keep
10222 other functions from trying.
10224 Each function can access the current prefix argument through the
10225 variable `current-prefix-argument'. Note that a single prefix is
10226 used to force opening a link in Emacs, so it may be good to only
10227 use a numeric or double prefix to guide the search function.
10229 In case this is needed, a function in this hook can also restore
10230 the window configuration before `org-open-at-point' was called using:
10232 (set-window-configuration org-window-config-before-follow-link)")
10234 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10235 (defun org-link-search (s &optional type avoid-pos stealth)
10236 "Search for a link search option.
10237 If S is surrounded by forward slashes, it is interpreted as a
10238 regular expression. In org-mode files, this will create an `org-occur'
10239 sparse tree. In ordinary files, `occur' will be used to list matches.
10240 If the current buffer is in `dired-mode', grep will be used to search
10241 in all files. If AVOID-POS is given, ignore matches near that position.
10243 When optional argument STEALTH is non-nil, do not modify
10244 visibility around point, thus ignoring
10245 `org-show-hierarchy-above', `org-show-following-heading' and
10246 `org-show-siblings' variables."
10247 (let ((case-fold-search t)
10248 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10249 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10250 (append '(("") (" ") ("\t") ("\n"))
10251 org-emphasis-alist)
10252 "\\|") "\\)"))
10253 (pos (point))
10254 (pre nil) (post nil)
10255 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10256 (cond
10257 ;; First check if there are any special search functions
10258 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10259 ;; Now try the builtin stuff
10260 ((and (equal (string-to-char s0) ?#)
10261 (> (length s0) 1)
10262 (save-excursion
10263 (goto-char (point-min))
10264 (and
10265 (re-search-forward
10266 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10267 (setq type 'dedicated
10268 pos (match-beginning 0))))
10269 ;; There is an exact target for this
10270 (goto-char pos)
10271 (org-back-to-heading t)))
10272 ((save-excursion
10273 (goto-char (point-min))
10274 (and
10275 (re-search-forward
10276 (concat "<<" (regexp-quote s0) ">>") nil t)
10277 (setq type 'dedicated
10278 pos (match-beginning 0))))
10279 ;; There is an exact target for this
10280 (goto-char pos))
10281 ((save-excursion
10282 (goto-char (point-min))
10283 (and
10284 (re-search-forward
10285 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10286 (setq type 'dedicated pos (match-beginning 0))))
10287 ;; Found an invisible target.
10288 (goto-char pos))
10289 ((save-excursion
10290 (goto-char (point-min))
10291 (and
10292 (re-search-forward
10293 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10294 (setq type 'dedicated pos (match-beginning 0))))
10295 ;; Found an element with a matching #+name affiliated keyword.
10296 (goto-char pos))
10297 ((and (string-match "^(\\(.*\\))$" s0)
10298 (save-excursion
10299 (goto-char (point-min))
10300 (and
10301 (re-search-forward
10302 (concat "[^[]" (regexp-quote
10303 (format org-coderef-label-format
10304 (match-string 1 s0))))
10305 nil t)
10306 (setq type 'dedicated
10307 pos (1+ (match-beginning 0))))))
10308 ;; There is a coderef target for this
10309 (goto-char pos))
10310 ((string-match "^/\\(.*\\)/$" s)
10311 ;; A regular expression
10312 (cond
10313 ((derived-mode-p 'org-mode)
10314 (org-occur (match-string 1 s)))
10315 ;;((eq major-mode 'dired-mode)
10316 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10317 (t (org-do-occur (match-string 1 s)))))
10318 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10319 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10320 (goto-char (point-min))
10321 (cond
10322 ((let (case-fold-search)
10323 (re-search-forward (format org-complex-heading-regexp-format
10324 (regexp-quote s))
10325 nil t))
10326 ;; OK, found a match
10327 (setq type 'dedicated)
10328 (goto-char (match-beginning 0)))
10329 ((and (not org-link-search-inhibit-query)
10330 (eq org-link-search-must-match-exact-headline 'query-to-create)
10331 (y-or-n-p "No match - create this as a new heading? "))
10332 (goto-char (point-max))
10333 (or (bolp) (newline))
10334 (insert "* " s "\n")
10335 (beginning-of-line 0))
10337 (goto-char pos)
10338 (error "No match"))))
10340 ;; A normal search string
10341 (when (equal (string-to-char s) ?*)
10342 ;; Anchor on headlines, post may include tags.
10343 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10344 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10345 s (substring s 1)))
10346 (remove-text-properties
10347 0 (length s)
10348 '(face nil mouse-face nil keymap nil fontified nil) s)
10349 ;; Make a series of regular expressions to find a match
10350 (setq words (org-split-string s "[ \n\r\t]+")
10352 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10353 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10354 "\\)" markers)
10355 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10356 re2a (concat "[ \t\r\n]" re2a_)
10357 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10358 re4 (concat "[^a-zA-Z_]" re4_)
10360 re1 (concat pre re2 post)
10361 re3 (concat pre (if pre re4_ re4) post)
10362 re5 (concat pre ".*" re4)
10363 re2 (concat pre re2)
10364 re2a (concat pre (if pre re2a_ re2a))
10365 re4 (concat pre (if pre re4_ re4))
10366 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10367 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10368 re5 "\\)"
10370 (cond
10371 ((eq type 'org-occur) (org-occur reall))
10372 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10373 (t (goto-char (point-min))
10374 (setq type 'fuzzy)
10375 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10376 (org-search-not-self 1 re1 nil t)
10377 (org-search-not-self 1 re2 nil t)
10378 (org-search-not-self 1 re2a nil t)
10379 (org-search-not-self 1 re3 nil t)
10380 (org-search-not-self 1 re4 nil t)
10381 (org-search-not-self 1 re5 nil t)
10383 (goto-char (match-beginning 1))
10384 (goto-char pos)
10385 (error "No match"))))))
10386 (and (derived-mode-p 'org-mode)
10387 (not stealth)
10388 (org-show-context 'link-search))
10389 type))
10391 (defun org-search-not-self (group &rest args)
10392 "Execute `re-search-forward', but only accept matches that do not
10393 enclose the position of `org-open-link-marker'."
10394 (let ((m org-open-link-marker))
10395 (catch 'exit
10396 (while (apply 're-search-forward args)
10397 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10398 (goto-char (match-end group))
10399 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10400 (> (match-beginning 0) (marker-position m))
10401 (< (match-end 0) (marker-position m)))
10402 (save-match-data
10403 (or (not (org-in-regexp
10404 org-bracket-link-analytic-regexp 1))
10405 (not (match-end 4)) ; no description
10406 (and (<= (match-beginning 4) (point))
10407 (>= (match-end 4) (point))))))
10408 (throw 'exit (point))))))))
10410 (defun org-get-buffer-for-internal-link (buffer)
10411 "Return a buffer to be used for displaying the link target of internal links."
10412 (cond
10413 ((not org-display-internal-link-with-indirect-buffer)
10414 buffer)
10415 ((string-match "(Clone)$" (buffer-name buffer))
10416 (message "Buffer is already a clone, not making another one")
10417 ;; we also do not modify visibility in this case
10418 buffer)
10419 (t ; make a new indirect buffer for displaying the link
10420 (let* ((bn (buffer-name buffer))
10421 (ibn (concat bn "(Clone)"))
10422 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10423 (with-current-buffer ib (org-overview))
10424 ib))))
10426 (defun org-do-occur (regexp &optional cleanup)
10427 "Call the Emacs command `occur'.
10428 If CLEANUP is non-nil, remove the printout of the regular expression
10429 in the *Occur* buffer. This is useful if the regex is long and not useful
10430 to read."
10431 (occur regexp)
10432 (when cleanup
10433 (let ((cwin (selected-window)) win beg end)
10434 (when (setq win (get-buffer-window "*Occur*"))
10435 (select-window win))
10436 (goto-char (point-min))
10437 (when (re-search-forward "match[a-z]+" nil t)
10438 (setq beg (match-end 0))
10439 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10440 (setq end (1- (match-beginning 0)))))
10441 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10442 (goto-char (point-min))
10443 (select-window cwin))))
10445 ;;; The mark ring for links jumps
10447 (defvar org-mark-ring nil
10448 "Mark ring for positions before jumps in Org-mode.")
10449 (defvar org-mark-ring-last-goto nil
10450 "Last position in the mark ring used to go back.")
10451 ;; Fill and close the ring
10452 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10453 (loop for i from 1 to org-mark-ring-length do
10454 (push (make-marker) org-mark-ring))
10455 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10456 org-mark-ring)
10458 (defun org-mark-ring-push (&optional pos buffer)
10459 "Put the current position or POS into the mark ring and rotate it."
10460 (interactive)
10461 (setq pos (or pos (point)))
10462 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10463 (move-marker (car org-mark-ring)
10464 (or pos (point))
10465 (or buffer (current-buffer)))
10466 (message "%s"
10467 (substitute-command-keys
10468 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10470 (defun org-mark-ring-goto (&optional n)
10471 "Jump to the previous position in the mark ring.
10472 With prefix arg N, jump back that many stored positions. When
10473 called several times in succession, walk through the entire ring.
10474 Org-mode commands jumping to a different position in the current file,
10475 or to another Org-mode file, automatically push the old position
10476 onto the ring."
10477 (interactive "p")
10478 (let (p m)
10479 (if (eq last-command this-command)
10480 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10481 (setq p org-mark-ring))
10482 (setq org-mark-ring-last-goto p)
10483 (setq m (car p))
10484 (org-pop-to-buffer-same-window (marker-buffer m))
10485 (goto-char m)
10486 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10488 (defun org-remove-angle-brackets (s)
10489 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10490 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10492 (defun org-add-angle-brackets (s)
10493 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10494 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10496 (defun org-remove-double-quotes (s)
10497 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10498 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10501 ;;; Following specific links
10503 (defun org-follow-timestamp-link ()
10504 "Open an agenda view for the time-stamp date/range at point."
10505 (cond
10506 ((org-at-date-range-p t)
10507 (let ((org-agenda-start-on-weekday)
10508 (t1 (match-string 1))
10509 (t2 (match-string 2)) tt1 tt2)
10510 (setq tt1 (time-to-days (org-time-string-to-time t1))
10511 tt2 (time-to-days (org-time-string-to-time t2)))
10512 (let ((org-agenda-buffer-tmp-name
10513 (format "*Org Agenda(a:%s)"
10514 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10515 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10516 ((org-at-timestamp-p t)
10517 (let ((org-agenda-buffer-tmp-name
10518 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10519 (org-agenda-list nil (time-to-days (org-time-string-to-time
10520 (substring (match-string 1) 0 10)))
10521 1)))
10522 (t (error "This should not happen"))))
10525 ;;; Following file links
10526 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10527 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10528 (declare-function mailcap-mime-info
10529 "mailcap" (string &optional request no-decode))
10530 (defvar org-wait nil)
10531 (defun org-open-file (path &optional in-emacs line search)
10532 "Open the file at PATH.
10533 First, this expands any special file name abbreviations. Then the
10534 configuration variable `org-file-apps' is checked if it contains an
10535 entry for this file type, and if yes, the corresponding command is launched.
10537 If no application is found, Emacs simply visits the file.
10539 With optional prefix argument IN-EMACS, Emacs will visit the file.
10540 With a double \\[universal-argument] \\[universal-argument] \
10541 prefix arg, Org tries to avoid opening in Emacs
10542 and to use an external application to visit the file.
10544 Optional LINE specifies a line to go to, optional SEARCH a string
10545 to search for. If LINE or SEARCH is given, the file will be
10546 opened in Emacs, unless an entry from org-file-apps that makes
10547 use of groups in a regexp matches.
10549 If you want to change the way frames are used when following a
10550 link, please customize `org-link-frame-setup'.
10552 If the file does not exist, an error is thrown."
10553 (let* ((file (if (equal path "")
10554 buffer-file-name
10555 (substitute-in-file-name (expand-file-name path))))
10556 (file-apps (append org-file-apps (org-default-apps)))
10557 (apps (org-remove-if
10558 'org-file-apps-entry-match-against-dlink-p file-apps))
10559 (apps-dlink (org-remove-if-not
10560 'org-file-apps-entry-match-against-dlink-p file-apps))
10561 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10562 (dirp (if remp nil (file-directory-p file)))
10563 (file (if (and dirp org-open-directory-means-index-dot-org)
10564 (concat (file-name-as-directory file) "index.org")
10565 file))
10566 (a-m-a-p (assq 'auto-mode apps))
10567 (dfile (downcase file))
10568 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10569 (link (cond ((and (eq line nil)
10570 (eq search nil))
10571 file)
10572 (line
10573 (concat file "::" (number-to-string line)))
10574 (search
10575 (concat file "::" search))))
10576 (dlink (downcase link))
10577 (old-buffer (current-buffer))
10578 (old-pos (point))
10579 (old-mode major-mode)
10580 ext cmd link-match-data)
10581 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10582 (setq ext (match-string 1 dfile))
10583 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10584 (setq ext (match-string 1 dfile))))
10585 (cond
10586 ((member in-emacs '((16) system))
10587 (setq cmd (cdr (assoc 'system apps))))
10588 (in-emacs (setq cmd 'emacs))
10590 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10591 (and dirp (cdr (assoc 'directory apps)))
10592 ; first, try matching against apps-dlink
10593 ; if we get a match here, store the match data for later
10594 (let ((match (assoc-default dlink apps-dlink
10595 'string-match)))
10596 (if match
10597 (progn (setq link-match-data (match-data))
10598 match)
10599 (progn (setq in-emacs (or in-emacs line search))
10600 nil))) ; if we have no match in apps-dlink,
10601 ; always open the file in emacs if line or search
10602 ; is given (for backwards compatibility)
10603 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10604 'string-match)
10605 (cdr (assoc ext apps))
10606 (cdr (assoc t apps))))))
10607 (when (eq cmd 'system)
10608 (setq cmd (cdr (assoc 'system apps))))
10609 (when (eq cmd 'default)
10610 (setq cmd (cdr (assoc t apps))))
10611 (when (eq cmd 'mailcap)
10612 (require 'mailcap)
10613 (mailcap-parse-mailcaps)
10614 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10615 (command (mailcap-mime-info mime-type)))
10616 (if (stringp command)
10617 (setq cmd command)
10618 (setq cmd 'emacs))))
10619 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10620 (not (file-exists-p file))
10621 (not org-open-non-existing-files))
10622 (error "No such file: %s" file))
10623 (cond
10624 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10625 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10626 (while (string-match "['\"]%s['\"]" cmd)
10627 (setq cmd (replace-match "%s" t t cmd)))
10628 (while (string-match "%s" cmd)
10629 (setq cmd (replace-match
10630 (save-match-data
10631 (shell-quote-argument
10632 (convert-standard-filename file)))
10633 t t cmd)))
10635 ;; Replace "%1", "%2" etc. in command with group matches from regex
10636 (save-match-data
10637 (let ((match-index 1)
10638 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10639 (set-match-data link-match-data)
10640 (while (<= match-index number-of-groups)
10641 (let ((regex (concat "%" (number-to-string match-index)))
10642 (replace-with (match-string match-index dlink)))
10643 (while (string-match regex cmd)
10644 (setq cmd (replace-match replace-with t t cmd))))
10645 (setq match-index (+ match-index 1)))))
10647 (save-window-excursion
10648 (message "Running %s...done" cmd)
10649 (start-process-shell-command cmd nil cmd)
10650 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10651 ((or (stringp cmd)
10652 (eq cmd 'emacs))
10653 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10654 (widen)
10655 (if line (org-goto-line line)
10656 (if search (org-link-search search))))
10657 ((consp cmd)
10658 (let ((file (convert-standard-filename file)))
10659 (save-match-data
10660 (set-match-data link-match-data)
10661 (eval cmd))))
10662 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10663 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10664 (or (not (equal old-buffer (current-buffer)))
10665 (not (equal old-pos (point))))
10666 (org-mark-ring-push old-pos old-buffer))))
10668 (defun org-file-apps-entry-match-against-dlink-p (entry)
10669 "This function returns non-nil if `entry' uses a regular
10670 expression which should be matched against the whole link by
10671 org-open-file.
10673 It assumes that is the case when the entry uses a regular
10674 expression which has at least one grouping construct and the
10675 action is either a lisp form or a command string containing
10676 '%1', i.e. using at least one subexpression match as a
10677 parameter."
10678 (let ((selector (car entry))
10679 (action (cdr entry)))
10680 (if (stringp selector)
10681 (and (> (regexp-opt-depth selector) 0)
10682 (or (and (stringp action)
10683 (string-match "%[0-9]" action))
10684 (consp action)))
10685 nil)))
10687 (defun org-default-apps ()
10688 "Return the default applications for this operating system."
10689 (cond
10690 ((eq system-type 'darwin)
10691 org-file-apps-defaults-macosx)
10692 ((eq system-type 'windows-nt)
10693 org-file-apps-defaults-windowsnt)
10694 (t org-file-apps-defaults-gnu)))
10696 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10697 "Convert extensions to regular expressions in the cars of LIST.
10698 Also, weed out any non-string entries, because the return value is used
10699 only for regexp matching.
10700 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10701 point to the symbol `emacs', indicating that the file should
10702 be opened in Emacs."
10703 (append
10704 (delq nil
10705 (mapcar (lambda (x)
10706 (if (not (stringp (car x)))
10708 (if (string-match "\\W" (car x))
10710 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10711 list))
10712 (if add-auto-mode
10713 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10715 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10716 (defun org-file-remote-p (file)
10717 "Test whether FILE specifies a location on a remote system.
10718 Return non-nil if the location is indeed remote.
10720 For example, the filename \"/user@host:/foo\" specifies a location
10721 on the system \"/user@host:\"."
10722 (cond ((fboundp 'file-remote-p)
10723 (file-remote-p file))
10724 ((fboundp 'tramp-handle-file-remote-p)
10725 (tramp-handle-file-remote-p file))
10726 ((and (boundp 'ange-ftp-name-format)
10727 (string-match (car ange-ftp-name-format) file))
10728 t)))
10731 ;;;; Refiling
10733 (defun org-get-org-file ()
10734 "Read a filename, with default directory `org-directory'."
10735 (let ((default (or org-default-notes-file remember-data-file)))
10736 (read-file-name (format "File name [%s]: " default)
10737 (file-name-as-directory org-directory)
10738 default)))
10740 (defun org-notes-order-reversed-p ()
10741 "Check if the current file should receive notes in reversed order."
10742 (cond
10743 ((not org-reverse-note-order) nil)
10744 ((eq t org-reverse-note-order) t)
10745 ((not (listp org-reverse-note-order)) nil)
10746 (t (catch 'exit
10747 (let ((all org-reverse-note-order)
10748 entry)
10749 (while (setq entry (pop all))
10750 (if (string-match (car entry) buffer-file-name)
10751 (throw 'exit (cdr entry))))
10752 nil)))))
10754 (defvar org-refile-target-table nil
10755 "The list of refile targets, created by `org-refile'.")
10757 (defvar org-agenda-new-buffers nil
10758 "Buffers created to visit agenda files.")
10760 (defvar org-refile-cache nil
10761 "Cache for refile targets.")
10763 (defvar org-refile-markers nil
10764 "All the markers used for caching refile locations.")
10766 (defun org-refile-marker (pos)
10767 "Get a new refile marker, but only if caching is in use."
10768 (if (not org-refile-use-cache)
10770 (let ((m (make-marker)))
10771 (move-marker m pos)
10772 (push m org-refile-markers)
10773 m)))
10775 (defun org-refile-cache-clear ()
10776 "Clear the refile cache and disable all the markers."
10777 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10778 (setq org-refile-markers nil)
10779 (setq org-refile-cache nil)
10780 (message "Refile cache has been cleared"))
10782 (defun org-refile-cache-check-set (set)
10783 "Check if all the markers in the cache still have live buffers."
10784 (let (marker)
10785 (catch 'exit
10786 (while (and set (setq marker (nth 3 (pop set))))
10787 ;; if org-refile-use-outline-path is 'file, marker may be nil
10788 (when (and marker (null (marker-buffer marker)))
10789 (message "not found") (sit-for 3)
10790 (throw 'exit nil)))
10791 t)))
10793 (defun org-refile-cache-put (set &rest identifiers)
10794 "Push the refile targets SET into the cache, under IDENTIFIERS."
10795 (let* ((key (sha1 (prin1-to-string identifiers)))
10796 (entry (assoc key org-refile-cache)))
10797 (if entry
10798 (setcdr entry set)
10799 (push (cons key set) org-refile-cache))))
10801 (defun org-refile-cache-get (&rest identifiers)
10802 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10803 (cond
10804 ((not org-refile-cache) nil)
10805 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10807 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10808 org-refile-cache))))
10809 (and set (org-refile-cache-check-set set) set)))))
10811 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10812 "Produce a table with refile targets."
10813 (let ((case-fold-search nil)
10814 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10815 (entries (or org-refile-targets '((nil . (:level . 1)))))
10816 targets tgs txt re files f desc descre fast-path-p level pos0)
10817 (message "Getting targets...")
10818 (with-current-buffer (or default-buffer (current-buffer))
10819 (while (setq entry (pop entries))
10820 (setq files (car entry) desc (cdr entry))
10821 (setq fast-path-p nil)
10822 (cond
10823 ((null files) (setq files (list (current-buffer))))
10824 ((eq files 'org-agenda-files)
10825 (setq files (org-agenda-files 'unrestricted)))
10826 ((and (symbolp files) (fboundp files))
10827 (setq files (funcall files)))
10828 ((and (symbolp files) (boundp files))
10829 (setq files (symbol-value files))))
10830 (if (stringp files) (setq files (list files)))
10831 (cond
10832 ((eq (car desc) :tag)
10833 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10834 ((eq (car desc) :todo)
10835 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10836 ((eq (car desc) :regexp)
10837 (setq descre (cdr desc)))
10838 ((eq (car desc) :level)
10839 (setq descre (concat "^\\*\\{" (number-to-string
10840 (if org-odd-levels-only
10841 (1- (* 2 (cdr desc)))
10842 (cdr desc)))
10843 "\\}[ \t]")))
10844 ((eq (car desc) :maxlevel)
10845 (setq fast-path-p t)
10846 (setq descre (concat "^\\*\\{1," (number-to-string
10847 (if org-odd-levels-only
10848 (1- (* 2 (cdr desc)))
10849 (cdr desc)))
10850 "\\}[ \t]")))
10851 (t (error "Bad refiling target description %s" desc)))
10852 (while (setq f (pop files))
10853 (with-current-buffer
10854 (if (bufferp f) f (org-get-agenda-file-buffer f))
10856 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10857 (progn
10858 (if (bufferp f) (setq f (buffer-file-name
10859 (buffer-base-buffer f))))
10860 (setq f (and f (expand-file-name f)))
10861 (if (eq org-refile-use-outline-path 'file)
10862 (push (list (file-name-nondirectory f) f nil nil) tgs))
10863 (save-excursion
10864 (save-restriction
10865 (widen)
10866 (goto-char (point-min))
10867 (while (re-search-forward descre nil t)
10868 (goto-char (setq pos0 (point-at-bol)))
10869 (catch 'next
10870 (when org-refile-target-verify-function
10871 (save-match-data
10872 (or (funcall org-refile-target-verify-function)
10873 (throw 'next t))))
10874 (when (and (looking-at org-complex-heading-regexp)
10875 (not (member (match-string 4) excluded-entries))
10876 (match-string 4))
10877 (setq level (org-reduced-level
10878 (- (match-end 1) (match-beginning 1)))
10879 txt (org-link-display-format (match-string 4))
10880 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10881 re (format org-complex-heading-regexp-format
10882 (regexp-quote (match-string 4))))
10883 (when org-refile-use-outline-path
10884 (setq txt (mapconcat
10885 'org-protect-slash
10886 (append
10887 (if (eq org-refile-use-outline-path
10888 'file)
10889 (list (file-name-nondirectory
10890 (buffer-file-name
10891 (buffer-base-buffer))))
10892 (if (eq org-refile-use-outline-path
10893 'full-file-path)
10894 (list (buffer-file-name
10895 (buffer-base-buffer)))))
10896 (org-get-outline-path fast-path-p
10897 level txt)
10898 (list txt))
10899 "/")))
10900 (push (list txt f re (org-refile-marker (point)))
10901 tgs)))
10902 (when (= (point) pos0)
10903 ;; verification function has not moved point
10904 (goto-char (point-at-eol))))))))
10905 (when org-refile-use-cache
10906 (org-refile-cache-put tgs (buffer-file-name) descre))
10907 (setq targets (append tgs targets))
10908 ))))
10909 (message "Getting targets...done")
10910 (nreverse targets)))
10912 (defun org-protect-slash (s)
10913 (while (string-match "/" s)
10914 (setq s (replace-match "\\" t t s)))
10917 (defvar org-olpa (make-vector 20 nil))
10919 (defun org-get-outline-path (&optional fastp level heading)
10920 "Return the outline path to the current entry, as a list.
10922 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10923 routine which makes outline path derivations for an entire file,
10924 avoiding backtracing. Refile target collection makes use of that."
10925 (if fastp
10926 (progn
10927 (if (> level 19)
10928 (error "Outline path failure, more than 19 levels"))
10929 (loop for i from level upto 19 do
10930 (aset org-olpa i nil))
10931 (prog1
10932 (delq nil (append org-olpa nil))
10933 (aset org-olpa level heading)))
10934 (let (rtn case-fold-search)
10935 (save-excursion
10936 (save-restriction
10937 (widen)
10938 (while (org-up-heading-safe)
10939 (when (looking-at org-complex-heading-regexp)
10940 (push (org-match-string-no-properties 4) rtn)))
10941 rtn)))))
10943 (defun org-format-outline-path (path &optional width prefix separator)
10944 "Format the outline path PATH for display.
10945 WIDTH is the maximum number of characters that is available.
10946 PREFIX is a prefix to be included in the returned string,
10947 such as the file name.
10948 SEPARATOR is inserted between the different parts of the path,
10949 the default is \"/\"."
10950 (setq width (or width 79))
10951 (if prefix (setq width (- width (length prefix))))
10952 (if (not path)
10953 (or prefix "")
10954 (let* ((nsteps (length path))
10955 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10956 (maxwidth (if (<= total-width width)
10957 10000 ;; everything fits
10958 ;; we need to shorten the level headings
10959 (/ (- width nsteps) nsteps)))
10960 (org-odd-levels-only nil)
10961 (n 0)
10962 (total (1+ (length prefix))))
10963 (setq maxwidth (max maxwidth 10))
10964 (concat prefix
10965 (if prefix (or separator "/"))
10966 (mapconcat
10967 (lambda (h)
10968 (setq n (1+ n))
10969 (if (and (= n nsteps) (< maxwidth 10000))
10970 (setq maxwidth (- total-width total)))
10971 (if (< (length h) maxwidth)
10972 (progn (setq total (+ total (length h) 1)) h)
10973 (setq h (substring h 0 (- maxwidth 2))
10974 total (+ total maxwidth 1))
10975 (if (string-match "[ \t]+\\'" h)
10976 (setq h (substring h 0 (match-beginning 0))))
10977 (setq h (concat h "..")))
10978 (org-add-props h nil 'face
10979 (nth (% (1- n) org-n-level-faces)
10980 org-level-faces))
10982 path (or separator "/"))))))
10984 (defun org-display-outline-path (&optional file current separator just-return-string)
10985 "Display the current outline path in the echo area.
10987 If FILE is non-nil, prepend the output with the file name.
10988 If CURRENT is non-nil, append the current heading to the output.
10989 SEPARATOR is passed through to `org-format-outline-path'. It separates
10990 the different parts of the path and defaults to \"/\".
10991 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10992 (interactive "P")
10993 (let* (case-fold-search
10994 message-log-max ; Don't populate the *Messages* buffer
10995 (bfn (buffer-file-name (buffer-base-buffer)))
10996 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10997 res)
10998 (if current (setq path (append path
10999 (save-excursion
11000 (org-back-to-heading t)
11001 (if (looking-at org-complex-heading-regexp)
11002 (list (match-string 4)))))))
11003 (setq res
11004 (org-format-outline-path
11005 path
11006 (1- (frame-width))
11007 (and file bfn (concat (file-name-nondirectory bfn) separator))
11008 separator))
11009 (if just-return-string
11010 (org-no-properties res)
11011 (message "%s" res))))
11013 (defvar org-refile-history nil
11014 "History for refiling operations.")
11016 (defvar org-after-refile-insert-hook nil
11017 "Hook run after `org-refile' has inserted its stuff at the new location.
11018 Note that this is still *before* the stuff will be removed from
11019 the *old* location.")
11021 (defvar org-capture-last-stored-marker)
11022 (defvar org-refile-keep nil
11023 "Non-nil means `org-refile' will copy instead of refile.")
11025 (defun org-copy ()
11026 "Like `org-refile', but copy."
11027 (interactive)
11028 (let ((org-refile-keep t))
11029 (funcall 'org-refile nil nil nil "Copy")))
11031 (defun org-refile (&optional goto default-buffer rfloc msg)
11032 "Move the entry or entries at point to another heading.
11033 The list of target headings is compiled using the information in
11034 `org-refile-targets', which see.
11036 At the target location, the entry is filed as a subitem of the target
11037 heading. Depending on `org-reverse-note-order', the new subitem will
11038 either be the first or the last subitem.
11040 If there is an active region, all entries in that region will be moved.
11041 However, the region must fulfill the requirement that the first heading
11042 is the first one sets the top-level of the moved text - at most siblings
11043 below it are allowed.
11045 With prefix arg GOTO, the command will only visit the target location
11046 and not actually move anything.
11048 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11049 go to the location where the last refiling operation has put the subtree.
11050 With a prefix argument of `2', refile to the running clock.
11052 RFLOC can be a refile location obtained in a different way.
11054 MSG is a string to replace \"Refile\" in the default prompt with
11055 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11057 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11059 If you are using target caching (see `org-refile-use-cache'),
11060 you have to clear the target cache in order to find new targets.
11061 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11062 prefix argument (`C-u C-u C-u C-c C-w')."
11064 (interactive "P")
11065 (if (member goto '(0 (64)))
11066 (org-refile-cache-clear)
11067 (let* ((actionmsg (or msg "Refile"))
11068 (cbuf (current-buffer))
11069 (regionp (org-region-active-p))
11070 (region-start (and regionp (region-beginning)))
11071 (region-end (and regionp (region-end)))
11072 (region-length (and regionp (- region-end region-start)))
11073 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11074 pos it nbuf file re level reversed)
11075 (setq last-command nil)
11076 (when regionp
11077 (goto-char region-start)
11078 (or (bolp) (goto-char (point-at-bol)))
11079 (setq region-start (point))
11080 (unless (or (org-kill-is-subtree-p
11081 (buffer-substring region-start region-end))
11082 (prog1 org-refile-active-region-within-subtree
11083 (org-toggle-heading)))
11084 (error "The region is not a (sequence of) subtree(s)")))
11085 (if (equal goto '(16))
11086 (org-refile-goto-last-stored)
11087 (when (or
11088 (and (equal goto 2)
11089 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11090 (prog1
11091 (setq it (list (or org-clock-heading "running clock")
11092 (buffer-file-name
11093 (marker-buffer org-clock-hd-marker))
11095 (marker-position org-clock-hd-marker)))
11096 (setq goto nil)))
11097 (setq it (or rfloc
11098 (let (heading-text)
11099 (save-excursion
11100 (unless goto
11101 (org-back-to-heading t)
11102 (setq heading-text
11103 (nth 4 (org-heading-components))))
11105 (org-refile-get-location
11106 (cond (goto "Goto")
11107 (regionp (concat actionmsg " region to"))
11108 (t (concat actionmsg " subtree \""
11109 heading-text "\" to")))
11110 default-buffer
11111 (and (not (equal '(4) goto))
11112 org-refile-allow-creating-parent-nodes)
11113 goto))))))
11114 (setq file (nth 1 it)
11115 re (nth 2 it)
11116 pos (nth 3 it))
11117 (if (and (not goto)
11119 (equal (buffer-file-name) file)
11120 (if regionp
11121 (and (>= pos region-start)
11122 (<= pos region-end))
11123 (and (>= pos (point))
11124 (< pos (save-excursion
11125 (org-end-of-subtree t t))))))
11126 (error "Cannot refile to position inside the tree or region"))
11128 (setq nbuf (or (find-buffer-visiting file)
11129 (find-file-noselect file)))
11130 (if goto
11131 (progn
11132 (org-pop-to-buffer-same-window nbuf)
11133 (goto-char pos)
11134 (org-show-context 'org-goto))
11135 (if regionp
11136 (progn
11137 (org-kill-new (buffer-substring region-start region-end))
11138 (org-save-markers-in-region region-start region-end))
11139 (org-copy-subtree 1 nil t))
11140 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11141 (find-file-noselect file)))
11142 (setq reversed (org-notes-order-reversed-p))
11143 (save-excursion
11144 (save-restriction
11145 (widen)
11146 (if pos
11147 (progn
11148 (goto-char pos)
11149 (looking-at org-outline-regexp)
11150 (setq level (org-get-valid-level (funcall outline-level) 1))
11151 (goto-char
11152 (if reversed
11153 (or (outline-next-heading) (point-max))
11154 (or (save-excursion (org-get-next-sibling))
11155 (org-end-of-subtree t t)
11156 (point-max)))))
11157 (setq level 1)
11158 (if (not reversed)
11159 (goto-char (point-max))
11160 (goto-char (point-min))
11161 (or (outline-next-heading) (goto-char (point-max)))))
11162 (if (not (bolp)) (newline))
11163 (org-paste-subtree level)
11164 (when org-log-refile
11165 (org-add-log-setup 'refile nil nil 'findpos
11166 org-log-refile)
11167 (unless (eq org-log-refile 'note)
11168 (save-excursion (org-add-log-note))))
11169 (and org-auto-align-tags
11170 (let ((org-loop-over-headlines-in-active-region nil))
11171 (org-set-tags nil t)))
11172 (with-demoted-errors
11173 (bookmark-set "org-refile-last-stored"))
11174 ;; If we are refiling for capture, make sure that the
11175 ;; last-capture pointers point here
11176 (when (org-bound-and-true-p org-refile-for-capture)
11177 (with-demoted-errors
11178 (bookmark-set "org-capture-last-stored-marker"))
11179 (move-marker org-capture-last-stored-marker (point)))
11180 (if (fboundp 'deactivate-mark) (deactivate-mark))
11181 (run-hooks 'org-after-refile-insert-hook))))
11182 (unless org-refile-keep
11183 (if regionp
11184 (delete-region (point) (+ (point) region-length))
11185 (org-cut-subtree)))
11186 (when (featurep 'org-inlinetask)
11187 (org-inlinetask-remove-END-maybe))
11188 (setq org-markers-to-move nil)
11189 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11191 (defun org-refile-goto-last-stored ()
11192 "Go to the location where the last refile was stored."
11193 (interactive)
11194 (bookmark-jump "org-refile-last-stored")
11195 (message "This is the location of the last refile"))
11197 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11198 no-exclude)
11199 "Prompt the user for a refile location, using PROMPT.
11200 PROMPT should not be suffixed with a colon and a space, because
11201 this function appends the default value from
11202 `org-refile-history' automatically, if that is not empty.
11203 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11204 this is used for the GOTO interface."
11205 (let ((org-refile-targets org-refile-targets)
11206 (org-refile-use-outline-path org-refile-use-outline-path)
11207 excluded-entries)
11208 (when (and (derived-mode-p 'org-mode)
11209 (not org-refile-use-cache)
11210 (not no-exclude))
11211 (org-map-tree
11212 (lambda()
11213 (setq excluded-entries
11214 (append excluded-entries (list (org-get-heading t t)))))))
11215 (setq org-refile-target-table
11216 (org-refile-get-targets default-buffer excluded-entries)))
11217 (unless org-refile-target-table
11218 (error "No refile targets"))
11219 (let* ((cbuf (current-buffer))
11220 (partial-completion-mode nil)
11221 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11222 (cfunc (if (and org-refile-use-outline-path
11223 org-outline-path-complete-in-steps)
11224 'org-olpath-completing-read
11225 'org-icompleting-read))
11226 (extra (if org-refile-use-outline-path "/" ""))
11227 (cbnex (concat (buffer-name) extra))
11228 (filename (and cfn (expand-file-name cfn)))
11229 (tbl (mapcar
11230 (lambda (x)
11231 (if (and (not (member org-refile-use-outline-path
11232 '(file full-file-path)))
11233 (not (equal filename (nth 1 x))))
11234 (cons (concat (car x) extra " ("
11235 (file-name-nondirectory (nth 1 x)) ")")
11236 (cdr x))
11237 (cons (concat (car x) extra) (cdr x))))
11238 org-refile-target-table))
11239 (completion-ignore-case t)
11240 cdef
11241 (prompt (concat prompt
11242 (or (and (car org-refile-history)
11243 (concat " (default " (car org-refile-history) ")"))
11244 (and (assoc cbnex tbl) (setq cdef cbnex)
11245 (concat " (default " cbnex ")"))) ": "))
11246 pa answ parent-target child parent old-hist)
11247 (setq old-hist org-refile-history)
11248 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11249 nil 'org-refile-history (or cdef (car org-refile-history))))
11250 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11251 (org-refile-check-position pa)
11252 (if pa
11253 (progn
11254 (when (or (not org-refile-history)
11255 (not (eq old-hist org-refile-history))
11256 (not (equal (car pa) (car org-refile-history))))
11257 (setq org-refile-history
11258 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11259 org-refile-history
11260 (cdr org-refile-history))))
11261 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11262 (pop org-refile-history)))
11264 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11265 (progn
11266 (setq parent (match-string 1 answ)
11267 child (match-string 2 answ))
11268 (setq parent-target (or (assoc parent tbl)
11269 (assoc (concat parent "/") tbl)))
11270 (when (and parent-target
11271 (or (eq new-nodes t)
11272 (and (eq new-nodes 'confirm)
11273 (y-or-n-p (format "Create new node \"%s\"? "
11274 child)))))
11275 (org-refile-new-child parent-target child)))
11276 (error "Invalid target location")))))
11278 (declare-function org-string-nw-p "org-macs" (s))
11279 (defun org-refile-check-position (refile-pointer)
11280 "Check if the refile pointer matches the headline to which it points."
11281 (let* ((file (nth 1 refile-pointer))
11282 (re (nth 2 refile-pointer))
11283 (pos (nth 3 refile-pointer))
11284 buffer)
11285 (if (and (not (markerp pos)) (not file))
11286 (error "Please save the buffer to a file before refiling")
11287 (when (org-string-nw-p re)
11288 (setq buffer (if (markerp pos)
11289 (marker-buffer pos)
11290 (or (find-buffer-visiting file)
11291 (find-file-noselect file))))
11292 (with-current-buffer buffer
11293 (save-excursion
11294 (save-restriction
11295 (widen)
11296 (goto-char pos)
11297 (beginning-of-line 1)
11298 (unless (org-looking-at-p re)
11299 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11301 (defun org-refile-new-child (parent-target child)
11302 "Use refile target PARENT-TARGET to add new CHILD below it."
11303 (unless parent-target
11304 (error "Cannot find parent for new node"))
11305 (let ((file (nth 1 parent-target))
11306 (pos (nth 3 parent-target))
11307 level)
11308 (with-current-buffer (or (find-buffer-visiting file)
11309 (find-file-noselect file))
11310 (save-excursion
11311 (save-restriction
11312 (widen)
11313 (if pos
11314 (goto-char pos)
11315 (goto-char (point-max))
11316 (if (not (bolp)) (newline)))
11317 (when (looking-at org-outline-regexp)
11318 (setq level (funcall outline-level))
11319 (org-end-of-subtree t t))
11320 (org-back-over-empty-lines)
11321 (insert "\n" (make-string
11322 (if pos (org-get-valid-level level 1) 1) ?*)
11323 " " child "\n")
11324 (beginning-of-line 0)
11325 (list (concat (car parent-target) "/" child) file "" (point)))))))
11327 (defun org-olpath-completing-read (prompt collection &rest args)
11328 "Read an outline path like a file name."
11329 (let ((thetable collection)
11330 (org-completion-use-ido nil) ; does not work with ido.
11331 (org-completion-use-iswitchb nil)) ; or iswitchb
11332 (apply
11333 'org-icompleting-read prompt
11334 (lambda (string predicate &optional flag)
11335 (let (rtn r f (l (length string)))
11336 (cond
11337 ((eq flag nil)
11338 ;; try completion
11339 (try-completion string thetable))
11340 ((eq flag t)
11341 ;; all-completions
11342 (setq rtn (all-completions string thetable predicate))
11343 (mapcar
11344 (lambda (x)
11345 (setq r (substring x l))
11346 (if (string-match " ([^)]*)$" x)
11347 (setq f (match-string 0 x))
11348 (setq f ""))
11349 (if (string-match "/" r)
11350 (concat string (substring r 0 (match-end 0)) f)
11352 rtn))
11353 ((eq flag 'lambda)
11354 ;; exact match?
11355 (assoc string thetable)))))
11356 args)))
11358 ;;;; Dynamic blocks
11360 (defun org-find-dblock (name)
11361 "Find the first dynamic block with name NAME in the buffer.
11362 If not found, stay at current position and return nil."
11363 (let ((case-fold-search t) pos)
11364 (save-excursion
11365 (goto-char (point-min))
11366 (setq pos (and (re-search-forward
11367 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11368 (match-beginning 0))))
11369 (if pos (goto-char pos))
11370 pos))
11372 (defconst org-dblock-start-re
11373 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11374 "Matches the start line of a dynamic block, with parameters.")
11376 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11377 "Matches the end of a dynamic block.")
11379 (defun org-create-dblock (plist)
11380 "Create a dynamic block section, with parameters taken from PLIST.
11381 PLIST must contain a :name entry which is used as name of the block."
11382 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11383 (end-of-line 1)
11384 (newline))
11385 (let ((col (current-column))
11386 (name (plist-get plist :name)))
11387 (insert "#+BEGIN: " name)
11388 (while plist
11389 (if (eq (car plist) :name)
11390 (setq plist (cddr plist))
11391 (insert " " (prin1-to-string (pop plist)))))
11392 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11393 (beginning-of-line -2)))
11395 (defun org-prepare-dblock ()
11396 "Prepare dynamic block for refresh.
11397 This empties the block, puts the cursor at the insert position and returns
11398 the property list including an extra property :name with the block name."
11399 (unless (looking-at org-dblock-start-re)
11400 (error "Not at a dynamic block"))
11401 (let* ((begdel (1+ (match-end 0)))
11402 (name (org-no-properties (match-string 1)))
11403 (params (append (list :name name)
11404 (read (concat "(" (match-string 3) ")")))))
11405 (save-excursion
11406 (beginning-of-line 1)
11407 (skip-chars-forward " \t")
11408 (setq params (plist-put params :indentation-column (current-column))))
11409 (unless (re-search-forward org-dblock-end-re nil t)
11410 (error "Dynamic block not terminated"))
11411 (setq params
11412 (append params
11413 (list :content (buffer-substring
11414 begdel (match-beginning 0)))))
11415 (delete-region begdel (match-beginning 0))
11416 (goto-char begdel)
11417 (open-line 1)
11418 params))
11420 (defun org-map-dblocks (&optional command)
11421 "Apply COMMAND to all dynamic blocks in the current buffer.
11422 If COMMAND is not given, use `org-update-dblock'."
11423 (let ((cmd (or command 'org-update-dblock)))
11424 (save-excursion
11425 (goto-char (point-min))
11426 (while (re-search-forward org-dblock-start-re nil t)
11427 (goto-char (match-beginning 0))
11428 (save-excursion
11429 (condition-case nil
11430 (funcall cmd)
11431 (error (message "Error during update of dynamic block"))))
11432 (unless (re-search-forward org-dblock-end-re nil t)
11433 (error "Dynamic block not terminated"))))))
11435 (defun org-dblock-update (&optional arg)
11436 "User command for updating dynamic blocks.
11437 Update the dynamic block at point. With prefix ARG, update all dynamic
11438 blocks in the buffer."
11439 (interactive "P")
11440 (if arg
11441 (org-update-all-dblocks)
11442 (or (looking-at org-dblock-start-re)
11443 (org-beginning-of-dblock))
11444 (org-update-dblock)))
11446 (defun org-update-dblock ()
11447 "Update the dynamic block at point.
11448 This means to empty the block, parse for parameters and then call
11449 the correct writing function."
11450 (interactive)
11451 (save-window-excursion
11452 (let* ((pos (point))
11453 (line (org-current-line))
11454 (params (org-prepare-dblock))
11455 (name (plist-get params :name))
11456 (indent (plist-get params :indentation-column))
11457 (cmd (intern (concat "org-dblock-write:" name))))
11458 (message "Updating dynamic block `%s' at line %d..." name line)
11459 (funcall cmd params)
11460 (message "Updating dynamic block `%s' at line %d...done" name line)
11461 (goto-char pos)
11462 (when (and indent (> indent 0))
11463 (setq indent (make-string indent ?\ ))
11464 (save-excursion
11465 (org-beginning-of-dblock)
11466 (forward-line 1)
11467 (while (not (looking-at org-dblock-end-re))
11468 (insert indent)
11469 (beginning-of-line 2))
11470 (when (looking-at org-dblock-end-re)
11471 (and (looking-at "[ \t]+")
11472 (replace-match ""))
11473 (insert indent)))))))
11475 (defun org-beginning-of-dblock ()
11476 "Find the beginning of the dynamic block at point.
11477 Error if there is no such block at point."
11478 (let ((pos (point))
11479 beg)
11480 (end-of-line 1)
11481 (if (and (re-search-backward org-dblock-start-re nil t)
11482 (setq beg (match-beginning 0))
11483 (re-search-forward org-dblock-end-re nil t)
11484 (> (match-end 0) pos))
11485 (goto-char beg)
11486 (goto-char pos)
11487 (error "Not in a dynamic block"))))
11489 (defun org-update-all-dblocks ()
11490 "Update all dynamic blocks in the buffer.
11491 This function can be used in a hook."
11492 (interactive)
11493 (when (derived-mode-p 'org-mode)
11494 (org-map-dblocks 'org-update-dblock)))
11497 ;;;; Completion
11499 (defconst org-additional-option-like-keywords
11500 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11501 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11502 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11503 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11504 "BEGIN:" "END:"
11505 "ORGTBL" "TBLFM:" "TBLNAME:"
11506 "BEGIN_EXAMPLE" "END_EXAMPLE"
11507 "BEGIN_VERBATIM" "END_VERBATIM"
11508 "BEGIN_QUOTE" "END_QUOTE"
11509 "BEGIN_VERSE" "END_VERSE"
11510 "BEGIN_CENTER" "END_CENTER"
11511 "BEGIN_SRC" "END_SRC"
11512 "BEGIN_RESULT" "END_RESULT"
11513 "BEGIN_lstlisting" "END_lstlisting"
11514 "NAME:" "RESULTS:"
11515 "HEADER:" "HEADERS:"
11516 "COLUMNS:" "PROPERTY:"
11517 "CAPTION:" "LABEL:"
11518 "SETUPFILE:"
11519 "INCLUDE:" "INDEX:"
11520 "BIND:"
11521 "MACRO:"))
11523 (defconst org-options-keywords
11524 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11525 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11526 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11527 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11528 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11529 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11530 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11532 (defconst org-additional-option-like-keywords-for-flyspell
11533 (delete-dups
11534 (split-string
11535 (mapconcat (lambda(k)
11536 (replace-regexp-in-string
11537 "_\\|:" " "
11538 (concat k " " (downcase k) " " (upcase k))))
11539 (append org-options-keywords org-additional-option-like-keywords)
11540 " ")
11541 " +" t)))
11543 (defcustom org-structure-template-alist
11544 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11545 "<src lang=\"?\">\n\n</src>")
11546 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11547 "<example>\n?\n</example>")
11548 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11549 "<quote>\n?\n</quote>")
11550 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11551 "<verse>\n?\n</verse>")
11552 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11553 "<verbatim>\n?\n</verbatim>")
11554 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11555 "<center>\n?\n</center>")
11556 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11557 "<literal style=\"latex\">\n?\n</literal>")
11558 ("L" "#+LaTeX: "
11559 "<literal style=\"latex\">?</literal>")
11560 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11561 "<literal style=\"html\">\n?\n</literal>")
11562 ("H" "#+HTML: "
11563 "<literal style=\"html\">?</literal>")
11564 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11565 ("A" "#+ASCII: ")
11566 ("i" "#+INDEX: ?"
11567 "#+INDEX: ?")
11568 ("I" "#+INCLUDE: %file ?"
11569 "<include file=%file markup=\"?\">"))
11570 "Structure completion elements.
11571 This is a list of abbreviation keys and values. The value gets inserted
11572 if you type `<' followed by the key and then press the completion key,
11573 usually `M-TAB'. %file will be replaced by a file name after prompting
11574 for the file using completion. The cursor will be placed at the position
11575 of the `?` in the template.
11576 There are two templates for each key, the first uses the original Org syntax,
11577 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11578 the default when the /org-mtags.el/ module has been loaded. See also the
11579 variable `org-mtags-prefer-muse-templates'."
11580 :group 'org-completion
11581 :type '(repeat
11582 (string :tag "Key")
11583 (string :tag "Template")
11584 (string :tag "Muse Template")))
11586 (defun org-try-structure-completion ()
11587 "Try to complete a structure template before point.
11588 This looks for strings like \"<e\" on an otherwise empty line and
11589 expands them."
11590 (let ((l (buffer-substring (point-at-bol) (point)))
11592 (when (and (looking-at "[ \t]*$")
11593 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11594 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11595 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11596 (match-beginning 1)) a)
11597 t)))
11599 (defun org-complete-expand-structure-template (start cell)
11600 "Expand a structure template."
11601 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11602 (rpl (nth (if musep 2 1) cell))
11603 (ind ""))
11604 (delete-region start (point))
11605 (when (string-match "\\`#\\+" rpl)
11606 (cond
11607 ((bolp))
11608 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11609 (setq ind (buffer-substring (point-at-bol) (point))))
11610 (t (newline))))
11611 (setq start (point))
11612 (if (string-match "%file" rpl)
11613 (setq rpl (replace-match
11614 (concat
11615 "\""
11616 (save-match-data
11617 (abbreviate-file-name (read-file-name "Include file: ")))
11618 "\"")
11619 t t rpl)))
11620 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11621 (concat "\n" ind)))
11622 (insert rpl)
11623 (if (re-search-backward "\\?" start t) (delete-char 1))))
11625 ;;;; TODO, DEADLINE, Comments
11627 (defun org-toggle-comment ()
11628 "Change the COMMENT state of an entry."
11629 (interactive)
11630 (save-excursion
11631 (org-back-to-heading)
11632 (let (case-fold-search)
11633 (cond
11634 ((looking-at (format org-heading-keyword-regexp-format
11635 org-comment-string))
11636 (goto-char (match-end 1))
11637 (looking-at (concat " +" org-comment-string))
11638 (replace-match "" t t)
11639 (when (eolp) (insert " ")))
11640 ((looking-at org-outline-regexp)
11641 (goto-char (match-end 0))
11642 (insert org-comment-string " "))))))
11644 (defvar org-last-todo-state-is-todo nil
11645 "This is non-nil when the last TODO state change led to a TODO state.
11646 If the last change removed the TODO tag or switched to DONE, then
11647 this is nil.")
11649 (defvar org-setting-tags nil) ; dynamically skipped
11651 (defvar org-todo-setup-filter-hook nil
11652 "Hook for functions that pre-filter todo specs.
11653 Each function takes a todo spec and returns either nil or the spec
11654 transformed into canonical form." )
11656 (defvar org-todo-get-default-hook nil
11657 "Hook for functions that get a default item for todo.
11658 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11659 nil or a string to be used for the todo mark." )
11661 (defvar org-agenda-headline-snapshot-before-repeat)
11663 (defun org-current-effective-time ()
11664 "Return current time adjusted for `org-extend-today-until' variable."
11665 (let* ((ct (org-current-time))
11666 (dct (decode-time ct))
11667 (ct1
11668 (cond
11669 (org-use-last-clock-out-time-as-effective-time
11670 (or (org-clock-get-last-clock-out-time) ct))
11671 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11672 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11673 (t ct))))
11674 ct1))
11676 (defun org-todo-yesterday (&optional arg)
11677 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11678 (interactive "P")
11679 (if (eq major-mode 'org-agenda-mode)
11680 (apply 'org-agenda-todo-yesterday arg)
11681 (let* ((hour (third (decode-time
11682 (org-current-time))))
11683 (org-extend-today-until (1+ hour)))
11684 (org-todo arg))))
11686 (defvar org-block-entry-blocking ""
11687 "First entry preventing the TODO state change.")
11689 (defun org-todo (&optional arg)
11690 "Change the TODO state of an item.
11691 The state of an item is given by a keyword at the start of the heading,
11692 like
11693 *** TODO Write paper
11694 *** DONE Call mom
11696 The different keywords are specified in the variable `org-todo-keywords'.
11697 By default the available states are \"TODO\" and \"DONE\".
11698 So for this example: when the item starts with TODO, it is changed to DONE.
11699 When it starts with DONE, the DONE is removed. And when neither TODO nor
11700 DONE are present, add TODO at the beginning of the heading.
11702 With \\[universal-argument] prefix arg, use completion to determine the new \
11703 state.
11704 With numeric prefix arg, switch to that state.
11705 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11706 keywords (nextset).
11707 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11708 With a numeric prefix arg of 0, inhibit note taking for the change.
11710 For calling through lisp, arg is also interpreted in the following way:
11711 'none -> empty state
11712 \"\"(empty string) -> switch to empty state
11713 'done -> switch to DONE
11714 'nextset -> switch to the next set of keywords
11715 'previousset -> switch to the previous set of keywords
11716 \"WAITING\" -> switch to the specified keyword, but only if it
11717 really is a member of `org-todo-keywords'."
11718 (interactive "P")
11719 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11720 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11721 'region-start-level 'region))
11722 org-loop-over-headlines-in-active-region)
11723 (org-map-entries
11724 `(org-todo ,arg)
11725 org-loop-over-headlines-in-active-region
11726 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11727 (if (equal arg '(16)) (setq arg 'nextset))
11728 (let ((org-blocker-hook org-blocker-hook)
11729 commentp
11730 case-fold-search)
11731 (when (equal arg '(64))
11732 (setq arg nil org-blocker-hook nil))
11733 (when (and org-blocker-hook
11734 (or org-inhibit-blocking
11735 (org-entry-get nil "NOBLOCKING")))
11736 (setq org-blocker-hook nil))
11737 (save-excursion
11738 (catch 'exit
11739 (org-back-to-heading t)
11740 (when (looking-at (concat "^\\*+ " org-comment-string))
11741 (org-toggle-comment)
11742 (setq commentp t))
11743 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11744 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11745 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11746 (let* ((match-data (match-data))
11747 (startpos (point-at-bol))
11748 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11749 (org-log-done org-log-done)
11750 (org-log-repeat org-log-repeat)
11751 (org-todo-log-states org-todo-log-states)
11752 (org-inhibit-logging
11753 (if (equal arg 0)
11754 (progn (setq arg nil) 'note) org-inhibit-logging))
11755 (this (match-string 1))
11756 (hl-pos (match-beginning 0))
11757 (head (org-get-todo-sequence-head this))
11758 (ass (assoc head org-todo-kwd-alist))
11759 (interpret (nth 1 ass))
11760 (done-word (nth 3 ass))
11761 (final-done-word (nth 4 ass))
11762 (org-last-state (or this ""))
11763 (completion-ignore-case t)
11764 (member (member this org-todo-keywords-1))
11765 (tail (cdr member))
11766 (org-state (cond
11767 ((and org-todo-key-trigger
11768 (or (and (equal arg '(4))
11769 (eq org-use-fast-todo-selection 'prefix))
11770 (and (not arg) org-use-fast-todo-selection
11771 (not (eq org-use-fast-todo-selection
11772 'prefix)))))
11773 ;; Use fast selection
11774 (org-fast-todo-selection))
11775 ((and (equal arg '(4))
11776 (or (not org-use-fast-todo-selection)
11777 (not org-todo-key-trigger)))
11778 ;; Read a state with completion
11779 (org-icompleting-read
11780 "State: " (mapcar (lambda(x) (list x))
11781 org-todo-keywords-1)
11782 nil t))
11783 ((eq arg 'right)
11784 (if this
11785 (if tail (car tail) nil)
11786 (car org-todo-keywords-1)))
11787 ((eq arg 'left)
11788 (if (equal member org-todo-keywords-1)
11790 (if this
11791 (nth (- (length org-todo-keywords-1)
11792 (length tail) 2)
11793 org-todo-keywords-1)
11794 (org-last org-todo-keywords-1))))
11795 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11796 (setq arg nil))) ; hack to fall back to cycling
11797 (arg
11798 ;; user or caller requests a specific state
11799 (cond
11800 ((equal arg "") nil)
11801 ((eq arg 'none) nil)
11802 ((eq arg 'done) (or done-word (car org-done-keywords)))
11803 ((eq arg 'nextset)
11804 (or (car (cdr (member head org-todo-heads)))
11805 (car org-todo-heads)))
11806 ((eq arg 'previousset)
11807 (let ((org-todo-heads (reverse org-todo-heads)))
11808 (or (car (cdr (member head org-todo-heads)))
11809 (car org-todo-heads))))
11810 ((car (member arg org-todo-keywords-1)))
11811 ((stringp arg)
11812 (error "State `%s' not valid in this file" arg))
11813 ((nth (1- (prefix-numeric-value arg))
11814 org-todo-keywords-1))))
11815 ((null member) (or head (car org-todo-keywords-1)))
11816 ((equal this final-done-word) nil) ;; -> make empty
11817 ((null tail) nil) ;; -> first entry
11818 ((memq interpret '(type priority))
11819 (if (eq this-command last-command)
11820 (car tail)
11821 (if (> (length tail) 0)
11822 (or done-word (car org-done-keywords))
11823 nil)))
11825 (car tail))))
11826 (org-state (or
11827 (run-hook-with-args-until-success
11828 'org-todo-get-default-hook org-state org-last-state)
11829 org-state))
11830 (next (if org-state (concat " " org-state " ") " "))
11831 (change-plist (list :type 'todo-state-change :from this :to org-state
11832 :position startpos))
11833 dolog now-done-p)
11834 (when org-blocker-hook
11835 (setq org-last-todo-state-is-todo
11836 (not (member this org-done-keywords)))
11837 (unless (save-excursion
11838 (save-match-data
11839 (org-with-wide-buffer
11840 (run-hook-with-args-until-failure
11841 'org-blocker-hook change-plist))))
11842 (if (org-called-interactively-p 'interactive)
11843 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11844 this org-state org-block-entry-blocking)
11845 ;; fail silently
11846 (message "TODO state change from %s to %s blocked (by \"%s\")"
11847 this org-state org-block-entry-blocking)
11848 (throw 'exit nil))))
11849 (store-match-data match-data)
11850 (replace-match next t t)
11851 (unless (pos-visible-in-window-p hl-pos)
11852 (message "TODO state changed to %s" (org-trim next)))
11853 (unless head
11854 (setq head (org-get-todo-sequence-head org-state)
11855 ass (assoc head org-todo-kwd-alist)
11856 interpret (nth 1 ass)
11857 done-word (nth 3 ass)
11858 final-done-word (nth 4 ass)))
11859 (when (memq arg '(nextset previousset))
11860 (message "Keyword-Set %d/%d: %s"
11861 (- (length org-todo-sets) -1
11862 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11863 (length org-todo-sets)
11864 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11865 (setq org-last-todo-state-is-todo
11866 (not (member org-state org-done-keywords)))
11867 (setq now-done-p (and (member org-state org-done-keywords)
11868 (not (member this org-done-keywords))))
11869 (and logging (org-local-logging logging))
11870 (when (and (or org-todo-log-states org-log-done)
11871 (not (eq org-inhibit-logging t))
11872 (not (memq arg '(nextset previousset))))
11873 ;; we need to look at recording a time and note
11874 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11875 (nth 2 (assoc this org-todo-log-states))))
11876 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11877 (setq dolog 'time))
11878 (when (and org-state
11879 (member org-state org-not-done-keywords)
11880 (not (member this org-not-done-keywords)))
11881 ;; This is now a todo state and was not one before
11882 ;; If there was a CLOSED time stamp, get rid of it.
11883 (org-add-planning-info nil nil 'closed))
11884 (when (and now-done-p org-log-done)
11885 ;; It is now done, and it was not done before
11886 (org-add-planning-info 'closed (org-current-effective-time))
11887 (if (and (not dolog) (eq 'note org-log-done))
11888 (org-add-log-setup 'done org-state this 'findpos 'note)))
11889 (when (and org-state dolog)
11890 ;; This is a non-nil state, and we need to log it
11891 (org-add-log-setup 'state org-state this 'findpos dolog)))
11892 ;; Fixup tag positioning
11893 (org-todo-trigger-tag-changes org-state)
11894 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11895 (when org-provide-todo-statistics
11896 (org-update-parent-todo-statistics))
11897 (run-hooks 'org-after-todo-state-change-hook)
11898 (if (and arg (not (member org-state org-done-keywords)))
11899 (setq head (org-get-todo-sequence-head org-state)))
11900 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11901 ;; Do we need to trigger a repeat?
11902 (when now-done-p
11903 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11904 ;; This is for the agenda, take a snapshot of the headline.
11905 (save-match-data
11906 (setq org-agenda-headline-snapshot-before-repeat
11907 (org-get-heading))))
11908 (org-auto-repeat-maybe org-state))
11909 ;; Fixup cursor location if close to the keyword
11910 (if (and (outline-on-heading-p)
11911 (not (bolp))
11912 (save-excursion (beginning-of-line 1)
11913 (looking-at org-todo-line-regexp))
11914 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11915 (progn
11916 (goto-char (or (match-end 2) (match-end 1)))
11917 (and (looking-at " ") (just-one-space))))
11918 (when org-trigger-hook
11919 (save-excursion
11920 (run-hook-with-args 'org-trigger-hook change-plist)))
11921 (when commentp (org-toggle-comment))))))))
11923 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11924 "Block turning an entry into a TODO, using the hierarchy.
11925 This checks whether the current task should be blocked from state
11926 changes. Such blocking occurs when:
11928 1. The task has children which are not all in a completed state.
11930 2. A task has a parent with the property :ORDERED:, and there
11931 are siblings prior to the current task with incomplete
11932 status.
11934 3. The parent of the task is blocked because it has siblings that should
11935 be done first, or is child of a block grandparent TODO entry."
11937 (if (not org-enforce-todo-dependencies)
11938 t ; if locally turned off don't block
11939 (catch 'dont-block
11940 ;; If this is not a todo state change, or if this entry is already DONE,
11941 ;; do not block
11942 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11943 (member (plist-get change-plist :from)
11944 (cons 'done org-done-keywords))
11945 (member (plist-get change-plist :to)
11946 (cons 'todo org-not-done-keywords))
11947 (not (plist-get change-plist :to)))
11948 (throw 'dont-block t))
11949 ;; If this task has children, and any are undone, it's blocked
11950 (save-excursion
11951 (org-back-to-heading t)
11952 (let ((this-level (funcall outline-level)))
11953 (outline-next-heading)
11954 (let ((child-level (funcall outline-level)))
11955 (while (and (not (eobp))
11956 (> child-level this-level))
11957 ;; this todo has children, check whether they are all
11958 ;; completed
11959 (if (and (not (org-entry-is-done-p))
11960 (org-entry-is-todo-p))
11961 (progn (setq org-block-entry-blocking (org-get-heading))
11962 (throw 'dont-block nil)))
11963 (outline-next-heading)
11964 (setq child-level (funcall outline-level))))))
11965 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11966 ;; any previous siblings are undone, it's blocked
11967 (save-excursion
11968 (org-back-to-heading t)
11969 (let* ((pos (point))
11970 (parent-pos (and (org-up-heading-safe) (point))))
11971 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11972 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11973 (forward-line 1)
11974 (re-search-forward org-not-done-heading-regexp pos t))
11975 (setq org-block-entry-blocking (match-string 0))
11976 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11977 ;; Search further up the hierarchy, to see if an ancestor is blocked
11978 (while t
11979 (goto-char parent-pos)
11980 (if (not (looking-at org-not-done-heading-regexp))
11981 (throw 'dont-block t)) ; do not block, parent is not a TODO
11982 (setq pos (point))
11983 (setq parent-pos (and (org-up-heading-safe) (point)))
11984 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11985 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11986 (forward-line 1)
11987 (re-search-forward org-not-done-heading-regexp pos t)
11988 (setq org-block-entry-blocking (org-get-heading)))
11989 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11991 (defcustom org-track-ordered-property-with-tag nil
11992 "Should the ORDERED property also be shown as a tag?
11993 The ORDERED property decides if an entry should require subtasks to be
11994 completed in sequence. Since a property is not very visible, setting
11995 this option means that toggling the ORDERED property with the command
11996 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11997 not relevant for the behavior, but it makes things more visible.
11999 Note that toggling the tag with tags commands will not change the property
12000 and therefore not influence behavior!
12002 This can be t, meaning the tag ORDERED should be used, It can also be a
12003 string to select a different tag for this task."
12004 :group 'org-todo
12005 :type '(choice
12006 (const :tag "No tracking" nil)
12007 (const :tag "Track with ORDERED tag" t)
12008 (string :tag "Use other tag")))
12010 (defun org-toggle-ordered-property ()
12011 "Toggle the ORDERED property of the current entry.
12012 For better visibility, you can track the value of this property with a tag.
12013 See variable `org-track-ordered-property-with-tag'."
12014 (interactive)
12015 (let* ((t1 org-track-ordered-property-with-tag)
12016 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12017 (save-excursion
12018 (org-back-to-heading)
12019 (if (org-entry-get nil "ORDERED")
12020 (progn
12021 (org-delete-property "ORDERED")
12022 (and tag (org-toggle-tag tag 'off))
12023 (message "Subtasks can be completed in arbitrary order"))
12024 (org-entry-put nil "ORDERED" "t")
12025 (and tag (org-toggle-tag tag 'on))
12026 (message "Subtasks must be completed in sequence")))))
12028 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12029 (defun org-block-todo-from-checkboxes (change-plist)
12030 "Block turning an entry into a TODO, using checkboxes.
12031 This checks whether the current task should be blocked from state
12032 changes because there are unchecked boxes in this entry."
12033 (if (not org-enforce-todo-checkbox-dependencies)
12034 t ; if locally turned off don't block
12035 (catch 'dont-block
12036 ;; If this is not a todo state change, or if this entry is already DONE,
12037 ;; do not block
12038 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12039 (member (plist-get change-plist :from)
12040 (cons 'done org-done-keywords))
12041 (member (plist-get change-plist :to)
12042 (cons 'todo org-not-done-keywords))
12043 (not (plist-get change-plist :to)))
12044 (throw 'dont-block t))
12045 ;; If this task has checkboxes that are not checked, it's blocked
12046 (save-excursion
12047 (org-back-to-heading t)
12048 (let ((beg (point)) end)
12049 (outline-next-heading)
12050 (setq end (point))
12051 (goto-char beg)
12052 (if (org-list-search-forward
12053 (concat (org-item-beginning-re)
12054 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12055 "\\[[- ]\\]")
12056 end t)
12057 (progn
12058 (if (boundp 'org-blocked-by-checkboxes)
12059 (setq org-blocked-by-checkboxes t))
12060 (throw 'dont-block nil)))))
12061 t))) ; do not block
12063 (defun org-entry-blocked-p ()
12064 "Is the current entry blocked?"
12065 (org-with-buffer-modified-unmodified
12066 (if (org-entry-get nil "NOBLOCKING")
12067 nil ;; Never block this entry
12068 (not
12069 (run-hook-with-args-until-failure
12070 'org-blocker-hook
12071 (list :type 'todo-state-change
12072 :position (point)
12073 :from 'todo
12074 :to 'done))))))
12076 (defun org-update-statistics-cookies (all)
12077 "Update the statistics cookie, either from TODO or from checkboxes.
12078 This should be called with the cursor in a line with a statistics cookie."
12079 (interactive "P")
12080 (if all
12081 (progn
12082 (org-update-checkbox-count 'all)
12083 (org-map-entries 'org-update-parent-todo-statistics))
12084 (if (not (org-at-heading-p))
12085 (org-update-checkbox-count)
12086 (let ((pos (point-marker))
12087 end l1 l2)
12088 (ignore-errors (org-back-to-heading t))
12089 (if (not (org-at-heading-p))
12090 (org-update-checkbox-count)
12091 (setq l1 (org-outline-level))
12092 (setq end (save-excursion
12093 (outline-next-heading)
12094 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12095 (point)))
12096 (if (and (save-excursion
12097 (re-search-forward
12098 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12099 (not (save-excursion (re-search-forward
12100 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12101 (org-update-checkbox-count)
12102 (if (and l2 (> l2 l1))
12103 (progn
12104 (goto-char end)
12105 (org-update-parent-todo-statistics))
12106 (goto-char pos)
12107 (beginning-of-line 1)
12108 (while (re-search-forward
12109 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12110 (point-at-eol) t)
12111 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12112 (goto-char pos)
12113 (move-marker pos nil)))))
12115 (defvar org-entry-property-inherited-from) ;; defined below
12116 (defun org-update-parent-todo-statistics ()
12117 "Update any statistics cookie in the parent of the current headline.
12118 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12119 the entire subtree and this will travel up the hierarchy and update
12120 statistics everywhere."
12121 (let* ((prop (save-excursion (org-up-heading-safe)
12122 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12123 (recursive (or (not org-hierarchical-todo-statistics)
12124 (and prop (string-match "\\<recursive\\>" prop))))
12125 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12127 (first t)
12128 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12129 level ltoggle l1 new ndel
12130 (cnt-all 0) (cnt-done 0) is-percent kwd
12131 checkbox-beg ov ovs ove cookie-present)
12132 (catch 'exit
12133 (save-excursion
12134 (beginning-of-line 1)
12135 (setq ltoggle (funcall outline-level))
12136 ;; Three situations are to consider:
12138 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12139 ;; to the top-level ancestor on the headline;
12141 ;; 2. If parent has "recursive" property, repeat up to the
12142 ;; headline setting that property, taking inheritance into
12143 ;; account;
12145 ;; 3. Else, move up to direct parent and proceed only once.
12146 (while (and (setq level (org-up-heading-safe))
12147 (or recursive first)
12148 (>= (point) lim))
12149 (setq first nil cookie-present nil)
12150 (unless (and level
12151 (not (string-match
12152 "\\<checkbox\\>"
12153 (downcase (or (org-entry-get nil "COOKIE_DATA")
12154 "")))))
12155 (throw 'exit nil))
12156 (while (re-search-forward box-re (point-at-eol) t)
12157 (setq cnt-all 0 cnt-done 0 cookie-present t)
12158 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12159 (save-match-data
12160 (unless (outline-next-heading) (throw 'exit nil))
12161 (while (and (looking-at org-complex-heading-regexp)
12162 (> (setq l1 (length (match-string 1))) level))
12163 (setq kwd (and (or recursive (= l1 ltoggle))
12164 (match-string 2)))
12165 (if (or (eq org-provide-todo-statistics 'all-headlines)
12166 (and (listp org-provide-todo-statistics)
12167 (or (member kwd org-provide-todo-statistics)
12168 (member kwd org-done-keywords))))
12169 (setq cnt-all (1+ cnt-all))
12170 (if (eq org-provide-todo-statistics t)
12171 (and kwd (setq cnt-all (1+ cnt-all)))))
12172 (and (member kwd org-done-keywords)
12173 (setq cnt-done (1+ cnt-done)))
12174 (outline-next-heading)))
12175 (setq new
12176 (if is-percent
12177 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12178 (format "[%d/%d]" cnt-done cnt-all))
12179 ndel (- (match-end 0) checkbox-beg))
12180 ;; handle overlays when updating cookie from column view
12181 (when (setq ov (car (overlays-at checkbox-beg)))
12182 (setq ovs (overlay-start ov) ove (overlay-end ov))
12183 (delete-overlay ov))
12184 (goto-char checkbox-beg)
12185 (insert new)
12186 (delete-region (point) (+ (point) ndel))
12187 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12188 (when ov (move-overlay ov ovs ove)))
12189 (when cookie-present
12190 (run-hook-with-args 'org-after-todo-statistics-hook
12191 cnt-done (- cnt-all cnt-done))))))
12192 (run-hooks 'org-todo-statistics-hook)))
12194 (defvar org-after-todo-statistics-hook nil
12195 "Hook that is called after a TODO statistics cookie has been updated.
12196 Each function is called with two arguments: the number of not-done entries
12197 and the number of done entries.
12199 For example, the following function, when added to this hook, will switch
12200 an entry to DONE when all children are done, and back to TODO when new
12201 entries are set to a TODO status. Note that this hook is only called
12202 when there is a statistics cookie in the headline!
12204 (defun org-summary-todo (n-done n-not-done)
12205 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12206 (let (org-log-done org-log-states) ; turn off logging
12207 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12210 (defvar org-todo-statistics-hook nil
12211 "Hook that is run whenever Org thinks TODO statistics should be updated.
12212 This hook runs even if there is no statistics cookie present, in which case
12213 `org-after-todo-statistics-hook' would not run.")
12215 (defun org-todo-trigger-tag-changes (state)
12216 "Apply the changes defined in `org-todo-state-tags-triggers'."
12217 (let ((l org-todo-state-tags-triggers)
12218 changes)
12219 (when (or (not state) (equal state ""))
12220 (setq changes (append changes (cdr (assoc "" l)))))
12221 (when (and (stringp state) (> (length state) 0))
12222 (setq changes (append changes (cdr (assoc state l)))))
12223 (when (member state org-not-done-keywords)
12224 (setq changes (append changes (cdr (assoc 'todo l)))))
12225 (when (member state org-done-keywords)
12226 (setq changes (append changes (cdr (assoc 'done l)))))
12227 (dolist (c changes)
12228 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12230 (defun org-local-logging (value)
12231 "Get logging settings from a property VALUE."
12232 (let* (words w a)
12233 ;; directly set the variables, they are already local.
12234 (setq org-log-done nil
12235 org-log-repeat nil
12236 org-todo-log-states nil)
12237 (setq words (org-split-string value))
12238 (while (setq w (pop words))
12239 (cond
12240 ((setq a (assoc w org-startup-options))
12241 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12242 (set (nth 1 a) (nth 2 a))))
12243 ((setq a (org-extract-log-state-settings w))
12244 (and (member (car a) org-todo-keywords-1)
12245 (push a org-todo-log-states)))))))
12247 (defun org-get-todo-sequence-head (kwd)
12248 "Return the head of the TODO sequence to which KWD belongs.
12249 If KWD is not set, check if there is a text property remembering the
12250 right sequence."
12251 (let (p)
12252 (cond
12253 ((not kwd)
12254 (or (get-text-property (point-at-bol) 'org-todo-head)
12255 (progn
12256 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12257 nil (point-at-eol)))
12258 (get-text-property p 'org-todo-head))))
12259 ((not (member kwd org-todo-keywords-1))
12260 (car org-todo-keywords-1))
12261 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12263 (defun org-fast-todo-selection ()
12264 "Fast TODO keyword selection with single keys.
12265 Returns the new TODO keyword, or nil if no state change should occur."
12266 (let* ((fulltable org-todo-key-alist)
12267 (done-keywords org-done-keywords) ;; needed for the faces.
12268 (maxlen (apply 'max (mapcar
12269 (lambda (x)
12270 (if (stringp (car x)) (string-width (car x)) 0))
12271 fulltable)))
12272 (expert nil)
12273 (fwidth (+ maxlen 3 1 3))
12274 (ncol (/ (- (window-width) 4) fwidth))
12275 tg cnt e c tbl
12276 groups ingroup)
12277 (save-excursion
12278 (save-window-excursion
12279 (if expert
12280 (set-buffer (get-buffer-create " *Org todo*"))
12281 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12282 (erase-buffer)
12283 (org-set-local 'org-done-keywords done-keywords)
12284 (setq tbl fulltable cnt 0)
12285 (while (setq e (pop tbl))
12286 (cond
12287 ((equal e '(:startgroup))
12288 (push '() groups) (setq ingroup t)
12289 (when (not (= cnt 0))
12290 (setq cnt 0)
12291 (insert "\n"))
12292 (insert "{ "))
12293 ((equal e '(:endgroup))
12294 (setq ingroup nil cnt 0)
12295 (insert "}\n"))
12296 ((equal e '(:newline))
12297 (when (not (= cnt 0))
12298 (setq cnt 0)
12299 (insert "\n")
12300 (setq e (car tbl))
12301 (while (equal (car tbl) '(:newline))
12302 (insert "\n")
12303 (setq tbl (cdr tbl)))))
12305 (setq tg (car e) c (cdr e))
12306 (if ingroup (push tg (car groups)))
12307 (setq tg (org-add-props tg nil 'face
12308 (org-get-todo-face tg)))
12309 (if (and (= cnt 0) (not ingroup)) (insert " "))
12310 (insert "[" c "] " tg (make-string
12311 (- fwidth 4 (length tg)) ?\ ))
12312 (when (= (setq cnt (1+ cnt)) ncol)
12313 (insert "\n")
12314 (if ingroup (insert " "))
12315 (setq cnt 0)))))
12316 (insert "\n")
12317 (goto-char (point-min))
12318 (if (not expert) (org-fit-window-to-buffer))
12319 (message "[a-z..]:Set [SPC]:clear")
12320 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12321 (cond
12322 ((or (= c ?\C-g)
12323 (and (= c ?q) (not (rassoc c fulltable))))
12324 (setq quit-flag t))
12325 ((= c ?\ ) nil)
12326 ((setq e (rassoc c fulltable) tg (car e))
12328 (t (setq quit-flag t)))))))
12330 (defun org-entry-is-todo-p ()
12331 (member (org-get-todo-state) org-not-done-keywords))
12333 (defun org-entry-is-done-p ()
12334 (member (org-get-todo-state) org-done-keywords))
12336 (defun org-get-todo-state ()
12337 (save-excursion
12338 (org-back-to-heading t)
12339 (and (looking-at org-todo-line-regexp)
12340 (match-end 2)
12341 (match-string 2))))
12343 (defun org-at-date-range-p (&optional inactive-ok)
12344 "Is the cursor inside a date range?"
12345 (interactive)
12346 (save-excursion
12347 (catch 'exit
12348 (let ((pos (point)))
12349 (skip-chars-backward "^[<\r\n")
12350 (skip-chars-backward "<[")
12351 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12352 (>= (match-end 0) pos)
12353 (throw 'exit t))
12354 (skip-chars-backward "^<[\r\n")
12355 (skip-chars-backward "<[")
12356 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12357 (>= (match-end 0) pos)
12358 (throw 'exit t)))
12359 nil)))
12361 (defun org-get-repeat (&optional tagline)
12362 "Check if there is a deadline/schedule with repeater in this entry."
12363 (save-match-data
12364 (save-excursion
12365 (org-back-to-heading t)
12366 (and (re-search-forward (if tagline
12367 (concat tagline "\\s-*" org-repeat-re)
12368 org-repeat-re)
12369 (org-entry-end-position) t)
12370 (match-string-no-properties 1)))))
12372 (defvar org-last-changed-timestamp)
12373 (defvar org-last-inserted-timestamp)
12374 (defvar org-log-post-message)
12375 (defvar org-log-note-purpose)
12376 (defvar org-log-note-how)
12377 (defvar org-log-note-extra)
12378 (defun org-auto-repeat-maybe (done-word)
12379 "Check if the current headline contains a repeated deadline/schedule.
12380 If yes, set TODO state back to what it was and change the base date
12381 of repeating deadline/scheduled time stamps to new date.
12382 This function is run automatically after each state change to a DONE state."
12383 ;; last-state is dynamically scoped into this function
12384 (let* ((repeat (org-get-repeat))
12385 (aa (assoc org-last-state org-todo-kwd-alist))
12386 (interpret (nth 1 aa))
12387 (head (nth 2 aa))
12388 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12389 (msg "Entry repeats: ")
12390 (org-log-done nil)
12391 (org-todo-log-states nil)
12392 re type n what ts time to-state)
12393 (when repeat
12394 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12395 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12396 org-todo-repeat-to-state))
12397 (unless (and to-state (member to-state org-todo-keywords-1))
12398 (setq to-state (if (eq interpret 'type) org-last-state head)))
12399 (org-todo to-state)
12400 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12401 (org-entry-put nil "LAST_REPEAT" (format-time-string
12402 (org-time-stamp-format t t))))
12403 (when org-log-repeat
12404 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12405 (memq 'org-add-log-note post-command-hook))
12406 ;; OK, we are already setup for some record
12407 (if (eq org-log-repeat 'note)
12408 ;; make sure we take a note, not only a time stamp
12409 (setq org-log-note-how 'note))
12410 ;; Set up for taking a record
12411 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12412 org-last-state
12413 'findpos org-log-repeat)))
12414 (org-back-to-heading t)
12415 (org-add-planning-info nil nil 'closed)
12416 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12417 org-deadline-time-regexp "\\)\\|\\("
12418 org-ts-regexp "\\)"))
12419 (while (re-search-forward
12420 re (save-excursion (outline-next-heading) (point)) t)
12421 (setq type (if (match-end 1) org-scheduled-string
12422 (if (match-end 3) org-deadline-string "Plain:"))
12423 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12424 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12425 (setq n (string-to-number (match-string 2 ts))
12426 what (match-string 3 ts))
12427 (if (equal what "w") (setq n (* n 7) what "d"))
12428 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12429 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12430 ;; Preparation, see if we need to modify the start date for the change
12431 (when (match-end 1)
12432 (setq time (save-match-data (org-time-string-to-time ts)))
12433 (cond
12434 ((equal (match-string 1 ts) ".")
12435 ;; Shift starting date to today
12436 (org-timestamp-change
12437 (- (org-today) (time-to-days time))
12438 'day))
12439 ((equal (match-string 1 ts) "+")
12440 (let ((nshiftmax 10) (nshift 0))
12441 (while (or (= nshift 0)
12442 (<= (time-to-days time)
12443 (time-to-days (current-time))))
12444 (when (= (incf nshift) nshiftmax)
12445 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12446 (error "Abort")))
12447 (org-timestamp-change n (cdr (assoc what whata)))
12448 (org-at-timestamp-p t)
12449 (setq ts (match-string 1))
12450 (setq time (save-match-data (org-time-string-to-time ts)))))
12451 (org-timestamp-change (- n) (cdr (assoc what whata)))
12452 ;; rematch, so that we have everything in place for the real shift
12453 (org-at-timestamp-p t)
12454 (setq ts (match-string 1))
12455 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12456 (org-timestamp-change n (cdr (assoc what whata)))
12457 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12458 (setq org-log-post-message msg)
12459 (message "%s" msg))))
12461 (defun org-show-todo-tree (arg)
12462 "Make a compact tree which shows all headlines marked with TODO.
12463 The tree will show the lines where the regexp matches, and all higher
12464 headlines above the match.
12465 With a \\[universal-argument] prefix, prompt for a regexp to match.
12466 With a numeric prefix N, construct a sparse tree for the Nth element
12467 of `org-todo-keywords-1'."
12468 (interactive "P")
12469 (let ((case-fold-search nil)
12470 (kwd-re
12471 (cond ((null arg) org-not-done-regexp)
12472 ((equal arg '(4))
12473 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12474 (mapcar 'list org-todo-keywords-1))))
12475 (concat "\\("
12476 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12477 "\\)\\>")))
12478 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12479 (regexp-quote (nth (1- (prefix-numeric-value arg))
12480 org-todo-keywords-1)))
12481 (t (error "Invalid prefix argument: %s" arg)))))
12482 (message "%d TODO entries found"
12483 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12485 (defun org-deadline (&optional remove time)
12486 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12487 With argument REMOVE, remove any deadline from the item.
12488 With argument TIME, set the deadline at the corresponding date. TIME
12489 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12490 (interactive "P")
12491 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12492 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12493 'region-start-level 'region))
12494 org-loop-over-headlines-in-active-region)
12495 (org-map-entries
12496 `(org-deadline ',remove ,time)
12497 org-loop-over-headlines-in-active-region
12498 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12499 (let* ((old-date (org-entry-get nil "DEADLINE"))
12500 (repeater (and old-date
12501 (string-match
12502 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12503 old-date)
12504 (match-string 1 old-date))))
12505 (if remove
12506 (progn
12507 (when (and old-date org-log-redeadline)
12508 (org-add-log-setup 'deldeadline nil old-date 'findpos
12509 org-log-redeadline))
12510 (org-remove-timestamp-with-keyword org-deadline-string)
12511 (message "Item no longer has a deadline."))
12512 (org-add-planning-info 'deadline time 'closed)
12513 (when (and old-date org-log-redeadline
12514 (not (equal old-date
12515 (substring org-last-inserted-timestamp 1 -1))))
12516 (org-add-log-setup 'redeadline nil old-date 'findpos
12517 org-log-redeadline))
12518 (when repeater
12519 (save-excursion
12520 (org-back-to-heading t)
12521 (when (re-search-forward (concat org-deadline-string " "
12522 org-last-inserted-timestamp)
12523 (save-excursion
12524 (outline-next-heading) (point)) t)
12525 (goto-char (1- (match-end 0)))
12526 (insert " " repeater)
12527 (setq org-last-inserted-timestamp
12528 (concat (substring org-last-inserted-timestamp 0 -1)
12529 " " repeater
12530 (substring org-last-inserted-timestamp -1))))))
12531 (message "Deadline on %s" org-last-inserted-timestamp)))))
12533 (defun org-schedule (&optional remove time)
12534 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12535 With argument REMOVE, remove any scheduling date from the item.
12536 With argument TIME, scheduled at the corresponding date. TIME can
12537 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12538 (interactive "P")
12539 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12540 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12541 'region-start-level 'region))
12542 org-loop-over-headlines-in-active-region)
12543 (org-map-entries
12544 `(org-schedule ',remove ,time)
12545 org-loop-over-headlines-in-active-region
12546 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12547 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12548 (repeater (and old-date
12549 (string-match
12550 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12551 old-date)
12552 (match-string 1 old-date))))
12553 (if remove
12554 (progn
12555 (when (and old-date org-log-reschedule)
12556 (org-add-log-setup 'delschedule nil old-date 'findpos
12557 org-log-reschedule))
12558 (org-remove-timestamp-with-keyword org-scheduled-string)
12559 (message "Item is no longer scheduled."))
12560 (org-add-planning-info 'scheduled time 'closed)
12561 (when (and old-date org-log-reschedule
12562 (not (equal old-date
12563 (substring org-last-inserted-timestamp 1 -1))))
12564 (org-add-log-setup 'reschedule nil old-date 'findpos
12565 org-log-reschedule))
12566 (when repeater
12567 (save-excursion
12568 (org-back-to-heading t)
12569 (when (re-search-forward (concat org-scheduled-string " "
12570 org-last-inserted-timestamp)
12571 (save-excursion
12572 (outline-next-heading) (point)) t)
12573 (goto-char (1- (match-end 0)))
12574 (insert " " repeater)
12575 (setq org-last-inserted-timestamp
12576 (concat (substring org-last-inserted-timestamp 0 -1)
12577 " " repeater
12578 (substring org-last-inserted-timestamp -1))))))
12579 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12581 (defun org-get-scheduled-time (pom &optional inherit)
12582 "Get the scheduled time as a time tuple, of a format suitable
12583 for calling org-schedule with, or if there is no scheduling,
12584 returns nil."
12585 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12586 (when time
12587 (apply 'encode-time (org-parse-time-string time)))))
12589 (defun org-get-deadline-time (pom &optional inherit)
12590 "Get the deadline as a time tuple, of a format suitable for
12591 calling org-deadline with, or if there is no scheduling, returns
12592 nil."
12593 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12594 (when time
12595 (apply 'encode-time (org-parse-time-string time)))))
12597 (defun org-remove-timestamp-with-keyword (keyword)
12598 "Remove all time stamps with KEYWORD in the current entry."
12599 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12600 beg)
12601 (save-excursion
12602 (org-back-to-heading t)
12603 (setq beg (point))
12604 (outline-next-heading)
12605 (while (re-search-backward re beg t)
12606 (replace-match "")
12607 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12608 (equal (char-before) ?\ ))
12609 (backward-delete-char 1)
12610 (if (string-match "^[ \t]*$" (buffer-substring
12611 (point-at-bol) (point-at-eol)))
12612 (delete-region (point-at-bol)
12613 (min (point-max) (1+ (point-at-eol))))))))))
12615 (defun org-add-planning-info (what &optional time &rest remove)
12616 "Insert new timestamp with keyword in the line directly after the headline.
12617 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12618 If non is given, the user is prompted for a date.
12619 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12620 be removed."
12621 (interactive)
12622 (let (org-time-was-given org-end-time-was-given ts
12623 end default-time default-input)
12625 (catch 'exit
12626 (when (and (memq what '(scheduled deadline))
12627 (or (not time)
12628 (and (stringp time)
12629 (string-match "^[-+]+[0-9]" time))))
12630 ;; Try to get a default date/time from existing timestamp
12631 (save-excursion
12632 (org-back-to-heading t)
12633 (setq end (save-excursion (outline-next-heading) (point)))
12634 (when (re-search-forward (if (eq what 'scheduled)
12635 org-scheduled-time-regexp
12636 org-deadline-time-regexp)
12637 end t)
12638 (setq ts (match-string 1)
12639 default-time
12640 (apply 'encode-time (org-parse-time-string ts))
12641 default-input (and ts (org-get-compact-tod ts))))))
12642 (when what
12643 (setq time
12644 (if (stringp time)
12645 ;; This is a string (relative or absolute), set proper date
12646 (apply 'encode-time
12647 (org-read-date-analyze
12648 time default-time (decode-time default-time)))
12649 ;; If necessary, get the time from the user
12650 (or time (org-read-date nil 'to-time nil nil
12651 default-time default-input)))))
12653 (when (and org-insert-labeled-timestamps-at-point
12654 (member what '(scheduled deadline)))
12655 (insert
12656 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12657 (org-insert-time-stamp time org-time-was-given
12658 nil nil nil (list org-end-time-was-given))
12659 (setq what nil))
12660 (save-excursion
12661 (save-restriction
12662 (let (col list elt ts buffer-invisibility-spec)
12663 (org-back-to-heading t)
12664 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12665 (goto-char (match-end 1))
12666 (setq col (current-column))
12667 (goto-char (match-end 0))
12668 (if (eobp) (insert "\n") (forward-char 1))
12669 (when (and (not what)
12670 (not (looking-at
12671 (concat "[ \t]*"
12672 org-keyword-time-not-clock-regexp))))
12673 ;; Nothing to add, nothing to remove...... :-)
12674 (throw 'exit nil))
12675 (if (and (not (looking-at org-outline-regexp))
12676 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12677 "[^\r\n]*"))
12678 (not (equal (match-string 1) org-clock-string)))
12679 (narrow-to-region (match-beginning 0) (match-end 0))
12680 (insert-before-markers "\n")
12681 (backward-char 1)
12682 (narrow-to-region (point) (point))
12683 (and org-adapt-indentation (org-indent-to-column col)))
12684 ;; Check if we have to remove something.
12685 (setq list (cons what remove))
12686 (while list
12687 (setq elt (pop list))
12688 (when (or (and (eq elt 'scheduled)
12689 (re-search-forward org-scheduled-time-regexp nil t))
12690 (and (eq elt 'deadline)
12691 (re-search-forward org-deadline-time-regexp nil t))
12692 (and (eq elt 'closed)
12693 (re-search-forward org-closed-time-regexp nil t)))
12694 (replace-match "")
12695 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12696 (and (looking-at "[ \t]+") (replace-match ""))
12697 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12698 (when what
12699 (insert
12700 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12701 (cond ((eq what 'scheduled) org-scheduled-string)
12702 ((eq what 'deadline) org-deadline-string)
12703 ((eq what 'closed) org-closed-string))
12704 " ")
12705 (setq ts (org-insert-time-stamp
12706 time
12707 (or org-time-was-given
12708 (and (eq what 'closed) org-log-done-with-time))
12709 (eq what 'closed)
12710 nil nil (list org-end-time-was-given)))
12711 (insert
12712 (if (not (or (bolp) (eq (char-before) ?\ )
12713 (memq (char-after) '(32 10))
12714 (eobp))) " " ""))
12715 (end-of-line 1))
12716 (goto-char (point-min))
12717 (widen)
12718 (if (and (looking-at "[ \t]*\n")
12719 (equal (char-before) ?\n))
12720 (delete-region (1- (point)) (point-at-eol)))
12721 ts))))))
12723 (defvar org-log-note-marker (make-marker))
12724 (defvar org-log-note-purpose nil)
12725 (defvar org-log-note-state nil)
12726 (defvar org-log-note-previous-state nil)
12727 (defvar org-log-note-how nil)
12728 (defvar org-log-note-extra nil)
12729 (defvar org-log-note-window-configuration nil)
12730 (defvar org-log-note-return-to (make-marker))
12731 (defvar org-log-note-effective-time nil
12732 "Remembered current time so that dynamically scoped
12733 `org-extend-today-until' affects tha timestamps in state change
12734 log")
12736 (defvar org-log-post-message nil
12737 "Message to be displayed after a log note has been stored.
12738 The auto-repeater uses this.")
12740 (defun org-add-note ()
12741 "Add a note to the current entry.
12742 This is done in the same way as adding a state change note."
12743 (interactive)
12744 (org-add-log-setup 'note nil nil 'findpos nil))
12746 (defvar org-property-end-re)
12747 (defun org-add-log-setup (&optional purpose state prev-state
12748 findpos how extra)
12749 "Set up the post command hook to take a note.
12750 If this is about to TODO state change, the new state is expected in STATE.
12751 When FINDPOS is non-nil, find the correct position for the note in
12752 the current entry. If not, assume that it can be inserted at point.
12753 HOW is an indicator what kind of note should be created.
12754 EXTRA is additional text that will be inserted into the notes buffer."
12755 (let* ((org-log-into-drawer (org-log-into-drawer))
12756 (drawer (cond ((stringp org-log-into-drawer)
12757 org-log-into-drawer)
12758 (org-log-into-drawer "LOGBOOK"))))
12759 (save-restriction
12760 (save-excursion
12761 (when findpos
12762 (org-back-to-heading t)
12763 (narrow-to-region (point) (save-excursion
12764 (outline-next-heading) (point)))
12765 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12766 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12767 "[^\r\n]*\\)?"))
12768 (goto-char (match-end 0))
12769 (cond
12770 (drawer
12771 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12772 nil t)
12773 (progn
12774 (goto-char (match-end 0))
12775 (or org-log-states-order-reversed
12776 (and (re-search-forward org-property-end-re nil t)
12777 (goto-char (1- (match-beginning 0))))))
12778 (insert "\n:" drawer ":\n:END:")
12779 (beginning-of-line 0)
12780 (org-indent-line)
12781 (beginning-of-line 2)
12782 (org-indent-line)
12783 (end-of-line 0)))
12784 ((and org-log-state-notes-insert-after-drawers
12785 (save-excursion
12786 (forward-line) (looking-at org-drawer-regexp)))
12787 (forward-line)
12788 (while (looking-at org-drawer-regexp)
12789 (goto-char (match-end 0))
12790 (re-search-forward org-property-end-re (point-max) t)
12791 (forward-line))
12792 (forward-line -1)))
12793 (unless org-log-states-order-reversed
12794 (and (= (char-after) ?\n) (forward-char 1))
12795 (org-skip-over-state-notes)
12796 (skip-chars-backward " \t\n\r")))
12797 (move-marker org-log-note-marker (point))
12798 (setq org-log-note-purpose purpose
12799 org-log-note-state state
12800 org-log-note-previous-state prev-state
12801 org-log-note-how how
12802 org-log-note-extra extra
12803 org-log-note-effective-time (org-current-effective-time))
12804 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12806 (defun org-skip-over-state-notes ()
12807 "Skip past the list of State notes in an entry."
12808 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12809 (when (ignore-errors (goto-char (org-in-item-p)))
12810 (let* ((struct (org-list-struct))
12811 (prevs (org-list-prevs-alist struct)))
12812 (while (looking-at "[ \t]*- State")
12813 (goto-char (or (org-list-get-next-item (point) struct prevs)
12814 (org-list-get-item-end (point) struct)))))))
12816 (defun org-add-log-note (&optional purpose)
12817 "Pop up a window for taking a note, and add this note later at point."
12818 (remove-hook 'post-command-hook 'org-add-log-note)
12819 (setq org-log-note-window-configuration (current-window-configuration))
12820 (delete-other-windows)
12821 (move-marker org-log-note-return-to (point))
12822 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12823 (goto-char org-log-note-marker)
12824 (org-switch-to-buffer-other-window "*Org Note*")
12825 (erase-buffer)
12826 (if (memq org-log-note-how '(time state))
12827 (let (current-prefix-arg) (org-store-log-note))
12828 (let ((org-inhibit-startup t)) (org-mode))
12829 (insert (format "# Insert note for %s.
12830 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12831 (cond
12832 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12833 ((eq org-log-note-purpose 'done) "closed todo item")
12834 ((eq org-log-note-purpose 'state)
12835 (format "state change from \"%s\" to \"%s\""
12836 (or org-log-note-previous-state "")
12837 (or org-log-note-state "")))
12838 ((eq org-log-note-purpose 'reschedule)
12839 "rescheduling")
12840 ((eq org-log-note-purpose 'delschedule)
12841 "no longer scheduled")
12842 ((eq org-log-note-purpose 'redeadline)
12843 "changing deadline")
12844 ((eq org-log-note-purpose 'deldeadline)
12845 "removing deadline")
12846 ((eq org-log-note-purpose 'refile)
12847 "refiling")
12848 ((eq org-log-note-purpose 'note)
12849 "this entry")
12850 (t (error "This should not happen")))))
12851 (if org-log-note-extra (insert org-log-note-extra))
12852 (org-set-local 'org-finish-function 'org-store-log-note)
12853 (run-hooks 'org-log-buffer-setup-hook)))
12855 (defvar org-note-abort nil) ; dynamically scoped
12856 (defun org-store-log-note ()
12857 "Finish taking a log note, and insert it to where it belongs."
12858 (let ((txt (buffer-string)))
12859 (kill-buffer (current-buffer))
12860 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12861 lines ind bul)
12862 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12863 (setq txt (replace-match "" t t txt)))
12864 (if (string-match "\\s-+\\'" txt)
12865 (setq txt (replace-match "" t t txt)))
12866 (setq lines (org-split-string txt "\n"))
12867 (when (and note (string-match "\\S-" note))
12868 (setq note
12869 (org-replace-escapes
12870 note
12871 (list (cons "%u" (user-login-name))
12872 (cons "%U" user-full-name)
12873 (cons "%t" (format-time-string
12874 (org-time-stamp-format 'long 'inactive)
12875 org-log-note-effective-time))
12876 (cons "%T" (format-time-string
12877 (org-time-stamp-format 'long nil)
12878 org-log-note-effective-time))
12879 (cons "%d" (format-time-string
12880 (org-time-stamp-format nil 'inactive)
12881 org-log-note-effective-time))
12882 (cons "%D" (format-time-string
12883 (org-time-stamp-format nil nil)
12884 org-log-note-effective-time))
12885 (cons "%s" (if org-log-note-state
12886 (concat "\"" org-log-note-state "\"")
12887 ""))
12888 (cons "%S" (if org-log-note-previous-state
12889 (concat "\"" org-log-note-previous-state "\"")
12890 "\"\"")))))
12891 (if lines (setq note (concat note " \\\\")))
12892 (push note lines))
12893 (when (or current-prefix-arg org-note-abort)
12894 (when org-log-into-drawer
12895 (org-remove-empty-drawer-at
12896 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12897 org-log-note-marker))
12898 (setq lines nil))
12899 (when lines
12900 (with-current-buffer (marker-buffer org-log-note-marker)
12901 (save-excursion
12902 (goto-char org-log-note-marker)
12903 (move-marker org-log-note-marker nil)
12904 (end-of-line 1)
12905 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12906 (setq ind (save-excursion
12907 (if (ignore-errors (goto-char (org-in-item-p)))
12908 (let ((struct (org-list-struct)))
12909 (org-list-get-ind
12910 (org-list-get-top-point struct) struct))
12911 (skip-chars-backward " \r\t\n")
12912 (cond
12913 ((and (org-at-heading-p)
12914 org-adapt-indentation)
12915 (1+ (org-current-level)))
12916 ((org-at-heading-p) 0)
12917 (t (org-get-indentation))))))
12918 (setq bul (org-list-bullet-string "-"))
12919 (org-indent-line-to ind)
12920 (insert bul (pop lines))
12921 (let ((ind-body (+ (length bul) ind)))
12922 (while lines
12923 (insert "\n")
12924 (org-indent-line-to ind-body)
12925 (insert (pop lines))))
12926 (message "Note stored")
12927 (org-back-to-heading t)
12928 (org-cycle-hide-drawers 'children))))))
12929 (set-window-configuration org-log-note-window-configuration)
12930 (with-current-buffer (marker-buffer org-log-note-return-to)
12931 (goto-char org-log-note-return-to))
12932 (move-marker org-log-note-return-to nil)
12933 (and org-log-post-message (message "%s" org-log-post-message)))
12935 (defun org-remove-empty-drawer-at (drawer pos)
12936 "Remove an empty drawer DRAWER at position POS.
12937 POS may also be a marker."
12938 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12939 (save-excursion
12940 (save-restriction
12941 (widen)
12942 (goto-char pos)
12943 (if (org-in-regexp
12944 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12945 (replace-match ""))))))
12947 (defvar org-ts-type nil)
12948 (defun org-sparse-tree (&optional arg type)
12949 "Create a sparse tree, prompt for the details.
12950 This command can create sparse trees. You first need to select the type
12951 of match used to create the tree:
12953 t Show all TODO entries.
12954 T Show entries with a specific TODO keyword.
12955 m Show entries selected by a tags/property match.
12956 p Enter a property name and its value (both with completion on existing
12957 names/values) and show entries with that property.
12958 r Show entries matching a regular expression (`/' can be used as well).
12959 b Show deadlines and scheduled items before a date.
12960 a Show deadlines and scheduled items after a date.
12961 d Show deadlines due within `org-deadline-warning-days'.
12962 D Show deadlines and scheduled items between a date range."
12963 (interactive "P")
12964 (let (ans kwd value ts-type)
12965 (setq type (or type org-sparse-tree-default-date-type))
12966 (setq org-ts-type type)
12967 (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"
12968 (cond ((eq type 'all) "all timestamps")
12969 ((eq type 'scheduled) "only scheduled")
12970 ((eq type 'deadline) "only deadline")
12971 ((eq type 'active) "only active timestamps")
12972 ((eq type 'inactive) "only inactive timestamps")
12973 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12974 (t "scheduled/deadline")))
12975 (setq ans (read-char-exclusive))
12976 (cond
12977 ((equal ans ?c)
12978 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12979 ((equal ans ?d)
12980 (call-interactively 'org-check-deadlines))
12981 ((equal ans ?b)
12982 (call-interactively 'org-check-before-date))
12983 ((equal ans ?a)
12984 (call-interactively 'org-check-after-date))
12985 ((equal ans ?D)
12986 (call-interactively 'org-check-dates-range))
12987 ((equal ans ?t)
12988 (call-interactively 'org-show-todo-tree))
12989 ((equal ans ?T)
12990 (org-show-todo-tree '(4)))
12991 ((member ans '(?T ?m))
12992 (call-interactively 'org-match-sparse-tree))
12993 ((member ans '(?p ?P))
12994 (setq kwd (org-icompleting-read "Property: "
12995 (mapcar 'list (org-buffer-property-keys))))
12996 (setq value (org-icompleting-read "Value: "
12997 (mapcar 'list (org-property-values kwd))))
12998 (unless (string-match "\\`{.*}\\'" value)
12999 (setq value (concat "\"" value "\"")))
13000 (org-match-sparse-tree arg (concat kwd "=" value)))
13001 ((member ans '(?r ?R ?/))
13002 (call-interactively 'org-occur))
13003 (t (error "No such sparse tree command \"%c\"" ans)))))
13005 (defvar org-occur-highlights nil
13006 "List of overlays used for occur matches.")
13007 (make-variable-buffer-local 'org-occur-highlights)
13008 (defvar org-occur-parameters nil
13009 "Parameters of the active org-occur calls.
13010 This is a list, each call to org-occur pushes as cons cell,
13011 containing the regular expression and the callback, onto the list.
13012 The list can contain several entries if `org-occur' has been called
13013 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13014 will only contain one set of parameters. When the highlights are
13015 removed (for example with `C-c C-c', or with the next edit (depending
13016 on `org-remove-highlights-with-change'), this variable is emptied
13017 as well.")
13018 (make-variable-buffer-local 'org-occur-parameters)
13020 (defun org-occur (regexp &optional keep-previous callback)
13021 "Make a compact tree which shows all matches of REGEXP.
13022 The tree will show the lines where the regexp matches, and all higher
13023 headlines above the match. It will also show the heading after the match,
13024 to make sure editing the matching entry is easy.
13025 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13026 call to `org-occur' will be kept, to allow stacking of calls to this
13027 command.
13028 If CALLBACK is non-nil, it is a function which is called to confirm
13029 that the match should indeed be shown."
13030 (interactive "sRegexp: \nP")
13031 (when (equal regexp "")
13032 (error "Regexp cannot be empty"))
13033 (unless keep-previous
13034 (org-remove-occur-highlights nil nil t))
13035 (push (cons regexp callback) org-occur-parameters)
13036 (let ((cnt 0))
13037 (save-excursion
13038 (goto-char (point-min))
13039 (if (or (not keep-previous) ; do not want to keep
13040 (not org-occur-highlights)) ; no previous matches
13041 ;; hide everything
13042 (org-overview))
13043 (while (re-search-forward regexp nil t)
13044 (when (or (not callback)
13045 (save-match-data (funcall callback)))
13046 (setq cnt (1+ cnt))
13047 (when org-highlight-sparse-tree-matches
13048 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13049 (org-show-context 'occur-tree))))
13050 (when org-remove-highlights-with-change
13051 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13052 nil 'local))
13053 (unless org-sparse-tree-open-archived-trees
13054 (org-hide-archived-subtrees (point-min) (point-max)))
13055 (run-hooks 'org-occur-hook)
13056 (if (org-called-interactively-p 'interactive)
13057 (message "%d match(es) for regexp %s" cnt regexp))
13058 cnt))
13060 (defun org-occur-next-match (&optional n reset)
13061 "Function for `next-error-function' to find sparse tree matches.
13062 N is the number of matches to move, when negative move backwards.
13063 RESET is entirely ignored - this function always goes back to the
13064 starting point when no match is found."
13065 (let* ((limit (if (< n 0) (point-min) (point-max)))
13066 (search-func (if (< n 0)
13067 'previous-single-char-property-change
13068 'next-single-char-property-change))
13069 (n (abs n))
13070 (pos (point))
13072 (catch 'exit
13073 (while (setq p1 (funcall search-func (point) 'org-type))
13074 (when (equal p1 limit)
13075 (goto-char pos)
13076 (error "No more matches"))
13077 (when (equal (get-char-property p1 'org-type) 'org-occur)
13078 (setq n (1- n))
13079 (when (= n 0)
13080 (goto-char p1)
13081 (throw 'exit (point))))
13082 (goto-char p1))
13083 (goto-char p1)
13084 (error "No more matches"))))
13086 (defun org-show-context (&optional key)
13087 "Make sure point and context are visible.
13088 How much context is shown depends upon the variables
13089 `org-show-hierarchy-above', `org-show-following-heading',
13090 `org-show-entry-below' and `org-show-siblings'."
13091 (let ((heading-p (org-at-heading-p t))
13092 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13093 (following-p (org-get-alist-option org-show-following-heading key))
13094 (entry-p (org-get-alist-option org-show-entry-below key))
13095 (siblings-p (org-get-alist-option org-show-siblings key)))
13096 (catch 'exit
13097 ;; Show heading or entry text
13098 (if (and heading-p (not entry-p))
13099 (org-flag-heading nil) ; only show the heading
13100 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13101 (org-show-hidden-entry))) ; show entire entry
13102 (when following-p
13103 ;; Show next sibling, or heading below text
13104 (save-excursion
13105 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13106 (org-flag-heading nil))))
13107 (when siblings-p (org-show-siblings))
13108 (when hierarchy-p
13109 ;; show all higher headings, possibly with siblings
13110 (save-excursion
13111 (while (and (condition-case nil
13112 (progn (org-up-heading-all 1) t)
13113 (error nil))
13114 (not (bobp)))
13115 (org-flag-heading nil)
13116 (when siblings-p (org-show-siblings))))))))
13118 (defvar org-reveal-start-hook nil
13119 "Hook run before revealing a location.")
13121 (defun org-reveal (&optional siblings)
13122 "Show current entry, hierarchy above it, and the following headline.
13123 This can be used to show a consistent set of context around locations
13124 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13125 not t for the search context.
13127 With optional argument SIBLINGS, on each level of the hierarchy all
13128 siblings are shown. This repairs the tree structure to what it would
13129 look like when opened with hierarchical calls to `org-cycle'.
13130 With double optional argument \\[universal-argument] \\[universal-argument], \
13131 go to the parent and show the
13132 entire tree."
13133 (interactive "P")
13134 (run-hooks 'org-reveal-start-hook)
13135 (let ((org-show-hierarchy-above t)
13136 (org-show-following-heading t)
13137 (org-show-siblings (if siblings t org-show-siblings)))
13138 (org-show-context nil))
13139 (when (equal siblings '(16))
13140 (save-excursion
13141 (when (org-up-heading-safe)
13142 (org-show-subtree)
13143 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13145 (defun org-highlight-new-match (beg end)
13146 "Highlight from BEG to END and mark the highlight is an occur headline."
13147 (let ((ov (make-overlay beg end)))
13148 (overlay-put ov 'face 'secondary-selection)
13149 (overlay-put ov 'org-type 'org-occur)
13150 (push ov org-occur-highlights)))
13152 (defun org-remove-occur-highlights (&optional beg end noremove)
13153 "Remove the occur highlights from the buffer.
13154 BEG and END are ignored. If NOREMOVE is nil, remove this function
13155 from the `before-change-functions' in the current buffer."
13156 (interactive)
13157 (unless org-inhibit-highlight-removal
13158 (mapc 'delete-overlay org-occur-highlights)
13159 (setq org-occur-highlights nil)
13160 (setq org-occur-parameters nil)
13161 (unless noremove
13162 (remove-hook 'before-change-functions
13163 'org-remove-occur-highlights 'local))))
13165 ;;;; Priorities
13167 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13168 "Regular expression matching the priority indicator.")
13170 (defvar org-remove-priority-next-time nil)
13172 (defun org-priority-up ()
13173 "Increase the priority of the current item."
13174 (interactive)
13175 (org-priority 'up))
13177 (defun org-priority-down ()
13178 "Decrease the priority of the current item."
13179 (interactive)
13180 (org-priority 'down))
13182 (defun org-priority (&optional action show)
13183 "Change the priority of an item.
13184 ACTION can be `set', `up', `down', or a character."
13185 (interactive "P")
13186 (if (equal action '(4))
13187 (org-show-priority)
13188 (unless org-enable-priority-commands
13189 (error "Priority commands are disabled"))
13190 (setq action (or action 'set))
13191 (let (current new news have remove)
13192 (save-excursion
13193 (org-back-to-heading t)
13194 (if (looking-at org-priority-regexp)
13195 (setq current (string-to-char (match-string 2))
13196 have t))
13197 (cond
13198 ((eq action 'remove)
13199 (setq remove t new ?\ ))
13200 ((or (eq action 'set)
13201 (if (featurep 'xemacs) (characterp action) (integerp action)))
13202 (if (not (eq action 'set))
13203 (setq new action)
13204 (message "Priority %c-%c, SPC to remove: "
13205 org-highest-priority org-lowest-priority)
13206 (save-match-data
13207 (setq new (read-char-exclusive))))
13208 (if (and (= (upcase org-highest-priority) org-highest-priority)
13209 (= (upcase org-lowest-priority) org-lowest-priority))
13210 (setq new (upcase new)))
13211 (cond ((equal new ?\ ) (setq remove t))
13212 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13213 (error "Priority must be between `%c' and `%c'"
13214 org-highest-priority org-lowest-priority))))
13215 ((eq action 'up)
13216 (setq new (if have
13217 (1- current) ; normal cycling
13218 ;; last priority was empty
13219 (if (eq last-command this-command)
13220 org-lowest-priority ; wrap around empty to lowest
13221 ;; default
13222 (if org-priority-start-cycle-with-default
13223 org-default-priority
13224 (1- org-default-priority))))))
13225 ((eq action 'down)
13226 (setq new (if have
13227 (1+ current) ; normal cycling
13228 ;; last priority was empty
13229 (if (eq last-command this-command)
13230 org-highest-priority ; wrap around empty to highest
13231 ;; default
13232 (if org-priority-start-cycle-with-default
13233 org-default-priority
13234 (1+ org-default-priority))))))
13235 (t (error "Invalid action")))
13236 (if (or (< (upcase new) org-highest-priority)
13237 (> (upcase new) org-lowest-priority))
13238 (if (and (memq action '(up down))
13239 (not have) (not (eq last-command this-command)))
13240 ;; `new' is from default priority
13241 (error
13242 "The default can not be set, see `org-default-priority' why")
13243 ;; normal cycling: `new' is beyond highest/lowest priority
13244 ;; and is wrapped around to the empty priority
13245 (setq remove t)))
13246 (setq news (format "%c" new))
13247 (if have
13248 (if remove
13249 (replace-match "" t t nil 1)
13250 (replace-match news t t nil 2))
13251 (if remove
13252 (error "No priority cookie found in line")
13253 (let ((case-fold-search nil))
13254 (looking-at org-todo-line-regexp))
13255 (if (match-end 2)
13256 (progn
13257 (goto-char (match-end 2))
13258 (insert " [#" news "]"))
13259 (goto-char (match-beginning 3))
13260 (insert "[#" news "] "))))
13261 (org-preserve-lc (org-set-tags nil 'align)))
13262 (if remove
13263 (message "Priority removed")
13264 (message "Priority of current item set to %s" news)))))
13266 (defun org-show-priority ()
13267 "Show the priority of the current item.
13268 This priority is composed of the main priority given with the [#A] cookies,
13269 and by additional input from the age of a schedules or deadline entry."
13270 (interactive)
13271 (let ((pri (if (eq major-mode 'org-agenda-mode)
13272 (org-get-at-bol 'priority)
13273 (save-excursion
13274 (save-match-data
13275 (beginning-of-line)
13276 (and (looking-at org-heading-regexp)
13277 (org-get-priority (match-string 0))))))))
13278 (message "Priority is %d" (if pri pri -1000))))
13280 (defun org-get-priority (s)
13281 "Find priority cookie and return priority."
13282 (save-match-data
13283 (if (functionp org-get-priority-function)
13284 (funcall org-get-priority-function)
13285 (if (not (string-match org-priority-regexp s))
13286 (* 1000 (- org-lowest-priority org-default-priority))
13287 (* 1000 (- org-lowest-priority
13288 (string-to-char (match-string 2 s))))))))
13290 ;;;; Tags
13292 (defvar org-agenda-archives-mode)
13293 (defvar org-map-continue-from nil
13294 "Position from where mapping should continue.
13295 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13297 (defvar org-scanner-tags nil
13298 "The current tag list while the tags scanner is running.")
13299 (defvar org-trust-scanner-tags nil
13300 "Should `org-get-tags-at' use the tags for the scanner.
13301 This is for internal dynamical scoping only.
13302 When this is non-nil, the function `org-get-tags-at' will return the value
13303 of `org-scanner-tags' instead of building the list by itself. This
13304 can lead to large speed-ups when the tags scanner is used in a file with
13305 many entries, and when the list of tags is retrieved, for example to
13306 obtain a list of properties. Building the tags list for each entry in such
13307 a file becomes an N^2 operation - but with this variable set, it scales
13308 as N.")
13310 (defun org-scan-tags (action matcher todo-only &optional start-level)
13311 "Scan headline tags with inheritance and produce output ACTION.
13313 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13314 or `agenda' to produce an entry list for an agenda view. It can also be
13315 a Lisp form or a function that should be called at each matched headline, in
13316 this case the return value is a list of all return values from these calls.
13318 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13319 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13320 only lines with a not-done TODO keyword are included in the output.
13321 This should be the same variable that was scoped into
13322 and set by `org-make-tags-matcher' when it constructed MATCHER.
13324 START-LEVEL can be a string with asterisks, reducing the scope to
13325 headlines matching this string."
13326 (require 'org-agenda)
13327 (let* ((re (concat "^"
13328 (if start-level
13329 ;; Get the correct level to match
13330 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13331 org-outline-regexp)
13332 " *\\(\\<\\("
13333 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13334 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13335 (props (list 'face 'default
13336 'done-face 'org-agenda-done
13337 'undone-face 'default
13338 'mouse-face 'highlight
13339 'org-not-done-regexp org-not-done-regexp
13340 'org-todo-regexp org-todo-regexp
13341 'org-complex-heading-regexp org-complex-heading-regexp
13342 'help-echo
13343 (format "mouse-2 or RET jump to org file %s"
13344 (abbreviate-file-name
13345 (or (buffer-file-name (buffer-base-buffer))
13346 (buffer-name (buffer-base-buffer)))))))
13347 (case-fold-search nil)
13348 (org-map-continue-from nil)
13349 lspos tags tags-list
13350 (tags-alist (list (cons 0 org-file-tags)))
13351 (llast 0) rtn rtn1 level category i txt
13352 todo marker entry priority)
13353 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13354 (setq action (list 'lambda nil action)))
13355 (save-excursion
13356 (goto-char (point-min))
13357 (when (eq action 'sparse-tree)
13358 (org-overview)
13359 (org-remove-occur-highlights))
13360 (while (re-search-forward re nil t)
13361 (setq org-map-continue-from nil)
13362 (catch :skip
13363 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13364 tags (if (match-end 4) (org-match-string-no-properties 4)))
13365 (goto-char (setq lspos (match-beginning 0)))
13366 (setq level (org-reduced-level (org-outline-level))
13367 category (org-get-category))
13368 (setq i llast llast level)
13369 ;; remove tag lists from same and sublevels
13370 (while (>= i level)
13371 (when (setq entry (assoc i tags-alist))
13372 (setq tags-alist (delete entry tags-alist)))
13373 (setq i (1- i)))
13374 ;; add the next tags
13375 (when tags
13376 (setq tags (org-split-string tags ":")
13377 tags-alist
13378 (cons (cons level tags) tags-alist)))
13379 ;; compile tags for current headline
13380 (setq tags-list
13381 (if org-use-tag-inheritance
13382 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13383 tags)
13384 org-scanner-tags tags-list)
13385 (when org-use-tag-inheritance
13386 (setcdr (car tags-alist)
13387 (mapcar (lambda (x)
13388 (setq x (copy-sequence x))
13389 (org-add-prop-inherited x))
13390 (cdar tags-alist))))
13391 (when (and tags org-use-tag-inheritance
13392 (or (not (eq t org-use-tag-inheritance))
13393 org-tags-exclude-from-inheritance))
13394 ;; selective inheritance, remove uninherited ones
13395 (setcdr (car tags-alist)
13396 (org-remove-uninherited-tags (cdar tags-alist))))
13397 (when (and
13399 ;; eval matcher only when the todo condition is OK
13400 (and (or (not todo-only) (member todo org-not-done-keywords))
13401 (let ((case-fold-search t) (org-trust-scanner-tags t))
13402 (eval matcher)))
13404 ;; Call the skipper, but return t if it does not skip,
13405 ;; so that the `and' form continues evaluating
13406 (progn
13407 (unless (eq action 'sparse-tree) (org-agenda-skip))
13410 ;; Check if timestamps are deselecting this entry
13411 (or (not todo-only)
13412 (and (member todo org-not-done-keywords)
13413 (or (not org-agenda-tags-todo-honor-ignore-options)
13414 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13416 ;; select this headline
13417 (cond
13418 ((eq action 'sparse-tree)
13419 (and org-highlight-sparse-tree-matches
13420 (org-get-heading) (match-end 0)
13421 (org-highlight-new-match
13422 (match-beginning 1) (match-end 1)))
13423 (org-show-context 'tags-tree))
13424 ((eq action 'agenda)
13425 (setq txt (org-agenda-format-item
13427 (concat
13428 (if (eq org-tags-match-list-sublevels 'indented)
13429 (make-string (1- level) ?.) "")
13430 (org-get-heading))
13431 level category
13432 tags-list)
13433 priority (org-get-priority txt))
13434 (goto-char lspos)
13435 (setq marker (org-agenda-new-marker))
13436 (org-add-props txt props
13437 'org-marker marker 'org-hd-marker marker 'org-category category
13438 'todo-state todo
13439 'priority priority 'type "tagsmatch")
13440 (push txt rtn))
13441 ((functionp action)
13442 (setq org-map-continue-from nil)
13443 (save-excursion
13444 (setq rtn1 (funcall action))
13445 (push rtn1 rtn)))
13446 (t (error "Invalid action")))
13448 ;; if we are to skip sublevels, jump to end of subtree
13449 (unless org-tags-match-list-sublevels
13450 (org-end-of-subtree t)
13451 (backward-char 1))))
13452 ;; Get the correct position from where to continue
13453 (if org-map-continue-from
13454 (goto-char org-map-continue-from)
13455 (and (= (point) lspos) (end-of-line 1)))))
13456 (when (and (eq action 'sparse-tree)
13457 (not org-sparse-tree-open-archived-trees))
13458 (org-hide-archived-subtrees (point-min) (point-max)))
13459 (nreverse rtn)))
13461 (defun org-remove-uninherited-tags (tags)
13462 "Remove all tags that are not inherited from the list TAGS."
13463 (cond
13464 ((eq org-use-tag-inheritance t)
13465 (if org-tags-exclude-from-inheritance
13466 (org-delete-all org-tags-exclude-from-inheritance tags)
13467 tags))
13468 ((not org-use-tag-inheritance) nil)
13469 ((stringp org-use-tag-inheritance)
13470 (delq nil (mapcar
13471 (lambda (x)
13472 (if (and (string-match org-use-tag-inheritance x)
13473 (not (member x org-tags-exclude-from-inheritance)))
13474 x nil))
13475 tags)))
13476 ((listp org-use-tag-inheritance)
13477 (delq nil (mapcar
13478 (lambda (x)
13479 (if (member x org-use-tag-inheritance) x nil))
13480 tags)))))
13482 (defun org-match-sparse-tree (&optional todo-only match)
13483 "Create a sparse tree according to tags string MATCH.
13484 MATCH can contain positive and negative selection of tags, like
13485 \"+WORK+URGENT-WITHBOSS\".
13486 If optional argument TODO-ONLY is non-nil, only select lines that are
13487 also TODO lines."
13488 (interactive "P")
13489 (org-agenda-prepare-buffers (list (current-buffer)))
13490 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13492 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13494 (defvar org-cached-props nil)
13495 (defun org-cached-entry-get (pom property)
13496 (if (or (eq t org-use-property-inheritance)
13497 (and (stringp org-use-property-inheritance)
13498 (string-match org-use-property-inheritance property))
13499 (and (listp org-use-property-inheritance)
13500 (member property org-use-property-inheritance)))
13501 ;; Caching is not possible, check it directly
13502 (org-entry-get pom property 'inherit)
13503 ;; Get all properties, so that we can do complicated checks easily
13504 (cdr (assoc property (or org-cached-props
13505 (setq org-cached-props
13506 (org-entry-properties pom)))))))
13508 (defun org-global-tags-completion-table (&optional files)
13509 "Return the list of all tags in all agenda buffer/files.
13510 Optional FILES argument is a list of files which can be used
13511 instead of the agenda files."
13512 (save-excursion
13513 (org-uniquify
13514 (delq nil
13515 (apply 'append
13516 (mapcar
13517 (lambda (file)
13518 (set-buffer (find-file-noselect file))
13519 (append (org-get-buffer-tags)
13520 (mapcar (lambda (x) (if (stringp (car-safe x))
13521 (list (car-safe x)) nil))
13522 org-tag-alist)))
13523 (if (and files (car files))
13524 files
13525 (org-agenda-files))))))))
13527 (defun org-make-tags-matcher (match)
13528 "Create the TAGS/TODO matcher form for the selection string MATCH.
13530 The variable `todo-only' is scoped dynamically into this function.
13531 It will be set to t if the matcher restricts matching to TODO entries,
13532 otherwise will not be touched.
13534 Returns a cons of the selection string MATCH and the constructed
13535 lisp form implementing the matcher. The matcher is to be evaluated
13536 at an Org entry, with point on the headline, and returns t if the
13537 entry matches the selection string MATCH. The returned lisp form
13538 references two variables with information about the entry, which
13539 must be bound around the form's evaluation: todo, the TODO keyword
13540 at the entry (or nil of none); and tags-list, the list of all tags
13541 at the entry including inherited ones. Additionally, the category
13542 of the entry (if any) must be specified as the text property
13543 'org-category on the headline.
13545 See also `org-scan-tags'.
13547 (declare (special todo-only))
13548 (unless (boundp 'todo-only)
13549 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13550 (unless match
13551 ;; Get a new match request, with completion
13552 (let ((org-last-tags-completion-table
13553 (org-global-tags-completion-table)))
13554 (setq match (org-completing-read-no-i
13555 "Match: " 'org-tags-completion-function nil nil nil
13556 'org-tags-history))))
13558 ;; Parse the string and create a lisp form
13559 (let ((match0 match)
13560 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13561 minus tag mm
13562 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13563 orterms term orlist re-p str-p level-p level-op time-p
13564 prop-p pn pv po gv rest)
13565 (if (string-match "/+" match)
13566 ;; match contains also a todo-matching request
13567 (progn
13568 (setq tagsmatch (substring match 0 (match-beginning 0))
13569 todomatch (substring match (match-end 0)))
13570 (if (string-match "^!" todomatch)
13571 (setq todo-only t todomatch (substring todomatch 1)))
13572 (if (string-match "^\\s-*$" todomatch)
13573 (setq todomatch nil)))
13574 ;; only matching tags
13575 (setq tagsmatch match todomatch nil))
13577 ;; Make the tags matcher
13578 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13579 (setq tagsmatcher t)
13580 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13581 (while (setq term (pop orterms))
13582 (while (and (equal (substring term -1) "\\") orterms)
13583 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13584 (while (string-match re term)
13585 (setq rest (substring term (match-end 0))
13586 minus (and (match-end 1)
13587 (equal (match-string 1 term) "-"))
13588 tag (save-match-data (replace-regexp-in-string
13589 "\\\\-" "-"
13590 (match-string 2 term)))
13591 re-p (equal (string-to-char tag) ?{)
13592 level-p (match-end 4)
13593 prop-p (match-end 5)
13594 mm (cond
13595 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13596 (level-p
13597 (setq level-op (org-op-to-function (match-string 3 term)))
13598 `(,level-op level ,(string-to-number
13599 (match-string 4 term))))
13600 (prop-p
13601 (setq pn (match-string 5 term)
13602 po (match-string 6 term)
13603 pv (match-string 7 term)
13604 re-p (equal (string-to-char pv) ?{)
13605 str-p (equal (string-to-char pv) ?\")
13606 time-p (save-match-data
13607 (string-match "^\"[[<].*[]>]\"$" pv))
13608 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13609 (if time-p (setq pv (org-matcher-time pv)))
13610 (setq po (org-op-to-function po (if time-p 'time str-p)))
13611 (cond
13612 ((equal pn "CATEGORY")
13613 (setq gv '(get-text-property (point) 'org-category)))
13614 ((equal pn "TODO")
13615 (setq gv 'todo))
13617 (setq gv `(org-cached-entry-get nil ,pn))))
13618 (if re-p
13619 (if (eq po 'org<>)
13620 `(not (string-match ,pv (or ,gv "")))
13621 `(string-match ,pv (or ,gv "")))
13622 (if str-p
13623 `(,po (or ,gv "") ,pv)
13624 `(,po (string-to-number (or ,gv ""))
13625 ,(string-to-number pv) ))))
13626 (t `(member ,tag tags-list)))
13627 mm (if minus (list 'not mm) mm)
13628 term rest)
13629 (push mm tagsmatcher))
13630 (push (if (> (length tagsmatcher) 1)
13631 (cons 'and tagsmatcher)
13632 (car tagsmatcher))
13633 orlist)
13634 (setq tagsmatcher nil))
13635 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13636 (setq tagsmatcher
13637 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13638 ;; Make the todo matcher
13639 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13640 (setq todomatcher t)
13641 (setq orterms (org-split-string todomatch "|") orlist nil)
13642 (while (setq term (pop orterms))
13643 (while (string-match re term)
13644 (setq minus (and (match-end 1)
13645 (equal (match-string 1 term) "-"))
13646 kwd (match-string 2 term)
13647 re-p (equal (string-to-char kwd) ?{)
13648 term (substring term (match-end 0))
13649 mm (if re-p
13650 `(string-match ,(substring kwd 1 -1) todo)
13651 (list 'equal 'todo kwd))
13652 mm (if minus (list 'not mm) mm))
13653 (push mm todomatcher))
13654 (push (if (> (length todomatcher) 1)
13655 (cons 'and todomatcher)
13656 (car todomatcher))
13657 orlist)
13658 (setq todomatcher nil))
13659 (setq todomatcher (if (> (length orlist) 1)
13660 (cons 'or orlist) (car orlist))))
13662 ;; Return the string and lisp forms of the matcher
13663 (setq matcher (if todomatcher
13664 (list 'and tagsmatcher todomatcher)
13665 tagsmatcher))
13666 (when todo-only
13667 (setq matcher (list 'and '(member todo org-not-done-keywords)
13668 matcher)))
13669 (cons match0 matcher)))
13671 (defun org-op-to-function (op &optional stringp)
13672 "Turn an operator into the appropriate function."
13673 (setq op
13674 (cond
13675 ((equal op "<" ) '(< string< org-time<))
13676 ((equal op ">" ) '(> org-string> org-time>))
13677 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13678 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13679 ((member op '("=" "==")) '(= string= org-time=))
13680 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13681 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13683 (defun org<> (a b) (not (= a b)))
13684 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13685 (defun org-string>= (a b) (not (string< a b)))
13686 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13687 (defun org-string<> (a b) (not (string= a b)))
13688 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13689 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13690 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13691 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13692 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13693 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13694 (defun org-2ft (s)
13695 "Convert S to a floating point time.
13696 If S is already a number, just return it. If it is a string, parse
13697 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13698 (cond
13699 ((numberp s) s)
13700 ((stringp s)
13701 (condition-case nil
13702 (float-time (apply 'encode-time (org-parse-time-string s)))
13703 (error 0.)))
13704 (t 0.)))
13706 (defun org-time-today ()
13707 "Time in seconds today at 0:00.
13708 Returns the float number of seconds since the beginning of the
13709 epoch to the beginning of today (00:00)."
13710 (float-time (apply 'encode-time
13711 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13713 (defun org-matcher-time (s)
13714 "Interpret a time comparison value."
13715 (save-match-data
13716 (cond
13717 ((string= s "<now>") (float-time))
13718 ((string= s "<today>") (org-time-today))
13719 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13720 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13721 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13722 (+ (org-time-today)
13723 (* (string-to-number (match-string 1 s))
13724 (cdr (assoc (match-string 2 s)
13725 '(("d" . 86400.0) ("w" . 604800.0)
13726 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13727 (t (org-2ft s)))))
13729 (defun org-match-any-p (re list)
13730 "Does re match any element of list?"
13731 (setq list (mapcar (lambda (x) (string-match re x)) list))
13732 (delq nil list))
13734 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13735 (defvar org-tags-overlay (make-overlay 1 1))
13736 (org-detach-overlay org-tags-overlay)
13738 (defun org-get-local-tags-at (&optional pos)
13739 "Get a list of tags defined in the current headline."
13740 (org-get-tags-at pos 'local))
13742 (defun org-get-local-tags ()
13743 "Get a list of tags defined in the current headline."
13744 (org-get-tags-at nil 'local))
13746 (defun org-get-tags-at (&optional pos local)
13747 "Get a list of all headline tags applicable at POS.
13748 POS defaults to point. If tags are inherited, the list contains
13749 the targets in the same sequence as the headlines appear, i.e.
13750 the tags of the current headline come last.
13751 When LOCAL is non-nil, only return tags from the current headline,
13752 ignore inherited ones."
13753 (interactive)
13754 (if (and org-trust-scanner-tags
13755 (or (not pos) (equal pos (point)))
13756 (not local))
13757 org-scanner-tags
13758 (let (tags ltags lastpos parent)
13759 (save-excursion
13760 (save-restriction
13761 (widen)
13762 (goto-char (or pos (point)))
13763 (save-match-data
13764 (catch 'done
13765 (condition-case nil
13766 (progn
13767 (org-back-to-heading t)
13768 (while (not (equal lastpos (point)))
13769 (setq lastpos (point))
13770 (when (looking-at
13771 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13772 (setq ltags (org-split-string
13773 (org-match-string-no-properties 1) ":"))
13774 (when parent
13775 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13776 (setq tags (append
13777 (if parent
13778 (org-remove-uninherited-tags ltags)
13779 ltags)
13780 tags)))
13781 (or org-use-tag-inheritance (throw 'done t))
13782 (if local (throw 'done t))
13783 (or (org-up-heading-safe) (error nil))
13784 (setq parent t)))
13785 (error nil)))))
13786 (if local
13787 tags
13788 (reverse (delete-dups
13789 (reverse (append
13790 (org-remove-uninherited-tags
13791 org-file-tags) tags)))))))))
13793 (defun org-add-prop-inherited (s)
13794 (add-text-properties 0 (length s) '(inherited t) s)
13797 (defun org-toggle-tag (tag &optional onoff)
13798 "Toggle the tag TAG for the current line.
13799 If ONOFF is `on' or `off', don't toggle but set to this state."
13800 (let (res current)
13801 (save-excursion
13802 (org-back-to-heading t)
13803 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13804 (point-at-eol) t)
13805 (progn
13806 (setq current (match-string 1))
13807 (replace-match ""))
13808 (setq current ""))
13809 (setq current (nreverse (org-split-string current ":")))
13810 (cond
13811 ((eq onoff 'on)
13812 (setq res t)
13813 (or (member tag current) (push tag current)))
13814 ((eq onoff 'off)
13815 (or (not (member tag current)) (setq current (delete tag current))))
13816 (t (if (member tag current)
13817 (setq current (delete tag current))
13818 (setq res t)
13819 (push tag current))))
13820 (end-of-line 1)
13821 (if current
13822 (progn
13823 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13824 (org-set-tags nil t))
13825 (delete-horizontal-space))
13826 (run-hooks 'org-after-tags-change-hook))
13827 res))
13829 (defun org-align-tags-here (to-col)
13830 ;; Assumes that this is a headline
13831 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13832 (beginning-of-line 1)
13833 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13834 (< pos (match-beginning 2)))
13835 (progn
13836 (setq tags-l (- (match-end 2) (match-beginning 2)))
13837 (goto-char (match-beginning 1))
13838 (insert " ")
13839 (delete-region (point) (1+ (match-beginning 2)))
13840 (setq ncol (max (current-column)
13841 (1+ col)
13842 (if (> to-col 0)
13843 to-col
13844 (- (abs to-col) tags-l))))
13845 (setq p (point))
13846 (insert (make-string (- ncol (current-column)) ?\ ))
13847 (setq ncol (current-column))
13848 (when indent-tabs-mode (tabify p (point-at-eol)))
13849 (org-move-to-column (min ncol col) t))
13850 (goto-char pos))))
13852 (defun org-set-tags-command (&optional arg just-align)
13853 "Call the set-tags command for the current entry."
13854 (interactive "P")
13855 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13856 (org-set-tags arg just-align)
13857 (save-excursion
13858 (org-back-to-heading t)
13859 (org-set-tags arg just-align))))
13861 (defun org-set-tags-to (data)
13862 "Set the tags of the current entry to DATA, replacing the current tags.
13863 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13864 If DATA is nil or the empty string, any tags will be removed."
13865 (interactive "sTags: ")
13866 (setq data
13867 (cond
13868 ((eq data nil) "")
13869 ((equal data "") "")
13870 ((stringp data)
13871 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13872 ":"))
13873 ((listp data)
13874 (concat ":" (mapconcat 'identity data ":") ":"))))
13875 (when data
13876 (save-excursion
13877 (org-back-to-heading t)
13878 (when (looking-at org-complex-heading-regexp)
13879 (if (match-end 5)
13880 (progn
13881 (goto-char (match-beginning 5))
13882 (insert data)
13883 (delete-region (point) (point-at-eol))
13884 (org-set-tags nil 'align))
13885 (goto-char (point-at-eol))
13886 (insert " " data)
13887 (org-set-tags nil 'align)))
13888 (beginning-of-line 1)
13889 (if (looking-at ".*?\\([ \t]+\\)$")
13890 (delete-region (match-beginning 1) (match-end 1))))))
13892 (defun org-align-all-tags ()
13893 "Align the tags i all headings."
13894 (interactive)
13895 (save-excursion
13896 (or (ignore-errors (org-back-to-heading t))
13897 (outline-next-heading))
13898 (if (org-at-heading-p)
13899 (org-set-tags t)
13900 (message "No headings"))))
13902 (defvar org-indent-indentation-per-level)
13903 (defun org-set-tags (&optional arg just-align)
13904 "Set the tags for the current headline.
13905 With prefix ARG, realign all tags in headings in the current buffer."
13906 (interactive "P")
13907 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13908 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13909 'region-start-level 'region))
13910 org-loop-over-headlines-in-active-region)
13911 (org-map-entries
13912 ;; We don't use ARG and JUST-ALIGN here these args are not
13913 ;; useful when looping over headlines
13914 `(org-set-tags)
13915 org-loop-over-headlines-in-active-region
13916 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13917 (let* ((re org-outline-regexp-bol)
13918 (current (unless arg (org-get-tags-string)))
13919 (col (current-column))
13920 (org-setting-tags t)
13921 table current-tags inherited-tags ; computed below when needed
13922 tags p0 c0 c1 rpl di tc level)
13923 (if arg
13924 (save-excursion
13925 (goto-char (point-min))
13926 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13927 (while (re-search-forward re nil t)
13928 (org-set-tags nil t)
13929 (end-of-line 1)))
13930 (message "All tags realigned to column %d" org-tags-column))
13931 (if just-align
13932 (setq tags current)
13933 ;; Get a new set of tags from the user
13934 (save-excursion
13935 (setq table (append org-tag-persistent-alist
13936 (or org-tag-alist (org-get-buffer-tags))
13937 (and
13938 org-complete-tags-always-offer-all-agenda-tags
13939 (org-global-tags-completion-table
13940 (org-agenda-files))))
13941 org-last-tags-completion-table table
13942 current-tags (org-split-string current ":")
13943 inherited-tags (nreverse
13944 (nthcdr (length current-tags)
13945 (nreverse (org-get-tags-at))))
13946 tags
13947 (if (or (eq t org-use-fast-tag-selection)
13948 (and org-use-fast-tag-selection
13949 (delq nil (mapcar 'cdr table))))
13950 (org-fast-tag-selection
13951 current-tags inherited-tags table
13952 (if org-fast-tag-selection-include-todo
13953 org-todo-key-alist))
13954 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13955 (org-trim
13956 (org-icompleting-read "Tags: "
13957 'org-tags-completion-function
13958 nil nil current 'org-tags-history))))))
13959 (while (string-match "[-+&]+" tags)
13960 ;; No boolean logic, just a list
13961 (setq tags (replace-match ":" t t tags))))
13963 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13965 (if org-tags-sort-function
13966 (setq tags (mapconcat 'identity
13967 (sort (org-split-string
13968 tags (org-re "[^[:alnum:]_@#%]+"))
13969 org-tags-sort-function) ":")))
13971 (if (string-match "\\`[\t ]*\\'" tags)
13972 (setq tags "")
13973 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13974 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13976 ;; Insert new tags at the correct column
13977 (beginning-of-line 1)
13978 (setq level (or (and (looking-at org-outline-regexp)
13979 (- (match-end 0) (point) 1))
13981 (cond
13982 ((and (equal current "") (equal tags "")))
13983 ((re-search-forward
13984 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13985 (point-at-eol) t)
13986 (if (equal tags "")
13987 (setq rpl "")
13988 (goto-char (match-beginning 0))
13989 (setq c0 (current-column)
13990 ;; compute offset for the case of org-indent-mode active
13991 di (if org-indent-mode
13992 (* (1- org-indent-indentation-per-level) (1- level))
13994 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13995 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13996 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13997 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13998 (replace-match rpl t t)
13999 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14000 tags)
14001 (t (error "Tags alignment failed")))
14002 (org-move-to-column col)
14003 (unless just-align
14004 (run-hooks 'org-after-tags-change-hook))))))
14006 (defun org-change-tag-in-region (beg end tag off)
14007 "Add or remove TAG for each entry in the region.
14008 This works in the agenda, and also in an org-mode buffer."
14009 (interactive
14010 (list (region-beginning) (region-end)
14011 (let ((org-last-tags-completion-table
14012 (if (derived-mode-p 'org-mode)
14013 (org-get-buffer-tags)
14014 (org-global-tags-completion-table))))
14015 (org-icompleting-read
14016 "Tag: " 'org-tags-completion-function nil nil nil
14017 'org-tags-history))
14018 (progn
14019 (message "[s]et or [r]emove? ")
14020 (equal (read-char-exclusive) ?r))))
14021 (if (fboundp 'deactivate-mark) (deactivate-mark))
14022 (let ((agendap (equal major-mode 'org-agenda-mode))
14023 l1 l2 m buf pos newhead (cnt 0))
14024 (goto-char end)
14025 (setq l2 (1- (org-current-line)))
14026 (goto-char beg)
14027 (setq l1 (org-current-line))
14028 (loop for l from l1 to l2 do
14029 (org-goto-line l)
14030 (setq m (get-text-property (point) 'org-hd-marker))
14031 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14032 (and agendap m))
14033 (setq buf (if agendap (marker-buffer m) (current-buffer))
14034 pos (if agendap m (point)))
14035 (with-current-buffer buf
14036 (save-excursion
14037 (save-restriction
14038 (goto-char pos)
14039 (setq cnt (1+ cnt))
14040 (org-toggle-tag tag (if off 'off 'on))
14041 (setq newhead (org-get-heading)))))
14042 (and agendap (org-agenda-change-all-lines newhead m))))
14043 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14045 (defun org-tags-completion-function (string predicate &optional flag)
14046 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14047 (confirm (lambda (x) (stringp (car x)))))
14048 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14049 (setq s1 (match-string 1 string)
14050 s2 (match-string 2 string))
14051 (setq s1 "" s2 string))
14052 (cond
14053 ((eq flag nil)
14054 ;; try completion
14055 (setq rtn (try-completion s2 ctable confirm))
14056 (if (stringp rtn)
14057 (setq rtn
14058 (concat s1 s2 (substring rtn (length s2))
14059 (if (and org-add-colon-after-tag-completion
14060 (assoc rtn ctable))
14061 ":" ""))))
14062 rtn)
14063 ((eq flag t)
14064 ;; all-completions
14065 (all-completions s2 ctable confirm)
14067 ((eq flag 'lambda)
14068 ;; exact match?
14069 (assoc s2 ctable)))
14072 (defun org-fast-tag-insert (kwd tags face &optional end)
14073 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14074 (insert (format "%-12s" (concat kwd ":"))
14075 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14076 (or end "")))
14078 (defun org-fast-tag-show-exit (flag)
14079 (save-excursion
14080 (org-goto-line 3)
14081 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14082 (replace-match ""))
14083 (when flag
14084 (end-of-line 1)
14085 (org-move-to-column (- (window-width) 19) t)
14086 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14088 (defun org-set-current-tags-overlay (current prefix)
14089 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14090 (if (featurep 'xemacs)
14091 (org-overlay-display org-tags-overlay (concat prefix s)
14092 'secondary-selection)
14093 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14094 (org-overlay-display org-tags-overlay (concat prefix s)))))
14096 (defvar org-last-tag-selection-key nil)
14097 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14098 "Fast tag selection with single keys.
14099 CURRENT is the current list of tags in the headline, INHERITED is the
14100 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14101 possibly with grouping information. TODO-TABLE is a similar table with
14102 TODO keywords, should these have keys assigned to them.
14103 If the keys are nil, a-z are automatically assigned.
14104 Returns the new tags string, or nil to not change the current settings."
14105 (let* ((fulltable (append table todo-table))
14106 (maxlen (apply 'max (mapcar
14107 (lambda (x)
14108 (if (stringp (car x)) (string-width (car x)) 0))
14109 fulltable)))
14110 (buf (current-buffer))
14111 (expert (eq org-fast-tag-selection-single-key 'expert))
14112 (buffer-tags nil)
14113 (fwidth (+ maxlen 3 1 3))
14114 (ncol (/ (- (window-width) 4) fwidth))
14115 (i-face 'org-done)
14116 (c-face 'org-todo)
14117 tg cnt e c char c1 c2 ntable tbl rtn
14118 ov-start ov-end ov-prefix
14119 (exit-after-next org-fast-tag-selection-single-key)
14120 (done-keywords org-done-keywords)
14121 groups ingroup)
14122 (save-excursion
14123 (beginning-of-line 1)
14124 (if (looking-at
14125 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14126 (setq ov-start (match-beginning 1)
14127 ov-end (match-end 1)
14128 ov-prefix "")
14129 (setq ov-start (1- (point-at-eol))
14130 ov-end (1+ ov-start))
14131 (skip-chars-forward "^\n\r")
14132 (setq ov-prefix
14133 (concat
14134 (buffer-substring (1- (point)) (point))
14135 (if (> (current-column) org-tags-column)
14137 (make-string (- org-tags-column (current-column)) ?\ ))))))
14138 (move-overlay org-tags-overlay ov-start ov-end)
14139 (save-window-excursion
14140 (if expert
14141 (set-buffer (get-buffer-create " *Org tags*"))
14142 (delete-other-windows)
14143 (split-window-vertically)
14144 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14145 (erase-buffer)
14146 (org-set-local 'org-done-keywords done-keywords)
14147 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14148 (org-fast-tag-insert "Current" current c-face "\n\n")
14149 (org-fast-tag-show-exit exit-after-next)
14150 (org-set-current-tags-overlay current ov-prefix)
14151 (setq tbl fulltable char ?a cnt 0)
14152 (while (setq e (pop tbl))
14153 (cond
14154 ((equal (car e) :startgroup)
14155 (push '() groups) (setq ingroup t)
14156 (when (not (= cnt 0))
14157 (setq cnt 0)
14158 (insert "\n"))
14159 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14160 ((equal (car e) :endgroup)
14161 (setq ingroup nil cnt 0)
14162 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14163 ((equal e '(:newline))
14164 (when (not (= cnt 0))
14165 (setq cnt 0)
14166 (insert "\n")
14167 (setq e (car tbl))
14168 (while (equal (car tbl) '(:newline))
14169 (insert "\n")
14170 (setq tbl (cdr tbl)))))
14172 (setq tg (copy-sequence (car e)) c2 nil)
14173 (if (cdr e)
14174 (setq c (cdr e))
14175 ;; automatically assign a character.
14176 (setq c1 (string-to-char
14177 (downcase (substring
14178 tg (if (= (string-to-char tg) ?@) 1 0)))))
14179 (if (or (rassoc c1 ntable) (rassoc c1 table))
14180 (while (or (rassoc char ntable) (rassoc char table))
14181 (setq char (1+ char)))
14182 (setq c2 c1))
14183 (setq c (or c2 char)))
14184 (if ingroup (push tg (car groups)))
14185 (setq tg (org-add-props tg nil 'face
14186 (cond
14187 ((not (assoc tg table))
14188 (org-get-todo-face tg))
14189 ((member tg current) c-face)
14190 ((member tg inherited) i-face))))
14191 (if (and (= cnt 0) (not ingroup)) (insert " "))
14192 (insert "[" c "] " tg (make-string
14193 (- fwidth 4 (length tg)) ?\ ))
14194 (push (cons tg c) ntable)
14195 (when (= (setq cnt (1+ cnt)) ncol)
14196 (insert "\n")
14197 (if ingroup (insert " "))
14198 (setq cnt 0)))))
14199 (setq ntable (nreverse ntable))
14200 (insert "\n")
14201 (goto-char (point-min))
14202 (if (not expert) (org-fit-window-to-buffer))
14203 (setq rtn
14204 (catch 'exit
14205 (while t
14206 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14207 (if (not groups) "no " "")
14208 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14209 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14210 (setq org-last-tag-selection-key c)
14211 (cond
14212 ((= c ?\r) (throw 'exit t))
14213 ((= c ?!)
14214 (setq groups (not groups))
14215 (goto-char (point-min))
14216 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14217 ((= c ?\C-c)
14218 (if (not expert)
14219 (org-fast-tag-show-exit
14220 (setq exit-after-next (not exit-after-next)))
14221 (setq expert nil)
14222 (delete-other-windows)
14223 (set-window-buffer (split-window-vertically) " *Org tags*")
14224 (org-switch-to-buffer-other-window " *Org tags*")
14225 (org-fit-window-to-buffer)))
14226 ((or (= c ?\C-g)
14227 (and (= c ?q) (not (rassoc c ntable))))
14228 (org-detach-overlay org-tags-overlay)
14229 (setq quit-flag t))
14230 ((= c ?\ )
14231 (setq current nil)
14232 (if exit-after-next (setq exit-after-next 'now)))
14233 ((= c ?\t)
14234 (condition-case nil
14235 (setq tg (org-icompleting-read
14236 "Tag: "
14237 (or buffer-tags
14238 (with-current-buffer buf
14239 (org-get-buffer-tags)))))
14240 (quit (setq tg "")))
14241 (when (string-match "\\S-" tg)
14242 (add-to-list 'buffer-tags (list tg))
14243 (if (member tg current)
14244 (setq current (delete tg current))
14245 (push tg current)))
14246 (if exit-after-next (setq exit-after-next 'now)))
14247 ((setq e (rassoc c todo-table) tg (car e))
14248 (with-current-buffer buf
14249 (save-excursion (org-todo tg)))
14250 (if exit-after-next (setq exit-after-next 'now)))
14251 ((setq e (rassoc c ntable) tg (car e))
14252 (if (member tg current)
14253 (setq current (delete tg current))
14254 (loop for g in groups do
14255 (if (member tg g)
14256 (mapc (lambda (x)
14257 (setq current (delete x current)))
14258 g)))
14259 (push tg current))
14260 (if exit-after-next (setq exit-after-next 'now))))
14262 ;; Create a sorted list
14263 (setq current
14264 (sort current
14265 (lambda (a b)
14266 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14267 (if (eq exit-after-next 'now) (throw 'exit t))
14268 (goto-char (point-min))
14269 (beginning-of-line 2)
14270 (delete-region (point) (point-at-eol))
14271 (org-fast-tag-insert "Current" current c-face)
14272 (org-set-current-tags-overlay current ov-prefix)
14273 (while (re-search-forward
14274 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14275 (setq tg (match-string 1))
14276 (add-text-properties
14277 (match-beginning 1) (match-end 1)
14278 (list 'face
14279 (cond
14280 ((member tg current) c-face)
14281 ((member tg inherited) i-face)
14282 (t (get-text-property (match-beginning 1) 'face))))))
14283 (goto-char (point-min)))))
14284 (org-detach-overlay org-tags-overlay)
14285 (if rtn
14286 (mapconcat 'identity current ":")
14287 nil))))
14289 (defun org-get-tags-string ()
14290 "Get the TAGS string in the current headline."
14291 (unless (org-at-heading-p t)
14292 (error "Not on a heading"))
14293 (save-excursion
14294 (beginning-of-line 1)
14295 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14296 (org-match-string-no-properties 1)
14297 "")))
14299 (defun org-get-tags ()
14300 "Get the list of tags specified in the current headline."
14301 (org-split-string (org-get-tags-string) ":"))
14303 (defun org-get-buffer-tags ()
14304 "Get a table of all tags used in the buffer, for completion."
14305 (let (tags)
14306 (save-excursion
14307 (goto-char (point-min))
14308 (while (re-search-forward
14309 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14310 (when (equal (char-after (point-at-bol 0)) ?*)
14311 (mapc (lambda (x) (add-to-list 'tags x))
14312 (org-split-string (org-match-string-no-properties 1) ":")))))
14313 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14314 (mapcar 'list tags)))
14316 ;;;; The mapping API
14318 (defun org-map-entries (func &optional match scope &rest skip)
14319 "Call FUNC at each headline selected by MATCH in SCOPE.
14321 FUNC is a function or a lisp form. The function will be called without
14322 arguments, with the cursor positioned at the beginning of the headline.
14323 The return values of all calls to the function will be collected and
14324 returned as a list.
14326 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14327 does not need to preserve point. After evaluation, the cursor will be
14328 moved to the end of the line (presumably of the headline of the
14329 processed entry) and search continues from there. Under some
14330 circumstances, this may not produce the wanted results. For example,
14331 if you have removed (e.g. archived) the current (sub)tree it could
14332 mean that the next entry will be skipped entirely. In such cases, you
14333 can specify the position from where search should continue by making
14334 FUNC set the variable `org-map-continue-from' to the desired buffer
14335 position.
14337 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14338 Only headlines that are matched by this query will be considered during
14339 the iteration. When MATCH is nil or t, all headlines will be
14340 visited by the iteration.
14342 SCOPE determines the scope of this command. It can be any of:
14344 nil The current buffer, respecting the restriction if any
14345 tree The subtree started with the entry at point
14346 region The entries within the active region, if any
14347 region-start-level
14348 The entries within the active region, but only those at
14349 the same level than the first one.
14350 file The current buffer, without restriction
14351 file-with-archives
14352 The current buffer, and any archives associated with it
14353 agenda All agenda files
14354 agenda-with-archives
14355 All agenda files with any archive files associated with them
14356 \(file1 file2 ...)
14357 If this is a list, all files in the list will be scanned
14359 The remaining args are treated as settings for the skipping facilities of
14360 the scanner. The following items can be given here:
14362 archive skip trees with the archive tag.
14363 comment skip trees with the COMMENT keyword
14364 function or Emacs Lisp form:
14365 will be used as value for `org-agenda-skip-function', so whenever
14366 the function returns t, FUNC will not be called for that
14367 entry and search will continue from the point where the
14368 function leaves it.
14370 If your function needs to retrieve the tags including inherited tags
14371 at the *current* entry, you can use the value of the variable
14372 `org-scanner-tags' which will be much faster than getting the value
14373 with `org-get-tags-at'. If your function gets properties with
14374 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14375 to t around the call to `org-entry-properties' to get the same speedup.
14376 Note that if your function moves around to retrieve tags and properties at
14377 a *different* entry, you cannot use these techniques."
14378 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14379 (not (org-region-active-p)))
14380 (let* ((org-agenda-archives-mode nil) ; just to make sure
14381 (org-agenda-skip-archived-trees (memq 'archive skip))
14382 (org-agenda-skip-comment-trees (memq 'comment skip))
14383 (org-agenda-skip-function
14384 (car (org-delete-all '(comment archive) skip)))
14385 (org-tags-match-list-sublevels t)
14386 (start-level (eq scope 'region-start-level))
14387 matcher file res
14388 org-todo-keywords-for-agenda
14389 org-done-keywords-for-agenda
14390 org-todo-keyword-alist-for-agenda
14391 org-drawers-for-agenda
14392 org-tag-alist-for-agenda
14393 todo-only)
14395 (cond
14396 ((eq match t) (setq matcher t))
14397 ((eq match nil) (setq matcher t))
14398 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14400 (save-excursion
14401 (save-restriction
14402 (cond ((eq scope 'tree)
14403 (org-back-to-heading t)
14404 (org-narrow-to-subtree)
14405 (setq scope nil))
14406 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14407 (org-region-active-p))
14408 ;; If needed, set start-level to a string like "2"
14409 (when start-level
14410 (save-excursion
14411 (goto-char (region-beginning))
14412 (unless (org-at-heading-p) (outline-next-heading))
14413 (setq start-level (org-current-level))))
14414 (narrow-to-region (region-beginning)
14415 (save-excursion
14416 (goto-char (region-end))
14417 (unless (and (bolp) (org-at-heading-p))
14418 (outline-next-heading))
14419 (point)))
14420 (setq scope nil)))
14422 (if (not scope)
14423 (progn
14424 (org-agenda-prepare-buffers
14425 (list (buffer-file-name (current-buffer))))
14426 (setq res (org-scan-tags func matcher todo-only start-level)))
14427 ;; Get the right scope
14428 (cond
14429 ((and scope (listp scope) (symbolp (car scope)))
14430 (setq scope (eval scope)))
14431 ((eq scope 'agenda)
14432 (setq scope (org-agenda-files t)))
14433 ((eq scope 'agenda-with-archives)
14434 (setq scope (org-agenda-files t))
14435 (setq scope (org-add-archive-files scope)))
14436 ((eq scope 'file)
14437 (setq scope (list (buffer-file-name))))
14438 ((eq scope 'file-with-archives)
14439 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14440 (org-agenda-prepare-buffers scope)
14441 (while (setq file (pop scope))
14442 (with-current-buffer (org-find-base-buffer-visiting file)
14443 (save-excursion
14444 (save-restriction
14445 (widen)
14446 (goto-char (point-min))
14447 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14448 res)))
14450 ;;;; Properties
14452 ;;; Setting and retrieving properties
14454 (defconst org-special-properties
14455 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14456 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14457 "The special properties valid in Org-mode.
14459 These are properties that are not defined in the property drawer,
14460 but in some other way.")
14462 (defconst org-default-properties
14463 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14464 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14465 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14466 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14467 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14468 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14469 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14470 "Some properties that are used by Org-mode for various purposes.
14471 Being in this list makes sure that they are offered for completion.")
14473 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14474 "Regular expression matching the first line of a property drawer.")
14476 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14477 "Regular expression matching the last line of a property drawer.")
14479 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14480 "Regular expression matching the first line of a property drawer.")
14482 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14483 "Regular expression matching the first line of a property drawer.")
14485 (defconst org-property-drawer-re
14486 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14487 org-property-end-re "\\)\n?")
14488 "Matches an entire property drawer.")
14490 (defconst org-clock-drawer-re
14491 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14492 org-property-end-re "\\)\n?")
14493 "Matches an entire clock drawer.")
14495 (defsubst org-re-property (property)
14496 "Return a regexp matching a PROPERTY line.
14497 Match group 1 will be set to the value."
14498 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14500 (defsubst org-re-property-keyword (property)
14501 "Return a regexp matching a PROPERTY line, possibly with no
14502 value for the property."
14503 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14505 (defun org-property-action ()
14506 "Do an action on properties."
14507 (interactive)
14508 (let (c)
14509 (org-at-property-p)
14510 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14511 (setq c (read-char-exclusive))
14512 (cond
14513 ((equal c ?s)
14514 (call-interactively 'org-set-property))
14515 ((equal c ?d)
14516 (call-interactively 'org-delete-property))
14517 ((equal c ?D)
14518 (call-interactively 'org-delete-property-globally))
14519 ((equal c ?c)
14520 (call-interactively 'org-compute-property-at-point))
14521 (t (error "No such property action %c" c)))))
14523 (defun org-inc-effort ()
14524 "Increment the value of the effort property in the current entry."
14525 (interactive)
14526 (org-set-effort nil t))
14528 (defun org-set-effort (&optional value increment)
14529 "Set the effort property of the current entry.
14530 With numerical prefix arg, use the nth allowed value, 0 stands for the
14531 10th allowed value.
14533 When INCREMENT is non-nil, set the property to the next allowed value."
14534 (interactive "P")
14535 (if (equal value 0) (setq value 10))
14536 (let* ((completion-ignore-case t)
14537 (prop org-effort-property)
14538 (cur (org-entry-get nil prop))
14539 (allowed (org-property-get-allowed-values nil prop 'table))
14540 (existing (mapcar 'list (org-property-values prop)))
14542 (val (cond
14543 ((stringp value) value)
14544 ((and allowed (integerp value))
14545 (or (car (nth (1- value) allowed))
14546 (car (org-last allowed))))
14547 ((and allowed increment)
14548 (or (caadr (member (list cur) allowed))
14549 (error "Allowed effort values are not set")))
14550 (allowed
14551 (message "Select 1-9,0, [RET%s]: %s"
14552 (if cur (concat "=" cur) "")
14553 (mapconcat 'car allowed " "))
14554 (setq rpl (read-char-exclusive))
14555 (if (equal rpl ?\r)
14557 (setq rpl (- rpl ?0))
14558 (if (equal rpl 0) (setq rpl 10))
14559 (if (and (> rpl 0) (<= rpl (length allowed)))
14560 (car (nth (1- rpl) allowed))
14561 (org-completing-read "Effort: " allowed nil))))
14563 (let (org-completion-use-ido org-completion-use-iswitchb)
14564 (org-completing-read
14565 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14566 (concat "[" cur "]") "")
14567 ": ")
14568 existing nil nil "" nil cur))))))
14569 (unless (equal (org-entry-get nil prop) val)
14570 (org-entry-put nil prop val))
14571 (save-excursion
14572 (org-back-to-heading t)
14573 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14574 (message "%s is now %s" prop val)))
14576 (defun org-at-property-p ()
14577 "Is cursor inside a property drawer?"
14578 (save-excursion
14579 (beginning-of-line 1)
14580 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14581 (save-match-data ;; Used by calling procedures
14582 (let ((p (point))
14583 (range (unless (org-before-first-heading-p)
14584 (org-get-property-block))))
14585 (and range (<= (car range) p) (< p (cdr range))))))))
14587 (defun org-get-property-block (&optional beg end force)
14588 "Return the (beg . end) range of the body of the property drawer.
14589 BEG and END are the beginning and end of the current subtree, or of
14590 the part before the first headline. If they are not given, they will
14591 be found. If the drawer does not exist and FORCE is non-nil, create
14592 the drawer."
14593 (catch 'exit
14594 (save-excursion
14595 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14596 (progn (org-back-to-heading t) (point))))
14597 (end (or end (and (not (outline-next-heading)) (point-max))
14598 (point))))
14599 (goto-char beg)
14600 (if (re-search-forward org-property-start-re end t)
14601 (setq beg (1+ (match-end 0)))
14602 (if force
14603 (save-excursion
14604 (org-insert-property-drawer)
14605 (setq end (progn (outline-next-heading) (point))))
14606 (throw 'exit nil))
14607 (goto-char beg)
14608 (if (re-search-forward org-property-start-re end t)
14609 (setq beg (1+ (match-end 0)))))
14610 (if (re-search-forward org-property-end-re end t)
14611 (setq end (match-beginning 0))
14612 (or force (throw 'exit nil))
14613 (goto-char beg)
14614 (setq end beg)
14615 (org-indent-line)
14616 (insert ":END:\n"))
14617 (cons beg end)))))
14619 (defun org-entry-properties (&optional pom which specific)
14620 "Get all properties of the entry at point-or-marker POM.
14621 This includes the TODO keyword, the tags, time strings for deadline,
14622 scheduled, and clocking, and any additional properties defined in the
14623 entry. The return value is an alist, keys may occur multiple times
14624 if the property key was used several times.
14625 POM may also be nil, in which case the current entry is used.
14626 If WHICH is nil or `all', get all properties. If WHICH is
14627 `special' or `standard', only get that subclass. If WHICH
14628 is a string only get exactly this property. SPECIFIC can be a string, the
14629 specific property we are interested in. Specifying it can speed
14630 things up because then unnecessary parsing is avoided."
14631 (setq which (or which 'all))
14632 (org-with-point-at pom
14633 (let ((clockstr (substring org-clock-string 0 -1))
14634 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14635 (case-fold-search nil)
14636 beg end range props sum-props key key1 value string clocksum clocksumt)
14637 (save-excursion
14638 (when (condition-case nil
14639 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14640 (error nil))
14641 (setq beg (point))
14642 (setq sum-props (get-text-property (point) 'org-summaries))
14643 (setq clocksum (get-text-property (point) :org-clock-minutes)
14644 clocksumt (get-text-property (point) :org-clock-minutes-today))
14645 (outline-next-heading)
14646 (setq end (point))
14647 (when (memq which '(all special))
14648 ;; Get the special properties, like TODO and tags
14649 (goto-char beg)
14650 (when (and (or (not specific) (string= specific "TODO"))
14651 (looking-at org-todo-line-regexp) (match-end 2))
14652 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14653 (when (and (or (not specific) (string= specific "PRIORITY"))
14654 (looking-at org-priority-regexp))
14655 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14656 (when (or (not specific) (string= specific "FILE"))
14657 (push (cons "FILE" buffer-file-name) props))
14658 (when (and (or (not specific) (string= specific "TAGS"))
14659 (setq value (org-get-tags-string))
14660 (string-match "\\S-" value))
14661 (push (cons "TAGS" value) props))
14662 (when (and (or (not specific) (string= specific "ALLTAGS"))
14663 (setq value (org-get-tags-at)))
14664 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14665 ":"))
14666 props))
14667 (when (or (not specific) (string= specific "BLOCKED"))
14668 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14669 (when (or (not specific)
14670 (member specific
14671 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14672 "TIMESTAMP" "TIMESTAMP_IA")))
14673 (catch 'match
14674 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14675 (setq key (if (match-end 1)
14676 (substring (org-match-string-no-properties 1)
14677 0 -1))
14678 string (if (equal key clockstr)
14679 (org-trim
14680 (buffer-substring-no-properties
14681 (match-beginning 3) (goto-char
14682 (point-at-eol))))
14683 (substring (org-match-string-no-properties 3)
14684 1 -1)))
14685 ;; Get the correct property name from the key. This is
14686 ;; necessary if the user has configured time keywords.
14687 (setq key1 (concat key ":"))
14688 (cond
14689 ((not key)
14690 (setq key
14691 (if (= (char-after (match-beginning 3)) ?\[)
14692 "TIMESTAMP_IA" "TIMESTAMP")))
14693 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14694 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14695 ((equal key1 org-closed-string) (setq key "CLOSED"))
14696 ((equal key1 org-clock-string) (setq key "CLOCK")))
14697 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14698 (progn
14699 (push (cons key string) props)
14700 ;; no need to search further if match is found
14701 (throw 'match t))
14702 (when (or (equal key "CLOCK") (not (assoc key props)))
14703 (push (cons key string) props)))))))
14705 (when (memq which '(all standard))
14706 ;; Get the standard properties, like :PROP: ...
14707 (setq range (org-get-property-block beg end))
14708 (when range
14709 (goto-char (car range))
14710 (while (re-search-forward
14711 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14712 (cdr range) t)
14713 (setq key (org-match-string-no-properties 1)
14714 value (org-trim (or (org-match-string-no-properties 2) "")))
14715 (unless (member key excluded)
14716 (push (cons key (or value "")) props)))))
14717 (if clocksum
14718 (push (cons "CLOCKSUM"
14719 (org-columns-number-to-string (/ (float clocksum) 60.)
14720 'add_times))
14721 props))
14722 (if clocksumt
14723 (push (cons "CLOCKSUM_T"
14724 (org-columns-number-to-string (/ (float clocksumt) 60.)
14725 'add_times))
14726 props))
14727 (unless (assoc "CATEGORY" props)
14728 (push (cons "CATEGORY" (org-get-category)) props))
14729 (append sum-props (nreverse props)))))))
14731 (defun org-entry-get (pom property &optional inherit literal-nil)
14732 "Get value of PROPERTY for entry or content at point-or-marker POM.
14733 If INHERIT is non-nil and the entry does not have the property,
14734 then also check higher levels of the hierarchy.
14735 If INHERIT is the symbol `selective', use inheritance only if the setting
14736 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14737 If the property is present but empty, the return value is the empty string.
14738 If the property is not present at all, nil is returned.
14740 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14741 do not interpret it as the list atom nil. This is used for inheritance
14742 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14743 (org-with-point-at pom
14744 (if (and inherit (if (eq inherit 'selective)
14745 (org-property-inherit-p property)
14747 (org-entry-get-with-inheritance property literal-nil)
14748 (if (member property org-special-properties)
14749 ;; We need a special property. Use `org-entry-properties' to
14750 ;; retrieve it, but specify the wanted property
14751 (cdr (assoc property (org-entry-properties nil 'special property)))
14752 (let ((range (org-get-property-block)))
14753 (when (and range (not (eq (car range) (cdr range))))
14754 (let* ((props (list (or (assoc property org-file-properties)
14755 (assoc property org-global-properties)
14756 (assoc property org-global-properties-fixed))))
14757 (ap (lambda (key)
14758 (when (re-search-forward
14759 (org-re-property key) (cdr range) t)
14760 (setq props
14761 (org-update-property-plist
14763 (if (match-end 1)
14764 (org-match-string-no-properties 1) "")
14765 props)))))
14766 val)
14767 (goto-char (car range))
14768 (funcall ap property)
14769 (goto-char (car range))
14770 (while (funcall ap (concat property "+")))
14771 (setq val (cdr (assoc property props)))
14772 (when val (if literal-nil val (org-not-nil val))))))))))
14774 (defun org-property-or-variable-value (var &optional inherit)
14775 "Check if there is a property fixing the value of VAR.
14776 If yes, return this value. If not, return the current value of the variable."
14777 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14778 (if (and prop (stringp prop) (string-match "\\S-" prop))
14779 (read prop)
14780 (symbol-value var))))
14782 (defun org-entry-delete (pom property)
14783 "Delete the property PROPERTY from entry at point-or-marker POM."
14784 (org-with-point-at pom
14785 (if (member property org-special-properties)
14786 nil ; cannot delete these properties.
14787 (let ((range (org-get-property-block)))
14788 (if (and range
14789 (goto-char (car range))
14790 (re-search-forward
14791 (org-re-property property)
14792 (cdr range) t))
14793 (progn
14794 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14796 nil)))))
14798 ;; Multi-values properties are properties that contain multiple values
14799 ;; These values are assumed to be single words, separated by whitespace.
14800 (defun org-entry-add-to-multivalued-property (pom property value)
14801 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14802 (let* ((old (org-entry-get pom property))
14803 (values (and old (org-split-string old "[ \t]"))))
14804 (setq value (org-entry-protect-space value))
14805 (unless (member value values)
14806 (setq values (cons value values))
14807 (org-entry-put pom property
14808 (mapconcat 'identity values " ")))))
14810 (defun org-entry-remove-from-multivalued-property (pom property value)
14811 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14812 (let* ((old (org-entry-get pom property))
14813 (values (and old (org-split-string old "[ \t]"))))
14814 (setq value (org-entry-protect-space value))
14815 (when (member value values)
14816 (setq values (delete value values))
14817 (org-entry-put pom property
14818 (mapconcat 'identity values " ")))))
14820 (defun org-entry-member-in-multivalued-property (pom property value)
14821 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14822 (let* ((old (org-entry-get pom property))
14823 (values (and old (org-split-string old "[ \t]"))))
14824 (setq value (org-entry-protect-space value))
14825 (member value values)))
14827 (defun org-entry-get-multivalued-property (pom property)
14828 "Return a list of values in a multivalued property."
14829 (let* ((value (org-entry-get pom property))
14830 (values (and value (org-split-string value "[ \t]"))))
14831 (mapcar 'org-entry-restore-space values)))
14833 (defun org-entry-put-multivalued-property (pom property &rest values)
14834 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14835 VALUES should be a list of strings. Spaces will be protected."
14836 (org-entry-put pom property
14837 (mapconcat 'org-entry-protect-space values " "))
14838 (let* ((value (org-entry-get pom property))
14839 (values (and value (org-split-string value "[ \t]"))))
14840 (mapcar 'org-entry-restore-space values)))
14842 (defun org-entry-protect-space (s)
14843 "Protect spaces and newline in string S."
14844 (while (string-match " " s)
14845 (setq s (replace-match "%20" t t s)))
14846 (while (string-match "\n" s)
14847 (setq s (replace-match "%0A" t t s)))
14850 (defun org-entry-restore-space (s)
14851 "Restore spaces and newline in string S."
14852 (while (string-match "%20" s)
14853 (setq s (replace-match " " t t s)))
14854 (while (string-match "%0A" s)
14855 (setq s (replace-match "\n" t t s)))
14858 (defvar org-entry-property-inherited-from (make-marker)
14859 "Marker pointing to the entry from where a property was inherited.
14860 Each call to `org-entry-get-with-inheritance' will set this marker to the
14861 location of the entry where the inheritance search matched. If there was
14862 no match, the marker will point nowhere.
14863 Note that also `org-entry-get' calls this function, if the INHERIT flag
14864 is set.")
14866 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14867 "Get PROPERTY of entry or content at point, search higher levels if needed.
14868 The search will stop at the first ancestor which has the property defined.
14869 If the value found is \"nil\", return nil to show that the property
14870 should be considered as undefined (this is the meaning of nil here).
14871 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14872 (move-marker org-entry-property-inherited-from nil)
14873 (let (tmp)
14874 (save-excursion
14875 (save-restriction
14876 (widen)
14877 (catch 'ex
14878 (while t
14879 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14880 (or (ignore-errors (org-back-to-heading t))
14881 (goto-char (point-min)))
14882 (move-marker org-entry-property-inherited-from (point))
14883 (throw 'ex tmp))
14884 (or (ignore-errors (org-up-heading-safe))
14885 (throw 'ex nil))))))
14886 (setq tmp (or tmp
14887 (cdr (assoc property org-file-properties))
14888 (cdr (assoc property org-global-properties))
14889 (cdr (assoc property org-global-properties-fixed))))
14890 (if literal-nil tmp (org-not-nil tmp))))
14892 (defvar org-property-changed-functions nil
14893 "Hook called when the value of a property has changed.
14894 Each hook function should accept two arguments, the name of the property
14895 and the new value.")
14897 (defun org-entry-put (pom property value)
14898 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14899 (org-with-point-at pom
14900 (org-back-to-heading t)
14901 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14902 range)
14903 (cond
14904 ((equal property "TODO")
14905 (when (and (stringp value) (string-match "\\S-" value)
14906 (not (member value org-todo-keywords-1)))
14907 (error "\"%s\" is not a valid TODO state" value))
14908 (if (or (not value)
14909 (not (string-match "\\S-" value)))
14910 (setq value 'none))
14911 (org-todo value)
14912 (org-set-tags nil 'align))
14913 ((equal property "PRIORITY")
14914 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14915 (string-to-char value) ?\ ))
14916 (org-set-tags nil 'align))
14917 ((equal property "CLOCKSUM")
14918 (if (not (re-search-forward
14919 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14920 (error "Cannot find a clock log")
14921 (goto-char (- (match-end 1) 2))
14922 (cond
14923 ((eq value 'earlier) (org-timestamp-down))
14924 ((eq value 'later) (org-timestamp-up)))
14925 (org-clock-sum-current-item)))
14926 ((equal property "SCHEDULED")
14927 (if (re-search-forward org-scheduled-time-regexp end t)
14928 (cond
14929 ((eq value 'earlier) (org-timestamp-change -1 'day))
14930 ((eq value 'later) (org-timestamp-change 1 'day))
14931 (t (call-interactively 'org-schedule)))
14932 (call-interactively 'org-schedule)))
14933 ((equal property "DEADLINE")
14934 (if (re-search-forward org-deadline-time-regexp end t)
14935 (cond
14936 ((eq value 'earlier) (org-timestamp-change -1 'day))
14937 ((eq value 'later) (org-timestamp-change 1 'day))
14938 (t (call-interactively 'org-deadline)))
14939 (call-interactively 'org-deadline)))
14940 ((member property org-special-properties)
14941 (error "The %s property can not yet be set with `org-entry-put'"
14942 property))
14943 (t ; a non-special property
14944 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14945 (setq range (org-get-property-block beg end 'force))
14946 (goto-char (car range))
14947 (if (re-search-forward
14948 (org-re-property-keyword property) (cdr range) t)
14949 (progn
14950 (delete-region (match-beginning 0) (match-end 0))
14951 (goto-char (match-beginning 0)))
14952 (goto-char (cdr range))
14953 (insert "\n")
14954 (backward-char 1)
14955 (org-indent-line))
14956 (insert ":" property ":")
14957 (and value (insert " " value))
14958 (org-indent-line)))))
14959 (run-hook-with-args 'org-property-changed-functions property value)))
14961 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14962 "Get all property keys in the current buffer.
14963 With INCLUDE-SPECIALS, also list the special properties that reflect things
14964 like tags and TODO state.
14965 With INCLUDE-DEFAULTS, also include properties that has special meaning
14966 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14967 and others.
14968 With INCLUDE-COLUMNS, also include property names given in COLUMN
14969 formats in the current buffer."
14970 (let (rtn range cfmt s p)
14971 (save-excursion
14972 (save-restriction
14973 (widen)
14974 (goto-char (point-min))
14975 (while (re-search-forward org-property-start-re nil t)
14976 (setq range (org-get-property-block))
14977 (goto-char (car range))
14978 (while (re-search-forward
14979 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14980 (cdr range) t)
14981 (add-to-list 'rtn (org-match-string-no-properties 1)))
14982 (outline-next-heading))))
14984 (when include-specials
14985 (setq rtn (append org-special-properties rtn)))
14987 (when include-defaults
14988 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14989 (add-to-list 'rtn org-effort-property))
14991 (when include-columns
14992 (save-excursion
14993 (save-restriction
14994 (widen)
14995 (goto-char (point-min))
14996 (while (re-search-forward
14997 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14998 nil t)
14999 (setq cfmt (match-string 2) s 0)
15000 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15001 cfmt s)
15002 (setq s (match-end 0)
15003 p (match-string 1 cfmt))
15004 (unless (or (equal p "ITEM")
15005 (member p org-special-properties))
15006 (add-to-list 'rtn (match-string 1 cfmt))))))))
15008 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15010 (defun org-property-values (key)
15011 "Return a list of all values of property KEY in the current buffer."
15012 (save-excursion
15013 (save-restriction
15014 (widen)
15015 (goto-char (point-min))
15016 (let ((re (org-re-property key))
15017 values)
15018 (while (re-search-forward re nil t)
15019 (add-to-list 'values (org-trim (match-string 1))))
15020 (delete "" values)))))
15022 (defun org-insert-property-drawer ()
15023 "Insert a property drawer into the current entry."
15024 (org-back-to-heading t)
15025 (looking-at org-outline-regexp)
15026 (let ((indent (if org-adapt-indentation
15027 (- (match-end 0) (match-beginning 0))
15029 (beg (point))
15030 (re (concat "^[ \t]*" org-keyword-time-regexp))
15031 end hiddenp)
15032 (outline-next-heading)
15033 (setq end (point))
15034 (goto-char beg)
15035 (while (re-search-forward re end t))
15036 (setq hiddenp (outline-invisible-p))
15037 (end-of-line 1)
15038 (and (equal (char-after) ?\n) (forward-char 1))
15039 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15040 (if (member (match-string 1) '("CLOCK:" ":END:"))
15041 ;; just skip this line
15042 (beginning-of-line 2)
15043 ;; Drawer start, find the end
15044 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15045 (beginning-of-line 1)))
15046 (org-skip-over-state-notes)
15047 (skip-chars-backward " \t\n\r")
15048 (if (eq (char-before) ?*) (forward-char 1))
15049 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15050 (beginning-of-line 0)
15051 (org-indent-to-column indent)
15052 (beginning-of-line 2)
15053 (org-indent-to-column indent)
15054 (beginning-of-line 0)
15055 (if hiddenp
15056 (save-excursion
15057 (org-back-to-heading t)
15058 (hide-entry))
15059 (org-flag-drawer t))))
15061 (defun org-insert-drawer (&optional arg drawer)
15062 "Insert a drawer at point.
15064 Optional argument DRAWER, when non-nil, is a string representing
15065 drawer's name. Otherwise, the user is prompted for a name.
15067 If a region is active, insert the drawer around that region
15068 instead.
15070 Point is left between drawer's boundaries."
15071 (interactive "P")
15072 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15073 "LOGBOOK"))
15074 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15075 ;; internally by Org. They are meant to be inserted
15076 ;; automatically.
15077 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15078 ;; Remove system drawers from list. Note: For some reason,
15079 ;; `org-completing-read' ignores the predicate while
15080 ;; `completing-read' handles it fine.
15081 (drawer (if arg "PROPERTIES"
15082 (or drawer
15083 (completing-read
15084 "Drawer: " org-drawers
15085 (lambda (d) (not (member d system-drawers))))))))
15086 (cond
15087 ;; With C-u, fall back on `org-insert-property-drawer'
15088 (arg (org-insert-property-drawer))
15089 ;; With an active region, insert a drawer at point.
15090 ((not (org-region-active-p))
15091 (progn
15092 (unless (bolp) (insert "\n"))
15093 (insert (format ":%s:\n\n:END:\n" drawer))
15094 (forward-line -2)))
15095 ;; Otherwise, insert the drawer at point
15097 (let ((rbeg (region-beginning))
15098 (rend (copy-marker (region-end))))
15099 (unwind-protect
15100 (progn
15101 (goto-char rbeg)
15102 (beginning-of-line)
15103 (when (save-excursion
15104 (re-search-forward org-outline-regexp-bol rend t))
15105 (error "Drawers cannot contain headlines"))
15106 ;; Position point at the beginning of the first
15107 ;; non-blank line in region. Insert drawer's opening
15108 ;; there, then indent it.
15109 (org-skip-whitespace)
15110 (beginning-of-line)
15111 (insert ":" drawer ":\n")
15112 (forward-line -1)
15113 (indent-for-tab-command)
15114 ;; Move point to the beginning of the first blank line
15115 ;; after the last non-blank line in region. Insert
15116 ;; drawer's closing, then indent it.
15117 (goto-char rend)
15118 (skip-chars-backward " \r\t\n")
15119 (insert "\n:END:")
15120 (deactivate-mark t)
15121 (indent-for-tab-command)
15122 (unless (eolp) (insert "\n")))
15123 ;; Clear marker, whatever the outcome of insertion is.
15124 (set-marker rend nil)))))))
15126 (defvar org-property-set-functions-alist nil
15127 "Property set function alist.
15128 Each entry should have the following format:
15130 (PROPERTY . READ-FUNCTION)
15132 The read function will be called with the same argument as
15133 `org-completing-read'.")
15135 (defun org-set-property-function (property)
15136 "Get the function that should be used to set PROPERTY.
15137 This is computed according to `org-property-set-functions-alist'."
15138 (or (cdr (assoc property org-property-set-functions-alist))
15139 'org-completing-read))
15141 (defun org-read-property-value (property)
15142 "Read PROPERTY value from user."
15143 (let* ((completion-ignore-case t)
15144 (allowed (org-property-get-allowed-values nil property 'table))
15145 (cur (org-entry-get nil property))
15146 (prompt (concat property " value"
15147 (if (and cur (string-match "\\S-" cur))
15148 (concat " [" cur "]") "") ": "))
15149 (set-function (org-set-property-function property))
15150 (val (if allowed
15151 (funcall set-function prompt allowed nil
15152 (not (get-text-property 0 'org-unrestricted
15153 (caar allowed))))
15154 (let (org-completion-use-ido org-completion-use-iswitchb)
15155 (funcall set-function prompt
15156 (mapcar 'list (org-property-values property))
15157 nil nil "" nil cur)))))
15158 (if (equal val "")
15160 val)))
15162 (defvar org-last-set-property nil)
15163 (defvar org-last-set-property-value nil)
15164 (defun org-read-property-name ()
15165 "Read a property name."
15166 (let* ((completion-ignore-case t)
15167 (keys (org-buffer-property-keys nil t t))
15168 (default-prop (or (save-excursion
15169 (save-match-data
15170 (beginning-of-line)
15171 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15172 (null (string= (match-string 1) "END"))
15173 (match-string 1))))
15174 org-last-set-property))
15175 (property (org-icompleting-read
15176 (concat "Property"
15177 (if default-prop (concat " [" default-prop "]") "")
15178 ": ")
15179 (mapcar 'list keys)
15180 nil nil nil nil
15181 default-prop)))
15182 (if (member property keys)
15183 property
15184 (or (cdr (assoc (downcase property)
15185 (mapcar (lambda (x) (cons (downcase x) x))
15186 keys)))
15187 property))))
15189 (defun org-set-property-and-value (use-last)
15190 "Allow to set [PROPERTY]: [value] direction from prompt.
15191 When use-default, don't even ask, just use the last
15192 \"[PROPERTY]: [value]\" string from the history."
15193 (interactive "P")
15194 (let* ((completion-ignore-case t)
15195 (pv (or (and use-last org-last-set-property-value)
15196 (org-completing-read
15197 "Enter a \"[Property]: [value]\" pair: "
15198 nil nil nil nil nil
15199 org-last-set-property-value)))
15200 prop val)
15201 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15202 (setq prop (match-string 1 pv)
15203 val (match-string 2 pv))
15204 (org-set-property prop val))))
15206 (defun org-set-property (property value)
15207 "In the current entry, set PROPERTY to VALUE.
15208 When called interactively, this will prompt for a property name, offering
15209 completion on existing and default properties. And then it will prompt
15210 for a value, offering completion either on allowed values (via an inherited
15211 xxx_ALL property) or on existing values in other instances of this property
15212 in the current file."
15213 (interactive (list nil nil))
15214 (let* ((property (or property (org-read-property-name)))
15215 (value (or value (org-read-property-value property)))
15216 (fn (cdr (assoc property org-properties-postprocess-alist))))
15217 (setq org-last-set-property property)
15218 (setq org-last-set-property-value (concat property ": " value))
15219 ;; Possibly postprocess the inserted value:
15220 (when fn (setq value (funcall fn value)))
15221 (unless (equal (org-entry-get nil property) value)
15222 (org-entry-put nil property value))))
15224 (defun org-delete-property (property)
15225 "In the current entry, delete PROPERTY."
15226 (interactive
15227 (let* ((completion-ignore-case t)
15228 (prop (org-icompleting-read "Property: "
15229 (org-entry-properties nil 'standard))))
15230 (list prop)))
15231 (message "Property %s %s" property
15232 (if (org-entry-delete nil property)
15233 "deleted"
15234 "was not present in the entry")))
15236 (defun org-delete-property-globally (property)
15237 "Remove PROPERTY globally, from all entries."
15238 (interactive
15239 (let* ((completion-ignore-case t)
15240 (prop (org-icompleting-read
15241 "Globally remove property: "
15242 (mapcar 'list (org-buffer-property-keys)))))
15243 (list prop)))
15244 (save-excursion
15245 (save-restriction
15246 (widen)
15247 (goto-char (point-min))
15248 (let ((cnt 0))
15249 (while (re-search-forward
15250 (org-re-property property)
15251 nil t)
15252 (setq cnt (1+ cnt))
15253 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15254 (message "Property \"%s\" removed from %d entries" property cnt)))))
15256 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15258 (defun org-compute-property-at-point ()
15259 "Compute the property at point.
15260 This looks for an enclosing column format, extracts the operator and
15261 then applies it to the property in the column format's scope."
15262 (interactive)
15263 (unless (org-at-property-p)
15264 (error "Not at a property"))
15265 (let ((prop (org-match-string-no-properties 2)))
15266 (org-columns-get-format-and-top-level)
15267 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15268 (error "No operator defined for property %s" prop))
15269 (org-columns-compute prop)))
15271 (defvar org-property-allowed-value-functions nil
15272 "Hook for functions supplying allowed values for a specific property.
15273 The functions must take a single argument, the name of the property, and
15274 return a flat list of allowed values. If \":ETC\" is one of
15275 the values, this means that these values are intended as defaults for
15276 completion, but that other values should be allowed too.
15277 The functions must return nil if they are not responsible for this
15278 property.")
15280 (defun org-property-get-allowed-values (pom property &optional table)
15281 "Get allowed values for the property PROPERTY.
15282 When TABLE is non-nil, return an alist that can directly be used for
15283 completion."
15284 (let (vals)
15285 (cond
15286 ((equal property "TODO")
15287 (setq vals (org-with-point-at pom
15288 (append org-todo-keywords-1 '("")))))
15289 ((equal property "PRIORITY")
15290 (let ((n org-lowest-priority))
15291 (while (>= n org-highest-priority)
15292 (push (char-to-string n) vals)
15293 (setq n (1- n)))))
15294 ((member property org-special-properties))
15295 ((setq vals (run-hook-with-args-until-success
15296 'org-property-allowed-value-functions property)))
15298 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15299 (when (and vals (string-match "\\S-" vals))
15300 (setq vals (car (read-from-string (concat "(" vals ")"))))
15301 (setq vals (mapcar (lambda (x)
15302 (cond ((stringp x) x)
15303 ((numberp x) (number-to-string x))
15304 ((symbolp x) (symbol-name x))
15305 (t "???")))
15306 vals)))))
15307 (when (member ":ETC" vals)
15308 (setq vals (remove ":ETC" vals))
15309 (org-add-props (car vals) '(org-unrestricted t)))
15310 (if table (mapcar 'list vals) vals)))
15312 (defun org-property-previous-allowed-value (&optional previous)
15313 "Switch to the next allowed value for this property."
15314 (interactive)
15315 (org-property-next-allowed-value t))
15317 (defun org-property-next-allowed-value (&optional previous)
15318 "Switch to the next allowed value for this property."
15319 (interactive)
15320 (unless (org-at-property-p)
15321 (error "Not at a property"))
15322 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15323 (key (match-string 2))
15324 (value (match-string 3))
15325 (allowed (or (org-property-get-allowed-values (point) key)
15326 (and (member value '("[ ]" "[-]" "[X]"))
15327 '("[ ]" "[X]"))))
15328 nval)
15329 (unless allowed
15330 (error "Allowed values for this property have not been defined"))
15331 (if previous (setq allowed (reverse allowed)))
15332 (if (member value allowed)
15333 (setq nval (car (cdr (member value allowed)))))
15334 (setq nval (or nval (car allowed)))
15335 (if (equal nval value)
15336 (error "Only one allowed value for this property"))
15337 (org-at-property-p)
15338 (replace-match (concat " :" key ": " nval) t t)
15339 (org-indent-line)
15340 (beginning-of-line 1)
15341 (skip-chars-forward " \t")
15342 (when (equal prop org-effort-property)
15343 (save-excursion
15344 (org-back-to-heading t)
15345 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15346 (run-hook-with-args 'org-property-changed-functions key nval)))
15348 (defun org-find-olp (path &optional this-buffer)
15349 "Return a marker pointing to the entry at outline path OLP.
15350 If anything goes wrong, throw an error.
15351 You can wrap this call to catch the error like this:
15353 (condition-case msg
15354 (org-mobile-locate-entry (match-string 4))
15355 (error (nth 1 msg)))
15357 The return value will then be either a string with the error message,
15358 or a marker if everything is OK.
15360 If THIS-BUFFER is set, the outline path does not contain a file,
15361 only headings."
15362 (let* ((file (if this-buffer buffer-file-name (pop path)))
15363 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15364 (level 1)
15365 (lmin 1)
15366 (lmax 1)
15367 limit re end found pos heading cnt flevel)
15368 (unless buffer (error "File not found :%s" file))
15369 (with-current-buffer buffer
15370 (save-excursion
15371 (save-restriction
15372 (widen)
15373 (setq limit (point-max))
15374 (goto-char (point-min))
15375 (while (setq heading (pop path))
15376 (setq re (format org-complex-heading-regexp-format
15377 (regexp-quote heading)))
15378 (setq cnt 0 pos (point))
15379 (while (re-search-forward re end t)
15380 (setq level (- (match-end 1) (match-beginning 1)))
15381 (if (and (>= level lmin) (<= level lmax))
15382 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15383 (when (= cnt 0) (error "Heading not found on level %d: %s"
15384 lmax heading))
15385 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15386 lmax heading))
15387 (goto-char found)
15388 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15389 (setq end (save-excursion (org-end-of-subtree t t))))
15390 (when (org-at-heading-p)
15391 (point-marker)))))))
15393 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15394 "Find node HEADING in BUFFER.
15395 Return a marker to the heading if it was found, or nil if not.
15396 If POS-ONLY is set, return just the position instead of a marker.
15398 The heading text must match exact, but it may have a TODO keyword,
15399 a priority cookie and tags in the standard locations."
15400 (with-current-buffer (or buffer (current-buffer))
15401 (save-excursion
15402 (save-restriction
15403 (widen)
15404 (goto-char (point-min))
15405 (let (case-fold-search)
15406 (if (re-search-forward
15407 (format org-complex-heading-regexp-format
15408 (regexp-quote heading)) nil t)
15409 (if pos-only
15410 (match-beginning 0)
15411 (move-marker (make-marker) (match-beginning 0)))))))))
15413 (defun org-find-exact-heading-in-directory (heading &optional dir)
15414 "Find Org node headline HEADING in all .org files in directory DIR.
15415 When the target headline is found, return a marker to this location."
15416 (let ((files (directory-files (or dir default-directory)
15417 nil "\\`[^.#].*\\.org\\'"))
15418 file visiting m buffer)
15419 (catch 'found
15420 (while (setq file (pop files))
15421 (message "trying %s" file)
15422 (setq visiting (org-find-base-buffer-visiting file))
15423 (setq buffer (or visiting (find-file-noselect file)))
15424 (setq m (org-find-exact-headline-in-buffer
15425 heading buffer))
15426 (when (and (not m) (not visiting)) (kill-buffer buffer))
15427 (and m (throw 'found m))))))
15429 (defun org-find-entry-with-id (ident)
15430 "Locate the entry that contains the ID property with exact value IDENT.
15431 IDENT can be a string, a symbol or a number, this function will search for
15432 the string representation of it.
15433 Return the position where this entry starts, or nil if there is no such entry."
15434 (interactive "sID: ")
15435 (let ((id (cond
15436 ((stringp ident) ident)
15437 ((symbol-name ident) (symbol-name ident))
15438 ((numberp ident) (number-to-string ident))
15439 (t (error "IDENT %s must be a string, symbol or number" ident))))
15440 (case-fold-search nil))
15441 (save-excursion
15442 (save-restriction
15443 (widen)
15444 (goto-char (point-min))
15445 (when (re-search-forward
15446 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15447 nil t)
15448 (org-back-to-heading t)
15449 (point))))))
15451 ;;;; Timestamps
15453 (defvar org-last-changed-timestamp nil)
15454 (defvar org-last-inserted-timestamp nil
15455 "The last time stamp inserted with `org-insert-time-stamp'.")
15456 (defvar org-time-was-given) ; dynamically scoped parameter
15457 (defvar org-end-time-was-given) ; dynamically scoped parameter
15458 (defvar org-ts-what) ; dynamically scoped parameter
15460 (defun org-time-stamp (arg &optional inactive)
15461 "Prompt for a date/time and insert a time stamp.
15462 If the user specifies a time like HH:MM or if this command is
15463 called with at least one prefix argument, the time stamp contains
15464 the date and the time. Otherwise, only the date is be included.
15466 All parts of a date not specified by the user is filled in from
15467 the current date/time. So if you just press return without
15468 typing anything, the time stamp will represent the current
15469 date/time.
15471 If there is already a timestamp at the cursor, it will be
15472 modified.
15474 With two universal prefix arguments, insert an active timestamp
15475 with the current time without prompting the user."
15476 (interactive "P")
15477 (let* ((ts nil)
15478 (default-time
15479 ;; Default time is either today, or, when entering a range,
15480 ;; the range start.
15481 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15482 (save-excursion
15483 (re-search-backward
15484 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15485 (- (point) 20) t)))
15486 (apply 'encode-time (org-parse-time-string (match-string 1)))
15487 (current-time)))
15488 (default-input (and ts (org-get-compact-tod ts)))
15489 (repeater (save-excursion
15490 (save-match-data
15491 (beginning-of-line)
15492 (when (re-search-forward
15493 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15494 (save-excursion (progn (end-of-line) (point))) t)
15495 (match-string 0)))))
15496 org-time-was-given org-end-time-was-given time)
15497 (cond
15498 ((and (org-at-timestamp-p t)
15499 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15500 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15501 (insert "--")
15502 (setq time (let ((this-command this-command))
15503 (org-read-date arg 'totime nil nil
15504 default-time default-input inactive)))
15505 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15506 ((org-at-timestamp-p t)
15507 (setq time (let ((this-command this-command))
15508 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15509 (when (org-at-timestamp-p t) ; just to get the match data
15510 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15511 (replace-match "")
15512 (setq org-last-changed-timestamp
15513 (org-insert-time-stamp
15514 time (or org-time-was-given arg)
15515 inactive nil nil (list org-end-time-was-given)))
15516 (when repeater (goto-char (1- (point))) (insert " " repeater)
15517 (setq org-last-changed-timestamp
15518 (concat (substring org-last-inserted-timestamp 0 -1)
15519 " " repeater ">"))))
15520 (message "Timestamp updated"))
15521 ((equal arg '(16))
15522 (org-insert-time-stamp (current-time) t))
15524 (setq time (let ((this-command this-command))
15525 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15526 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15527 nil nil (list org-end-time-was-given))))))
15529 ;; FIXME: can we use this for something else, like computing time differences?
15530 (defun org-get-compact-tod (s)
15531 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15532 (let* ((t1 (match-string 1 s))
15533 (h1 (string-to-number (match-string 2 s)))
15534 (m1 (string-to-number (match-string 3 s)))
15535 (t2 (and (match-end 4) (match-string 5 s)))
15536 (h2 (and t2 (string-to-number (match-string 6 s))))
15537 (m2 (and t2 (string-to-number (match-string 7 s))))
15538 dh dm)
15539 (if (not t2)
15541 (setq dh (- h2 h1) dm (- m2 m1))
15542 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15543 (concat t1 "+" (number-to-string dh)
15544 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15546 (defun org-time-stamp-inactive (&optional arg)
15547 "Insert an inactive time stamp.
15548 An inactive time stamp is enclosed in square brackets instead of angle
15549 brackets. It is inactive in the sense that it does not trigger agenda entries,
15550 does not link to the calendar and cannot be changed with the S-cursor keys.
15551 So these are more for recording a certain time/date."
15552 (interactive "P")
15553 (org-time-stamp arg 'inactive))
15555 (defvar org-date-ovl (make-overlay 1 1))
15556 (overlay-put org-date-ovl 'face 'org-date-selected)
15557 (org-detach-overlay org-date-ovl)
15559 (defvar org-ans1) ; dynamically scoped parameter
15560 (defvar org-ans2) ; dynamically scoped parameter
15562 (defvar org-plain-time-of-day-regexp) ; defined below
15564 (defvar org-overriding-default-time nil) ; dynamically scoped
15565 (defvar org-read-date-overlay nil)
15566 (defvar org-dcst nil) ; dynamically scoped
15567 (defvar org-read-date-history nil)
15568 (defvar org-read-date-final-answer nil)
15569 (defvar org-read-date-analyze-futurep nil)
15570 (defvar org-read-date-analyze-forced-year nil)
15571 (defvar org-read-date-inactive)
15573 (defun org-read-date (&optional org-with-time to-time from-string prompt
15574 default-time default-input inactive)
15575 "Read a date, possibly a time, and make things smooth for the user.
15576 The prompt will suggest to enter an ISO date, but you can also enter anything
15577 which will at least partially be understood by `parse-time-string'.
15578 Unrecognized parts of the date will default to the current day, month, year,
15579 hour and minute. If this command is called to replace a timestamp at point,
15580 or to enter the second timestamp of a range, the default time is taken
15581 from the existing stamp. Furthermore, the command prefers the future,
15582 so if you are giving a date where the year is not given, and the day-month
15583 combination is already past in the current year, it will assume you
15584 mean next year. For details, see the manual. A few examples:
15586 3-2-5 --> 2003-02-05
15587 feb 15 --> currentyear-02-15
15588 2/15 --> currentyear-02-15
15589 sep 12 9 --> 2009-09-12
15590 12:45 --> today 12:45
15591 22 sept 0:34 --> currentyear-09-22 0:34
15592 12 --> currentyear-currentmonth-12
15593 Fri --> nearest Friday (today or later)
15594 etc.
15596 Furthermore you can specify a relative date by giving, as the *first* thing
15597 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15598 change in days weeks, months, years.
15599 With a single plus or minus, the date is relative to today. With a double
15600 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15601 +4d --> four days from today
15602 +4 --> same as above
15603 +2w --> two weeks from today
15604 ++5 --> five days from default date
15606 The function understands only English month and weekday abbreviations.
15608 While prompting, a calendar is popped up - you can also select the
15609 date with the mouse (button 1). The calendar shows a period of three
15610 months. To scroll it to other months, use the keys `>' and `<'.
15611 If you don't like the calendar, turn it off with
15612 \(setq org-read-date-popup-calendar nil)
15614 With optional argument TO-TIME, the date will immediately be converted
15615 to an internal time.
15616 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15617 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15618 still enter a time, and this function will inform the calling routine
15619 about this change. The calling routine may then choose to change the
15620 format used to insert the time stamp into the buffer to include the time.
15621 With optional argument FROM-STRING, read from this string instead from
15622 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15623 the time/date that is used for everything that is not specified by the
15624 user."
15625 (require 'parse-time)
15626 (let* ((org-time-stamp-rounding-minutes
15627 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15628 (org-dcst org-display-custom-times)
15629 (ct (org-current-time))
15630 (org-def (or org-overriding-default-time default-time ct))
15631 (org-defdecode (decode-time org-def))
15632 (dummy (progn
15633 (when (< (nth 2 org-defdecode) org-extend-today-until)
15634 (setcar (nthcdr 2 org-defdecode) -1)
15635 (setcar (nthcdr 1 org-defdecode) 59)
15636 (setq org-def (apply 'encode-time org-defdecode)
15637 org-defdecode (decode-time org-def)))))
15638 (mouse-autoselect-window nil) ; Don't let the mouse jump
15639 (calendar-frame-setup nil)
15640 (calendar-setup nil)
15641 (calendar-move-hook nil)
15642 (calendar-view-diary-initially-flag nil)
15643 (calendar-view-holidays-initially-flag nil)
15644 (timestr (format-time-string
15645 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15646 (prompt (concat (if prompt (concat prompt " ") "")
15647 (format "Date+time [%s]: " timestr)))
15648 ans (org-ans0 "") org-ans1 org-ans2 final)
15650 (cond
15651 (from-string (setq ans from-string))
15652 (org-read-date-popup-calendar
15653 (save-excursion
15654 (save-window-excursion
15655 (calendar)
15656 (org-eval-in-calendar '(setq cursor-type nil) t)
15657 (unwind-protect
15658 (progn
15659 (calendar-forward-day (- (time-to-days org-def)
15660 (calendar-absolute-from-gregorian
15661 (calendar-current-date))))
15662 (org-eval-in-calendar nil t)
15663 (let* ((old-map (current-local-map))
15664 (map (copy-keymap calendar-mode-map))
15665 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15666 (org-defkey map (kbd "RET") 'org-calendar-select)
15667 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15668 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15669 (org-defkey minibuffer-local-map [(meta shift left)]
15670 (lambda () (interactive)
15671 (org-eval-in-calendar '(calendar-backward-month 1))))
15672 (org-defkey minibuffer-local-map [(meta shift right)]
15673 (lambda () (interactive)
15674 (org-eval-in-calendar '(calendar-forward-month 1))))
15675 (org-defkey minibuffer-local-map [(meta shift up)]
15676 (lambda () (interactive)
15677 (org-eval-in-calendar '(calendar-backward-year 1))))
15678 (org-defkey minibuffer-local-map [(meta shift down)]
15679 (lambda () (interactive)
15680 (org-eval-in-calendar '(calendar-forward-year 1))))
15681 (org-defkey minibuffer-local-map [?\e (shift left)]
15682 (lambda () (interactive)
15683 (org-eval-in-calendar '(calendar-backward-month 1))))
15684 (org-defkey minibuffer-local-map [?\e (shift right)]
15685 (lambda () (interactive)
15686 (org-eval-in-calendar '(calendar-forward-month 1))))
15687 (org-defkey minibuffer-local-map [?\e (shift up)]
15688 (lambda () (interactive)
15689 (org-eval-in-calendar '(calendar-backward-year 1))))
15690 (org-defkey minibuffer-local-map [?\e (shift down)]
15691 (lambda () (interactive)
15692 (org-eval-in-calendar '(calendar-forward-year 1))))
15693 (org-defkey minibuffer-local-map [(shift up)]
15694 (lambda () (interactive)
15695 (org-eval-in-calendar '(calendar-backward-week 1))))
15696 (org-defkey minibuffer-local-map [(shift down)]
15697 (lambda () (interactive)
15698 (org-eval-in-calendar '(calendar-forward-week 1))))
15699 (org-defkey minibuffer-local-map [(shift left)]
15700 (lambda () (interactive)
15701 (org-eval-in-calendar '(calendar-backward-day 1))))
15702 (org-defkey minibuffer-local-map [(shift right)]
15703 (lambda () (interactive)
15704 (org-eval-in-calendar '(calendar-forward-day 1))))
15705 (org-defkey minibuffer-local-map "?"
15706 (lambda () (interactive)
15707 (org-eval-in-calendar '(diary-view-entries))
15708 (message "")))
15709 (org-defkey minibuffer-local-map ">"
15710 (lambda () (interactive)
15711 (org-eval-in-calendar '(scroll-calendar-left 1))))
15712 (org-defkey minibuffer-local-map "<"
15713 (lambda () (interactive)
15714 (org-eval-in-calendar '(scroll-calendar-right 1))))
15715 (org-defkey minibuffer-local-map "\C-v"
15716 (lambda () (interactive)
15717 (org-eval-in-calendar
15718 '(calendar-scroll-left-three-months 1))))
15719 (org-defkey minibuffer-local-map "\M-v"
15720 (lambda () (interactive)
15721 (org-eval-in-calendar
15722 '(calendar-scroll-right-three-months 1))))
15723 (run-hooks 'org-read-date-minibuffer-setup-hook)
15724 (unwind-protect
15725 (progn
15726 (use-local-map map)
15727 (setq org-read-date-inactive inactive)
15728 (add-hook 'post-command-hook 'org-read-date-display)
15729 (setq org-ans0 (read-string prompt default-input
15730 'org-read-date-history nil))
15731 ;; org-ans0: from prompt
15732 ;; org-ans1: from mouse click
15733 ;; org-ans2: from calendar motion
15734 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15735 (remove-hook 'post-command-hook 'org-read-date-display)
15736 (use-local-map old-map)
15737 (when org-read-date-overlay
15738 (delete-overlay org-read-date-overlay)
15739 (setq org-read-date-overlay nil)))))
15740 (bury-buffer "*Calendar*")))))
15742 (t ; Naked prompt only
15743 (unwind-protect
15744 (setq ans (read-string prompt default-input
15745 'org-read-date-history timestr))
15746 (when org-read-date-overlay
15747 (delete-overlay org-read-date-overlay)
15748 (setq org-read-date-overlay nil)))))
15750 (setq final (org-read-date-analyze ans org-def org-defdecode))
15752 (when org-read-date-analyze-forced-year
15753 (message "Year was forced into %s"
15754 (if org-read-date-force-compatible-dates
15755 "compatible range (1970-2037)"
15756 "range representable on this machine"))
15757 (ding))
15759 ;; One round trip to get rid of 34th of August and stuff like that....
15760 (setq final (decode-time (apply 'encode-time final)))
15762 (setq org-read-date-final-answer ans)
15764 (if to-time
15765 (apply 'encode-time final)
15766 (if (and (boundp 'org-time-was-given) org-time-was-given)
15767 (format "%04d-%02d-%02d %02d:%02d"
15768 (nth 5 final) (nth 4 final) (nth 3 final)
15769 (nth 2 final) (nth 1 final))
15770 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15772 (defvar org-def)
15773 (defvar org-defdecode)
15774 (defvar org-with-time)
15775 (defun org-read-date-display ()
15776 "Display the current date prompt interpretation in the minibuffer."
15777 (when org-read-date-display-live
15778 (when org-read-date-overlay
15779 (delete-overlay org-read-date-overlay))
15780 (when (minibufferp (current-buffer))
15781 (save-excursion
15782 (end-of-line 1)
15783 (while (not (equal (buffer-substring
15784 (max (point-min) (- (point) 4)) (point))
15785 " "))
15786 (insert " ")))
15787 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15788 " " (or org-ans1 org-ans2)))
15789 (org-end-time-was-given nil)
15790 (f (org-read-date-analyze ans org-def org-defdecode))
15791 (fmts (if org-dcst
15792 org-time-stamp-custom-formats
15793 org-time-stamp-formats))
15794 (fmt (if (or org-with-time
15795 (and (boundp 'org-time-was-given) org-time-was-given))
15796 (cdr fmts)
15797 (car fmts)))
15798 (txt (format-time-string fmt (apply 'encode-time f)))
15799 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15800 (txt (concat "=> " txt)))
15801 (when (and org-end-time-was-given
15802 (string-match org-plain-time-of-day-regexp txt))
15803 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15804 org-end-time-was-given
15805 (substring txt (match-end 0)))))
15806 (when org-read-date-analyze-futurep
15807 (setq txt (concat txt " (=>F)")))
15808 (setq org-read-date-overlay
15809 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15810 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15812 (defun org-read-date-analyze (ans org-def org-defdecode)
15813 "Analyze the combined answer of the date prompt."
15814 ;; FIXME: cleanup and comment
15815 (let ((nowdecode (decode-time (current-time)))
15816 delta deltan deltaw deltadef year month day
15817 hour minute second wday pm h2 m2 tl wday1
15818 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15819 (setq org-read-date-analyze-futurep nil
15820 org-read-date-analyze-forced-year nil)
15821 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15822 (setq ans "+0"))
15824 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15825 (setq ans (replace-match "" t t ans)
15826 deltan (car delta)
15827 deltaw (nth 1 delta)
15828 deltadef (nth 2 delta)))
15830 ;; Check if there is an iso week date in there. If yes, store the
15831 ;; info and postpone interpreting it until the rest of the parsing
15832 ;; is done.
15833 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15834 (setq iso-year (if (match-end 1)
15835 (org-small-year-to-year
15836 (string-to-number (match-string 1 ans))))
15837 iso-weekday (if (match-end 3)
15838 (string-to-number (match-string 3 ans)))
15839 iso-week (string-to-number (match-string 2 ans)))
15840 (setq ans (replace-match "" t t ans)))
15842 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15843 (when (string-match
15844 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15845 (setq year (if (match-end 2)
15846 (string-to-number (match-string 2 ans))
15847 (progn (setq kill-year t)
15848 (string-to-number (format-time-string "%Y"))))
15849 month (string-to-number (match-string 3 ans))
15850 day (string-to-number (match-string 4 ans)))
15851 (if (< year 100) (setq year (+ 2000 year)))
15852 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15853 t nil ans)))
15855 ;; Help matching dotted european dates
15856 (when (string-match
15857 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15858 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15859 (setq kill-year t)
15860 (string-to-number (format-time-string "%Y")))
15861 day (string-to-number (match-string 1 ans))
15862 month (string-to-number (match-string 2 ans))
15863 ans (replace-match (format "%04d-%02d-%02d" year month day)
15864 t nil ans)))
15866 ;; Help matching american dates, like 5/30 or 5/30/7
15867 (when (string-match
15868 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15869 (setq year (if (match-end 4)
15870 (string-to-number (match-string 4 ans))
15871 (progn (setq kill-year t)
15872 (string-to-number (format-time-string "%Y"))))
15873 month (string-to-number (match-string 1 ans))
15874 day (string-to-number (match-string 2 ans)))
15875 (if (< year 100) (setq year (+ 2000 year)))
15876 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15877 t nil ans)))
15878 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15879 ;; If there is a time with am/pm, and *no* time without it, we convert
15880 ;; so that matching will be successful.
15881 (loop for i from 1 to 2 do ; twice, for end time as well
15882 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15883 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15884 (setq hour (string-to-number (match-string 1 ans))
15885 minute (if (match-end 3)
15886 (string-to-number (match-string 3 ans))
15888 pm (equal ?p
15889 (string-to-char (downcase (match-string 4 ans)))))
15890 (if (and (= hour 12) (not pm))
15891 (setq hour 0)
15892 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15893 (setq ans (replace-match (format "%02d:%02d" hour minute)
15894 t t ans))))
15896 ;; Check if a time range is given as a duration
15897 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15898 (setq hour (string-to-number (match-string 1 ans))
15899 h2 (+ hour (string-to-number (match-string 3 ans)))
15900 minute (string-to-number (match-string 2 ans))
15901 m2 (+ minute (if (match-end 5) (string-to-number
15902 (match-string 5 ans))0)))
15903 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15904 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15905 t t ans)))
15907 ;; Check if there is a time range
15908 (when (boundp 'org-end-time-was-given)
15909 (setq org-time-was-given nil)
15910 (when (and (string-match org-plain-time-of-day-regexp ans)
15911 (match-end 8))
15912 (setq org-end-time-was-given (match-string 8 ans))
15913 (setq ans (concat (substring ans 0 (match-beginning 7))
15914 (substring ans (match-end 7))))))
15916 (setq tl (parse-time-string ans)
15917 day (or (nth 3 tl) (nth 3 org-defdecode))
15918 month (or (nth 4 tl)
15919 (if (and org-read-date-prefer-future
15920 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15921 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15922 (nth 4 org-defdecode)))
15923 year (or (and (not kill-year) (nth 5 tl))
15924 (if (and org-read-date-prefer-future
15925 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15926 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15927 (nth 5 org-defdecode)))
15928 hour (or (nth 2 tl) (nth 2 org-defdecode))
15929 minute (or (nth 1 tl) (nth 1 org-defdecode))
15930 second (or (nth 0 tl) 0)
15931 wday (nth 6 tl))
15933 (when (and (eq org-read-date-prefer-future 'time)
15934 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15935 (equal day (nth 3 nowdecode))
15936 (equal month (nth 4 nowdecode))
15937 (equal year (nth 5 nowdecode))
15938 (nth 2 tl)
15939 (or (< (nth 2 tl) (nth 2 nowdecode))
15940 (and (= (nth 2 tl) (nth 2 nowdecode))
15941 (nth 1 tl)
15942 (< (nth 1 tl) (nth 1 nowdecode)))))
15943 (setq day (1+ day)
15944 futurep t))
15946 ;; Special date definitions below
15947 (cond
15948 (iso-week
15949 ;; There was an iso week
15950 (require 'cal-iso)
15951 (setq futurep nil)
15952 (setq year (or iso-year year)
15953 day (or iso-weekday wday 1)
15954 wday nil ; to make sure that the trigger below does not match
15955 iso-date (calendar-gregorian-from-absolute
15956 (calendar-absolute-from-iso
15957 (list iso-week day year))))
15958 ; FIXME: Should we also push ISO weeks into the future?
15959 ; (when (and org-read-date-prefer-future
15960 ; (not iso-year)
15961 ; (< (calendar-absolute-from-gregorian iso-date)
15962 ; (time-to-days (current-time))))
15963 ; (setq year (1+ year)
15964 ; iso-date (calendar-gregorian-from-absolute
15965 ; (calendar-absolute-from-iso
15966 ; (list iso-week day year)))))
15967 (setq month (car iso-date)
15968 year (nth 2 iso-date)
15969 day (nth 1 iso-date)))
15970 (deltan
15971 (setq futurep nil)
15972 (unless deltadef
15973 (let ((now (decode-time (current-time))))
15974 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15975 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15976 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15977 ((equal deltaw "m") (setq month (+ month deltan)))
15978 ((equal deltaw "y") (setq year (+ year deltan)))))
15979 ((and wday (not (nth 3 tl)))
15980 ;; Weekday was given, but no day, so pick that day in the week
15981 ;; on or after the derived date.
15982 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15983 (unless (equal wday wday1)
15984 (setq day (+ day (% (- wday wday1 -7) 7))))))
15985 (if (and (boundp 'org-time-was-given)
15986 (nth 2 tl))
15987 (setq org-time-was-given t))
15988 (if (< year 100) (setq year (+ 2000 year)))
15989 ;; Check of the date is representable
15990 (if org-read-date-force-compatible-dates
15991 (progn
15992 (if (< year 1970)
15993 (setq year 1970 org-read-date-analyze-forced-year t))
15994 (if (> year 2037)
15995 (setq year 2037 org-read-date-analyze-forced-year t)))
15996 (condition-case nil
15997 (ignore (encode-time second minute hour day month year))
15998 (error
15999 (setq year (nth 5 org-defdecode))
16000 (setq org-read-date-analyze-forced-year t))))
16001 (setq org-read-date-analyze-futurep futurep)
16002 (list second minute hour day month year)))
16004 (defvar parse-time-weekdays)
16005 (defun org-read-date-get-relative (s today default)
16006 "Check string S for special relative date string.
16007 TODAY and DEFAULT are internal times, for today and for a default.
16008 Return shift list (N what def-flag)
16009 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16010 N is the number of WHATs to shift.
16011 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16012 the DEFAULT date rather than TODAY."
16013 (require 'parse-time)
16014 (when (and
16015 (string-match
16016 (concat
16017 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16018 "\\([0-9]+\\)?"
16019 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16020 "\\([ \t]\\|$\\)") s)
16021 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16022 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16023 (string-to-char (substring (match-string 1 s) -1))
16024 ?+))
16025 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16026 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16027 (what (if (match-end 3) (match-string 3 s) "d"))
16028 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16029 (date (if rel default today))
16030 (wday (nth 6 (decode-time date)))
16031 delta)
16032 (if wday1
16033 (progn
16034 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16035 (if (= dir ?-) (setq delta (- delta 7)))
16036 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16037 (list delta "d" rel))
16038 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16040 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16041 "Turn a user-specified date into the internal representation.
16042 The internal representation needed by the calendar is (month day year).
16043 This is a wrapper to handle the brain-dead convention in calendar that
16044 user function argument order change dependent on argument order."
16045 (if (boundp 'calendar-date-style)
16046 (cond
16047 ((eq calendar-date-style 'american)
16048 (list arg1 arg2 arg3))
16049 ((eq calendar-date-style 'european)
16050 (list arg2 arg1 arg3))
16051 ((eq calendar-date-style 'iso)
16052 (list arg2 arg3 arg1)))
16053 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16054 (if (org-bound-and-true-p european-calendar-style)
16055 (list arg2 arg1 arg3)
16056 (list arg1 arg2 arg3)))))
16058 (defun org-eval-in-calendar (form &optional keepdate)
16059 "Eval FORM in the calendar window and return to current window.
16060 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16061 otherwise stick to the current value of `org-ans2'."
16062 (let ((sf (selected-frame))
16063 (sw (selected-window)))
16064 (select-window (get-buffer-window "*Calendar*" t))
16065 (eval form)
16066 (when (and (not keepdate) (calendar-cursor-to-date))
16067 (let* ((date (calendar-cursor-to-date))
16068 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16069 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16070 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16071 (select-window sw)
16072 (org-select-frame-set-input-focus sf)))
16074 (defun org-calendar-select ()
16075 "Return to `org-read-date' with the date currently selected.
16076 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16077 (interactive)
16078 (when (calendar-cursor-to-date)
16079 (let* ((date (calendar-cursor-to-date))
16080 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16081 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16082 (if (active-minibuffer-window) (exit-minibuffer))))
16084 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16085 "Insert a date stamp for the date given by the internal TIME.
16086 WITH-HM means use the stamp format that includes the time of the day.
16087 INACTIVE means use square brackets instead of angular ones, so that the
16088 stamp will not contribute to the agenda.
16089 PRE and POST are optional strings to be inserted before and after the
16090 stamp.
16091 The command returns the inserted time stamp."
16092 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16093 stamp)
16094 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16095 (insert-before-markers (or pre ""))
16096 (when (listp extra)
16097 (setq extra (car extra))
16098 (if (and (stringp extra)
16099 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16100 (setq extra (format "-%02d:%02d"
16101 (string-to-number (match-string 1 extra))
16102 (string-to-number (match-string 2 extra))))
16103 (setq extra nil)))
16104 (when extra
16105 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16106 (insert-before-markers (setq stamp (format-time-string fmt time)))
16107 (insert-before-markers (or post ""))
16108 (setq org-last-inserted-timestamp stamp)))
16110 (defun org-toggle-time-stamp-overlays ()
16111 "Toggle the use of custom time stamp formats."
16112 (interactive)
16113 (setq org-display-custom-times (not org-display-custom-times))
16114 (unless org-display-custom-times
16115 (let ((p (point-min)) (bmp (buffer-modified-p)))
16116 (while (setq p (next-single-property-change p 'display))
16117 (if (and (get-text-property p 'display)
16118 (eq (get-text-property p 'face) 'org-date))
16119 (remove-text-properties
16120 p (setq p (next-single-property-change p 'display))
16121 '(display t))))
16122 (set-buffer-modified-p bmp)))
16123 (if (featurep 'xemacs)
16124 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16125 (org-restart-font-lock)
16126 (setq org-table-may-need-update t)
16127 (if org-display-custom-times
16128 (message "Time stamps are overlaid with custom format")
16129 (message "Time stamp overlays removed")))
16131 (defun org-display-custom-time (beg end)
16132 "Overlay modified time stamp format over timestamp between BEG and END."
16133 (let* ((ts (buffer-substring beg end))
16134 t1 w1 with-hm tf time str w2 (off 0))
16135 (save-match-data
16136 (setq t1 (org-parse-time-string ts t))
16137 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16138 (setq off (- (match-end 0) (match-beginning 0)))))
16139 (setq end (- end off))
16140 (setq w1 (- end beg)
16141 with-hm (and (nth 1 t1) (nth 2 t1))
16142 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16143 time (org-fix-decoded-time t1)
16144 str (org-add-props
16145 (format-time-string
16146 (substring tf 1 -1) (apply 'encode-time time))
16147 nil 'mouse-face 'highlight)
16148 w2 (length str))
16149 (if (not (= w2 w1))
16150 (add-text-properties (1+ beg) (+ 2 beg)
16151 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16152 (if (featurep 'xemacs)
16153 (progn
16154 (put-text-property beg end 'invisible t)
16155 (put-text-property beg end 'end-glyph (make-glyph str)))
16156 (put-text-property beg end 'display str))))
16158 (defun org-translate-time (string)
16159 "Translate all timestamps in STRING to custom format.
16160 But do this only if the variable `org-display-custom-times' is set."
16161 (when org-display-custom-times
16162 (save-match-data
16163 (let* ((start 0)
16164 (re org-ts-regexp-both)
16165 t1 with-hm inactive tf time str beg end)
16166 (while (setq start (string-match re string start))
16167 (setq beg (match-beginning 0)
16168 end (match-end 0)
16169 t1 (save-match-data
16170 (org-parse-time-string (substring string beg end) t))
16171 with-hm (and (nth 1 t1) (nth 2 t1))
16172 inactive (equal (substring string beg (1+ beg)) "[")
16173 tf (funcall (if with-hm 'cdr 'car)
16174 org-time-stamp-custom-formats)
16175 time (org-fix-decoded-time t1)
16176 str (format-time-string
16177 (concat
16178 (if inactive "[" "<") (substring tf 1 -1)
16179 (if inactive "]" ">"))
16180 (apply 'encode-time time))
16181 string (replace-match str t t string)
16182 start (+ start (length str)))))))
16183 string)
16185 (defun org-fix-decoded-time (time)
16186 "Set 0 instead of nil for the first 6 elements of time.
16187 Don't touch the rest."
16188 (let ((n 0))
16189 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16191 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16193 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16194 "Difference between TIMESTAMP-STRING and now in days.
16195 If SECONDS is non-nil, return the difference in seconds."
16196 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16197 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16198 (funcall fdiff (current-time)))))
16200 (defun org-deadline-close (timestamp-string &optional ndays)
16201 "Is the time in TIMESTAMP-STRING close to the current date?"
16202 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16203 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16204 (not (org-entry-is-done-p))))
16206 (defun org-get-wdays (ts)
16207 "Get the deadline lead time appropriate for timestring TS."
16208 (cond
16209 ((<= org-deadline-warning-days 0)
16210 ;; 0 or negative, enforce this value no matter what
16211 (- org-deadline-warning-days))
16212 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16213 ;; lead time is specified.
16214 (floor (* (string-to-number (match-string 1 ts))
16215 (cdr (assoc (match-string 2 ts)
16216 '(("d" . 1) ("w" . 7)
16217 ("m" . 30.4) ("y" . 365.25)))))))
16218 ;; go for the default.
16219 (t org-deadline-warning-days)))
16221 (defun org-calendar-select-mouse (ev)
16222 "Return to `org-read-date' with the date currently selected.
16223 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16224 (interactive "e")
16225 (mouse-set-point ev)
16226 (when (calendar-cursor-to-date)
16227 (let* ((date (calendar-cursor-to-date))
16228 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16229 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16230 (if (active-minibuffer-window) (exit-minibuffer))))
16232 (defun org-check-deadlines (ndays)
16233 "Check if there are any deadlines due or past due.
16234 A deadline is considered due if it happens within `org-deadline-warning-days'
16235 days from today's date. If the deadline appears in an entry marked DONE,
16236 it is not shown. The prefix arg NDAYS can be used to test that many
16237 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16238 (interactive "P")
16239 (let* ((org-warn-days
16240 (cond
16241 ((equal ndays '(4)) 100000)
16242 (ndays (prefix-numeric-value ndays))
16243 (t (abs org-deadline-warning-days))))
16244 (case-fold-search nil)
16245 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16246 (callback
16247 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16249 (message "%d deadlines past-due or due within %d days"
16250 (org-occur regexp nil callback)
16251 org-warn-days)))
16253 (defsubst org-re-timestamp (type)
16254 "Return a regexp for timestamp TYPE.
16255 Allowed values for TYPE are:
16257 all: all timestamps
16258 active: only active timestamps (<...>)
16259 inactive: only inactive timestamps ([...])
16260 scheduled: only scheduled timestamps
16261 deadline: only deadline timestamps
16263 When TYPE is nil, fall back on returning a regexp that matches
16264 both scheduled and deadline timestamps."
16265 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16266 ((eq type 'active) org-ts-regexp)
16267 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16268 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16269 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16270 ((eq type 'scheduled-or-deadline)
16271 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16273 (defun org-check-before-date (date)
16274 "Check if there are deadlines or scheduled entries before DATE."
16275 (interactive (list (org-read-date)))
16276 (let ((case-fold-search nil)
16277 (regexp (org-re-timestamp org-ts-type))
16278 (callback
16279 (lambda () (time-less-p
16280 (org-time-string-to-time (match-string 1))
16281 (org-time-string-to-time date)))))
16282 (message "%d entries before %s"
16283 (org-occur regexp nil callback) date)))
16285 (defun org-check-after-date (date)
16286 "Check if there are deadlines or scheduled entries after DATE."
16287 (interactive (list (org-read-date)))
16288 (let ((case-fold-search nil)
16289 (regexp (org-re-timestamp org-ts-type))
16290 (callback
16291 (lambda () (not
16292 (time-less-p
16293 (org-time-string-to-time (match-string 1))
16294 (org-time-string-to-time date))))))
16295 (message "%d entries after %s"
16296 (org-occur regexp nil callback) date)))
16298 (defun org-check-dates-range (start-date end-date)
16299 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16300 (interactive (list (org-read-date nil nil nil "Range starts")
16301 (org-read-date nil nil nil "Range end")))
16302 (let ((case-fold-search nil)
16303 (regexp (org-re-timestamp org-ts-type))
16304 (callback
16305 (lambda ()
16306 (let ((match (match-string 1)))
16307 (and
16308 (not (time-less-p
16309 (org-time-string-to-time match)
16310 (org-time-string-to-time start-date)))
16311 (time-less-p
16312 (org-time-string-to-time match)
16313 (org-time-string-to-time end-date)))))))
16314 (message "%d entries between %s and %s"
16315 (org-occur regexp nil callback) start-date end-date)))
16317 (defun org-evaluate-time-range (&optional to-buffer)
16318 "Evaluate a time range by computing the difference between start and end.
16319 Normally the result is just printed in the echo area, but with prefix arg
16320 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16321 If the time range is actually in a table, the result is inserted into the
16322 next column.
16323 For time difference computation, a year is assumed to be exactly 365
16324 days in order to avoid rounding problems."
16325 (interactive "P")
16327 (org-clock-update-time-maybe)
16328 (save-excursion
16329 (unless (org-at-date-range-p t)
16330 (goto-char (point-at-bol))
16331 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16332 (if (not (org-at-date-range-p t))
16333 (error "Not at a time-stamp range, and none found in current line")))
16334 (let* ((ts1 (match-string 1))
16335 (ts2 (match-string 2))
16336 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16337 (match-end (match-end 0))
16338 (time1 (org-time-string-to-time ts1))
16339 (time2 (org-time-string-to-time ts2))
16340 (t1 (org-float-time time1))
16341 (t2 (org-float-time time2))
16342 (diff (abs (- t2 t1)))
16343 (negative (< (- t2 t1) 0))
16344 ;; (ys (floor (* 365 24 60 60)))
16345 (ds (* 24 60 60))
16346 (hs (* 60 60))
16347 (fy "%dy %dd %02d:%02d")
16348 (fy1 "%dy %dd")
16349 (fd "%dd %02d:%02d")
16350 (fd1 "%dd")
16351 (fh "%02d:%02d")
16352 y d h m align)
16353 (if havetime
16354 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16356 d (floor (/ diff ds)) diff (mod diff ds)
16357 h (floor (/ diff hs)) diff (mod diff hs)
16358 m (floor (/ diff 60)))
16359 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16361 d (floor (+ (/ diff ds) 0.5))
16362 h 0 m 0))
16363 (if (not to-buffer)
16364 (message "%s" (org-make-tdiff-string y d h m))
16365 (if (org-at-table-p)
16366 (progn
16367 (goto-char match-end)
16368 (setq align t)
16369 (and (looking-at " *|") (goto-char (match-end 0))))
16370 (goto-char match-end))
16371 (if (looking-at
16372 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16373 (replace-match ""))
16374 (if negative (insert " -"))
16375 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16376 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16377 (insert " " (format fh h m))))
16378 (if align (org-table-align))
16379 (message "Time difference inserted")))))
16381 (defun org-make-tdiff-string (y d h m)
16382 (let ((fmt "")
16383 (l nil))
16384 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16385 l (push y l)))
16386 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16387 l (push d l)))
16388 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16389 l (push h l)))
16390 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16391 l (push m l)))
16392 (apply 'format fmt (nreverse l))))
16394 (defun org-time-string-to-time (s &optional buffer pos)
16395 "Convert a timestamp string into internal time."
16396 (condition-case errdata
16397 (apply 'encode-time (org-parse-time-string s))
16398 (error (error "Bad timestamp `%s'%s\nError was: %s"
16399 s (if (not (and buffer pos))
16401 (format " at %d in buffer `%s'" pos buffer))
16402 (cdr errdata)))))
16404 (defun org-time-string-to-seconds (s)
16405 "Convert a timestamp string to a number of seconds."
16406 (org-float-time (org-time-string-to-time s)))
16408 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16409 "Convert a time stamp to an absolute day number.
16410 If there is a specifier for a cyclic time stamp, get the closest date to
16411 DAYNR.
16412 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16413 The variable date is bound by the calendar when this is called."
16414 (cond
16415 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16416 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16417 daynr
16418 (+ daynr 1000)))
16419 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16420 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16421 (time-to-days (current-time))) (match-string 0 s)
16422 prefer show-all))
16423 (t (time-to-days
16424 (condition-case errdata
16425 (apply 'encode-time (org-parse-time-string s))
16426 (error (error "Bad timestamp `%s'%s\nError was: %s"
16427 s (if (not (and buffer pos))
16429 (format " at %d in buffer `%s'" pos buffer))
16430 (cdr errdata))))))))
16432 (defun org-days-to-iso-week (days)
16433 "Return the iso week number."
16434 (require 'cal-iso)
16435 (car (calendar-iso-from-absolute days)))
16437 (defun org-small-year-to-year (year)
16438 "Convert 2-digit years into 4-digit years.
16439 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16440 The year 2000 cannot be abbreviated. Any year larger than 99
16441 is returned unchanged."
16442 (if (< year 38)
16443 (setq year (+ 2000 year))
16444 (if (< year 100)
16445 (setq year (+ 1900 year))))
16446 year)
16448 (defun org-time-from-absolute (d)
16449 "Return the time corresponding to date D.
16450 D may be an absolute day number, or a calendar-type list (month day year)."
16451 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16452 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16454 (defun org-calendar-holiday ()
16455 "List of holidays, for Diary display in Org-mode."
16456 (require 'holidays)
16457 (let ((hl (funcall
16458 (if (fboundp 'calendar-check-holidays)
16459 'calendar-check-holidays 'check-calendar-holidays) date)))
16460 (if hl (mapconcat 'identity hl "; "))))
16462 (defun org-diary-sexp-entry (sexp entry date)
16463 "Process a SEXP diary ENTRY for DATE."
16464 (require 'diary-lib)
16465 (let ((result (if calendar-debug-sexp
16466 (let ((stack-trace-on-error t))
16467 (eval (car (read-from-string sexp))))
16468 (condition-case nil
16469 (eval (car (read-from-string sexp)))
16470 (error
16471 (beep)
16472 (message "Bad sexp at line %d in %s: %s"
16473 (org-current-line)
16474 (buffer-file-name) sexp)
16475 (sleep-for 2))))))
16476 (cond ((stringp result) (split-string result "; "))
16477 ((and (consp result)
16478 (not (consp (cdr result)))
16479 (stringp (cdr result))) (cdr result))
16480 ((and (consp result)
16481 (stringp (car result))) result)
16482 (result entry))))
16484 (defun org-diary-to-ical-string (frombuf)
16485 "Get iCalendar entries from diary entries in buffer FROMBUF.
16486 This uses the icalendar.el library."
16487 (let* ((tmpdir (if (featurep 'xemacs)
16488 (temp-directory)
16489 temporary-file-directory))
16490 (tmpfile (make-temp-name
16491 (expand-file-name "orgics" tmpdir)))
16492 buf rtn b e)
16493 (with-current-buffer frombuf
16494 (icalendar-export-region (point-min) (point-max) tmpfile)
16495 (setq buf (find-buffer-visiting tmpfile))
16496 (set-buffer buf)
16497 (goto-char (point-min))
16498 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16499 (setq b (match-beginning 0)))
16500 (goto-char (point-max))
16501 (if (re-search-backward "^END:VEVENT" nil t)
16502 (setq e (match-end 0)))
16503 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16504 (kill-buffer buf)
16505 (delete-file tmpfile)
16506 rtn))
16508 (defun org-closest-date (start current change prefer show-all)
16509 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16510 When PREFER is `past', return a date that is either CURRENT or past.
16511 When PREFER is `future', return a date that is either CURRENT or future.
16512 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16513 ;; Make the proper lists from the dates
16514 (catch 'exit
16515 (let ((a1 '(("h" . hour)
16516 ("d" . day)
16517 ("w" . week)
16518 ("m" . month)
16519 ("y" . year)))
16520 (shour (nth 2 (org-parse-time-string start)))
16521 dn dw sday cday n1 n2 n0
16522 d m y y1 y2 date1 date2 nmonths nm ny m2)
16524 (setq start (org-date-to-gregorian start)
16525 current (org-date-to-gregorian
16526 (if show-all
16527 current
16528 (time-to-days (current-time))))
16529 sday (calendar-absolute-from-gregorian start)
16530 cday (calendar-absolute-from-gregorian current))
16532 (if (<= cday sday) (throw 'exit sday))
16534 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16535 (setq dn (string-to-number (match-string 1 change))
16536 dw (cdr (assoc (match-string 2 change) a1)))
16537 (error "Invalid change specifier: %s" change))
16538 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16539 (cond
16540 ((eq dw 'hour)
16541 (let ((missing-hours
16542 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16543 dn)))
16544 (setq n1 (if (zerop missing-hours) cday
16545 (- cday (1+ (floor (/ missing-hours 24)))))
16546 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16547 ((eq dw 'day)
16548 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16549 n2 (+ n1 dn)))
16550 ((eq dw 'year)
16551 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16552 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16553 (setq date1 (list m d y1)
16554 n1 (calendar-absolute-from-gregorian date1)
16555 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16556 n2 (calendar-absolute-from-gregorian date2)))
16557 ((eq dw 'month)
16558 ;; approx number of month between the two dates
16559 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16560 ;; How often does dn fit in there?
16561 (setq d (nth 1 start) m (car start) y (nth 2 start)
16562 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16563 m (+ m nm)
16564 ny (floor (/ m 12))
16565 y (+ y ny)
16566 m (- m (* ny 12)))
16567 (while (> m 12) (setq m (- m 12) y (1+ y)))
16568 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16569 (setq m2 (+ m dn) y2 y)
16570 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16571 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16572 (while (<= n2 cday)
16573 (setq n1 n2 m m2 y y2)
16574 (setq m2 (+ m dn) y2 y)
16575 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16576 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16577 ;; Make sure n1 is the earlier date
16578 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16579 (if show-all
16580 (cond
16581 ((eq prefer 'past) (if (= cday n2) n2 n1))
16582 ((eq prefer 'future) (if (= cday n1) n1 n2))
16583 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16584 (cond
16585 ((eq prefer 'past) (if (= cday n2) n2 n1))
16586 ((eq prefer 'future) (if (= cday n1) n1 n2))
16587 (t (if (= cday n1) n1 n2)))))))
16589 (defun org-date-to-gregorian (date)
16590 "Turn any specification of DATE into a Gregorian date for the calendar."
16591 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16592 ((and (listp date) (= (length date) 3)) date)
16593 ((stringp date)
16594 (setq date (org-parse-time-string date))
16595 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16596 ((listp date)
16597 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16599 (defun org-parse-time-string (s &optional nodefault)
16600 "Parse the standard Org-mode time string.
16601 This should be a lot faster than the normal `parse-time-string'.
16602 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16603 hour and minute fields will be nil if not given."
16604 (cond ((string-match org-ts-regexp0 s)
16605 (list 0
16606 (if (or (match-beginning 8) (not nodefault))
16607 (string-to-number (or (match-string 8 s) "0")))
16608 (if (or (match-beginning 7) (not nodefault))
16609 (string-to-number (or (match-string 7 s) "0")))
16610 (string-to-number (match-string 4 s))
16611 (string-to-number (match-string 3 s))
16612 (string-to-number (match-string 2 s))
16613 nil nil nil))
16614 ((string-match "^<[^>]+>$" s)
16615 (decode-time (seconds-to-time (org-matcher-time s))))
16616 (t (error "Not a standard Org-mode time string: %s" s))))
16618 (defun org-timestamp-up (&optional arg)
16619 "Increase the date item at the cursor by one.
16620 If the cursor is on the year, change the year. If it is on the month,
16621 the day or the time, change that.
16622 With prefix ARG, change by that many units."
16623 (interactive "p")
16624 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16626 (defun org-timestamp-down (&optional arg)
16627 "Decrease the date item at the cursor by one.
16628 If the cursor is on the year, change the year. If it is on the month,
16629 the day or the time, change that.
16630 With prefix ARG, change by that many units."
16631 (interactive "p")
16632 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16634 (defun org-timestamp-up-day (&optional arg)
16635 "Increase the date in the time stamp by one day.
16636 With prefix ARG, change that many days."
16637 (interactive "p")
16638 (if (and (not (org-at-timestamp-p t))
16639 (org-at-heading-p))
16640 (org-todo 'up)
16641 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16643 (defun org-timestamp-down-day (&optional arg)
16644 "Decrease the date in the time stamp by one day.
16645 With prefix ARG, change that many days."
16646 (interactive "p")
16647 (if (and (not (org-at-timestamp-p t))
16648 (org-at-heading-p))
16649 (org-todo 'down)
16650 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16652 (defun org-at-timestamp-p (&optional inactive-ok)
16653 "Determine if the cursor is in or at a timestamp."
16654 (interactive)
16655 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16656 (pos (point))
16657 (ans (or (looking-at tsr)
16658 (save-excursion
16659 (skip-chars-backward "^[<\n\r\t")
16660 (if (> (point) (point-min)) (backward-char 1))
16661 (and (looking-at tsr)
16662 (> (- (match-end 0) pos) -1))))))
16663 (and ans
16664 (boundp 'org-ts-what)
16665 (setq org-ts-what
16666 (cond
16667 ((= pos (match-beginning 0)) 'bracket)
16668 ;; Point is considered to be "on the bracket" whether
16669 ;; it's really on it or right after it.
16670 ((= pos (1- (match-end 0))) 'bracket)
16671 ((= pos (match-end 0)) 'after)
16672 ((org-pos-in-match-range pos 2) 'year)
16673 ((org-pos-in-match-range pos 3) 'month)
16674 ((org-pos-in-match-range pos 7) 'hour)
16675 ((org-pos-in-match-range pos 8) 'minute)
16676 ((or (org-pos-in-match-range pos 4)
16677 (org-pos-in-match-range pos 5)) 'day)
16678 ((and (> pos (or (match-end 8) (match-end 5)))
16679 (< pos (match-end 0)))
16680 (- pos (or (match-end 8) (match-end 5))))
16681 (t 'day))))
16682 ans))
16684 (defun org-toggle-timestamp-type ()
16685 "Toggle the type (<active> or [inactive]) of a time stamp."
16686 (interactive)
16687 (when (org-at-timestamp-p t)
16688 (let ((beg (match-beginning 0)) (end (match-end 0))
16689 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16690 (save-excursion
16691 (goto-char beg)
16692 (while (re-search-forward "[][<>]" end t)
16693 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16694 t t)))
16695 (message "Timestamp is now %sactive"
16696 (if (equal (char-after beg) ?<) "" "in")))))
16698 (defvar org-clock-history) ; defined in org-clock.el
16699 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16700 (defun org-timestamp-change (n &optional what updown)
16701 "Change the date in the time stamp at point.
16702 The date will be changed by N times WHAT. WHAT can be `day', `month',
16703 `year', `minute', `second'. If WHAT is not given, the cursor position
16704 in the timestamp determines what will be changed."
16705 (let ((origin (point)) origin-cat
16706 with-hm inactive
16707 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16708 org-ts-what
16709 extra rem
16710 ts time time0 fixnext clrgx)
16711 (if (not (org-at-timestamp-p t))
16712 (error "Not at a timestamp"))
16713 (if (and (not what) (eq org-ts-what 'bracket))
16714 (org-toggle-timestamp-type)
16715 ;; Point isn't on brackets. Remember the part of the time-stamp
16716 ;; the point was in. Indeed, size of time-stamps may change,
16717 ;; but point must be kept in the same category nonetheless.
16718 (setq origin-cat org-ts-what)
16719 (if (and (not what) (not (eq org-ts-what 'day))
16720 org-display-custom-times
16721 (get-text-property (point) 'display)
16722 (not (get-text-property (1- (point)) 'display)))
16723 (setq org-ts-what 'day))
16724 (setq org-ts-what (or what org-ts-what)
16725 inactive (= (char-after (match-beginning 0)) ?\[)
16726 ts (match-string 0))
16727 (replace-match "")
16728 (if (string-match
16729 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16731 (setq extra (match-string 1 ts)))
16732 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16733 (setq with-hm t))
16734 (setq time0 (org-parse-time-string ts))
16735 (when (and updown
16736 (eq org-ts-what 'minute)
16737 (not current-prefix-arg))
16738 ;; This looks like s-up and s-down. Change by one rounding step.
16739 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16740 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16741 (setcar (cdr time0) (+ (nth 1 time0)
16742 (if (> n 0) (- rem) (- dm rem))))))
16743 (setq time
16744 (encode-time (or (car time0) 0)
16745 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16746 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16747 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16748 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16749 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16750 (nthcdr 6 time0)))
16751 (when (and (member org-ts-what '(hour minute))
16752 extra
16753 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16754 (setq extra (org-modify-ts-extra
16755 extra
16756 (if (eq org-ts-what 'hour) 2 5)
16757 n dm)))
16758 (when (integerp org-ts-what)
16759 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16760 (if (eq what 'calendar)
16761 (let ((cal-date (org-get-date-from-calendar)))
16762 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16763 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16764 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16765 (setcar time0 (or (car time0) 0))
16766 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16767 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16768 (setq time (apply 'encode-time time0))))
16769 ;; Insert the new time-stamp, and ensure point stays in the same
16770 ;; category as before (i.e. not after the last position in that
16771 ;; category).
16772 (let ((pos (point)))
16773 ;; Stay before inserted string. `save-excursion' is of no use.
16774 (setq org-last-changed-timestamp
16775 (org-insert-time-stamp time with-hm inactive nil nil extra))
16776 (goto-char pos))
16777 (save-match-data
16778 (looking-at org-ts-regexp3)
16779 (goto-char (cond
16780 ;; `day' category ends before `hour' if any, or at
16781 ;; the end of the day name.
16782 ((eq origin-cat 'day)
16783 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16784 ((eq origin-cat 'hour) (min (match-end 7) origin))
16785 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16786 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16787 ;; `year' and `month' have both fixed size: point
16788 ;; couldn't have moved into another part.
16789 (t origin))))
16790 ;; Update clock if on a CLOCK line.
16791 (org-clock-update-time-maybe)
16792 ;; Maybe adjust the closest clock in `org-clock-history'
16793 (when org-clock-adjust-closest
16794 (if (not (and (org-at-clock-log-p)
16795 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16796 org-clock-history))))))
16797 (message "No clock to adjust")
16798 (cond ((save-excursion ; fix previous clock?
16799 (re-search-backward org-ts-regexp0 nil t)
16800 (org-looking-back (concat org-clock-string " \\[")))
16801 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16802 ((save-excursion ; fix next clock?
16803 (re-search-backward org-ts-regexp0 nil t)
16804 (looking-at (concat org-ts-regexp0 "\\] =>")))
16805 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16806 (save-window-excursion
16807 ;; Find closest clock to point, adjust the previous/next one in history
16808 (let* ((p (save-excursion (org-back-to-heading t)))
16809 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16810 (clfixnth
16811 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16812 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16813 (if (not clfixpos)
16814 (message "No clock to adjust")
16815 (save-excursion
16816 (org-goto-marker-or-bmk clfixpos)
16817 (org-show-subtree)
16818 (when (re-search-forward clrgx nil t)
16819 (goto-char (match-beginning 1))
16820 (let (org-clock-adjust-closest)
16821 (org-timestamp-change n org-ts-what updown))
16822 (message "Clock adjusted in %s for heading: %s"
16823 (file-name-nondirectory (buffer-file-name))
16824 (org-get-heading t t)))))))))
16825 ;; Try to recenter the calendar window, if any.
16826 (if (and org-calendar-follow-timestamp-change
16827 (get-buffer-window "*Calendar*" t)
16828 (memq org-ts-what '(day month year)))
16829 (org-recenter-calendar (time-to-days time))))))
16831 (defun org-modify-ts-extra (s pos n dm)
16832 "Change the different parts of the lead-time and repeat fields in timestamp."
16833 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16834 ng h m new rem)
16835 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16836 (cond
16837 ((or (org-pos-in-match-range pos 2)
16838 (org-pos-in-match-range pos 3))
16839 (setq m (string-to-number (match-string 3 s))
16840 h (string-to-number (match-string 2 s)))
16841 (if (org-pos-in-match-range pos 2)
16842 (setq h (+ h n))
16843 (setq n (* dm (org-no-warnings (signum n))))
16844 (when (not (= 0 (setq rem (% m dm))))
16845 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16846 (setq m (+ m n)))
16847 (if (< m 0) (setq m (+ m 60) h (1- h)))
16848 (if (> m 59) (setq m (- m 60) h (1+ h)))
16849 (setq h (min 24 (max 0 h)))
16850 (setq ng 1 new (format "-%02d:%02d" h m)))
16851 ((org-pos-in-match-range pos 6)
16852 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16853 ((org-pos-in-match-range pos 5)
16854 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16856 ((org-pos-in-match-range pos 9)
16857 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16858 ((org-pos-in-match-range pos 8)
16859 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16861 (when ng
16862 (setq s (concat
16863 (substring s 0 (match-beginning ng))
16865 (substring s (match-end ng))))))
16868 (defun org-recenter-calendar (date)
16869 "If the calendar is visible, recenter it to DATE."
16870 (let ((cwin (get-buffer-window "*Calendar*" t)))
16871 (when cwin
16872 (let ((calendar-move-hook nil))
16873 (with-selected-window cwin
16874 (calendar-goto-date (if (listp date) date
16875 (calendar-gregorian-from-absolute date))))))))
16877 (defun org-goto-calendar (&optional arg)
16878 "Go to the Emacs calendar at the current date.
16879 If there is a time stamp in the current line, go to that date.
16880 A prefix ARG can be used to force the current date."
16881 (interactive "P")
16882 (let ((tsr org-ts-regexp) diff
16883 (calendar-move-hook nil)
16884 (calendar-view-holidays-initially-flag nil)
16885 (calendar-view-diary-initially-flag nil))
16886 (if (or (org-at-timestamp-p)
16887 (save-excursion
16888 (beginning-of-line 1)
16889 (looking-at (concat ".*" tsr))))
16890 (let ((d1 (time-to-days (current-time)))
16891 (d2 (time-to-days
16892 (org-time-string-to-time (match-string 1)))))
16893 (setq diff (- d2 d1))))
16894 (calendar)
16895 (calendar-goto-today)
16896 (if (and diff (not arg)) (calendar-forward-day diff))))
16898 (defun org-get-date-from-calendar ()
16899 "Return a list (month day year) of date at point in calendar."
16900 (with-current-buffer "*Calendar*"
16901 (save-match-data
16902 (calendar-cursor-to-date))))
16904 (defun org-date-from-calendar ()
16905 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16906 If there is already a time stamp at the cursor position, update it."
16907 (interactive)
16908 (if (org-at-timestamp-p t)
16909 (org-timestamp-change 0 'calendar)
16910 (let ((cal-date (org-get-date-from-calendar)))
16911 (org-insert-time-stamp
16912 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16914 (defcustom org-effort-durations
16915 `(("h" . 60)
16916 ("d" . ,(* 60 8))
16917 ("w" . ,(* 60 8 5))
16918 ("m" . ,(* 60 8 5 4))
16919 ("y" . ,(* 60 8 5 40)))
16920 "Conversion factor to minutes for an effort modifier.
16922 Each entry has the form (MODIFIER . MINUTES).
16924 In an effort string, a number followed by MODIFIER is multiplied
16925 by the specified number of MINUTES to obtain an effort in
16926 minutes.
16928 For example, if the value of this variable is ((\"hours\" . 60)), then an
16929 effort string \"2hours\" is equivalent to 120 minutes."
16930 :group 'org-agenda
16931 :version "24.1"
16932 :type '(alist :key-type (string :tag "Modifier")
16933 :value-type (number :tag "Minutes")))
16935 (defun org-minutes-to-clocksum-string (m)
16936 "Format number of minutes as a clocksum string.
16937 The format is determined by `org-time-clocksum-format',
16938 `org-time-clocksum-use-fractional' and
16939 `org-time-clocksum-fractional-format' and
16940 `org-time-clocksum-use-effort-durations'."
16941 (let ((clocksum "") h d w mo y fmt n)
16942 (setq h (if org-time-clocksum-use-effort-durations
16943 (cdr (assoc "h" org-effort-durations)) 60)
16944 d (if org-time-clocksum-use-effort-durations
16945 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
16946 w (if org-time-clocksum-use-effort-durations
16947 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
16948 mo (if org-time-clocksum-use-effort-durations
16949 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
16950 y (if org-time-clocksum-use-effort-durations
16951 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
16952 ;; fractional format
16953 (if org-time-clocksum-use-fractional
16954 (cond
16955 ;; single format string
16956 ((stringp org-time-clocksum-fractional-format)
16957 (format org-time-clocksum-fractional-format (/ m (float h))))
16958 ;; choice of fractional formats for different time units
16959 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
16960 (> (/ (truncate m) (* y d h)) 0))
16961 (format fmt (/ m (* y d (float h)))))
16962 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
16963 (> (/ (truncate m) (* mo d h)) 0))
16964 (format fmt (/ m (* mo d (float h)))))
16965 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16966 (> (/ (truncate m) (* w d h)) 0))
16967 (format fmt (/ m (* w d (float h)))))
16968 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
16969 (> (/ (truncate m) (* d h)) 0))
16970 (format fmt (/ m (* d (float h)))))
16971 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16972 (> (/ (truncate m) h) 0))
16973 (format fmt (/ m (float h))))
16974 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
16975 (format fmt m))
16976 ;; fall back to smallest time unit with a format
16977 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16978 (format fmt (/ m (float h))))
16979 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
16980 (format fmt (/ m (* d (float h)))))
16981 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16982 (format fmt (/ m (* w d (float h)))))
16983 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
16984 (format fmt (/ m (* mo d (float h)))))
16985 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
16986 (format fmt (/ m (* y d (float h))))))
16987 ;; standard (non-fractional) format, with single format string
16988 (if (stringp org-time-clocksum-format)
16989 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
16990 ;; separate formats components
16991 (and (setq fmt (plist-get org-time-clocksum-format :years))
16992 (or (> (setq n (/ (truncate m) (* y d h))) 0)
16993 (plist-get org-time-clocksum-format :require-years))
16994 (setq clocksum (concat clocksum (format fmt n))
16995 m (- m (* n y d h))))
16996 (and (setq fmt (plist-get org-time-clocksum-format :months))
16997 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
16998 (plist-get org-time-clocksum-format :require-months))
16999 (setq clocksum (concat clocksum (format fmt n))
17000 m (- m (* n mo d h))))
17001 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17002 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17003 (plist-get org-time-clocksum-format :require-weeks))
17004 (setq clocksum (concat clocksum (format fmt n))
17005 m (- m (* n w d h))))
17006 (and (setq fmt (plist-get org-time-clocksum-format :days))
17007 (or (> (setq n (/ (truncate m) (* d h))) 0)
17008 (plist-get org-time-clocksum-format :require-days))
17009 (setq clocksum (concat clocksum (format fmt n))
17010 m (- m (* n d h))))
17011 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17012 (or (> (setq n (/ (truncate m) h)) 0)
17013 (plist-get org-time-clocksum-format :require-hours))
17014 (setq clocksum (concat clocksum (format fmt n))
17015 m (- m (* n h))))
17016 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17017 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17018 (setq clocksum (concat clocksum (format fmt m))))
17019 ;; return formatted time duration
17020 clocksum))))
17022 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17023 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17024 "Org mode version 8.0")
17026 (defun org-hours-to-clocksum-string (n)
17027 (org-minutes-to-clocksum-string (* n 60)))
17029 (defun org-hh:mm-string-to-minutes (s)
17030 "Convert a string H:MM to a number of minutes.
17031 If the string is just a number, interpret it as minutes.
17032 In fact, the first hh:mm or number in the string will be taken,
17033 there can be extra stuff in the string.
17034 If no number is found, the return value is 0."
17035 (cond
17036 ((integerp s) s)
17037 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17038 (+ (* (string-to-number (match-string 1 s)) 60)
17039 (string-to-number (match-string 2 s))))
17040 ((string-match "\\([0-9]+\\)" s)
17041 (string-to-number (match-string 1 s)))
17042 (t 0)))
17044 (defcustom org-image-actual-width t
17045 "Should we use the actual width of images when inlining them?
17047 When set to `t', always use the image width.
17049 When set to a number, use imagemagick (when available) to set
17050 the image's width to this value.
17052 When set to a number in a list, try to get the width from the
17053 #+ATTR.* keyword if it matches a width specification like
17054 width=\"[0-9]+\", and fall back on that number if none is found.
17056 When set to nil, try to get the width from an #+ATTR.* keyword
17057 and fall back on the original width if none is found.
17059 This requires Emacs >= 24.1, build with imagemagick support."
17060 :group 'org-appearance
17061 :version "24.3"
17062 :type '(choice
17063 (const :tag "Use the image width" t)
17064 (integer :tag "Use a number of pixels")
17065 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17066 (const :tag "Use #+ATTR* or don't resize" nil)))
17068 (defcustom org-agenda-inhibit-startup-visibility-cycling t
17069 "Turn off visibility cycling when preparing agenda buffers.
17071 When preparing agenda buffers, Org visits agenda files. When
17072 this variable is `t' (the default), the visited buffers for
17073 agenda files will not honor `org-startup-folded' or any
17074 #+STARTUP: fold option. Turning this option off may slow down
17075 the generation of agenda, both because folding takes time and
17076 because finding entries in folded buffers takes longer than
17077 finding entries in unfolded ones."
17078 :type 'boolean
17079 :version "24.3"
17080 :group 'org-agenda)
17082 (defun org-duration-string-to-minutes (s &optional output-to-string)
17083 "Convert a duration string S to minutes.
17085 A bare number is interpreted as minutes, modifiers can be set by
17086 customizing `org-effort-durations' (which see).
17088 Entries containing a colon are interpreted as H:MM by
17089 `org-hh:mm-string-to-minutes'."
17090 (let ((result 0)
17091 (re (concat "\\([0-9.]+\\) *\\("
17092 (regexp-opt (mapcar 'car org-effort-durations))
17093 "\\)")))
17094 (while (string-match re s)
17095 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17096 (string-to-number (match-string 1 s))))
17097 (setq s (replace-match "" nil t s)))
17098 (setq result (floor result))
17099 (incf result (org-hh:mm-string-to-minutes s))
17100 (if output-to-string (number-to-string result) result)))
17102 ;;;; Files
17104 (defun org-save-all-org-buffers ()
17105 "Save all Org-mode buffers without user confirmation."
17106 (interactive)
17107 (message "Saving all Org-mode buffers...")
17108 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17109 (when (featurep 'org-id) (org-id-locations-save))
17110 (message "Saving all Org-mode buffers... done"))
17112 (defun org-revert-all-org-buffers ()
17113 "Revert all Org-mode buffers.
17114 Prompt for confirmation when there are unsaved changes.
17115 Be sure you know what you are doing before letting this function
17116 overwrite your changes.
17118 This function is useful in a setup where one tracks org files
17119 with a version control system, to revert on one machine after pulling
17120 changes from another. I believe the procedure must be like this:
17122 1. M-x org-save-all-org-buffers
17123 2. Pull changes from the other machine, resolve conflicts
17124 3. M-x org-revert-all-org-buffers"
17125 (interactive)
17126 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17127 (error "Abort"))
17128 (save-excursion
17129 (save-window-excursion
17130 (mapc
17131 (lambda (b)
17132 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17133 (with-current-buffer b buffer-file-name))
17134 (org-pop-to-buffer-same-window b)
17135 (revert-buffer t 'no-confirm)))
17136 (buffer-list))
17137 (when (and (featurep 'org-id) org-id-track-globally)
17138 (org-id-locations-load)))))
17140 ;;;; Agenda files
17142 ;;;###autoload
17143 (defun org-switchb (&optional arg)
17144 "Switch between Org buffers.
17145 With one prefix argument, restrict available buffers to files.
17146 With two prefix arguments, restrict available buffers to agenda files.
17148 Defaults to `iswitchb' for buffer name completion.
17149 Set `org-completion-use-ido' to make it use ido instead."
17150 (interactive "P")
17151 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17152 ((equal arg '(16)) (org-buffer-list 'agenda))
17153 (t (org-buffer-list))))
17154 (org-completion-use-iswitchb org-completion-use-iswitchb)
17155 (org-completion-use-ido org-completion-use-ido))
17156 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17157 (setq org-completion-use-iswitchb t))
17158 (org-pop-to-buffer-same-window
17159 (org-icompleting-read "Org buffer: "
17160 (mapcar 'list (mapcar 'buffer-name blist))
17161 nil t))))
17163 ;;; Define some older names previously used for this functionality
17164 ;;;###autoload
17165 (defalias 'org-ido-switchb 'org-switchb)
17166 ;;;###autoload
17167 (defalias 'org-iswitchb 'org-switchb)
17169 (defun org-buffer-list (&optional predicate exclude-tmp)
17170 "Return a list of Org buffers.
17171 PREDICATE can be `export', `files' or `agenda'.
17173 export restrict the list to Export buffers.
17174 files restrict the list to buffers visiting Org files.
17175 agenda restrict the list to buffers visiting agenda files.
17177 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17178 (let* ((bfn nil)
17179 (agenda-files (and (eq predicate 'agenda)
17180 (mapcar 'file-truename (org-agenda-files t))))
17181 (filter
17182 (cond
17183 ((eq predicate 'files)
17184 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17185 ((eq predicate 'export)
17186 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17187 ((eq predicate 'agenda)
17188 (lambda (b)
17189 (with-current-buffer b
17190 (and (derived-mode-p 'org-mode)
17191 (setq bfn (buffer-file-name b))
17192 (member (file-truename bfn) agenda-files)))))
17193 (t (lambda (b) (with-current-buffer b
17194 (or (derived-mode-p 'org-mode)
17195 (string-match "\*Org .*Export"
17196 (buffer-name b)))))))))
17197 (delq nil
17198 (mapcar
17199 (lambda(b)
17200 (if (and (funcall filter b)
17201 (or (not exclude-tmp)
17202 (not (string-match "tmp" (buffer-name b)))))
17204 nil))
17205 (buffer-list)))))
17207 (defun org-agenda-files (&optional unrestricted archives)
17208 "Get the list of agenda files.
17209 Optional UNRESTRICTED means return the full list even if a restriction
17210 is currently in place.
17211 When ARCHIVES is t, include all archive files that are really being
17212 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17213 `org-agenda-archives-mode' is t."
17214 (let ((files
17215 (cond
17216 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17217 ((stringp org-agenda-files) (org-read-agenda-file-list))
17218 ((listp org-agenda-files) org-agenda-files)
17219 (t (error "Invalid value of `org-agenda-files'")))))
17220 (setq files (apply 'append
17221 (mapcar (lambda (f)
17222 (if (file-directory-p f)
17223 (directory-files
17224 f t org-agenda-file-regexp)
17225 (list f)))
17226 files)))
17227 (when org-agenda-skip-unavailable-files
17228 (setq files (delq nil
17229 (mapcar (function
17230 (lambda (file)
17231 (and (file-readable-p file) file)))
17232 files))))
17233 (when (or (eq archives t)
17234 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17235 (setq files (org-add-archive-files files)))
17236 files))
17238 (defun org-agenda-file-p (&optional file)
17239 "Return non-nil, if FILE is an agenda file.
17240 If FILE is omitted, use the file associated with the current
17241 buffer."
17242 (member (or file (buffer-file-name))
17243 (org-agenda-files t)))
17245 (defun org-edit-agenda-file-list ()
17246 "Edit the list of agenda files.
17247 Depending on setup, this either uses customize to edit the variable
17248 `org-agenda-files', or it visits the file that is holding the list. In the
17249 latter case, the buffer is set up in a way that saving it automatically kills
17250 the buffer and restores the previous window configuration."
17251 (interactive)
17252 (if (stringp org-agenda-files)
17253 (let ((cw (current-window-configuration)))
17254 (find-file org-agenda-files)
17255 (org-set-local 'org-window-configuration cw)
17256 (org-add-hook 'after-save-hook
17257 (lambda ()
17258 (set-window-configuration
17259 (prog1 org-window-configuration
17260 (kill-buffer (current-buffer))))
17261 (org-install-agenda-files-menu)
17262 (message "New agenda file list installed"))
17263 nil 'local)
17264 (message "%s" (substitute-command-keys
17265 "Edit list and finish with \\[save-buffer]")))
17266 (customize-variable 'org-agenda-files)))
17268 (defun org-store-new-agenda-file-list (list)
17269 "Set new value for the agenda file list and save it correctly."
17270 (if (stringp org-agenda-files)
17271 (let ((fe (org-read-agenda-file-list t)) b u)
17272 (while (setq b (find-buffer-visiting org-agenda-files))
17273 (kill-buffer b))
17274 (with-temp-file org-agenda-files
17275 (insert
17276 (mapconcat
17277 (lambda (f) ;; Keep un-expanded entries.
17278 (if (setq u (assoc f fe))
17279 (cdr u)
17281 list "\n")
17282 "\n")))
17283 (let ((org-mode-hook nil) (org-inhibit-startup t)
17284 (org-insert-mode-line-in-empty-file nil))
17285 (setq org-agenda-files list)
17286 (customize-save-variable 'org-agenda-files org-agenda-files))))
17288 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17289 "Read the list of agenda files from a file.
17290 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17291 filenames, used by `org-store-new-agenda-file-list' to write back
17292 un-expanded file names."
17293 (when (file-directory-p org-agenda-files)
17294 (error "`org-agenda-files' cannot be a single directory"))
17295 (when (stringp org-agenda-files)
17296 (with-temp-buffer
17297 (insert-file-contents org-agenda-files)
17298 (mapcar
17299 (lambda (f)
17300 (let ((e (expand-file-name (substitute-in-file-name f)
17301 org-directory)))
17302 (if pair-with-expansion
17303 (cons e f)
17304 e)))
17305 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17307 ;;;###autoload
17308 (defun org-cycle-agenda-files ()
17309 "Cycle through the files in `org-agenda-files'.
17310 If the current buffer visits an agenda file, find the next one in the list.
17311 If the current buffer does not, find the first agenda file."
17312 (interactive)
17313 (let* ((fs (org-agenda-files t))
17314 (files (append fs (list (car fs))))
17315 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17316 file)
17317 (unless files (error "No agenda files"))
17318 (catch 'exit
17319 (while (setq file (pop files))
17320 (if (equal (file-truename file) tcf)
17321 (when (car files)
17322 (find-file (car files))
17323 (throw 'exit t))))
17324 (find-file (car fs)))
17325 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17327 (defun org-agenda-file-to-front (&optional to-end)
17328 "Move/add the current file to the top of the agenda file list.
17329 If the file is not present in the list, it is added to the front. If it is
17330 present, it is moved there. With optional argument TO-END, add/move to the
17331 end of the list."
17332 (interactive "P")
17333 (let ((org-agenda-skip-unavailable-files nil)
17334 (file-alist (mapcar (lambda (x)
17335 (cons (file-truename x) x))
17336 (org-agenda-files t)))
17337 (ctf (file-truename
17338 (or buffer-file-name
17339 (error "Please save the current buffer to a file"))))
17340 x had)
17341 (setq x (assoc ctf file-alist) had x)
17343 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17344 (if to-end
17345 (setq file-alist (append (delq x file-alist) (list x)))
17346 (setq file-alist (cons x (delq x file-alist))))
17347 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17348 (org-install-agenda-files-menu)
17349 (message "File %s to %s of agenda file list"
17350 (if had "moved" "added") (if to-end "end" "front"))))
17352 (defun org-remove-file (&optional file)
17353 "Remove current file from the list of files in variable `org-agenda-files'.
17354 These are the files which are being checked for agenda entries.
17355 Optional argument FILE means use this file instead of the current."
17356 (interactive)
17357 (let* ((org-agenda-skip-unavailable-files nil)
17358 (file (or file buffer-file-name
17359 (error "Current buffer does not visit a file")))
17360 (true-file (file-truename file))
17361 (afile (abbreviate-file-name file))
17362 (files (delq nil (mapcar
17363 (lambda (x)
17364 (if (equal true-file
17365 (file-truename x))
17366 nil x))
17367 (org-agenda-files t)))))
17368 (if (not (= (length files) (length (org-agenda-files t))))
17369 (progn
17370 (org-store-new-agenda-file-list files)
17371 (org-install-agenda-files-menu)
17372 (message "Removed file: %s" afile))
17373 (message "File was not in list: %s (not removed)" afile))))
17375 (defun org-file-menu-entry (file)
17376 (vector file (list 'find-file file) t))
17378 (defun org-check-agenda-file (file)
17379 "Make sure FILE exists. If not, ask user what to do."
17380 (when (not (file-exists-p file))
17381 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17382 (abbreviate-file-name file))
17383 (let ((r (downcase (read-char-exclusive))))
17384 (cond
17385 ((equal r ?r)
17386 (org-remove-file file)
17387 (throw 'nextfile t))
17388 (t (error "Abort"))))))
17390 (defun org-get-agenda-file-buffer (file)
17391 "Get a buffer visiting FILE. If the buffer needs to be created, add
17392 it to the list of buffers which might be released later."
17393 (let ((buf (org-find-base-buffer-visiting file)))
17394 (if buf
17395 buf ; just return it
17396 ;; Make a new buffer and remember it
17397 (setq buf (find-file-noselect file))
17398 (if buf (push buf org-agenda-new-buffers))
17399 buf)))
17401 (defun org-release-buffers (blist)
17402 "Release all buffers in list, asking the user for confirmation when needed.
17403 When a buffer is unmodified, it is just killed. When modified, it is saved
17404 \(if the user agrees) and then killed."
17405 (let (buf file)
17406 (while (setq buf (pop blist))
17407 (setq file (buffer-file-name buf))
17408 (when (and (buffer-modified-p buf)
17409 file
17410 (y-or-n-p (format "Save file %s? " file)))
17411 (with-current-buffer buf (save-buffer)))
17412 (kill-buffer buf))))
17414 (defun org-agenda-prepare-buffers (files)
17415 "Create buffers for all agenda files, protect archived trees and comments."
17416 (interactive)
17417 (let ((pa '(:org-archived t))
17418 (pc '(:org-comment t))
17419 (pall '(:org-archived t :org-comment t))
17420 (inhibit-read-only t)
17421 (org-inhibit-startup-visibility-stuff
17422 org-agenda-inhibit-startup-visibility-cycling)
17423 (rea (concat ":" org-archive-tag ":"))
17424 bmp file re)
17425 (save-excursion
17426 (save-restriction
17427 (while (setq file (pop files))
17428 (catch 'nextfile
17429 (if (bufferp file)
17430 (set-buffer file)
17431 (org-check-agenda-file file)
17432 (set-buffer (org-get-agenda-file-buffer file)))
17433 (widen)
17434 (setq bmp (buffer-modified-p))
17435 (org-refresh-category-properties)
17436 (org-refresh-properties org-effort-property 'org-effort)
17437 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17438 (setq org-todo-keywords-for-agenda
17439 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17440 (setq org-done-keywords-for-agenda
17441 (append org-done-keywords-for-agenda org-done-keywords))
17442 (setq org-todo-keyword-alist-for-agenda
17443 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17444 (setq org-drawers-for-agenda
17445 (append org-drawers-for-agenda org-drawers))
17446 (setq org-tag-alist-for-agenda
17447 (append org-tag-alist-for-agenda org-tag-alist))
17449 (save-excursion
17450 (remove-text-properties (point-min) (point-max) pall)
17451 (when org-agenda-skip-archived-trees
17452 (goto-char (point-min))
17453 (while (re-search-forward rea nil t)
17454 (if (org-at-heading-p t)
17455 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17456 (goto-char (point-min))
17457 (setq re (format org-heading-keyword-regexp-format
17458 org-comment-string))
17459 (while (re-search-forward re nil t)
17460 (add-text-properties
17461 (match-beginning 0) (org-end-of-subtree t) pc)))
17462 (set-buffer-modified-p bmp)))))
17463 (setq org-todo-keywords-for-agenda
17464 (org-uniquify org-todo-keywords-for-agenda))
17465 (setq org-todo-keyword-alist-for-agenda
17466 (org-uniquify org-todo-keyword-alist-for-agenda)
17467 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17469 ;;;; Embedded LaTeX
17471 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17472 "Keymap for the minor `org-cdlatex-mode'.")
17474 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17475 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17476 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17477 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17478 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17480 (defvar org-cdlatex-texmathp-advice-is-done nil
17481 "Flag remembering if we have applied the advice to texmathp already.")
17483 (define-minor-mode org-cdlatex-mode
17484 "Toggle the minor `org-cdlatex-mode'.
17485 This mode supports entering LaTeX environment and math in LaTeX fragments
17486 in Org-mode.
17487 \\{org-cdlatex-mode-map}"
17488 nil " OCDL" nil
17489 (when org-cdlatex-mode
17490 (require 'cdlatex)
17491 (run-hooks 'cdlatex-mode-hook)
17492 (cdlatex-compute-tables))
17493 (unless org-cdlatex-texmathp-advice-is-done
17494 (setq org-cdlatex-texmathp-advice-is-done t)
17495 (defadvice texmathp (around org-math-always-on activate)
17496 "Always return t in org-mode buffers.
17497 This is because we want to insert math symbols without dollars even outside
17498 the LaTeX math segments. If Orgmode thinks that point is actually inside
17499 an embedded LaTeX fragment, let texmathp do its job.
17500 \\[org-cdlatex-mode-map]"
17501 (interactive)
17502 (let (p)
17503 (cond
17504 ((not (derived-mode-p 'org-mode)) ad-do-it)
17505 ((eq this-command 'cdlatex-math-symbol)
17506 (setq ad-return-value t
17507 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17509 (let ((p (org-inside-LaTeX-fragment-p)))
17510 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17511 (setq ad-return-value t
17512 texmathp-why '("Org-mode embedded math" . 0))
17513 (if p ad-do-it)))))))))
17515 (defun turn-on-org-cdlatex ()
17516 "Unconditionally turn on `org-cdlatex-mode'."
17517 (org-cdlatex-mode 1))
17519 (defun org-inside-LaTeX-fragment-p ()
17520 "Test if point is inside a LaTeX fragment.
17521 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17522 sequence appearing also before point.
17523 Even though the matchers for math are configurable, this function assumes
17524 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17525 delimiters are skipped when they have been removed by customization.
17526 The return value is nil, or a cons cell with the delimiter and the
17527 position of this delimiter.
17529 This function does a reasonably good job, but can locally be fooled by
17530 for example currency specifications. For example it will assume being in
17531 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17532 fragments that are properly closed, but during editing, we have to live
17533 with the uncertainty caused by missing closing delimiters. This function
17534 looks only before point, not after."
17535 (catch 'exit
17536 (let ((pos (point))
17537 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17538 (lim (progn
17539 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17540 (point)))
17541 dd-on str (start 0) m re)
17542 (goto-char pos)
17543 (when dodollar
17544 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17545 re (nth 1 (assoc "$" org-latex-regexps)))
17546 (while (string-match re str start)
17547 (cond
17548 ((= (match-end 0) (length str))
17549 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17550 ((= (match-end 0) (- (length str) 5))
17551 (throw 'exit nil))
17552 (t (setq start (match-end 0))))))
17553 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17554 (goto-char pos)
17555 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17556 (and (match-beginning 2) (throw 'exit nil))
17557 ;; count $$
17558 (while (re-search-backward "\\$\\$" lim t)
17559 (setq dd-on (not dd-on)))
17560 (goto-char pos)
17561 (if dd-on (cons "$$" m))))))
17563 (defun org-inside-latex-macro-p ()
17564 "Is point inside a LaTeX macro or its arguments?"
17565 (save-match-data
17566 (org-in-regexp
17567 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17569 (defun org-try-cdlatex-tab ()
17570 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17571 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17572 - inside a LaTeX fragment, or
17573 - after the first word in a line, where an abbreviation expansion could
17574 insert a LaTeX environment."
17575 (when org-cdlatex-mode
17576 (cond
17577 ;; Before any word on the line: No expansion possible.
17578 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17579 ;; Just after first word on the line: Expand it. Make sure it
17580 ;; cannot happen on headlines, though.
17581 ((save-excursion
17582 (skip-chars-backward "a-zA-Z0-9*")
17583 (skip-chars-backward " \t")
17584 (and (bolp) (not (org-at-heading-p))))
17585 (cdlatex-tab) t)
17586 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17588 (defun org-cdlatex-underscore-caret (&optional arg)
17589 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17590 Revert to the normal definition outside of these fragments."
17591 (interactive "P")
17592 (if (org-inside-LaTeX-fragment-p)
17593 (call-interactively 'cdlatex-sub-superscript)
17594 (let (org-cdlatex-mode)
17595 (call-interactively (key-binding (vector last-input-event))))))
17597 (defun org-cdlatex-math-modify (&optional arg)
17598 "Execute `cdlatex-math-modify' in LaTeX fragments.
17599 Revert to the normal definition outside of these fragments."
17600 (interactive "P")
17601 (if (org-inside-LaTeX-fragment-p)
17602 (call-interactively 'cdlatex-math-modify)
17603 (let (org-cdlatex-mode)
17604 (call-interactively (key-binding (vector last-input-event))))))
17606 (defvar org-latex-fragment-image-overlays nil
17607 "List of overlays carrying the images of latex fragments.")
17608 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17610 (defun org-remove-latex-fragment-image-overlays ()
17611 "Remove all overlays with LaTeX fragment images in current buffer."
17612 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17613 (setq org-latex-fragment-image-overlays nil))
17615 (defun org-preview-latex-fragment (&optional subtree)
17616 "Preview the LaTeX fragment at point, or all locally or globally.
17617 If the cursor is in a LaTeX fragment, create the image and overlay
17618 it over the source code. If there is no fragment at point, display
17619 all fragments in the current text, from one headline to the next. With
17620 prefix SUBTREE, display all fragments in the current subtree. With a
17621 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17622 the cursor is before the first headline,
17623 display all fragments in the buffer.
17624 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17625 (interactive "P")
17626 (unless buffer-file-name
17627 (error "Can't preview LaTeX fragment in a non-file buffer"))
17628 (org-remove-latex-fragment-image-overlays)
17629 (save-excursion
17630 (save-restriction
17631 (let (beg end at msg)
17632 (cond
17633 ((or (equal subtree '(16))
17634 (not (save-excursion
17635 (re-search-backward org-outline-regexp-bol nil t))))
17636 (setq beg (point-min) end (point-max)
17637 msg "Creating images for buffer...%s"))
17638 ((equal subtree '(4))
17639 (org-back-to-heading)
17640 (setq beg (point) end (org-end-of-subtree t)
17641 msg "Creating images for subtree...%s"))
17643 (if (setq at (org-inside-LaTeX-fragment-p))
17644 (goto-char (max (point-min) (- (cdr at) 2)))
17645 (org-back-to-heading))
17646 (setq beg (point) end (progn (outline-next-heading) (point))
17647 msg (if at "Creating image...%s"
17648 "Creating images for entry...%s"))))
17649 (message msg "")
17650 (narrow-to-region beg end)
17651 (goto-char beg)
17652 (org-format-latex
17653 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17654 (file-name-nondirectory
17655 buffer-file-name)))
17656 default-directory 'overlays msg at 'forbuffer
17657 org-latex-create-formula-image-program)
17658 (message msg "done. Use `C-c C-c' to remove images.")))))
17660 (defvar org-latex-regexps
17661 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17662 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17663 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17664 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17665 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17666 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17667 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17668 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17669 "Regular expressions for matching embedded LaTeX.")
17671 (defvar org-export-have-math nil) ;; dynamic scoping
17672 (defun org-format-latex (prefix &optional dir overlays msg at
17673 forbuffer processing-type)
17674 "Replace LaTeX fragments with links to an image, and produce images.
17675 Some of the options can be changed using the variable
17676 `org-format-latex-options'."
17677 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17678 (let* ((prefixnodir (file-name-nondirectory prefix))
17679 (absprefix (expand-file-name prefix dir))
17680 (todir (file-name-directory absprefix))
17681 (opt org-format-latex-options)
17682 (optnew org-format-latex-options)
17683 (matchers (plist-get opt :matchers))
17684 (re-list org-latex-regexps)
17685 (org-format-latex-header-extra
17686 (plist-get (org-infile-export-plist) :latex-header-extra))
17687 (cnt 0) txt hash link beg end re e checkdir
17688 string
17689 m n block-type block linkfile movefile ov)
17690 ;; Check the different regular expressions
17691 (while (setq e (pop re-list))
17692 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17693 block (if block-type "\n\n" ""))
17694 (when (member m matchers)
17695 (goto-char (point-min))
17696 (while (re-search-forward re nil t)
17697 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17698 (not (get-text-property (match-beginning n)
17699 'org-protected))
17700 (or (not overlays)
17701 (not (eq (get-char-property (match-beginning n)
17702 'org-overlay-type)
17703 'org-latex-overlay))))
17704 (setq org-export-have-math t)
17705 (cond
17706 ((eq processing-type 'verbatim)
17707 ;; Leave the text verbatim, just protect it
17708 (add-text-properties (match-beginning n) (match-end n)
17709 '(org-protected t)))
17710 ((eq processing-type 'mathjax)
17711 ;; Prepare for MathJax processing
17712 (setq string (match-string n))
17713 (if (member m '("$" "$1"))
17714 (save-excursion
17715 (delete-region (match-beginning n) (match-end n))
17716 (goto-char (match-beginning n))
17717 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17718 "\\)")
17719 '(org-protected t))))
17720 (add-text-properties (match-beginning n) (match-end n)
17721 '(org-protected t))))
17722 ((or (eq processing-type 'dvipng)
17723 (eq processing-type 'imagemagick))
17724 ;; Process to an image
17725 (setq txt (match-string n)
17726 beg (match-beginning n) end (match-end n)
17727 cnt (1+ cnt))
17728 (let ((face (face-at-point))
17729 (fg (plist-get opt :foreground))
17730 (bg (plist-get opt :background))
17731 print-length print-level) ; make sure full list is printed
17732 (when forbuffer
17733 ; Get the colors from the face at point
17734 (goto-char beg)
17735 (when (eq fg 'auto)
17736 (setq fg (face-attribute face :foreground nil 'default)))
17737 (when (eq bg 'auto)
17738 (setq bg (face-attribute face :background nil 'default)))
17739 (setq optnew (copy-sequence opt))
17740 (plist-put optnew :foreground fg)
17741 (plist-put optnew :background bg))
17742 (setq hash (sha1 (prin1-to-string
17743 (list org-format-latex-header
17744 org-format-latex-header-extra
17745 org-export-latex-default-packages-alist
17746 org-export-latex-packages-alist
17747 org-format-latex-options
17748 forbuffer txt fg bg)))
17749 linkfile (format "%s_%s.png" prefix hash)
17750 movefile (format "%s_%s.png" absprefix hash)))
17751 (setq link (concat block "[[file:" linkfile "]]" block))
17752 (if msg (message msg cnt))
17753 (goto-char beg)
17754 (unless checkdir ; make sure the directory exists
17755 (setq checkdir t)
17756 (or (file-directory-p todir) (make-directory todir t)))
17757 (unless (file-exists-p movefile)
17758 (org-create-formula-image
17759 txt movefile optnew forbuffer processing-type))
17760 (if overlays
17761 (progn
17762 (mapc (lambda (o)
17763 (if (eq (overlay-get o 'org-overlay-type)
17764 'org-latex-overlay)
17765 (delete-overlay o)))
17766 (overlays-in beg end))
17767 (setq ov (make-overlay beg end))
17768 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17769 (if (featurep 'xemacs)
17770 (progn
17771 (overlay-put ov 'invisible t)
17772 (overlay-put
17773 ov 'end-glyph
17774 (make-glyph (vector 'png :file movefile))))
17775 (overlay-put
17776 ov 'display
17777 (list 'image :type 'png :file movefile :ascent 'center)))
17778 (push ov org-latex-fragment-image-overlays)
17779 (goto-char end))
17780 (delete-region beg end)
17781 (insert (org-add-props link
17782 (list 'org-latex-src
17783 (replace-regexp-in-string
17784 "\"" "" txt)
17785 'org-latex-src-embed-type
17786 (if block-type 'paragraph 'character))))))
17787 ((eq processing-type 'mathml)
17788 ;; Process to MathML
17789 (unless (save-match-data (org-format-latex-mathml-available-p))
17790 (error "LaTeX to MathML converter not configured"))
17791 (setq txt (match-string n)
17792 beg (match-beginning n) end (match-end n)
17793 cnt (1+ cnt))
17794 (if msg (message msg cnt))
17795 (goto-char beg)
17796 (delete-region beg end)
17797 (insert (org-format-latex-as-mathml
17798 txt block-type prefix dir)))
17800 (error "Unknown conversion type %s for latex fragments"
17801 processing-type)))))))))
17803 (defun org-create-math-formula (latex-frag &optional mathml-file)
17804 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17805 Use `org-latex-to-mathml-convert-command'. If the conversion is
17806 sucessful, return the portion between \"<math...> </math>\"
17807 elements otherwise return nil. When MATHML-FILE is specified,
17808 write the results in to that file. When invoked as an
17809 interactive command, prompt for LATEX-FRAG, with initial value
17810 set to the current active region and echo the results for user
17811 inspection."
17812 (interactive (list (let ((frag (when (org-region-active-p)
17813 (buffer-substring-no-properties
17814 (region-beginning) (region-end)))))
17815 (read-string "LaTeX Fragment: " frag nil frag))))
17816 (unless latex-frag (error "Invalid latex-frag"))
17817 (let* ((tmp-in-file (file-relative-name
17818 (make-temp-name (expand-file-name "ltxmathml-in"))))
17819 (ignore (write-region latex-frag nil tmp-in-file))
17820 (tmp-out-file (file-relative-name
17821 (make-temp-name (expand-file-name "ltxmathml-out"))))
17822 (cmd (format-spec
17823 org-latex-to-mathml-convert-command
17824 `((?j . ,(shell-quote-argument
17825 (expand-file-name org-latex-to-mathml-jar-file)))
17826 (?I . ,(shell-quote-argument tmp-in-file))
17827 (?o . ,(shell-quote-argument tmp-out-file)))))
17828 mathml shell-command-output)
17829 (when (org-called-interactively-p 'any)
17830 (unless (org-format-latex-mathml-available-p)
17831 (error "LaTeX to MathML converter not configured")))
17832 (message "Running %s" cmd)
17833 (setq shell-command-output (shell-command-to-string cmd))
17834 (setq mathml
17835 (when (file-readable-p tmp-out-file)
17836 (with-current-buffer (find-file-noselect tmp-out-file t)
17837 (goto-char (point-min))
17838 (when (re-search-forward
17839 (concat
17840 (regexp-quote
17841 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17842 "\\(.\\|\n\\)*"
17843 (regexp-quote "</math>")) nil t)
17844 (prog1 (match-string 0) (kill-buffer))))))
17845 (cond
17846 (mathml
17847 (setq mathml
17848 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17849 (when mathml-file
17850 (write-region mathml nil mathml-file))
17851 (when (org-called-interactively-p 'any)
17852 (message mathml)))
17853 ((message "LaTeX to MathML conversion failed")
17854 (message shell-command-output)))
17855 (delete-file tmp-in-file)
17856 (when (file-exists-p tmp-out-file)
17857 (delete-file tmp-out-file))
17858 mathml))
17860 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17861 prefix &optional dir)
17862 "Use `org-create-math-formula' but check local cache first."
17863 (let* ((absprefix (expand-file-name prefix dir))
17864 (print-length nil) (print-level nil)
17865 (formula-id (concat
17866 "formula-"
17867 (sha1
17868 (prin1-to-string
17869 (list latex-frag
17870 org-latex-to-mathml-convert-command)))))
17871 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17872 (formula-cache-dir (file-name-directory formula-cache)))
17874 (unless (file-directory-p formula-cache-dir)
17875 (make-directory formula-cache-dir t))
17877 (unless (file-exists-p formula-cache)
17878 (org-create-math-formula latex-frag formula-cache))
17880 (if (file-exists-p formula-cache)
17881 ;; Successful conversion. Return the link to MathML file.
17882 (org-add-props
17883 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17884 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17885 'org-latex-src-embed-type (if latex-frag-type
17886 'paragraph 'character)))
17887 ;; Failed conversion. Return the LaTeX fragment verbatim
17888 (add-text-properties
17889 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17890 latex-frag)))
17892 (defun org-create-formula-image (string tofile options buffer &optional type)
17893 "Create an image from LaTeX source using dvipng or convert.
17894 This function calls either `org-create-formula-image-with-dvipng'
17895 or `org-create-formula-image-with-imagemagick' depending on the
17896 value of `org-latex-create-formula-image-program' or on the value
17897 of the optional TYPE variable.
17899 Note: ultimately these two function should be combined as they
17900 share a good deal of logic."
17901 (org-check-external-command
17902 "latex" "needed to convert LaTeX fragments to images")
17903 (funcall
17904 (case (or type org-latex-create-formula-image-program)
17905 ('dvipng
17906 (org-check-external-command
17907 "dvipng" "needed to convert LaTeX fragments to images")
17908 #'org-create-formula-image-with-dvipng)
17909 ('imagemagick
17910 (org-check-external-command
17911 "convert" "you need to install imagemagick")
17912 #'org-create-formula-image-with-imagemagick)
17913 (t (error
17914 "invalid value of `org-latex-create-formula-image-program'")))
17915 string tofile options buffer))
17917 ;; This function borrows from Ganesh Swami's latex2png.el
17918 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17919 "This calls dvipng."
17920 (require 'org-latex)
17921 (let* ((tmpdir (if (featurep 'xemacs)
17922 (temp-directory)
17923 temporary-file-directory))
17924 (texfilebase (make-temp-name
17925 (expand-file-name "orgtex" tmpdir)))
17926 (texfile (concat texfilebase ".tex"))
17927 (dvifile (concat texfilebase ".dvi"))
17928 (pngfile (concat texfilebase ".png"))
17929 (fnh (if (featurep 'xemacs)
17930 (font-height (face-font 'default))
17931 (face-attribute 'default :height nil)))
17932 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17933 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17934 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17935 "Black"))
17936 (bg (or (plist-get options (if buffer :background :html-background))
17937 "Transparent")))
17938 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17939 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17940 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17941 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17942 (with-temp-file texfile
17943 (insert (org-splice-latex-header
17944 org-format-latex-header
17945 org-export-latex-default-packages-alist
17946 org-export-latex-packages-alist t
17947 org-format-latex-header-extra))
17948 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17949 (require 'org-latex)
17950 (org-export-latex-fix-inputenc))
17951 (let ((dir default-directory))
17952 (condition-case nil
17953 (progn
17954 (cd tmpdir)
17955 (call-process "latex" nil nil nil texfile))
17956 (error nil))
17957 (cd dir))
17958 (if (not (file-exists-p dvifile))
17959 (progn (message "Failed to create dvi file from %s" texfile) nil)
17960 (condition-case nil
17961 (if (featurep 'xemacs)
17962 (call-process "dvipng" nil nil nil
17963 "-fg" fg "-bg" bg
17964 "-T" "tight"
17965 "-o" pngfile
17966 dvifile)
17967 (call-process "dvipng" nil nil nil
17968 "-fg" fg "-bg" bg
17969 "-D" dpi
17970 ;;"-x" scale "-y" scale
17971 "-T" "tight"
17972 "-o" pngfile
17973 dvifile))
17974 (error nil))
17975 (if (not (file-exists-p pngfile))
17976 (if org-format-latex-signal-error
17977 (error "Failed to create png file from %s" texfile)
17978 (message "Failed to create png file from %s" texfile)
17979 nil)
17980 ;; Use the requested file name and clean up
17981 (copy-file pngfile tofile 'replace)
17982 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17983 (if (file-exists-p (concat texfilebase e))
17984 (delete-file (concat texfilebase e))))
17985 pngfile))))
17987 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17988 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17989 "This calls convert, which is included into imagemagick."
17990 (require 'org-latex)
17991 (let* ((tmpdir (if (featurep 'xemacs)
17992 (temp-directory)
17993 temporary-file-directory))
17994 (texfilebase (make-temp-name
17995 (expand-file-name "orgtex" tmpdir)))
17996 (texfile (concat texfilebase ".tex"))
17997 (pdffile (concat texfilebase ".pdf"))
17998 (pngfile (concat texfilebase ".png"))
17999 (fnh (if (featurep 'xemacs)
18000 (font-height (face-font 'default))
18001 (face-attribute 'default :height nil)))
18002 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18003 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18004 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18005 "black"))
18006 (bg (or (plist-get options (if buffer :background :html-background))
18007 "white")))
18008 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18009 (setq fg (org-latex-color-format fg)))
18010 (if (eq bg 'default) (setq bg (org-latex-color :background))
18011 (setq bg (org-latex-color-format
18012 (if (string= bg "Transparent") "white" bg))))
18013 (with-temp-file texfile
18014 (insert (org-splice-latex-header
18015 org-format-latex-header
18016 org-export-latex-default-packages-alist
18017 org-export-latex-packages-alist t
18018 org-format-latex-header-extra))
18019 (insert "\n\\begin{document}\n"
18020 "\\definecolor{fg}{rgb}{" fg "}\n"
18021 "\\definecolor{bg}{rgb}{" bg "}\n"
18022 "\n\\pagecolor{bg}\n"
18023 "\n{\\color{fg}\n"
18024 string
18025 "\n}\n"
18026 "\n\\end{document}\n" )
18027 (require 'org-latex)
18028 (org-export-latex-fix-inputenc))
18029 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18030 (condition-case nil
18031 (progn
18032 (cd tmpdir)
18033 (setq cmds org-latex-to-pdf-process)
18034 (while cmds
18035 (setq latex-frags-cmds (pop cmds))
18036 (if (listp latex-frags-cmds)
18037 (setq cmds nil)
18038 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
18039 (while latex-frags-cmds
18040 (setq cmd (pop latex-frags-cmds))
18041 (while (string-match "%b" cmd)
18042 (setq cmd (replace-match
18043 (save-match-data
18044 (shell-quote-argument texfile))
18045 t t cmd)))
18046 (while (string-match "%f" cmd)
18047 (setq cmd (replace-match
18048 (save-match-data
18049 (shell-quote-argument (file-name-nondirectory texfile)))
18050 t t cmd)))
18051 (while (string-match "%o" cmd)
18052 (setq cmd (replace-match
18053 (save-match-data
18054 (shell-quote-argument (file-name-directory texfile)))
18055 t t cmd)))
18056 (setq cmd (split-string cmd))
18057 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18058 (error nil))
18059 (cd dir))
18060 (if (not (file-exists-p pdffile))
18061 (progn (message "Failed to create pdf file from %s" texfile) nil)
18062 (condition-case nil
18063 (if (featurep 'xemacs)
18064 (call-process "convert" nil nil nil
18065 "-density" "96"
18066 "-trim"
18067 "-antialias"
18068 pdffile
18069 "-quality" "100"
18070 ;; "-sharpen" "0x1.0"
18071 pngfile)
18072 (call-process "convert" nil nil nil
18073 "-density" dpi
18074 "-trim"
18075 "-antialias"
18076 pdffile
18077 "-quality" "100"
18078 ; "-sharpen" "0x1.0"
18079 pngfile))
18080 (error nil))
18081 (if (not (file-exists-p pngfile))
18082 (if org-format-latex-signal-error
18083 (error "Failed to create png file from %s" texfile)
18084 (message "Failed to create png file from %s" texfile)
18085 nil)
18086 ;; Use the requested file name and clean up
18087 (copy-file pngfile tofile 'replace)
18088 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18089 (if (file-exists-p (concat texfilebase e))
18090 (delete-file (concat texfilebase e))))
18091 pngfile))))
18093 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18094 "Fill a LaTeX header template TPL.
18095 In the template, the following place holders will be recognized:
18097 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18098 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18099 [PACKAGES] \\usepackage statements for PKG
18100 [NO-PACKAGES] do not include PKG
18101 [EXTRA] the string EXTRA
18102 [NO-EXTRA] do not include EXTRA
18104 For backward compatibility, if both the positive and the negative place
18105 holder is missing, the positive one (without the \"NO-\") will be
18106 assumed to be present at the end of the template.
18107 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18108 EXTRA is a string.
18109 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18110 (let (rpl (end ""))
18111 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18112 (setq rpl (if (or (match-end 1) (not def-pkg))
18113 "" (org-latex-packages-to-string def-pkg snippets-p t))
18114 tpl (replace-match rpl t t tpl))
18115 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18117 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18118 (setq rpl (if (or (match-end 1) (not pkg))
18119 "" (org-latex-packages-to-string pkg snippets-p t))
18120 tpl (replace-match rpl t t tpl))
18121 (if pkg (setq end
18122 (concat end "\n"
18123 (org-latex-packages-to-string pkg snippets-p)))))
18125 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18126 (setq rpl (if (or (match-end 1) (not extra))
18127 "" (concat extra "\n"))
18128 tpl (replace-match rpl t t tpl))
18129 (if (and extra (string-match "\\S-" extra))
18130 (setq end (concat end "\n" extra))))
18132 (if (string-match "\\S-" end)
18133 (concat tpl "\n" end)
18134 tpl)))
18136 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18137 "Turn an alist of packages into a string with the \\usepackage macros."
18138 (setq pkg (mapconcat (lambda(p)
18139 (cond
18140 ((stringp p) p)
18141 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18142 (format "%% Package %s omitted" (cadr p)))
18143 ((equal "" (car p))
18144 (format "\\usepackage{%s}" (cadr p)))
18146 (format "\\usepackage[%s]{%s}"
18147 (car p) (cadr p)))))
18149 "\n"))
18150 (if newline (concat pkg "\n") pkg))
18152 (defun org-dvipng-color (attr)
18153 "Return a RGB color specification for dvipng."
18154 (apply 'format "rgb %s %s %s"
18155 (mapcar 'org-normalize-color
18156 (if (featurep 'xemacs)
18157 (color-rgb-components
18158 (face-property 'default
18159 (cond ((eq attr :foreground) 'foreground)
18160 ((eq attr :background) 'background))))
18161 (color-values (face-attribute 'default attr nil))))))
18163 (defun org-dvipng-color-format (color-name)
18164 "Convert COLOR-NAME to a RGB color value for dvipng."
18165 (apply 'format "rgb %s %s %s"
18166 (mapcar 'org-normalize-color
18167 (color-values color-name))))
18169 (defun org-latex-color (attr)
18170 "Return a RGB color for the LaTeX color package."
18171 (apply 'format "%s,%s,%s"
18172 (mapcar 'org-normalize-color
18173 (if (featurep 'xemacs)
18174 (color-rgb-components
18175 (face-property 'default
18176 (cond ((eq attr :foreground) 'foreground)
18177 ((eq attr :background) 'background))))
18178 (color-values (face-attribute 'default attr nil))))))
18180 (defun org-latex-color-format (color-name)
18181 "Convert COLOR-NAME to a RGB color value."
18182 (apply 'format "%s,%s,%s"
18183 (mapcar 'org-normalize-color
18184 (color-values color-name))))
18186 (defun org-normalize-color (value)
18187 "Return string to be used as color value for an RGB component."
18188 (format "%g" (/ value 65535.0)))
18190 ;; Image display
18193 (defvar org-inline-image-overlays nil)
18194 (make-variable-buffer-local 'org-inline-image-overlays)
18196 (defun org-toggle-inline-images (&optional include-linked)
18197 "Toggle the display of inline images.
18198 INCLUDE-LINKED is passed to `org-display-inline-images'."
18199 (interactive "P")
18200 (if org-inline-image-overlays
18201 (progn
18202 (org-remove-inline-images)
18203 (message "Inline image display turned off"))
18204 (org-display-inline-images include-linked)
18205 (if (and (org-called-interactively-p)
18206 org-inline-image-overlays)
18207 (message "%d images displayed inline"
18208 (length org-inline-image-overlays))
18209 (message "No images to display inline"))))
18211 (defun org-redisplay-inline-images ()
18212 "Refresh the display of inline images."
18213 (interactive)
18214 (if (not org-inline-image-overlays)
18215 (org-toggle-inline-images)
18216 (org-toggle-inline-images)
18217 (org-toggle-inline-images)))
18219 (defun org-display-inline-images (&optional include-linked refresh beg end)
18220 "Display inline images.
18221 Normally only links without a description part are inlined, because this
18222 is how it will work for export. When INCLUDE-LINKED is set, also links
18223 with a description part will be inlined. This can be nice for a quick
18224 look at those images, but it does not reflect what exported files will look
18225 like.
18226 When REFRESH is set, refresh existing images between BEG and END.
18227 This will create new image displays only if necessary.
18228 BEG and END default to the buffer boundaries."
18229 (interactive "P")
18230 (unless refresh
18231 (org-remove-inline-images)
18232 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18233 (save-excursion
18234 (save-restriction
18235 (widen)
18236 (setq beg (or beg (point-min)) end (or end (point-max)))
18237 (goto-char beg)
18238 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18239 (substring (org-image-file-name-regexp) 0 -2)
18240 "\\)\\]" (if include-linked "" "\\]")))
18241 old file ov img type attrwidth width)
18242 (while (re-search-forward re end t)
18243 (setq old (get-char-property-and-overlay (match-beginning 1)
18244 'org-image-overlay)
18245 file (expand-file-name
18246 (concat (or (match-string 3) "") (match-string 4))))
18247 (when (image-type-available-p 'imagemagick)
18248 (setq attrwidth (if (or (listp org-image-actual-width)
18249 (null org-image-actual-width))
18250 (save-excursion
18251 (save-match-data
18252 (when (re-search-backward
18253 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18254 (save-excursion
18255 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18256 (string-to-number (match-string 1))))))
18257 width (cond ((eq org-image-actual-width t) nil)
18258 ((null org-image-actual-width) attrwidth)
18259 ((numberp org-image-actual-width)
18260 org-image-actual-width)
18261 ((listp org-image-actual-width)
18262 (or attrwidth (car org-image-actual-width))))
18263 type (if width 'imagemagick)))
18264 (when (file-exists-p file)
18265 (if (and (car-safe old) refresh)
18266 (image-refresh (overlay-get (cdr old) 'display))
18267 (setq img (save-match-data (create-image file type nil :width width)))
18268 (when img
18269 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18270 (overlay-put ov 'display img)
18271 (overlay-put ov 'face 'default)
18272 (overlay-put ov 'org-image-overlay t)
18273 (overlay-put ov 'modification-hooks
18274 (list 'org-display-inline-remove-overlay))
18275 (push ov org-inline-image-overlays)))))))))
18277 (define-obsolete-function-alias
18278 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18280 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18281 "Remove inline-display overlay if a corresponding region is modified."
18282 (let ((inhibit-modification-hooks t))
18283 (when (and ov after)
18284 (delete ov org-inline-image-overlays)
18285 (delete-overlay ov))))
18287 (defun org-remove-inline-images ()
18288 "Remove inline display of images."
18289 (interactive)
18290 (mapc 'delete-overlay org-inline-image-overlays)
18291 (setq org-inline-image-overlays nil))
18293 ;;;; Key bindings
18295 ;; Outline functions from `outline-mode-prefix-map'
18296 ;; that can be remapped in Org:
18297 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18298 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18299 (define-key org-mode-map [remap outline-forward-same-level]
18300 'org-forward-heading-same-level)
18301 (define-key org-mode-map [remap outline-backward-same-level]
18302 'org-backward-heading-same-level)
18303 (define-key org-mode-map [remap show-branches]
18304 'org-kill-note-or-show-branches)
18305 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18306 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18307 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18309 ;; Outline functions from `outline-mode-prefix-map' that can not
18310 ;; be remapped in Org:
18312 ;; - the column "key binding" shows whether the Outline function is still
18313 ;; available in Org mode on the same key that it has been bound to in
18314 ;; Outline mode:
18315 ;; - "overridden": key used for a different functionality in Org mode
18316 ;; - else: key still bound to the same Outline function in Org mode
18318 ;; | Outline function | key binding | Org replacement |
18319 ;; |------------------------------------+-------------+-----------------------|
18320 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18321 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18322 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18323 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18324 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18325 ;; | `show-entry' | overridden | no replacement |
18326 ;; | `show-children' | `C-c C-i' | visibility cycling |
18327 ;; | `show-branches' | `C-c C-k' | still same function |
18328 ;; | `show-subtree' | overridden | visibility cycling |
18329 ;; | `show-all' | overridden | no replacement |
18330 ;; | `hide-subtree' | overridden | visibility cycling |
18331 ;; | `hide-body' | overridden | no replacement |
18332 ;; | `hide-entry' | overridden | visibility cycling |
18333 ;; | `hide-leaves' | overridden | no replacement |
18334 ;; | `hide-sublevels' | overridden | no replacement |
18335 ;; | `hide-other' | overridden | no replacement |
18337 ;; Make `C-c C-x' a prefix key
18338 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18340 ;; TAB key with modifiers
18341 (org-defkey org-mode-map "\C-i" 'org-cycle)
18342 (org-defkey org-mode-map [(tab)] 'org-cycle)
18343 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18344 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18345 ;; The following line is necessary under Suse GNU/Linux
18346 (unless (featurep 'xemacs)
18347 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18348 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18349 (define-key org-mode-map [backtab] 'org-shifttab)
18351 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18352 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18353 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18355 ;; Cursor keys with modifiers
18356 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18357 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18358 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18359 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18361 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18362 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18363 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18364 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18366 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18367 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18368 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18369 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18371 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18372 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18373 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18374 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18376 ;; Babel keys
18377 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18378 (mapc (lambda (pair)
18379 (define-key org-babel-map (car pair) (cdr pair)))
18380 org-babel-key-bindings)
18382 ;;; Extra keys for tty access.
18383 ;; We only set them when really needed because otherwise the
18384 ;; menus don't show the simple keys
18386 (when (or org-use-extra-keys
18387 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18388 (not window-system))
18389 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18390 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18391 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18392 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18393 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18394 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18395 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18396 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18397 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18398 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18399 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18400 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18401 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18402 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18403 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18404 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18405 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18406 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18407 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18408 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18409 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18410 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18411 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18412 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18413 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18414 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18415 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18416 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18418 ;; All the other keys
18420 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18421 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18422 (if (boundp 'narrow-map)
18423 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18424 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18425 (if (boundp 'narrow-map)
18426 (org-defkey narrow-map "b" 'org-narrow-to-block)
18427 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18428 (if (boundp 'narrow-map)
18429 (org-defkey narrow-map "e" 'org-narrow-to-element)
18430 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18431 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18432 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18433 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18434 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18435 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18436 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18437 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18438 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18439 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18440 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18441 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18442 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18443 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18444 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18445 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18446 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18447 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18448 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18449 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18450 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18451 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18452 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18453 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18454 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18455 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18456 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18457 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18458 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18459 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18460 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18461 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18462 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18463 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18464 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18465 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18466 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18467 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18468 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18469 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18470 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18471 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18472 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18473 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18474 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18475 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18476 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18477 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18478 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18479 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18480 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18481 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18482 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18483 (org-defkey org-mode-map "\C-c^" 'org-sort)
18484 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18485 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18486 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18487 (org-defkey org-mode-map "\C-m" 'org-return)
18488 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18489 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18490 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18491 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18492 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18493 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18494 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18495 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18496 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18497 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18498 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18499 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18500 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18501 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18502 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18503 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18504 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18505 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18506 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18507 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18508 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18509 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18510 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18512 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18513 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18514 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18516 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18517 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18518 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18519 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18520 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18521 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18522 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18523 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18524 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18525 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18526 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18527 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18528 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18529 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18530 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18531 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18532 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18533 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18534 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18535 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18536 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18537 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18538 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18540 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18541 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18542 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18543 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18544 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18546 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18548 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18550 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18551 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18553 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18556 (when (featurep 'xemacs)
18557 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18560 (defconst org-speed-commands-default
18562 ("Outline Navigation")
18563 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18564 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18565 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18566 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18567 ("u" . (org-speed-move-safe 'outline-up-heading))
18568 ("j" . org-goto)
18569 ("g" . (org-refile t))
18570 ("Outline Visibility")
18571 ("c" . org-cycle)
18572 ("C" . org-shifttab)
18573 (" " . org-display-outline-path)
18574 ("=" . org-columns)
18575 ("Outline Structure Editing")
18576 ("U" . org-shiftmetaup)
18577 ("D" . org-shiftmetadown)
18578 ("r" . org-metaright)
18579 ("l" . org-metaleft)
18580 ("R" . org-shiftmetaright)
18581 ("L" . org-shiftmetaleft)
18582 ("i" . (progn (forward-char 1) (call-interactively
18583 'org-insert-heading-respect-content)))
18584 ("^" . org-sort)
18585 ("w" . org-refile)
18586 ("a" . org-archive-subtree-default-with-confirmation)
18587 ("." . org-mark-subtree)
18588 ("#" . org-toggle-comment)
18589 ("Clock Commands")
18590 ("I" . org-clock-in)
18591 ("O" . org-clock-out)
18592 ("Meta Data Editing")
18593 ("t" . org-todo)
18594 ("," . (org-priority))
18595 ("0" . (org-priority ?\ ))
18596 ("1" . (org-priority ?A))
18597 ("2" . (org-priority ?B))
18598 ("3" . (org-priority ?C))
18599 (":" . org-set-tags-command)
18600 ("e" . org-set-effort)
18601 ("E" . org-inc-effort)
18602 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18603 (org-entry-put (point) "APPT_WARNTIME" m)))
18604 ("Agenda Views etc")
18605 ("v" . org-agenda)
18606 ("/" . org-sparse-tree)
18607 ("Misc")
18608 ("o" . org-open-at-point)
18609 ("?" . org-speed-command-help)
18610 ("<" . (org-agenda-set-restriction-lock 'subtree))
18611 (">" . (org-agenda-remove-restriction-lock))
18613 "The default speed commands.")
18615 (defun org-print-speed-command (e)
18616 (if (> (length (car e)) 1)
18617 (progn
18618 (princ "\n")
18619 (princ (car e))
18620 (princ "\n")
18621 (princ (make-string (length (car e)) ?-))
18622 (princ "\n"))
18623 (princ (car e))
18624 (princ " ")
18625 (if (symbolp (cdr e))
18626 (princ (symbol-name (cdr e)))
18627 (prin1 (cdr e)))
18628 (princ "\n")))
18630 (defun org-speed-command-help ()
18631 "Show the available speed commands."
18632 (interactive)
18633 (if (not org-use-speed-commands)
18634 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18635 (with-output-to-temp-buffer "*Help*"
18636 (princ "User-defined Speed commands\n===========================\n")
18637 (mapc 'org-print-speed-command org-speed-commands-user)
18638 (princ "\n")
18639 (princ "Built-in Speed commands\n=======================\n")
18640 (mapc 'org-print-speed-command org-speed-commands-default))
18641 (with-current-buffer "*Help*"
18642 (setq truncate-lines t))))
18644 (defun org-speed-move-safe (cmd)
18645 "Execute CMD, but make sure that the cursor always ends up in a headline.
18646 If not, return to the original position and throw an error."
18647 (interactive)
18648 (let ((pos (point)))
18649 (call-interactively cmd)
18650 (unless (and (bolp) (org-at-heading-p))
18651 (goto-char pos)
18652 (error "Boundary reached while executing %s" cmd))))
18654 (defvar org-self-insert-command-undo-counter 0)
18656 (defvar org-table-auto-blank-field) ; defined in org-table.el
18657 (defvar org-speed-command nil)
18659 (define-obsolete-function-alias
18660 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18662 (defun org-speed-command-activate (keys)
18663 "Hook for activating single-letter speed commands.
18664 `org-speed-commands-default' specifies a minimal command set.
18665 Use `org-speed-commands-user' for further customization."
18666 (when (or (and (bolp) (looking-at org-outline-regexp))
18667 (and (functionp org-use-speed-commands)
18668 (funcall org-use-speed-commands)))
18669 (cdr (assoc keys (append org-speed-commands-user
18670 org-speed-commands-default)))))
18672 (define-obsolete-function-alias
18673 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18675 (defun org-babel-speed-command-activate (keys)
18676 "Hook for activating single-letter code block commands."
18677 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18678 (cdr (assoc keys org-babel-key-bindings))))
18680 (defcustom org-speed-command-hook
18681 '(org-speed-command-default-hook org-babel-speed-command-hook)
18682 "Hook for activating speed commands at strategic locations.
18683 Hook functions are called in sequence until a valid handler is
18684 found.
18686 Each hook takes a single argument, a user-pressed command key
18687 which is also a `self-insert-command' from the global map.
18689 Within the hook, examine the cursor position and the command key
18690 and return nil or a valid handler as appropriate. Handler could
18691 be one of an interactive command, a function, or a form.
18693 Set `org-use-speed-commands' to non-nil value to enable this
18694 hook. The default setting is `org-speed-command-activate'."
18695 :group 'org-structure
18696 :version "24.1"
18697 :type 'hook)
18699 (defun org-self-insert-command (N)
18700 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18701 If the cursor is in a table looking at whitespace, the whitespace is
18702 overwritten, and the table is not marked as requiring realignment."
18703 (interactive "p")
18704 (org-check-before-invisible-edit 'insert)
18705 (cond
18706 ((and org-use-speed-commands
18707 (setq org-speed-command
18708 (run-hook-with-args-until-success
18709 'org-speed-command-hook (this-command-keys))))
18710 (cond
18711 ((commandp org-speed-command)
18712 (setq this-command org-speed-command)
18713 (call-interactively org-speed-command))
18714 ((functionp org-speed-command)
18715 (funcall org-speed-command))
18716 ((and org-speed-command (listp org-speed-command))
18717 (eval org-speed-command))
18718 (t (let (org-use-speed-commands)
18719 (call-interactively 'org-self-insert-command)))))
18720 ((and
18721 (org-table-p)
18722 (progn
18723 ;; check if we blank the field, and if that triggers align
18724 (and (featurep 'org-table) org-table-auto-blank-field
18725 (member last-command
18726 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18727 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18728 ;; got extra space, this field does not determine column width
18729 (let (org-table-may-need-update) (org-table-blank-field))
18730 ;; no extra space, this field may determine column width
18731 (org-table-blank-field)))
18733 (eq N 1)
18734 (looking-at "[^|\n]* |"))
18735 (let (org-table-may-need-update)
18736 (goto-char (1- (match-end 0)))
18737 (backward-delete-char 1)
18738 (goto-char (match-beginning 0))
18739 (self-insert-command N)))
18741 (setq org-table-may-need-update t)
18742 (self-insert-command N)
18743 (org-fix-tags-on-the-fly)
18744 (if org-self-insert-cluster-for-undo
18745 (if (not (eq last-command 'org-self-insert-command))
18746 (setq org-self-insert-command-undo-counter 1)
18747 (if (>= org-self-insert-command-undo-counter 20)
18748 (setq org-self-insert-command-undo-counter 1)
18749 (and (> org-self-insert-command-undo-counter 0)
18750 buffer-undo-list (listp buffer-undo-list)
18751 (not (cadr buffer-undo-list)) ; remove nil entry
18752 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18753 (setq org-self-insert-command-undo-counter
18754 (1+ org-self-insert-command-undo-counter))))))))
18756 (defun org-check-before-invisible-edit (kind)
18757 "Check is editing if kind KIND would be dangerous with invisible text around.
18758 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18759 ;; First, try to get out of here as quickly as possible, to reduce overhead
18760 (if (and org-catch-invisible-edits
18761 (or (not (boundp 'visible-mode)) (not visible-mode))
18762 (or (get-char-property (point) 'invisible)
18763 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18764 ;; OK, we need to take a closer look
18765 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18766 (invisible-before-point (if (bobp) nil (get-char-property
18767 (1- (point)) 'invisible)))
18768 (border-and-ok-direction
18770 ;; Check if we are acting predictably before invisible text
18771 (and invisible-at-point (not invisible-before-point)
18772 (memq kind '(insert delete-backward)))
18773 ;; Check if we are acting predictably after invisible text
18774 ;; This works not well, and I have turned it off. It seems
18775 ;; better to always show and stop after invisible text.
18776 ;; (and (not invisible-at-point) invisible-before-point
18777 ;; (memq kind '(insert delete)))
18779 (when (or (memq invisible-at-point '(outline org-hide-block t))
18780 (memq invisible-before-point '(outline org-hide-block t)))
18781 (if (eq org-catch-invisible-edits 'error)
18782 (error "Editing in invisible areas is prohibited - make visible first"))
18783 (if (and org-custom-properties-overlays
18784 (y-or-n-p "Display invisible properties in this buffer? "))
18785 (org-toggle-custom-properties-visibility)
18786 ;; Make the area visible
18787 (save-excursion
18788 (if invisible-before-point
18789 (goto-char (previous-single-char-property-change
18790 (point) 'invisible)))
18791 (org-cycle))
18792 (cond
18793 ((eq org-catch-invisible-edits 'show)
18794 ;; That's it, we do the edit after showing
18795 (message
18796 "Unfolding invisible region around point before editing")
18797 (sit-for 1))
18798 ((and (eq org-catch-invisible-edits 'smart)
18799 border-and-ok-direction)
18800 (message "Unfolding invisible region around point before editing"))
18802 ;; Don't do the edit, make the user repeat it in full visibility
18803 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18805 (defun org-fix-tags-on-the-fly ()
18806 (when (and (equal (char-after (point-at-bol)) ?*)
18807 (org-at-heading-p))
18808 (org-align-tags-here org-tags-column)))
18810 (defun org-delete-backward-char (N)
18811 "Like `delete-backward-char', insert whitespace at field end in tables.
18812 When deleting backwards, in tables this function will insert whitespace in
18813 front of the next \"|\" separator, to keep the table aligned. The table will
18814 still be marked for re-alignment if the field did fill the entire column,
18815 because, in this case the deletion might narrow the column."
18816 (interactive "p")
18817 (save-match-data
18818 (org-check-before-invisible-edit 'delete-backward)
18819 (if (and (org-table-p)
18820 (eq N 1)
18821 (string-match "|" (buffer-substring (point-at-bol) (point)))
18822 (looking-at ".*?|"))
18823 (let ((pos (point))
18824 (noalign (looking-at "[^|\n\r]* |"))
18825 (c org-table-may-need-update))
18826 (backward-delete-char N)
18827 (if (not overwrite-mode)
18828 (progn
18829 (skip-chars-forward "^|")
18830 (insert " ")
18831 (goto-char (1- pos))))
18832 ;; noalign: if there were two spaces at the end, this field
18833 ;; does not determine the width of the column.
18834 (if noalign (setq org-table-may-need-update c)))
18835 (backward-delete-char N)
18836 (org-fix-tags-on-the-fly))))
18838 (defun org-delete-char (N)
18839 "Like `delete-char', but insert whitespace at field end in tables.
18840 When deleting characters, in tables this function will insert whitespace in
18841 front of the next \"|\" separator, to keep the table aligned. The table will
18842 still be marked for re-alignment if the field did fill the entire column,
18843 because, in this case the deletion might narrow the column."
18844 (interactive "p")
18845 (save-match-data
18846 (org-check-before-invisible-edit 'delete)
18847 (if (and (org-table-p)
18848 (not (bolp))
18849 (not (= (char-after) ?|))
18850 (eq N 1))
18851 (if (looking-at ".*?|")
18852 (let ((pos (point))
18853 (noalign (looking-at "[^|\n\r]* |"))
18854 (c org-table-may-need-update))
18855 (replace-match (concat
18856 (substring (match-string 0) 1 -1)
18857 " |"))
18858 (goto-char pos)
18859 ;; noalign: if there were two spaces at the end, this field
18860 ;; does not determine the width of the column.
18861 (if noalign (setq org-table-may-need-update c)))
18862 (delete-char N))
18863 (delete-char N)
18864 (org-fix-tags-on-the-fly))))
18866 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18867 (put 'org-self-insert-command 'delete-selection t)
18868 (put 'orgtbl-self-insert-command 'delete-selection t)
18869 (put 'org-delete-char 'delete-selection 'supersede)
18870 (put 'org-delete-backward-char 'delete-selection 'supersede)
18871 (put 'org-yank 'delete-selection 'yank)
18873 ;; Make `flyspell-mode' delay after some commands
18874 (put 'org-self-insert-command 'flyspell-delayed t)
18875 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18876 (put 'org-delete-char 'flyspell-delayed t)
18877 (put 'org-delete-backward-char 'flyspell-delayed t)
18879 ;; Make pabbrev-mode expand after org-mode commands
18880 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18881 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18883 ;; How to do this: Measure non-white length of current string
18884 ;; If equal to column width, we should realign.
18886 (defun org-remap (map &rest commands)
18887 "In MAP, remap the functions given in COMMANDS.
18888 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18889 (let (new old)
18890 (while commands
18891 (setq old (pop commands) new (pop commands))
18892 (if (fboundp 'command-remapping)
18893 (org-defkey map (vector 'remap old) new)
18894 (substitute-key-definition old new map global-map)))))
18896 (when (eq org-enable-table-editor 'optimized)
18897 ;; If the user wants maximum table support, we need to hijack
18898 ;; some standard editing functions
18899 (org-remap org-mode-map
18900 'self-insert-command 'org-self-insert-command
18901 'delete-char 'org-delete-char
18902 'delete-backward-char 'org-delete-backward-char)
18903 (org-defkey org-mode-map "|" 'org-force-self-insert))
18905 (defvar org-ctrl-c-ctrl-c-hook nil
18906 "Hook for functions attaching themselves to `C-c C-c'.
18908 This can be used to add additional functionality to the C-c C-c
18909 key which executes context-dependent commands. This hook is run
18910 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18911 run after the last test.
18913 Each function will be called with no arguments. The function
18914 must check if the context is appropriate for it to act. If yes,
18915 it should do its thing and then return a non-nil value. If the
18916 context is wrong, just do nothing and return nil.")
18918 (defvar org-ctrl-c-ctrl-c-final-hook nil
18919 "Hook for functions attaching themselves to `C-c C-c'.
18921 This can be used to add additional functionality to the C-c C-c
18922 key which executes context-dependent commands. This hook is run
18923 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18924 before the first test.
18926 Each function will be called with no arguments. The function
18927 must check if the context is appropriate for it to act. If yes,
18928 it should do its thing and then return a non-nil value. If the
18929 context is wrong, just do nothing and return nil.")
18931 (defvar org-tab-first-hook nil
18932 "Hook for functions to attach themselves to TAB.
18933 See `org-ctrl-c-ctrl-c-hook' for more information.
18934 This hook runs as the first action when TAB is pressed, even before
18935 `org-cycle' messes around with the `outline-regexp' to cater for
18936 inline tasks and plain list item folding.
18937 If any function in this hook returns t, any other actions that
18938 would have been caused by TAB (such as table field motion or visibility
18939 cycling) will not occur.")
18941 (defvar org-tab-after-check-for-table-hook nil
18942 "Hook for functions to attach themselves to TAB.
18943 See `org-ctrl-c-ctrl-c-hook' for more information.
18944 This hook runs after it has been established that the cursor is not in a
18945 table, but before checking if the cursor is in a headline or if global cycling
18946 should be done.
18947 If any function in this hook returns t, not other actions like visibility
18948 cycling will be done.")
18950 (defvar org-tab-after-check-for-cycling-hook nil
18951 "Hook for functions to attach themselves to TAB.
18952 See `org-ctrl-c-ctrl-c-hook' for more information.
18953 This hook runs after it has been established that not table field motion and
18954 not visibility should be done because of current context. This is probably
18955 the place where a package like yasnippets can hook in.")
18957 (defvar org-tab-before-tab-emulation-hook nil
18958 "Hook for functions to attach themselves to TAB.
18959 See `org-ctrl-c-ctrl-c-hook' for more information.
18960 This hook runs after every other options for TAB have been exhausted, but
18961 before indentation and \t insertion takes place.")
18963 (defvar org-metaleft-hook nil
18964 "Hook for functions attaching themselves to `M-left'.
18965 See `org-ctrl-c-ctrl-c-hook' for more information.")
18966 (defvar org-metaright-hook nil
18967 "Hook for functions attaching themselves to `M-right'.
18968 See `org-ctrl-c-ctrl-c-hook' for more information.")
18969 (defvar org-metaup-hook nil
18970 "Hook for functions attaching themselves to `M-up'.
18971 See `org-ctrl-c-ctrl-c-hook' for more information.")
18972 (defvar org-metadown-hook nil
18973 "Hook for functions attaching themselves to `M-down'.
18974 See `org-ctrl-c-ctrl-c-hook' for more information.")
18975 (defvar org-shiftmetaleft-hook nil
18976 "Hook for functions attaching themselves to `M-S-left'.
18977 See `org-ctrl-c-ctrl-c-hook' for more information.")
18978 (defvar org-shiftmetaright-hook nil
18979 "Hook for functions attaching themselves to `M-S-right'.
18980 See `org-ctrl-c-ctrl-c-hook' for more information.")
18981 (defvar org-shiftmetaup-hook nil
18982 "Hook for functions attaching themselves to `M-S-up'.
18983 See `org-ctrl-c-ctrl-c-hook' for more information.")
18984 (defvar org-shiftmetadown-hook nil
18985 "Hook for functions attaching themselves to `M-S-down'.
18986 See `org-ctrl-c-ctrl-c-hook' for more information.")
18987 (defvar org-metareturn-hook nil
18988 "Hook for functions attaching themselves to `M-RET'.
18989 See `org-ctrl-c-ctrl-c-hook' for more information.")
18990 (defvar org-shiftup-hook nil
18991 "Hook for functions attaching themselves to `S-up'.
18992 See `org-ctrl-c-ctrl-c-hook' for more information.")
18993 (defvar org-shiftup-final-hook nil
18994 "Hook for functions attaching themselves to `S-up'.
18995 This one runs after all other options except shift-select have been excluded.
18996 See `org-ctrl-c-ctrl-c-hook' for more information.")
18997 (defvar org-shiftdown-hook nil
18998 "Hook for functions attaching themselves to `S-down'.
18999 See `org-ctrl-c-ctrl-c-hook' for more information.")
19000 (defvar org-shiftdown-final-hook nil
19001 "Hook for functions attaching themselves to `S-down'.
19002 This one runs after all other options except shift-select have been excluded.
19003 See `org-ctrl-c-ctrl-c-hook' for more information.")
19004 (defvar org-shiftleft-hook nil
19005 "Hook for functions attaching themselves to `S-left'.
19006 See `org-ctrl-c-ctrl-c-hook' for more information.")
19007 (defvar org-shiftleft-final-hook nil
19008 "Hook for functions attaching themselves to `S-left'.
19009 This one runs after all other options except shift-select have been excluded.
19010 See `org-ctrl-c-ctrl-c-hook' for more information.")
19011 (defvar org-shiftright-hook nil
19012 "Hook for functions attaching themselves to `S-right'.
19013 See `org-ctrl-c-ctrl-c-hook' for more information.")
19014 (defvar org-shiftright-final-hook nil
19015 "Hook for functions attaching themselves to `S-right'.
19016 This one runs after all other options except shift-select have been excluded.
19017 See `org-ctrl-c-ctrl-c-hook' for more information.")
19019 (defun org-modifier-cursor-error ()
19020 "Throw an error, a modified cursor command was applied in wrong context."
19021 (error "This command is active in special context like tables, headlines or items"))
19023 (defun org-shiftselect-error ()
19024 "Throw an error because Shift-Cursor command was applied in wrong context."
19025 (if (and (boundp 'shift-select-mode) shift-select-mode)
19026 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19027 (error "This command works only in special context like headlines or timestamps")))
19029 (defun org-call-for-shift-select (cmd)
19030 (let ((this-command-keys-shift-translated t))
19031 (call-interactively cmd)))
19033 (defun org-shifttab (&optional arg)
19034 "Global visibility cycling or move to previous table field.
19035 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19036 on context.
19037 See the individual commands for more information."
19038 (interactive "P")
19039 (cond
19040 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19041 ((integerp arg)
19042 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19043 (message "Content view to level: %d" arg)
19044 (org-content (prefix-numeric-value arg2))
19045 (setq org-cycle-global-status 'overview)))
19046 (t (call-interactively 'org-global-cycle))))
19048 (defun org-shiftmetaleft ()
19049 "Promote subtree or delete table column.
19050 Calls `org-promote-subtree', `org-outdent-item-tree', or
19051 `org-table-delete-column', depending on context. See the
19052 individual commands for more information."
19053 (interactive)
19054 (cond
19055 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19056 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19057 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19058 ((if (not (org-region-active-p)) (org-at-item-p)
19059 (save-excursion (goto-char (region-beginning))
19060 (org-at-item-p)))
19061 (call-interactively 'org-outdent-item-tree))
19062 (t (org-modifier-cursor-error))))
19064 (defun org-shiftmetaright ()
19065 "Demote subtree or insert table column.
19066 Calls `org-demote-subtree', `org-indent-item-tree', or
19067 `org-table-insert-column', depending on context. See the
19068 individual commands for more information."
19069 (interactive)
19070 (cond
19071 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19072 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19073 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19074 ((if (not (org-region-active-p)) (org-at-item-p)
19075 (save-excursion (goto-char (region-beginning))
19076 (org-at-item-p)))
19077 (call-interactively 'org-indent-item-tree))
19078 (t (org-modifier-cursor-error))))
19080 (defun org-shiftmetaup (&optional arg)
19081 "Move subtree up or kill table row.
19082 Calls `org-move-subtree-up' or `org-table-kill-row' or
19083 `org-move-item-up' or `org-timestamp-up', depending on context.
19084 See the individual commands for more information."
19085 (interactive "P")
19086 (cond
19087 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19088 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19089 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19090 ((org-at-item-p) (call-interactively 'org-move-item-up))
19091 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19092 (call-interactively 'org-timestamp-up)))
19093 (t (org-modifier-cursor-error))))
19095 (defun org-shiftmetadown (&optional arg)
19096 "Move subtree down or insert table row.
19097 Calls `org-move-subtree-down' or `org-table-insert-row' or
19098 `org-move-item-down' or `org-timestamp-up', depending on context.
19099 See the individual commands for more information."
19100 (interactive "P")
19101 (cond
19102 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19103 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19104 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19105 ((org-at-item-p) (call-interactively 'org-move-item-down))
19106 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19107 (call-interactively 'org-timestamp-down)))
19108 (t (org-modifier-cursor-error))))
19110 (defsubst org-hidden-tree-error ()
19111 (error
19112 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19114 (defun org-metaleft (&optional arg)
19115 "Promote heading or move table column to left.
19116 Calls `org-do-promote' or `org-table-move-column', depending on context.
19117 With no specific context, calls the Emacs default `backward-word'.
19118 See the individual commands for more information."
19119 (interactive "P")
19120 (cond
19121 ((run-hook-with-args-until-success 'org-metaleft-hook))
19122 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19123 ((org-with-limited-levels
19124 (or (org-at-heading-p)
19125 (and (org-region-active-p)
19126 (save-excursion
19127 (goto-char (region-beginning))
19128 (org-at-heading-p)))))
19129 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19130 (call-interactively 'org-do-promote))
19131 ;; At an inline task.
19132 ((org-at-heading-p)
19133 (call-interactively 'org-inlinetask-promote))
19134 ((or (org-at-item-p)
19135 (and (org-region-active-p)
19136 (save-excursion
19137 (goto-char (region-beginning))
19138 (org-at-item-p))))
19139 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19140 (call-interactively 'org-outdent-item))
19141 (t (call-interactively 'backward-word))))
19143 (defun org-metaright (&optional arg)
19144 "Demote a subtree, a list item or move table column to right.
19145 In front of a drawer or a block keyword, indent it correctly.
19146 With no specific context, calls the Emacs default `forward-word'.
19147 See the individual commands for more information."
19148 (interactive "P")
19149 (cond
19150 ((run-hook-with-args-until-success 'org-metaright-hook))
19151 ((org-at-table-p) (call-interactively 'org-table-move-column))
19152 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19153 ((org-at-block-p) (call-interactively 'org-indent-block))
19154 ((org-with-limited-levels
19155 (or (org-at-heading-p)
19156 (and (org-region-active-p)
19157 (save-excursion
19158 (goto-char (region-beginning))
19159 (org-at-heading-p)))))
19160 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19161 (call-interactively 'org-do-demote))
19162 ;; At an inline task.
19163 ((org-at-heading-p)
19164 (call-interactively 'org-inlinetask-demote))
19165 ((or (org-at-item-p)
19166 (and (org-region-active-p)
19167 (save-excursion
19168 (goto-char (region-beginning))
19169 (org-at-item-p))))
19170 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19171 (call-interactively 'org-indent-item))
19172 (t (call-interactively 'forward-word))))
19174 (defun org-check-for-hidden (what)
19175 "Check if there are hidden headlines/items in the current visual line.
19176 WHAT can be either `headlines' or `items'. If the current line is
19177 an outline or item heading and it has a folded subtree below it,
19178 this function returns t, nil otherwise."
19179 (let ((re (cond
19180 ((eq what 'headlines) org-outline-regexp-bol)
19181 ((eq what 'items) (org-item-beginning-re))
19182 (t (error "This should not happen"))))
19183 beg end)
19184 (save-excursion
19185 (catch 'exit
19186 (unless (org-region-active-p)
19187 (setq beg (point-at-bol))
19188 (beginning-of-line 2)
19189 (while (and (not (eobp)) ;; this is like `next-line'
19190 (get-char-property (1- (point)) 'invisible))
19191 (beginning-of-line 2))
19192 (setq end (point))
19193 (goto-char beg)
19194 (goto-char (point-at-eol))
19195 (setq end (max end (point)))
19196 (while (re-search-forward re end t)
19197 (if (get-char-property (match-beginning 0) 'invisible)
19198 (throw 'exit t))))
19199 nil))))
19201 (defun org-metaup (&optional arg)
19202 "Move subtree up or move table row up.
19203 Calls `org-move-subtree-up' or `org-table-move-row' or
19204 `org-move-item-up', depending on context. See the individual commands
19205 for more information."
19206 (interactive "P")
19207 (cond
19208 ((run-hook-with-args-until-success 'org-metaup-hook))
19209 ((org-region-active-p)
19210 (let* ((a (min (region-beginning) (region-end)))
19211 (b (1- (max (region-beginning) (region-end))))
19212 (c (save-excursion (goto-char a)
19213 (move-beginning-of-line 0)))
19214 (d (save-excursion (goto-char a)
19215 (move-end-of-line 0) (point))))
19216 (transpose-regions a b c d)
19217 (goto-char c)))
19218 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19219 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19220 ((org-at-item-p) (call-interactively 'org-move-item-up))
19221 (t (org-drag-element-backward))))
19223 (defun org-metadown (&optional arg)
19224 "Move subtree down or move table row down.
19225 Calls `org-move-subtree-down' or `org-table-move-row' or
19226 `org-move-item-down', depending on context. See the individual
19227 commands for more information."
19228 (interactive "P")
19229 (cond
19230 ((run-hook-with-args-until-success 'org-metadown-hook))
19231 ((org-region-active-p)
19232 (let* ((a (min (region-beginning) (region-end)))
19233 (b (max (region-beginning) (region-end)))
19234 (c (save-excursion (goto-char b)
19235 (move-beginning-of-line 1)))
19236 (d (save-excursion (goto-char b)
19237 (move-end-of-line 1) (1+ (point)))))
19238 (transpose-regions a b c d)
19239 (goto-char d)))
19240 ((org-at-table-p) (call-interactively 'org-table-move-row))
19241 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19242 ((org-at-item-p) (call-interactively 'org-move-item-down))
19243 (t (org-drag-element-forward))))
19245 (defun org-shiftup (&optional arg)
19246 "Increase item in timestamp or increase priority of current headline.
19247 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19248 depending on context. See the individual commands for more information."
19249 (interactive "P")
19250 (cond
19251 ((run-hook-with-args-until-success 'org-shiftup-hook))
19252 ((and org-support-shift-select (org-region-active-p))
19253 (org-call-for-shift-select 'previous-line))
19254 ((org-at-timestamp-p t)
19255 (call-interactively (if org-edit-timestamp-down-means-later
19256 'org-timestamp-down 'org-timestamp-up)))
19257 ((and (not (eq org-support-shift-select 'always))
19258 org-enable-priority-commands
19259 (org-at-heading-p))
19260 (call-interactively 'org-priority-up))
19261 ((and (not org-support-shift-select) (org-at-item-p))
19262 (call-interactively 'org-previous-item))
19263 ((org-clocktable-try-shift 'up arg))
19264 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19265 (org-support-shift-select
19266 (org-call-for-shift-select 'previous-line))
19267 (t (org-shiftselect-error))))
19269 (defun org-shiftdown (&optional arg)
19270 "Decrease item in timestamp or decrease priority of current headline.
19271 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19272 depending on context. See the individual commands for more information."
19273 (interactive "P")
19274 (cond
19275 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19276 ((and org-support-shift-select (org-region-active-p))
19277 (org-call-for-shift-select 'next-line))
19278 ((org-at-timestamp-p t)
19279 (call-interactively (if org-edit-timestamp-down-means-later
19280 'org-timestamp-up 'org-timestamp-down)))
19281 ((and (not (eq org-support-shift-select 'always))
19282 org-enable-priority-commands
19283 (org-at-heading-p))
19284 (call-interactively 'org-priority-down))
19285 ((and (not org-support-shift-select) (org-at-item-p))
19286 (call-interactively 'org-next-item))
19287 ((org-clocktable-try-shift 'down arg))
19288 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19289 (org-support-shift-select
19290 (org-call-for-shift-select 'next-line))
19291 (t (org-shiftselect-error))))
19293 (defun org-shiftright (&optional arg)
19294 "Cycle the thing at point or in the current line, depending on context.
19295 Depending on context, this does one of the following:
19297 - switch a timestamp at point one day into the future
19298 - on a headline, switch to the next TODO keyword.
19299 - on an item, switch entire list to the next bullet type
19300 - on a property line, switch to the next allowed value
19301 - on a clocktable definition line, move time block into the future"
19302 (interactive "P")
19303 (cond
19304 ((run-hook-with-args-until-success 'org-shiftright-hook))
19305 ((and org-support-shift-select (org-region-active-p))
19306 (org-call-for-shift-select 'forward-char))
19307 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19308 ((and (not (eq org-support-shift-select 'always))
19309 (org-at-heading-p))
19310 (let ((org-inhibit-logging
19311 (not org-treat-S-cursor-todo-selection-as-state-change))
19312 (org-inhibit-blocking
19313 (not org-treat-S-cursor-todo-selection-as-state-change)))
19314 (org-call-with-arg 'org-todo 'right)))
19315 ((or (and org-support-shift-select
19316 (not (eq org-support-shift-select 'always))
19317 (org-at-item-bullet-p))
19318 (and (not org-support-shift-select) (org-at-item-p)))
19319 (org-call-with-arg 'org-cycle-list-bullet nil))
19320 ((and (not (eq org-support-shift-select 'always))
19321 (org-at-property-p))
19322 (call-interactively 'org-property-next-allowed-value))
19323 ((org-clocktable-try-shift 'right arg))
19324 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19325 (org-support-shift-select
19326 (org-call-for-shift-select 'forward-char))
19327 (t (org-shiftselect-error))))
19329 (defun org-shiftleft (&optional arg)
19330 "Cycle the thing at point or in the current line, depending on context.
19331 Depending on context, this does one of the following:
19333 - switch a timestamp at point one day into the past
19334 - on a headline, switch to the previous TODO keyword.
19335 - on an item, switch entire list to the previous bullet type
19336 - on a property line, switch to the previous allowed value
19337 - on a clocktable definition line, move time block into the past"
19338 (interactive "P")
19339 (cond
19340 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19341 ((and org-support-shift-select (org-region-active-p))
19342 (org-call-for-shift-select 'backward-char))
19343 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19344 ((and (not (eq org-support-shift-select 'always))
19345 (org-at-heading-p))
19346 (let ((org-inhibit-logging
19347 (not org-treat-S-cursor-todo-selection-as-state-change))
19348 (org-inhibit-blocking
19349 (not org-treat-S-cursor-todo-selection-as-state-change)))
19350 (org-call-with-arg 'org-todo 'left)))
19351 ((or (and org-support-shift-select
19352 (not (eq org-support-shift-select 'always))
19353 (org-at-item-bullet-p))
19354 (and (not org-support-shift-select) (org-at-item-p)))
19355 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19356 ((and (not (eq org-support-shift-select 'always))
19357 (org-at-property-p))
19358 (call-interactively 'org-property-previous-allowed-value))
19359 ((org-clocktable-try-shift 'left arg))
19360 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19361 (org-support-shift-select
19362 (org-call-for-shift-select 'backward-char))
19363 (t (org-shiftselect-error))))
19365 (defun org-shiftcontrolright ()
19366 "Switch to next TODO set."
19367 (interactive)
19368 (cond
19369 ((and org-support-shift-select (org-region-active-p))
19370 (org-call-for-shift-select 'forward-word))
19371 ((and (not (eq org-support-shift-select 'always))
19372 (org-at-heading-p))
19373 (org-call-with-arg 'org-todo 'nextset))
19374 (org-support-shift-select
19375 (org-call-for-shift-select 'forward-word))
19376 (t (org-shiftselect-error))))
19378 (defun org-shiftcontrolleft ()
19379 "Switch to previous TODO set."
19380 (interactive)
19381 (cond
19382 ((and org-support-shift-select (org-region-active-p))
19383 (org-call-for-shift-select 'backward-word))
19384 ((and (not (eq org-support-shift-select 'always))
19385 (org-at-heading-p))
19386 (org-call-with-arg 'org-todo 'previousset))
19387 (org-support-shift-select
19388 (org-call-for-shift-select 'backward-word))
19389 (t (org-shiftselect-error))))
19391 (defun org-shiftcontrolup (&optional n)
19392 "Change timestamps synchronously up in CLOCK log lines.
19393 Optional argument N tells to change by that many units."
19394 (interactive "P")
19395 (cond ((and (not org-support-shift-select)
19396 (org-at-clock-log-p)
19397 (org-at-timestamp-p t))
19398 (org-clock-timestamps-up n))
19399 (t (org-shiftselect-error))))
19401 (defun org-shiftcontroldown (&optional n)
19402 "Change timestamps synchronously down in CLOCK log lines.
19403 Optional argument N tells to change by that many units."
19404 (interactive "P")
19405 (cond ((and (not org-support-shift-select)
19406 (org-at-clock-log-p)
19407 (org-at-timestamp-p t))
19408 (org-clock-timestamps-down n))
19409 (t (org-shiftselect-error))))
19411 (defun org-ctrl-c-ret ()
19412 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19413 (interactive)
19414 (cond
19415 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19416 (t (call-interactively 'org-insert-heading))))
19418 (defun org-find-visible ()
19419 (let ((s (point)))
19420 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19421 (get-char-property s 'invisible)))
19423 (defun org-find-invisible ()
19424 (let ((s (point)))
19425 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19426 (not (get-char-property s 'invisible))))
19429 (defun org-copy-visible (beg end)
19430 "Copy the visible parts of the region."
19431 (interactive "r")
19432 (let (snippets s)
19433 (save-excursion
19434 (save-restriction
19435 (narrow-to-region beg end)
19436 (setq s (goto-char (point-min)))
19437 (while (not (= (point) (point-max)))
19438 (goto-char (org-find-invisible))
19439 (push (buffer-substring s (point)) snippets)
19440 (setq s (goto-char (org-find-visible))))))
19441 (kill-new (apply 'concat (nreverse snippets)))))
19443 (defun org-copy-special ()
19444 "Copy region in table or copy current subtree.
19445 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19446 See the individual commands for more information."
19447 (interactive)
19448 (call-interactively
19449 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19451 (defun org-cut-special ()
19452 "Cut region in table or cut current subtree.
19453 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19454 See the individual commands for more information."
19455 (interactive)
19456 (call-interactively
19457 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19459 (defun org-paste-special (arg)
19460 "Paste rectangular region into table, or past subtree relative to level.
19461 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19462 See the individual commands for more information."
19463 (interactive "P")
19464 (if (org-at-table-p)
19465 (org-table-paste-rectangle)
19466 (org-paste-subtree arg)))
19468 (defsubst org-in-fixed-width-region-p ()
19469 "Is point in a fixed-width region?"
19470 (save-match-data
19471 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19473 (defun org-edit-special (&optional arg)
19474 "Call a special editor for the element at point.
19475 When at a table, call the formula editor with `org-table-edit-formulas'.
19476 When in a source code block, call `org-edit-src-code'.
19477 When in a fixed-width region, call `org-edit-fixed-width-region'.
19478 When at an #+INCLUDE keyword, visit the included file.
19479 On a link, call `ffap' to visit the link at point.
19480 Otherwise, return a user error."
19481 (interactive)
19482 (let ((element (org-element-at-point)))
19483 (case (org-element-type element)
19484 (src-block
19485 (if (not arg) (org-edit-src-code)
19486 (let* ((info (org-babel-get-src-block-info))
19487 (lang (nth 0 info))
19488 (params (nth 2 info))
19489 (session (cdr (assq :session params))))
19490 (if (not session) (org-edit-src-code)
19491 ;; At a src-block with a session and function called with
19492 ;; an ARG: switch to the buffer related to the inferior
19493 ;; process.
19494 (funcall (intern (concat "org-babel-prep-session:" lang))
19495 session params)))))
19496 (keyword
19497 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19498 (find-file
19499 (org-remove-double-quotes
19500 (car (org-split-string (org-element-property :value element)))))
19501 (user-error "No special environment to edit here")))
19502 (table
19503 (if (eq (org-element-property :type element) 'table.el)
19504 (org-edit-src-code)
19505 (call-interactively 'org-table-edit-formulas)))
19506 ;; Only Org tables contain `table-row' type elements.
19507 (table-row (call-interactively 'org-table-edit-formulas))
19508 ((example-block export-block) (org-edit-src-code))
19509 (fixed-width (org-edit-fixed-width-region))
19510 (otherwise
19511 ;; No notable element at point. Though, we may be at a link,
19512 ;; which is an object. Thus, scan deeper.
19513 (if (eq (org-element-type (org-element-context element)) 'link)
19514 (call-interactively 'ffap)
19515 (user-error "No special environment to edit here"))))))
19517 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19518 (defun org-ctrl-c-ctrl-c (&optional arg)
19519 "Set tags in headline, or update according to changed information at point.
19521 This command does many different things, depending on context:
19523 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19524 this is what we do.
19526 - If the cursor is on a statistics cookie, update it.
19528 - If the cursor is in a headline, prompt for tags and insert them
19529 into the current line, aligned to `org-tags-column'. When called
19530 with prefix arg, realign all tags in the current buffer.
19532 - If the cursor is in one of the special #+KEYWORD lines, this
19533 triggers scanning the buffer for these lines and updating the
19534 information.
19536 - If the cursor is inside a table, realign the table. This command
19537 works even if the automatic table editor has been turned off.
19539 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19540 the entire table.
19542 - If the cursor is at a footnote reference or definition, jump to
19543 the corresponding definition or references, respectively.
19545 - If the cursor is a the beginning of a dynamic block, update it.
19547 - If the current buffer is a capture buffer, close note and file it.
19549 - If the cursor is on a <<<target>>>, update radio targets and
19550 corresponding links in this buffer.
19552 - If the cursor is on a numbered item in a plain list, renumber the
19553 ordered list.
19555 - If the cursor is on a checkbox, toggle it.
19557 - If the cursor is on a code block, evaluate it. The variable
19558 `org-confirm-babel-evaluate' can be used to control prompting
19559 before code block evaluation, by default every code block
19560 evaluation requires confirmation. Code block evaluation can be
19561 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19562 (interactive "P")
19563 (cond
19564 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19565 org-occur-highlights
19566 org-latex-fragment-image-overlays)
19567 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19568 (org-remove-occur-highlights)
19569 (org-remove-latex-fragment-image-overlays)
19570 (message "Temporary highlights/overlays removed from current buffer"))
19571 ((and (local-variable-p 'org-finish-function (current-buffer))
19572 (fboundp org-finish-function))
19573 (funcall org-finish-function))
19574 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19576 (let* ((context (org-element-context)) (type (org-element-type context)))
19577 ;; Test if point is within blanks at the end of an element.
19578 (if (save-excursion
19579 (or (not context)
19580 (beginning-of-line)
19581 (and (looking-at "[ \t]*$")
19582 (skip-chars-forward " \r\t\n")
19583 (>= (point) (org-element-property :end context)))))
19584 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19585 (user-error "C-c C-c can do nothing useful at this location"))
19586 ;; For convenience: at the first line of a paragraph on the
19587 ;; same line as an item, apply function on that item instead.
19588 (when (eq type 'paragraph)
19589 (let ((parent (org-element-property :parent context)))
19590 (when (and (eq (org-element-type parent) 'item)
19591 (= (point-at-bol) (org-element-property :begin parent)))
19592 (setq context parent type 'item))))
19593 ;; Act according to type of element or object at point.
19594 (case type
19595 (clock (org-clock-update-time-maybe))
19596 (dynamic-block
19597 (save-excursion
19598 (goto-char (org-element-property :post-affiliated context))
19599 (org-update-dblock)))
19600 (footnote-definition
19601 (goto-char (org-element-property :post-affiliated context))
19602 (call-interactively 'org-footnote-action))
19603 (footnote-reference (call-interactively 'org-footnote-action))
19604 ((headline inlinetask)
19605 (save-excursion (goto-char (org-element-property :begin context))
19606 (call-interactively 'org-set-tags)))
19607 (item
19608 ;; At an item: a double C-u set checkbox to "[-]"
19609 ;; unconditionally, whereas a single one will toggle its
19610 ;; presence. Without an universal argument, if the item
19611 ;; has a checkbox, toggle it. Otherwise repair the list.
19612 (let* ((box (org-element-property :checkbox context))
19613 (struct (org-element-property :structure context))
19614 (old-struct (copy-tree struct))
19615 (parents (org-list-parents-alist struct))
19616 (prevs (org-list-prevs-alist struct))
19617 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19618 (org-list-set-checkbox
19619 (org-element-property :begin context) struct
19620 (cond ((equal arg '(16)) "[-]")
19621 ((and (not box) (equal arg '(4))) "[ ]")
19622 ((or (not box) (equal arg '(4))) nil)
19623 ((eq box 'on) "[ ]")
19624 (t "[X]")))
19625 ;; Mimic `org-list-write-struct' but with grabbing
19626 ;; a return value from `org-list-struct-fix-box'.
19627 (org-list-struct-fix-ind struct parents 2)
19628 (org-list-struct-fix-item-end struct)
19629 (org-list-struct-fix-bul struct prevs)
19630 (org-list-struct-fix-ind struct parents)
19631 (let ((block-item
19632 (org-list-struct-fix-box struct parents prevs orderedp)))
19633 (if (and box (equal struct old-struct))
19634 (if (equal arg '(16))
19635 (message "Checkboxes already reset")
19636 (user-error "Cannot toggle this checkbox: %s"
19637 (if (eq box 'on)
19638 "all subitems checked"
19639 "unchecked subitems")))
19640 (org-list-struct-apply-struct struct old-struct)
19641 (org-update-checkbox-count-maybe))
19642 (when block-item
19643 (message "Checkboxes were removed due to empty box at line %d"
19644 (org-current-line block-item))))))
19645 (keyword
19646 (let ((org-inhibit-startup-visibility-stuff t)
19647 (org-startup-align-all-tables nil))
19648 (when (boundp 'org-table-coordinate-overlays)
19649 (mapc 'delete-overlay org-table-coordinate-overlays)
19650 (setq org-table-coordinate-overlays nil))
19651 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19652 (message "Local setup has been refreshed"))
19653 (plain-list
19654 ;; At a plain list, with a double C-u argument, set
19655 ;; checkboxes of each item to "[-]", whereas a single one
19656 ;; will toggle their presence according to the state of the
19657 ;; first item in the list. Without an argument, repair the
19658 ;; list.
19659 (let* ((begin (org-element-property :contents-begin context))
19660 (struct (org-element-property :structure context))
19661 (old-struct (copy-tree struct))
19662 (first-box (save-excursion
19663 (goto-char begin)
19664 (looking-at org-list-full-item-re)
19665 (match-string-no-properties 3)))
19666 (new-box (cond ((equal arg '(16)) "[-]")
19667 ((equal arg '(4)) (unless first-box "[ ]"))
19668 ((equal first-box "[X]") "[ ]")
19669 (t "[X]"))))
19670 (cond
19671 (arg
19672 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19673 (org-list-get-all-items
19674 begin struct (org-list-prevs-alist struct))))
19675 ((and first-box (eq (point) begin))
19676 ;; For convenience, when point is at bol on the first
19677 ;; item of the list and no argument is provided, simply
19678 ;; toggle checkbox of that item, if any.
19679 (org-list-set-checkbox begin struct new-box)))
19680 (org-list-write-struct
19681 struct (org-list-parents-alist struct) old-struct)
19682 (org-update-checkbox-count-maybe)
19683 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19684 ((property-drawer node-property)
19685 (call-interactively 'org-property-action))
19686 ((radio-target target)
19687 (call-interactively 'org-update-radio-target-regexp))
19688 (statistics-cookie
19689 (call-interactively 'org-update-statistics-cookies))
19690 ((table table-cell table-row)
19691 ;; At a table, recalculate every field and align it. Also
19692 ;; send the table if necessary. If the table has
19693 ;; a `table.el' type, just give up. At a table row or
19694 ;; cell, maybe recalculate line but always align table.
19695 (if (eq (org-element-property :type context) 'table.el)
19696 (message "Use C-c ' to edit table.el tables")
19697 (let ((org-enable-table-editor t))
19698 (if (or (eq type 'table)
19699 ;; Check if point is at a TBLFM line.
19700 (and (eq type 'table-row)
19701 (= (point) (org-element-property :end context))))
19702 (save-excursion
19703 (goto-char (org-element-property :contents-begin context))
19704 (org-call-with-arg 'org-table-recalculate (or arg t))
19705 (orgtbl-send-table 'maybe))
19706 (org-table-maybe-eval-formula)
19707 (cond (arg (call-interactively 'org-table-recalculate))
19708 ((org-table-maybe-recalculate-line))
19709 (t (org-table-align)))))))
19710 (timestamp (org-timestamp-change 0 'day))
19711 (otherwise
19712 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19713 (user-error
19714 "C-c C-c can do nothing useful at this location")))))))))
19716 (defun org-mode-restart ()
19717 "Restart Org-mode, to scan again for special lines.
19718 Also updates the keyword regular expressions."
19719 (interactive)
19720 (org-mode)
19721 (message "Org-mode restarted"))
19723 (defun org-kill-note-or-show-branches ()
19724 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19725 (interactive)
19726 (if (not org-finish-function)
19727 (progn
19728 (hide-subtree)
19729 (call-interactively 'show-branches))
19730 (let ((org-note-abort t))
19731 (funcall org-finish-function))))
19733 (defun org-return (&optional indent)
19734 "Goto next table row or insert a newline.
19735 Calls `org-table-next-row' or `newline', depending on context.
19736 See the individual commands for more information."
19737 (interactive)
19738 (let (org-ts-what)
19739 (cond
19740 ((or (bobp) (org-in-src-block-p))
19741 (if indent (newline-and-indent) (newline)))
19742 ((org-at-table-p)
19743 (org-table-justify-field-maybe)
19744 (call-interactively 'org-table-next-row))
19745 ;; when `newline-and-indent' is called within a list, make sure
19746 ;; text moved stays inside the item.
19747 ((and (org-in-item-p) indent)
19748 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19749 (progn
19750 (save-match-data (newline))
19751 (org-indent-line-to (length (match-string 0))))
19752 (let ((ind (org-get-indentation)))
19753 (newline)
19754 (if (org-looking-back org-list-end-re)
19755 (org-indent-line)
19756 (org-indent-line-to ind)))))
19757 ((and org-return-follows-link
19758 (org-at-timestamp-p t)
19759 (not (eq org-ts-what 'after)))
19760 (org-follow-timestamp-link))
19761 ((and org-return-follows-link
19762 (let ((tprop (get-text-property (point) 'face)))
19763 (or (eq tprop 'org-link)
19764 (and (listp tprop) (memq 'org-link tprop)))))
19765 (call-interactively 'org-open-at-point))
19766 ((and (org-at-heading-p)
19767 (looking-at
19768 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19769 (org-show-entry)
19770 (end-of-line 1)
19771 (newline))
19772 (t (if indent (newline-and-indent) (newline))))))
19774 (defun org-return-indent ()
19775 "Goto next table row or insert a newline and indent.
19776 Calls `org-table-next-row' or `newline-and-indent', depending on
19777 context. See the individual commands for more information."
19778 (interactive)
19779 (org-return t))
19781 (defun org-ctrl-c-star ()
19782 "Compute table, or change heading status of lines.
19783 Calls `org-table-recalculate' or `org-toggle-heading',
19784 depending on context."
19785 (interactive)
19786 (cond
19787 ((org-at-table-p)
19788 (call-interactively 'org-table-recalculate))
19790 ;; Convert all lines in region to list items
19791 (call-interactively 'org-toggle-heading))))
19793 (defun org-ctrl-c-minus ()
19794 "Insert separator line in table or modify bullet status of line.
19795 Also turns a plain line or a region of lines into list items.
19796 Calls `org-table-insert-hline', `org-toggle-item', or
19797 `org-cycle-list-bullet', depending on context."
19798 (interactive)
19799 (cond
19800 ((org-at-table-p)
19801 (call-interactively 'org-table-insert-hline))
19802 ((org-region-active-p)
19803 (call-interactively 'org-toggle-item))
19804 ((org-in-item-p)
19805 (call-interactively 'org-cycle-list-bullet))
19807 (call-interactively 'org-toggle-item))))
19809 (defun org-toggle-item (arg)
19810 "Convert headings or normal lines to items, items to normal lines.
19811 If there is no active region, only the current line is considered.
19813 If the first non blank line in the region is an headline, convert
19814 all headlines to items, shifting text accordingly.
19816 If it is an item, convert all items to normal lines.
19818 If it is normal text, change region into an item. With a prefix
19819 argument ARG, change each line in region into an item."
19820 (interactive "P")
19821 (let ((shift-text
19822 (function
19823 ;; Shift text in current section to IND, from point to END.
19824 ;; The function leaves point to END line.
19825 (lambda (ind end)
19826 (let ((min-i 1000) (end (copy-marker end)))
19827 ;; First determine the minimum indentation (MIN-I) of
19828 ;; the text.
19829 (save-excursion
19830 (catch 'exit
19831 (while (< (point) end)
19832 (let ((i (org-get-indentation)))
19833 (cond
19834 ;; Skip blank lines and inline tasks.
19835 ((looking-at "^[ \t]*$"))
19836 ((looking-at org-outline-regexp-bol))
19837 ;; We can't find less than 0 indentation.
19838 ((zerop i) (throw 'exit (setq min-i 0)))
19839 ((< i min-i) (setq min-i i))))
19840 (forward-line))))
19841 ;; Then indent each line so that a line indented to
19842 ;; MIN-I becomes indented to IND. Ignore blank lines
19843 ;; and inline tasks in the process.
19844 (let ((delta (- ind min-i)))
19845 (while (< (point) end)
19846 (unless (or (looking-at "^[ \t]*$")
19847 (looking-at org-outline-regexp-bol))
19848 (org-indent-line-to (+ (org-get-indentation) delta)))
19849 (forward-line)))))))
19850 (skip-blanks
19851 (function
19852 ;; Return beginning of first non-blank line, starting from
19853 ;; line at POS.
19854 (lambda (pos)
19855 (save-excursion
19856 (goto-char pos)
19857 (skip-chars-forward " \r\t\n")
19858 (point-at-bol)))))
19859 beg end)
19860 ;; Determine boundaries of changes.
19861 (if (org-region-active-p)
19862 (setq beg (funcall skip-blanks (region-beginning))
19863 end (copy-marker (region-end)))
19864 (setq beg (funcall skip-blanks (point-at-bol))
19865 end (copy-marker (point-at-eol))))
19866 ;; Depending on the starting line, choose an action on the text
19867 ;; between BEG and END.
19868 (org-with-limited-levels
19869 (save-excursion
19870 (goto-char beg)
19871 (cond
19872 ;; Case 1. Start at an item: de-itemize. Note that it only
19873 ;; happens when a region is active: `org-ctrl-c-minus'
19874 ;; would call `org-cycle-list-bullet' otherwise.
19875 ((org-at-item-p)
19876 (while (< (point) end)
19877 (when (org-at-item-p)
19878 (skip-chars-forward " \t")
19879 (delete-region (point) (match-end 0)))
19880 (forward-line)))
19881 ;; Case 2. Start at an heading: convert to items.
19882 ((org-at-heading-p)
19883 (let* ((bul (org-list-bullet-string "-"))
19884 (bul-len (length bul))
19885 ;; Indentation of the first heading. It should be
19886 ;; relative to the indentation of its parent, if any.
19887 (start-ind (save-excursion
19888 (cond
19889 ((not org-adapt-indentation) 0)
19890 ((not (outline-previous-heading)) 0)
19891 (t (length (match-string 0))))))
19892 ;; Level of first heading. Further headings will be
19893 ;; compared to it to determine hierarchy in the list.
19894 (ref-level (org-reduced-level (org-outline-level))))
19895 (while (< (point) end)
19896 (let* ((level (org-reduced-level (org-outline-level)))
19897 (delta (max 0 (- level ref-level))))
19898 ;; If current headline is less indented than the first
19899 ;; one, set it as reference, in order to preserve
19900 ;; subtrees.
19901 (when (< level ref-level) (setq ref-level level))
19902 (replace-match bul t t)
19903 (org-indent-line-to (+ start-ind (* delta bul-len)))
19904 ;; Ensure all text down to END (or SECTION-END) belongs
19905 ;; to the newly created item.
19906 (let ((section-end (save-excursion
19907 (or (outline-next-heading) (point)))))
19908 (forward-line)
19909 (funcall shift-text
19910 (+ start-ind (* (1+ delta) bul-len))
19911 (min end section-end)))))))
19912 ;; Case 3. Normal line with ARG: turn each non-item line into
19913 ;; an item.
19914 (arg
19915 (while (< (point) end)
19916 (unless (or (org-at-heading-p) (org-at-item-p))
19917 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19918 (replace-match
19919 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19920 (forward-line)))
19921 ;; Case 4. Normal line without ARG: make the first line of
19922 ;; region an item, and shift indentation of others
19923 ;; lines to set them as item's body.
19924 (t (let* ((bul (org-list-bullet-string "-"))
19925 (bul-len (length bul))
19926 (ref-ind (org-get-indentation)))
19927 (skip-chars-forward " \t")
19928 (insert bul)
19929 (forward-line)
19930 (while (< (point) end)
19931 ;; Ensure that lines less indented than first one
19932 ;; still get included in item body.
19933 (funcall shift-text
19934 (+ ref-ind bul-len)
19935 (min end (save-excursion (or (outline-next-heading)
19936 (point)))))
19937 (forward-line)))))))))
19939 (defun org-toggle-heading (&optional nstars)
19940 "Convert headings to normal text, or items or text to headings.
19941 If there is no active region, only the current line is considered.
19943 With a \\[universal-argument] prefix, convert the whole list at
19944 point into heading.
19946 In a region:
19948 - If the first non blank line is an headline, remove the stars
19949 from all headlines in the region.
19951 - If it is a normal line turn each and every normal line (i.e. not an
19952 heading or an item) in the region into a heading.
19954 - If it is a plain list item, turn all plain list items into headings.
19956 When converting a line into a heading, the number of stars is chosen
19957 such that the lines become children of the current entry. However,
19958 when a prefix argument is given, its value determines the number of
19959 stars to add."
19960 (interactive "P")
19961 (let ((skip-blanks
19962 (function
19963 ;; Return beginning of first non-blank line, starting from
19964 ;; line at POS.
19965 (lambda (pos)
19966 (save-excursion
19967 (goto-char pos)
19968 (while (org-at-comment-p) (forward-line))
19969 (skip-chars-forward " \r\t\n")
19970 (point-at-bol)))))
19971 beg end toggled)
19972 ;; Determine boundaries of changes. If a universal prefix has
19973 ;; been given, put the list in a region. If region ends at a bol,
19974 ;; do not consider the last line to be in the region.
19976 (when (and current-prefix-arg (org-at-item-p))
19977 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19978 (org-mark-element))
19980 (if (org-region-active-p)
19981 (setq beg (funcall skip-blanks (region-beginning))
19982 end (copy-marker (save-excursion
19983 (goto-char (region-end))
19984 (if (bolp) (point) (point-at-eol)))))
19985 (setq beg (funcall skip-blanks (point-at-bol))
19986 end (copy-marker (point-at-eol))))
19987 ;; Ensure inline tasks don't count as headings.
19988 (org-with-limited-levels
19989 (save-excursion
19990 (goto-char beg)
19991 (cond
19992 ;; Case 1. Started at an heading: de-star headings.
19993 ((org-at-heading-p)
19994 (while (< (point) end)
19995 (when (org-at-heading-p t)
19996 (looking-at org-outline-regexp) (replace-match "")
19997 (setq toggled t))
19998 (forward-line)))
19999 ;; Case 2. Started at an item: change items into headlines.
20000 ;; One star will be added by `org-list-to-subtree'.
20001 ((org-at-item-p)
20002 (let* ((stars (make-string
20003 (if nstars
20004 ;; subtract the star that will be added again by
20005 ;; `org-list-to-subtree'
20006 (1- (prefix-numeric-value current-prefix-arg))
20007 (or (org-current-level) 0))
20008 ?*))
20009 (add-stars
20010 (cond (nstars "") ; stars from prefix only
20011 ((equal stars "") "") ; before first heading
20012 (org-odd-levels-only "*") ; inside heading, odd
20013 (t "")))) ; inside heading, oddeven
20014 (while (< (point) end)
20015 (when (org-at-item-p)
20016 ;; Pay attention to cases when region ends before list.
20017 (let* ((struct (org-list-struct))
20018 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20019 (save-restriction
20020 (narrow-to-region (point) list-end)
20021 (insert
20022 (org-list-to-subtree
20023 (org-list-parse-list t)
20024 '(:istart (concat stars add-stars (funcall get-stars depth))
20025 :icount (concat stars add-stars (funcall get-stars depth)))))))
20026 (setq toggled t))
20027 (forward-line))))
20028 ;; Case 3. Started at normal text: make every line an heading,
20029 ;; skipping headlines and items.
20030 (t (let* ((stars (make-string
20031 (if nstars
20032 (prefix-numeric-value current-prefix-arg)
20033 (or (org-current-level) 0))
20034 ?*))
20035 (add-stars
20036 (cond (nstars "") ; stars from prefix only
20037 ((equal stars "") "*") ; before first heading
20038 (org-odd-levels-only "**") ; inside heading, odd
20039 (t "*"))) ; inside heading, oddeven
20040 (rpl (concat stars add-stars " ")))
20041 (while (< (point) end)
20042 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20043 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20044 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20045 (forward-line)))))))
20046 (unless toggled (message "Cannot toggle heading from here"))))
20048 (defun org-meta-return (&optional arg)
20049 "Insert a new heading or wrap a region in a table.
20050 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20051 See the individual commands for more information."
20052 (interactive "P")
20053 (cond
20054 ((run-hook-with-args-until-success 'org-metareturn-hook))
20055 ((or (org-at-drawer-p) (org-at-property-p))
20056 (newline-and-indent))
20057 ((org-at-table-p)
20058 (call-interactively 'org-table-wrap-region))
20059 (t (call-interactively 'org-insert-heading))))
20061 ;;; Menu entries
20063 (defsubst org-in-subtree-not-table-p ()
20064 "Are we in a subtree and not in a table?"
20065 (and (not (org-before-first-heading-p))
20066 (not (org-at-table-p))))
20068 ;; Define the Org-mode menus
20069 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20070 '("Tbl"
20071 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20072 ["Next Field" org-cycle (org-at-table-p)]
20073 ["Previous Field" org-shifttab (org-at-table-p)]
20074 ["Next Row" org-return (org-at-table-p)]
20075 "--"
20076 ["Blank Field" org-table-blank-field (org-at-table-p)]
20077 ["Edit Field" org-table-edit-field (org-at-table-p)]
20078 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20079 "--"
20080 ("Column"
20081 ["Move Column Left" org-metaleft (org-at-table-p)]
20082 ["Move Column Right" org-metaright (org-at-table-p)]
20083 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20084 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20085 ("Row"
20086 ["Move Row Up" org-metaup (org-at-table-p)]
20087 ["Move Row Down" org-metadown (org-at-table-p)]
20088 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20089 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20090 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20091 "--"
20092 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20093 ("Rectangle"
20094 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20095 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20096 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20097 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20098 "--"
20099 ("Calculate"
20100 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20101 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20102 ["Edit Formulas" org-edit-special (org-at-table-p)]
20103 "--"
20104 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20105 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20106 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20107 "--"
20108 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20109 "--"
20110 ["Sum Column/Rectangle" org-table-sum
20111 (or (org-at-table-p) (org-region-active-p))]
20112 ["Which Column?" org-table-current-column (org-at-table-p)])
20113 ["Debug Formulas"
20114 org-table-toggle-formula-debugger
20115 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20116 ["Show Col/Row Numbers"
20117 org-table-toggle-coordinate-overlays
20118 :style toggle
20119 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20120 "--"
20121 ["Create" org-table-create (and (not (org-at-table-p))
20122 org-enable-table-editor)]
20123 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20124 ["Import from File" org-table-import (not (org-at-table-p))]
20125 ["Export to File" org-table-export (org-at-table-p)]
20126 "--"
20127 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20129 (easy-menu-define org-org-menu org-mode-map "Org menu"
20130 '("Org"
20131 ("Show/Hide"
20132 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20133 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20134 ["Sparse Tree..." org-sparse-tree t]
20135 ["Reveal Context" org-reveal t]
20136 ["Show All" show-all t]
20137 "--"
20138 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20139 "--"
20140 ["New Heading" org-insert-heading t]
20141 ("Navigate Headings"
20142 ["Up" outline-up-heading t]
20143 ["Next" outline-next-visible-heading t]
20144 ["Previous" outline-previous-visible-heading t]
20145 ["Next Same Level" outline-forward-same-level t]
20146 ["Previous Same Level" outline-backward-same-level t]
20147 "--"
20148 ["Jump" org-goto t])
20149 ("Edit Structure"
20150 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20151 "--"
20152 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20153 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20154 "--"
20155 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20156 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20157 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20158 "--"
20159 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20160 "--"
20161 ["Copy visible text" org-copy-visible t]
20162 "--"
20163 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20164 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20165 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20166 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20167 "--"
20168 ["Sort Region/Children" org-sort t]
20169 "--"
20170 ["Convert to odd levels" org-convert-to-odd-levels t]
20171 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20172 ("Editing"
20173 ["Emphasis..." org-emphasize t]
20174 ["Edit Source Example" org-edit-special t]
20175 "--"
20176 ["Footnote new/jump" org-footnote-action t]
20177 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20178 ("Archive"
20179 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20180 "--"
20181 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20182 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20183 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20185 "--"
20186 ("Hyperlinks"
20187 ["Store Link (Global)" org-store-link t]
20188 ["Find existing link to here" org-occur-link-in-agenda-files t]
20189 ["Insert Link" org-insert-link t]
20190 ["Follow Link" org-open-at-point t]
20191 "--"
20192 ["Next link" org-next-link t]
20193 ["Previous link" org-previous-link t]
20194 "--"
20195 ["Descriptive Links"
20196 org-toggle-link-display
20197 :style radio
20198 :selected org-descriptive-links
20200 ["Literal Links"
20201 org-toggle-link-display
20202 :style radio
20203 :selected (not org-descriptive-links)])
20204 "--"
20205 ("TODO Lists"
20206 ["TODO/DONE/-" org-todo t]
20207 ("Select keyword"
20208 ["Next keyword" org-shiftright (org-at-heading-p)]
20209 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20210 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20211 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20212 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20213 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20214 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20215 "--"
20216 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20217 :selected org-enforce-todo-dependencies :style toggle :active t]
20218 "Settings for tree at point"
20219 ["Do Children sequentially" org-toggle-ordered-property :style radio
20220 :selected (org-entry-get nil "ORDERED")
20221 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20222 ["Do Children parallel" org-toggle-ordered-property :style radio
20223 :selected (not (org-entry-get nil "ORDERED"))
20224 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20225 "--"
20226 ["Set Priority" org-priority t]
20227 ["Priority Up" org-shiftup t]
20228 ["Priority Down" org-shiftdown t]
20229 "--"
20230 ["Get news from all feeds" org-feed-update-all t]
20231 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20232 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20233 ("TAGS and Properties"
20234 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20235 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20236 "--"
20237 ["Set property" org-set-property (not (org-before-first-heading-p))]
20238 ["Column view of properties" org-columns t]
20239 ["Insert Column View DBlock" org-insert-columns-dblock t])
20240 ("Dates and Scheduling"
20241 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20242 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20243 ("Change Date"
20244 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20245 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20246 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20247 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20248 ["Compute Time Range" org-evaluate-time-range t]
20249 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20250 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20251 "--"
20252 ["Custom time format" org-toggle-time-stamp-overlays
20253 :style radio :selected org-display-custom-times]
20254 "--"
20255 ["Goto Calendar" org-goto-calendar t]
20256 ["Date from Calendar" org-date-from-calendar t]
20257 "--"
20258 ["Start/Restart Timer" org-timer-start t]
20259 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20260 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20261 ["Insert Timer String" org-timer t]
20262 ["Insert Timer Item" org-timer-item t])
20263 ("Logging work"
20264 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20265 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20266 ["Clock out" org-clock-out t]
20267 ["Clock cancel" org-clock-cancel t]
20268 "--"
20269 ["Mark as default task" org-clock-mark-default-task t]
20270 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20271 ["Goto running clock" org-clock-goto t]
20272 "--"
20273 ["Display times" org-clock-display t]
20274 ["Create clock table" org-clock-report t]
20275 "--"
20276 ["Record DONE time"
20277 (progn (setq org-log-done (not org-log-done))
20278 (message "Switching to %s will %s record a timestamp"
20279 (car org-done-keywords)
20280 (if org-log-done "automatically" "not")))
20281 :style toggle :selected org-log-done])
20282 "--"
20283 ["Agenda Command..." org-agenda t]
20284 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20285 ("File List for Agenda")
20286 ("Special views current file"
20287 ["TODO Tree" org-show-todo-tree t]
20288 ["Check Deadlines" org-check-deadlines t]
20289 ["Timeline" org-timeline t]
20290 ["Tags/Property tree" org-match-sparse-tree t])
20291 "--"
20292 ["Export/Publish..." org-export t]
20293 ("LaTeX"
20294 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20295 :selected org-cdlatex-mode]
20296 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20297 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20298 ["Modify math symbol" org-cdlatex-math-modify
20299 (org-inside-LaTeX-fragment-p)]
20300 ["Insert citation" org-reftex-citation t]
20301 "--"
20302 ["Template for BEAMER" (progn (require 'org-beamer)
20303 (org-insert-beamer-options-template)) t])
20304 "--"
20305 ("MobileOrg"
20306 ["Push Files and Views" org-mobile-push t]
20307 ["Get Captured and Flagged" org-mobile-pull t]
20308 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20309 "--"
20310 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20311 "--"
20312 ("Documentation"
20313 ["Show Version" org-version t]
20314 ["Info Documentation" org-info t])
20315 ("Customize"
20316 ["Browse Org Group" org-customize t]
20317 "--"
20318 ["Expand This Menu" org-create-customize-menu
20319 (fboundp 'customize-menu-create)])
20320 ["Send bug report" org-submit-bug-report t]
20321 "--"
20322 ("Refresh/Reload"
20323 ["Refresh setup current buffer" org-mode-restart t]
20324 ["Reload Org (after update)" org-reload t]
20325 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20328 (defun org-info (&optional node)
20329 "Read documentation for Org-mode in the info system.
20330 With optional NODE, go directly to that node."
20331 (interactive)
20332 (info (format "(org)%s" (or node ""))))
20334 ;;;###autoload
20335 (defun org-submit-bug-report ()
20336 "Submit a bug report on Org-mode via mail.
20338 Don't hesitate to report any problems or inaccurate documentation.
20340 If you don't have setup sending mail from (X)Emacs, please copy the
20341 output buffer into your mail program, as it gives us important
20342 information about your Org-mode version and configuration."
20343 (interactive)
20344 (require 'reporter)
20345 (org-load-modules-maybe)
20346 (org-require-autoloaded-modules)
20347 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20348 (reporter-submit-bug-report
20349 "emacs-orgmode@gnu.org"
20350 (org-version nil 'full)
20351 (let (list)
20352 (save-window-excursion
20353 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20354 (delete-other-windows)
20355 (erase-buffer)
20356 (insert "You are about to submit a bug report to the Org-mode mailing list.
20358 We would like to add your full Org-mode and Outline configuration to the
20359 bug report. This greatly simplifies the work of the maintainer and
20360 other experts on the mailing list.
20362 HOWEVER, some variables you have customized may contain private
20363 information. The names of customers, colleagues, or friends, might
20364 appear in the form of file names, tags, todo states, or search strings.
20365 If you answer yes to the prompt, you might want to check and remove
20366 such private information before sending the email.")
20367 (add-text-properties (point-min) (point-max) '(face org-warning))
20368 (when (yes-or-no-p "Include your Org-mode configuration ")
20369 (mapatoms
20370 (lambda (v)
20371 (and (boundp v)
20372 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20373 (or (and (symbol-value v)
20374 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20375 (and
20376 (get v 'custom-type) (get v 'standard-value)
20377 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20378 (push v list)))))
20379 (kill-buffer (get-buffer "*Warn about privacy*"))
20380 list))
20381 nil nil
20382 "Remember to cover the basics, that is, what you expected to happen and
20383 what in fact did happen. You don't know how to make a good report? See
20385 http://orgmode.org/manual/Feedback.html#Feedback
20387 Your bug report will be posted to the Org-mode mailing list.
20388 ------------------------------------------------------------------------")
20389 (save-excursion
20390 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20391 (replace-match "\\1Bug: \\3 [\\2]")))))
20394 (defun org-install-agenda-files-menu ()
20395 (let ((bl (buffer-list)))
20396 (save-excursion
20397 (while bl
20398 (set-buffer (pop bl))
20399 (if (derived-mode-p 'org-mode) (setq bl nil)))
20400 (when (derived-mode-p 'org-mode)
20401 (easy-menu-change
20402 '("Org") "File List for Agenda"
20403 (append
20404 (list
20405 ["Edit File List" (org-edit-agenda-file-list) t]
20406 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20407 ["Remove Current File from List" org-remove-file t]
20408 ["Cycle through agenda files" org-cycle-agenda-files t]
20409 ["Occur in all agenda files" org-occur-in-agenda-files t]
20410 "--")
20411 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20413 ;;;; Documentation
20415 (defun org-require-autoloaded-modules ()
20416 (interactive)
20417 (mapc 'require
20418 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20419 org-docbook org-exp org-html org-icalendar
20420 org-id org-latex
20421 org-publish org-remember org-table
20422 org-timer org-xoxo)))
20424 ;;;###autoload
20425 (defun org-reload (&optional uncompiled)
20426 "Reload all org lisp files.
20427 With prefix arg UNCOMPILED, load the uncompiled versions."
20428 (interactive "P")
20429 (require 'loadhist)
20430 (let* ((org-dir (org-find-library-dir "org"))
20431 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20432 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20433 (remove-re (mapconcat 'identity
20434 (mapcar (lambda (f) (concat "^" f "$"))
20435 (list (if (featurep 'xemacs)
20436 "org-colview"
20437 "org-colview-xemacs")
20438 "org" "org-loaddefs" "org-version"))
20439 "\\|"))
20440 (feats (delete-dups
20441 (mapcar 'file-name-sans-extension
20442 (mapcar 'file-name-nondirectory
20443 (delq nil
20444 (mapcar 'feature-file
20445 features))))))
20446 (lfeat (append
20447 (sort
20448 (setq feats
20449 (delq nil (mapcar
20450 (lambda (f)
20451 (if (and (string-match feature-re f)
20452 (not (string-match remove-re f)))
20453 f nil))
20454 feats)))
20455 'string-lessp)
20456 (list "org-version" "org")))
20457 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20458 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20459 load-uncore load-misses)
20460 (setq load-misses
20461 (delq 't
20462 (mapcar (lambda (f)
20463 (or (org-load-noerror-mustsuffix (concat org-dir f))
20464 (and (string= org-dir contrib-dir)
20465 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20466 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20467 (add-to-list 'load-uncore f 'append)
20470 lfeat)))
20471 (if load-uncore
20472 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20473 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20474 (if load-misses
20475 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20476 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20477 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20479 ;;;###autoload
20480 (defun org-customize ()
20481 "Call the customize function with org as argument."
20482 (interactive)
20483 (org-load-modules-maybe)
20484 (org-require-autoloaded-modules)
20485 (customize-browse 'org))
20487 (defun org-create-customize-menu ()
20488 "Create a full customization menu for Org-mode, insert it into the menu."
20489 (interactive)
20490 (org-load-modules-maybe)
20491 (org-require-autoloaded-modules)
20492 (if (fboundp 'customize-menu-create)
20493 (progn
20494 (easy-menu-change
20495 '("Org") "Customize"
20496 `(["Browse Org group" org-customize t]
20497 "--"
20498 ,(customize-menu-create 'org)
20499 ["Set" Custom-set t]
20500 ["Save" Custom-save t]
20501 ["Reset to Current" Custom-reset-current t]
20502 ["Reset to Saved" Custom-reset-saved t]
20503 ["Reset to Standard Settings" Custom-reset-standard t]))
20504 (message "\"Org\"-menu now contains full customization menu"))
20505 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20507 ;;;; Miscellaneous stuff
20509 ;;; Generally useful functions
20511 (defun org-get-at-bol (property)
20512 "Get text property PROPERTY at beginning of line."
20513 (get-text-property (point-at-bol) property))
20515 (defun org-find-text-property-in-string (prop s)
20516 "Return the first non-nil value of property PROP in string S."
20517 (or (get-text-property 0 prop s)
20518 (get-text-property (or (next-single-property-change 0 prop s) 0)
20519 prop s)))
20521 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20522 "Display the given MESSAGE as a warning."
20523 (if (fboundp 'display-warning)
20524 (display-warning 'org message
20525 (if (featurep 'xemacs) 'warning :warning))
20526 (let ((buf (get-buffer-create "*Org warnings*")))
20527 (with-current-buffer buf
20528 (goto-char (point-max))
20529 (insert "Warning (Org): " message)
20530 (unless (bolp)
20531 (newline)))
20532 (display-buffer buf)
20533 (sit-for 0))))
20535 (defun org-eval (form)
20536 "Eval FORM and return result."
20537 (condition-case error
20538 (eval form)
20539 (error (format "%%![Error: %s]" error))))
20541 (defun org-in-clocktable-p ()
20542 "Check if the cursor is in a clocktable."
20543 (let ((pos (point)) start)
20544 (save-excursion
20545 (end-of-line 1)
20546 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20547 (setq start (match-beginning 0))
20548 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20549 (>= (match-end 0) pos)
20550 start))))
20552 (defun org-in-commented-line ()
20553 "Is point in a line starting with `#'?"
20554 (equal (char-after (point-at-bol)) ?#))
20556 (defun org-in-indented-comment-line ()
20557 "Is point in a line starting with `#' after some white space?"
20558 (save-excursion
20559 (save-match-data
20560 (goto-char (point-at-bol))
20561 (looking-at "[ \t]*#"))))
20563 (defun org-in-verbatim-emphasis ()
20564 (save-match-data
20565 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20567 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20568 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20569 (if (and marker (marker-buffer marker)
20570 (buffer-live-p (marker-buffer marker)))
20571 (progn
20572 (org-pop-to-buffer-same-window (marker-buffer marker))
20573 (if (or (> marker (point-max)) (< marker (point-min)))
20574 (widen))
20575 (goto-char marker)
20576 (org-show-context 'org-goto))
20577 (if bookmark
20578 (bookmark-jump bookmark)
20579 (error "Cannot find location"))))
20581 (defun org-quote-csv-field (s)
20582 "Quote field for inclusion in CSV material."
20583 (if (string-match "[\",]" s)
20584 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20587 (defun org-force-self-insert (N)
20588 "Needed to enforce self-insert under remapping."
20589 (interactive "p")
20590 (self-insert-command N))
20592 (defun org-string-width (s)
20593 "Compute width of string, ignoring invisible characters.
20594 This ignores character with invisibility property `org-link', and also
20595 characters with property `org-cwidth', because these will become invisible
20596 upon the next fontification round."
20597 (let (b l)
20598 (when (or (eq t buffer-invisibility-spec)
20599 (assq 'org-link buffer-invisibility-spec))
20600 (while (setq b (text-property-any 0 (length s)
20601 'invisible 'org-link s))
20602 (setq s (concat (substring s 0 b)
20603 (substring s (or (next-single-property-change
20604 b 'invisible s) (length s)))))))
20605 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20606 (setq s (concat (substring s 0 b)
20607 (substring s (or (next-single-property-change
20608 b 'org-cwidth s) (length s))))))
20609 (setq l (string-width s) b -1)
20610 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20611 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20614 (defun org-shorten-string (s maxlength)
20615 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20616 If the string is shorter or has length MAXLENGTH, just return the
20617 original string. If it is longer, the functions finds a space in the
20618 string, breaks this string off at that locations and adds three dots
20619 as ellipsis. Including the ellipsis, the string will not be longer
20620 than MAXLENGTH. If finding a good breaking point in the string does
20621 not work, the string is just chopped off in the middle of a word
20622 if necessary."
20623 (if (<= (length s) maxlength)
20625 (let* ((n (max (- maxlength 4) 1))
20626 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20627 (if (string-match re s)
20628 (concat (match-string 1 s) "...")
20629 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20631 (defun org-get-indentation (&optional line)
20632 "Get the indentation of the current line, interpreting tabs.
20633 When LINE is given, assume it represents a line and compute its indentation."
20634 (if line
20635 (if (string-match "^ *" (org-remove-tabs line))
20636 (match-end 0))
20637 (save-excursion
20638 (beginning-of-line 1)
20639 (skip-chars-forward " \t")
20640 (current-column))))
20642 (defun org-get-string-indentation (s)
20643 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20644 (let ((n -1) (i 0) (w tab-width) c)
20645 (catch 'exit
20646 (while (< (setq n (1+ n)) (length s))
20647 (setq c (aref s n))
20648 (cond ((= c ?\ ) (setq i (1+ i)))
20649 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20650 (t (throw 'exit t)))))
20653 (defun org-remove-tabs (s &optional width)
20654 "Replace tabulators in S with spaces.
20655 Assumes that s is a single line, starting in column 0."
20656 (setq width (or width tab-width))
20657 (while (string-match "\t" s)
20658 (setq s (replace-match
20659 (make-string
20660 (- (* width (/ (+ (match-beginning 0) width) width))
20661 (match-beginning 0)) ?\ )
20662 t t s)))
20665 (defun org-fix-indentation (line ind)
20666 "Fix indentation in LINE.
20667 IND is a cons cell with target and minimum indentation.
20668 If the current indentation in LINE is smaller than the minimum,
20669 leave it alone. If it is larger than ind, set it to the target."
20670 (let* ((l (org-remove-tabs line))
20671 (i (org-get-indentation l))
20672 (i1 (car ind)) (i2 (cdr ind)))
20673 (if (>= i i2) (setq l (substring line i2)))
20674 (if (> i1 0)
20675 (concat (make-string i1 ?\ ) l)
20676 l)))
20678 (defun org-remove-indentation (code &optional n)
20679 "Remove the maximum common indentation from the lines in CODE.
20680 N may optionally be the number of spaces to remove."
20681 (with-temp-buffer
20682 (insert code)
20683 (org-do-remove-indentation n)
20684 (buffer-string)))
20686 (defun org-do-remove-indentation (&optional n)
20687 "Remove the maximum common indentation from the buffer."
20688 (untabify (point-min) (point-max))
20689 (let ((min 10000) re)
20690 (if n
20691 (setq min n)
20692 (goto-char (point-min))
20693 (while (re-search-forward "^ *[^ \n]" nil t)
20694 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20695 (unless (or (= min 0) (= min 10000))
20696 (setq re (format "^ \\{%d\\}" min))
20697 (goto-char (point-min))
20698 (while (re-search-forward re nil t)
20699 (replace-match "")
20700 (end-of-line 1))
20701 min)))
20703 (defun org-fill-template (template alist)
20704 "Find each %key of ALIST in TEMPLATE and replace it."
20705 (let ((case-fold-search nil)
20706 entry key value)
20707 (setq alist (sort (copy-sequence alist)
20708 (lambda (a b) (< (length (car a)) (length (car b))))))
20709 (while (setq entry (pop alist))
20710 (setq template
20711 (replace-regexp-in-string
20712 (concat "%" (regexp-quote (car entry)))
20713 (or (cdr entry) "") template t t)))
20714 template))
20716 (defun org-base-buffer (buffer)
20717 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20718 (if (not buffer)
20719 buffer
20720 (or (buffer-base-buffer buffer)
20721 buffer)))
20723 (defun org-trim (s)
20724 "Remove whitespace at beginning and end of string."
20725 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20726 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20729 (defun org-wrap (string &optional width lines)
20730 "Wrap string to either a number of lines, or a width in characters.
20731 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20732 that costs. If there is a word longer than WIDTH, the text is actually
20733 wrapped to the length of that word.
20734 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20735 many lines, whatever width that takes.
20736 The return value is a list of lines, without newlines at the end."
20737 (let* ((words (org-split-string string "[ \t\n]+"))
20738 (maxword (apply 'max (mapcar 'org-string-width words)))
20739 w ll)
20740 (cond (width
20741 (org-do-wrap words (max maxword width)))
20742 (lines
20743 (setq w maxword)
20744 (setq ll (org-do-wrap words maxword))
20745 (if (<= (length ll) lines)
20747 (setq ll words)
20748 (while (> (length ll) lines)
20749 (setq w (1+ w))
20750 (setq ll (org-do-wrap words w)))
20751 ll))
20752 (t (error "Cannot wrap this")))))
20754 (defun org-do-wrap (words width)
20755 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20756 (let (lines line)
20757 (while words
20758 (setq line (pop words))
20759 (while (and words (< (+ (length line) (length (car words))) width))
20760 (setq line (concat line " " (pop words))))
20761 (setq lines (push line lines)))
20762 (nreverse lines)))
20764 (defun org-split-string (string &optional separators)
20765 "Splits STRING into substrings at SEPARATORS.
20766 No empty strings are returned if there are matches at the beginning
20767 and end of string."
20768 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20769 (start 0)
20770 notfirst
20771 (list nil))
20772 (while (and (string-match rexp string
20773 (if (and notfirst
20774 (= start (match-beginning 0))
20775 (< start (length string)))
20776 (1+ start) start))
20777 (< (match-beginning 0) (length string)))
20778 (setq notfirst t)
20779 (or (eq (match-beginning 0) 0)
20780 (and (eq (match-beginning 0) (match-end 0))
20781 (eq (match-beginning 0) start))
20782 (setq list
20783 (cons (substring string start (match-beginning 0))
20784 list)))
20785 (setq start (match-end 0)))
20786 (or (eq start (length string))
20787 (setq list
20788 (cons (substring string start)
20789 list)))
20790 (nreverse list)))
20792 (defun org-quote-vert (s)
20793 "Replace \"|\" with \"\\vert\"."
20794 (while (string-match "|" s)
20795 (setq s (replace-match "\\vert" t t s)))
20798 (defun org-uuidgen-p (s)
20799 "Is S an ID created by UUIDGEN?"
20800 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20802 (defun org-in-src-block-p (&optional inside)
20803 "Whether point is in a code source block.
20804 When INSIDE is non-nil, don't consider we are within a src block
20805 when point is at #+BEGIN_SRC or #+END_SRC."
20806 (let ((case-fold-search t) ov)
20807 (or (and (setq ov (overlays-at (point)))
20808 (memq 'org-block-background
20809 (overlay-properties (car ov))))
20810 (and (not inside)
20811 (save-match-data
20812 (save-excursion
20813 (beginning-of-line)
20814 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20816 (defun org-context ()
20817 "Return a list of contexts of the current cursor position.
20818 If several contexts apply, all are returned.
20819 Each context entry is a list with a symbol naming the context, and
20820 two positions indicating start and end of the context. Possible
20821 contexts are:
20823 :headline anywhere in a headline
20824 :headline-stars on the leading stars in a headline
20825 :todo-keyword on a TODO keyword (including DONE) in a headline
20826 :tags on the TAGS in a headline
20827 :priority on the priority cookie in a headline
20828 :item on the first line of a plain list item
20829 :item-bullet on the bullet/number of a plain list item
20830 :checkbox on the checkbox in a plain list item
20831 :table in an org-mode table
20832 :table-special on a special filed in a table
20833 :table-table in a table.el table
20834 :clocktable in a clocktable
20835 :src-block in a source block
20836 :link on a hyperlink
20837 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20838 :target on a <<target>>
20839 :radio-target on a <<<radio-target>>>
20840 :latex-fragment on a LaTeX fragment
20841 :latex-preview on a LaTeX fragment with overlaid preview image
20843 This function expects the position to be visible because it uses font-lock
20844 faces as a help to recognize the following contexts: :table-special, :link,
20845 and :keyword."
20846 (let* ((f (get-text-property (point) 'face))
20847 (faces (if (listp f) f (list f)))
20848 (case-fold-search t)
20849 (p (point)) clist o)
20850 ;; First the large context
20851 (cond
20852 ((org-at-heading-p t)
20853 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20854 (when (progn
20855 (beginning-of-line 1)
20856 (looking-at org-todo-line-tags-regexp))
20857 (push (org-point-in-group p 1 :headline-stars) clist)
20858 (push (org-point-in-group p 2 :todo-keyword) clist)
20859 (push (org-point-in-group p 4 :tags) clist))
20860 (goto-char p)
20861 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20862 (if (looking-at "\\[#[A-Z0-9]\\]")
20863 (push (org-point-in-group p 0 :priority) clist)))
20865 ((org-at-item-p)
20866 (push (org-point-in-group p 2 :item-bullet) clist)
20867 (push (list :item (point-at-bol)
20868 (save-excursion (org-end-of-item) (point)))
20869 clist)
20870 (and (org-at-item-checkbox-p)
20871 (push (org-point-in-group p 0 :checkbox) clist)))
20873 ((org-at-table-p)
20874 (push (list :table (org-table-begin) (org-table-end)) clist)
20875 (if (memq 'org-formula faces)
20876 (push (list :table-special
20877 (previous-single-property-change p 'face)
20878 (next-single-property-change p 'face)) clist)))
20879 ((org-at-table-p 'any)
20880 (push (list :table-table) clist)))
20881 (goto-char p)
20883 (let ((case-fold-search t))
20884 ;; New the "medium" contexts: clocktables, source blocks
20885 (cond ((org-in-clocktable-p)
20886 (push (list :clocktable
20887 (and (or (looking-at "#\\+BEGIN: clocktable")
20888 (search-backward "#+BEGIN: clocktable" nil t))
20889 (match-beginning 0))
20890 (and (re-search-forward "#\\+END:?" nil t)
20891 (match-end 0))) clist))
20892 ((org-in-src-block-p)
20893 (push (list :src-block
20894 (and (or (looking-at "#\\+BEGIN_SRC")
20895 (search-backward "#+BEGIN_SRC" nil t))
20896 (match-beginning 0))
20897 (and (search-forward "#+END_SRC" nil t)
20898 (match-beginning 0))) clist))))
20899 (goto-char p)
20901 ;; Now the small context
20902 (cond
20903 ((org-at-timestamp-p)
20904 (push (org-point-in-group p 0 :timestamp) clist))
20905 ((memq 'org-link faces)
20906 (push (list :link
20907 (previous-single-property-change p 'face)
20908 (next-single-property-change p 'face)) clist))
20909 ((memq 'org-special-keyword faces)
20910 (push (list :keyword
20911 (previous-single-property-change p 'face)
20912 (next-single-property-change p 'face)) clist))
20913 ((org-at-target-p)
20914 (push (org-point-in-group p 0 :target) clist)
20915 (goto-char (1- (match-beginning 0)))
20916 (if (looking-at org-radio-target-regexp)
20917 (push (org-point-in-group p 0 :radio-target) clist))
20918 (goto-char p))
20919 ((setq o (car (delq nil
20920 (mapcar
20921 (lambda (x)
20922 (if (memq x org-latex-fragment-image-overlays) x))
20923 (overlays-at (point))))))
20924 (push (list :latex-fragment
20925 (overlay-start o) (overlay-end o)) clist)
20926 (push (list :latex-preview
20927 (overlay-start o) (overlay-end o)) clist))
20928 ((org-inside-LaTeX-fragment-p)
20929 ;; FIXME: positions wrong.
20930 (push (list :latex-fragment (point) (point)) clist)))
20932 (setq clist (nreverse (delq nil clist)))
20933 clist))
20935 ;; FIXME: Compare with at-regexp-p Do we need both?
20936 (defun org-in-regexp (re &optional nlines visually)
20937 "Check if point is inside a match of regexp.
20938 Normally only the current line is checked, but you can include NLINES extra
20939 lines both before and after point into the search.
20940 If VISUALLY is set, require that the cursor is not after the match but
20941 really on, so that the block visually is on the match."
20942 (catch 'exit
20943 (let ((pos (point))
20944 (eol (point-at-eol (+ 1 (or nlines 0))))
20945 (inc (if visually 1 0)))
20946 (save-excursion
20947 (beginning-of-line (- 1 (or nlines 0)))
20948 (while (re-search-forward re eol t)
20949 (if (and (<= (match-beginning 0) pos)
20950 (>= (+ inc (match-end 0)) pos))
20951 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20953 (defun org-at-regexp-p (regexp)
20954 "Is point inside a match of REGEXP in the current line?"
20955 (catch 'exit
20956 (save-excursion
20957 (let ((pos (point)) (end (point-at-eol)))
20958 (beginning-of-line 1)
20959 (while (re-search-forward regexp end t)
20960 (if (and (<= (match-beginning 0) pos)
20961 (>= (match-end 0) pos))
20962 (throw 'exit t)))
20963 nil))))
20965 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20966 "Non-nil when point is between matches of START-RE and END-RE.
20968 Also return a non-nil value when point is on one of the matches.
20970 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20971 buffer positions. Default values are the positions of headlines
20972 surrounding the point.
20974 The functions returns a cons cell whose car (resp. cdr) is the
20975 position before START-RE (resp. after END-RE)."
20976 (save-match-data
20977 (let ((pos (point))
20978 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20979 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20980 beg end)
20981 (save-excursion
20982 ;; Point is on a block when on START-RE or if START-RE can be
20983 ;; found before it...
20984 (and (or (org-at-regexp-p start-re)
20985 (re-search-backward start-re limit-up t))
20986 (setq beg (match-beginning 0))
20987 ;; ... and END-RE after it...
20988 (goto-char (match-end 0))
20989 (re-search-forward end-re limit-down t)
20990 (> (setq end (match-end 0)) pos)
20991 ;; ... without another START-RE in-between.
20992 (goto-char (match-beginning 0))
20993 (not (re-search-backward start-re (1+ beg) t))
20994 ;; Return value.
20995 (cons beg end))))))
20997 (defun org-in-block-p (names)
20998 "Non-nil when point belongs to a block whose name belongs to NAMES.
21000 NAMES is a list of strings containing names of blocks.
21002 Return first block name matched, or nil. Beware that in case of
21003 nested blocks, the returned name may not belong to the closest
21004 block from point."
21005 (save-match-data
21006 (catch 'exit
21007 (let ((case-fold-search t)
21008 (lim-up (save-excursion (outline-previous-heading)))
21009 (lim-down (save-excursion (outline-next-heading))))
21010 (mapc (lambda (name)
21011 (let ((n (regexp-quote name)))
21012 (when (org-between-regexps-p
21013 (concat "^[ \t]*#\\+begin_" n)
21014 (concat "^[ \t]*#\\+end_" n)
21015 lim-up lim-down)
21016 (throw 'exit n))))
21017 names))
21018 nil)))
21020 (defun org-occur-in-agenda-files (regexp &optional nlines)
21021 "Call `multi-occur' with buffers for all agenda files."
21022 (interactive "sOrg-files matching: \np")
21023 (let* ((files (org-agenda-files))
21024 (tnames (mapcar 'file-truename files))
21025 (extra org-agenda-text-search-extra-files)
21027 (when (eq (car extra) 'agenda-archives)
21028 (setq extra (cdr extra))
21029 (setq files (org-add-archive-files files)))
21030 (while (setq f (pop extra))
21031 (unless (member (file-truename f) tnames)
21032 (add-to-list 'files f 'append)
21033 (add-to-list 'tnames (file-truename f) 'append)))
21034 (multi-occur
21035 (mapcar (lambda (x)
21036 (with-current-buffer
21037 (or (get-file-buffer x) (find-file-noselect x))
21038 (widen)
21039 (current-buffer)))
21040 files)
21041 regexp)))
21043 (if (boundp 'occur-mode-find-occurrence-hook)
21044 ;; Emacs 23
21045 (add-hook 'occur-mode-find-occurrence-hook
21046 (lambda ()
21047 (when (derived-mode-p 'org-mode)
21048 (org-reveal))))
21049 ;; Emacs 22
21050 (defadvice occur-mode-goto-occurrence
21051 (after org-occur-reveal activate)
21052 (and (derived-mode-p 'org-mode) (org-reveal)))
21053 (defadvice occur-mode-goto-occurrence-other-window
21054 (after org-occur-reveal activate)
21055 (and (derived-mode-p 'org-mode) (org-reveal)))
21056 (defadvice occur-mode-display-occurrence
21057 (after org-occur-reveal activate)
21058 (when (derived-mode-p 'org-mode)
21059 (let ((pos (occur-mode-find-occurrence)))
21060 (with-current-buffer (marker-buffer pos)
21061 (save-excursion
21062 (goto-char pos)
21063 (org-reveal)))))))
21065 (defun org-occur-link-in-agenda-files ()
21066 "Create a link and search for it in the agendas.
21067 The link is not stored in `org-stored-links', it is just created
21068 for the search purpose."
21069 (interactive)
21070 (let ((link (condition-case nil
21071 (org-store-link nil)
21072 (error "Unable to create a link to here"))))
21073 (org-occur-in-agenda-files (regexp-quote link))))
21075 (defun org-uniquify (list)
21076 "Remove duplicate elements from LIST."
21077 (let (res)
21078 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21079 res))
21081 (defun org-delete-all (elts list)
21082 "Remove all elements in ELTS from LIST."
21083 (while elts
21084 (setq list (delete (pop elts) list)))
21085 list)
21087 (defun org-count (cl-item cl-seq)
21088 "Count the number of occurrences of ITEM in SEQ.
21089 Taken from `count' in cl-seq.el with all keyword arguments removed."
21090 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21091 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21092 (while (< cl-start cl-end)
21093 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21094 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21095 (setq cl-start (1+ cl-start)))
21096 cl-count))
21098 (defun org-remove-if (predicate seq)
21099 "Remove everything from SEQ that fulfills PREDICATE."
21100 (let (res e)
21101 (while seq
21102 (setq e (pop seq))
21103 (if (not (funcall predicate e)) (push e res)))
21104 (nreverse res)))
21106 (defun org-remove-if-not (predicate seq)
21107 "Remove everything from SEQ that does not fulfill PREDICATE."
21108 (let (res e)
21109 (while seq
21110 (setq e (pop seq))
21111 (if (funcall predicate e) (push e res)))
21112 (nreverse res)))
21114 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21115 "Reduce two-argument FUNCTION across SEQ.
21116 Taken from `reduce' in cl-seq.el with all keyword arguments but
21117 \":initial-value\" removed."
21118 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21119 (cadr (memq :initial-value cl-keys)))
21120 (cl-seq (pop cl-seq))
21121 (t (funcall cl-func)))))
21122 (while cl-seq
21123 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21124 cl-accum))
21126 (defun org-back-over-empty-lines ()
21127 "Move backwards over whitespace, to the beginning of the first empty line.
21128 Returns the number of empty lines passed."
21129 (let ((pos (point)))
21130 (if (cdr (assoc 'heading org-blank-before-new-entry))
21131 (skip-chars-backward " \t\n\r")
21132 (unless (eobp)
21133 (forward-line -1)))
21134 (beginning-of-line 2)
21135 (goto-char (min (point) pos))
21136 (count-lines (point) pos)))
21138 (defun org-skip-whitespace ()
21139 (skip-chars-forward " \t\n\r"))
21141 (defun org-point-in-group (point group &optional context)
21142 "Check if POINT is in match-group GROUP.
21143 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21144 match. If the match group does not exist or point is not inside it,
21145 return nil."
21146 (and (match-beginning group)
21147 (>= point (match-beginning group))
21148 (<= point (match-end group))
21149 (if context
21150 (list context (match-beginning group) (match-end group))
21151 t)))
21153 (defun org-switch-to-buffer-other-window (&rest args)
21154 "Switch to buffer in a second window on the current frame.
21155 In particular, do not allow pop-up frames.
21156 Returns the newly created buffer."
21157 (org-no-popups
21158 (apply 'switch-to-buffer-other-window args)))
21160 (defun org-combine-plists (&rest plists)
21161 "Create a single property list from all plists in PLISTS.
21162 The process starts by copying the first list, and then setting properties
21163 from the other lists. Settings in the last list are the most significant
21164 ones and overrule settings in the other lists."
21165 (let ((rtn (copy-sequence (pop plists)))
21166 p v ls)
21167 (while plists
21168 (setq ls (pop plists))
21169 (while ls
21170 (setq p (pop ls) v (pop ls))
21171 (setq rtn (plist-put rtn p v))))
21172 rtn))
21174 (defun org-replace-escapes (string table)
21175 "Replace %-escapes in STRING with values in TABLE.
21176 TABLE is an association list with keys like \"%a\" and string values.
21177 The sequences in STRING may contain normal field width and padding information,
21178 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21179 so values can contain further %-escapes if they are define later in TABLE."
21180 (let ((tbl (copy-alist table))
21181 (case-fold-search nil)
21182 (pchg 0)
21183 e re rpl)
21184 (while (setq e (pop tbl))
21185 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21186 (when (and (cdr e) (string-match re (cdr e)))
21187 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21188 (safe "SREF"))
21189 (add-text-properties 0 3 (list 'sref sref) safe)
21190 (setcdr e (replace-match safe t t (cdr e)))))
21191 (while (string-match re string)
21192 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21193 (cdr e)))
21194 (setq string (replace-match rpl t t string))))
21195 (while (setq pchg (next-property-change pchg string))
21196 (let ((sref (get-text-property pchg 'sref string)))
21197 (when (and sref (string-match "SREF" string pchg))
21198 (setq string (replace-match sref t t string)))))
21199 string))
21201 (defun org-sublist (list start end)
21202 "Return a section of LIST, from START to END.
21203 Counting starts at 1."
21204 (let (rtn (c start))
21205 (setq list (nthcdr (1- start) list))
21206 (while (and list (<= c end))
21207 (push (pop list) rtn)
21208 (setq c (1+ c)))
21209 (nreverse rtn)))
21211 (defun org-find-base-buffer-visiting (file)
21212 "Like `find-buffer-visiting' but always return the base buffer and
21213 not an indirect buffer."
21214 (let ((buf (or (get-file-buffer file)
21215 (find-buffer-visiting file))))
21216 (if buf
21217 (or (buffer-base-buffer buf) buf)
21218 nil)))
21220 (defun org-image-file-name-regexp (&optional extensions)
21221 "Return regexp matching the file names of images.
21222 If EXTENSIONS is given, only match these."
21223 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21224 (image-file-name-regexp)
21225 (let ((image-file-name-extensions
21226 (or extensions
21227 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21228 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21229 (concat "\\."
21230 (regexp-opt (nconc (mapcar 'upcase
21231 image-file-name-extensions)
21232 image-file-name-extensions)
21234 "\\'"))))
21236 (defun org-file-image-p (file &optional extensions)
21237 "Return non-nil if FILE is an image."
21238 (save-match-data
21239 (string-match (org-image-file-name-regexp extensions) file)))
21241 (defun org-get-cursor-date (&optional with-time)
21242 "Return the date at cursor in as a time.
21243 This works in the calendar and in the agenda, anywhere else it just
21244 returns the current time.
21245 If WITH-TIME is non-nil, returns the time of the event at point (in
21246 the agenda) or the current time of the day."
21247 (let (date day defd tp tm hod mod)
21248 (when with-time
21249 (setq tp (get-text-property (point) 'time))
21250 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21251 (setq hod (string-to-number (match-string 1 tp))
21252 mod (string-to-number (match-string 2 tp))))
21253 (or tp (setq hod (nth 2 (decode-time (current-time)))
21254 mod (nth 1 (decode-time (current-time))))))
21255 (cond
21256 ((eq major-mode 'calendar-mode)
21257 (setq date (calendar-cursor-to-date)
21258 defd (encode-time 0 (or mod 0) (or hod 0)
21259 (nth 1 date) (nth 0 date) (nth 2 date))))
21260 ((eq major-mode 'org-agenda-mode)
21261 (setq day (get-text-property (point) 'day))
21262 (if day
21263 (setq date (calendar-gregorian-from-absolute day)
21264 defd (encode-time 0 (or mod 0) (or hod 0)
21265 (nth 1 date) (nth 0 date) (nth 2 date))))))
21266 (or defd (current-time))))
21268 (defun org-mark-subtree (&optional up)
21269 "Mark the current subtree.
21270 This puts point at the start of the current subtree, and mark at
21271 the end. If a numeric prefix UP is given, move up into the
21272 hierarchy of headlines by UP levels before marking the subtree."
21273 (interactive "P")
21274 (org-with-limited-levels
21275 (cond ((org-at-heading-p) (beginning-of-line))
21276 ((org-before-first-heading-p) (error "Not in a subtree"))
21277 (t (outline-previous-visible-heading 1))))
21278 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21279 (if (org-called-interactively-p 'any)
21280 (call-interactively 'org-mark-element)
21281 (org-mark-element)))
21284 ;;; Macros
21286 ;; Macros are expanded with `org-macro-replace-all', which relies
21287 ;; internally on `org-macro-expand'.
21289 ;; Default templates for expansion are stored in the buffer-local
21290 ;; variable `org-macro-templates'. This variable is updated by
21291 ;; `org-macro-initialize-templates'.
21293 ;; Along with macros defined through #+MACRO: keyword, default
21294 ;; templates include the following hard-coded macros:
21295 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21296 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21298 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21299 ;; {{{title}}} will also be provided.
21302 (defvar org-macro-templates nil
21303 "Alist containing all macro templates in current buffer.
21304 Associations are in the shape of (NAME . TEMPLATE) where NAME
21305 stands for macro's name and template for its replacement value,
21306 both as strings. This is an internal variable. Do not set it
21307 directly, use instead:
21309 #+MACRO: name template")
21310 (make-variable-buffer-local 'org-macro-templates)
21312 (defun org-macro-expand (macro templates)
21313 "Return expanded MACRO, as a string.
21314 MACRO is an object, obtained, for example, with
21315 `org-element-context'. TEMPLATES is an alist of templates used
21316 for expansion. See `org-macro-templates' for a buffer-local
21317 default value. Return nil if no template was found."
21318 (let ((template
21319 ;; Macro names are case-insensitive.
21320 (cdr (assoc-string (org-element-property :key macro) templates t))))
21321 (when template
21322 (let ((value (replace-regexp-in-string
21323 "\\$[0-9]+"
21324 (lambda (arg)
21325 (or (nth (1- (string-to-number (substring arg 1)))
21326 (org-element-property :args macro))
21327 ;; No argument provided: remove
21328 ;; place-holder.
21329 ""))
21330 template)))
21331 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21332 (when (string-match "\\`(eval\\>" value)
21333 (setq value (eval (read value))))
21334 ;; Return string.
21335 (format "%s" (or value ""))))))
21337 (defun org-macro-replace-all (templates)
21338 "Replace all macros in current buffer by their expansion.
21339 TEMPLATES is an alist of templates used for expansion. See
21340 `org-macro-templates' for a buffer-local default value."
21341 (save-excursion
21342 (goto-char (point-min))
21343 (let (record)
21344 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21345 (let ((object (org-element-context)))
21346 (when (eq (org-element-type object) 'macro)
21347 (let* ((value (org-macro-expand object templates))
21348 (begin (org-element-property :begin object))
21349 (signature (list begin
21350 object
21351 (org-element-property :args object))))
21352 ;; Avoid circular dependencies by checking if the same
21353 ;; macro with the same arguments is expanded at the same
21354 ;; position twice.
21355 (if (member signature record)
21356 (error "Circular macro expansion: %s"
21357 (org-element-property :key object))
21358 (when value
21359 (push signature record)
21360 (delete-region
21361 begin
21362 ;; Preserve white spaces after the macro.
21363 (progn (goto-char (org-element-property :end object))
21364 (skip-chars-backward " \t")
21365 (point)))
21366 ;; Leave point before replacement in case of recursive
21367 ;; expansions.
21368 (save-excursion (insert value)))))))))))
21370 (defun org-macro-initialize-templates ()
21371 "Collect macro templates defined in current buffer.
21372 Templates are stored in buffer-local variable
21373 `org-macro-templates'. In addition to buffer-defined macros, the
21374 function installs the following ones: \"property\",
21375 \"time\". and, if the buffer is associated to a file,
21376 \"input-file\" and \"modification-time\"."
21377 (let ((case-fold-search t)
21378 (set-template
21379 (lambda (cell)
21380 ;; Add CELL to `org-macro-templates' if there's no
21381 ;; association matching its name already. Otherwise,
21382 ;; replace old association with the new one in that
21383 ;; variable.
21384 (let ((old-template (assoc (car cell) org-macro-templates)))
21385 (if old-template (setcdr old-template (cdr cell))
21386 (push cell org-macro-templates))))))
21387 ;; Install buffer-local macros.
21388 (org-with-wide-buffer
21389 (goto-char (point-min))
21390 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21391 (let ((element (org-element-at-point)))
21392 (when (eq (org-element-type element) 'keyword)
21393 (let ((value (org-element-property :value element)))
21394 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21395 (funcall set-template
21396 (cons (match-string 1 value)
21397 (or (match-string 2 value) "")))))))))
21398 ;; Install hard-coded macros.
21399 (mapc (lambda (cell) (funcall set-template cell))
21400 (list
21401 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21402 (cons "time" "(eval (format-time-string \"$1\"))")))
21403 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21404 (when (and visited-file (file-exists-p visited-file))
21405 (mapc (lambda (cell) (funcall set-template cell))
21406 (list
21407 (cons "input-file" (file-name-nondirectory visited-file))
21408 (cons "modification-time"
21409 (format "(eval (format-time-string \"$1\" '%s))"
21410 (prin1-to-string
21411 (nth 5 (file-attributes visited-file)))))))))))
21414 ;;; Indentation
21416 (defun org-indent-line ()
21417 "Indent line depending on context."
21418 (interactive)
21419 (let* ((pos (point))
21420 (itemp (org-at-item-p))
21421 (case-fold-search t)
21422 (org-drawer-regexp (or org-drawer-regexp "\000"))
21423 (inline-task-p (and (featurep 'org-inlinetask)
21424 (org-inlinetask-in-task-p)))
21425 (inline-re (and inline-task-p
21426 (org-inlinetask-outline-regexp)))
21427 column)
21428 (if (and orgstruct-is-++ (eq pos (point)))
21429 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21430 (indent-according-to-mode))
21431 (beginning-of-line 1)
21432 (cond
21433 ;; Headings
21434 ((looking-at org-outline-regexp) (setq column 0))
21435 ;; Included files
21436 ((looking-at "#\\+include:") (setq column 0))
21437 ;; Footnote definition
21438 ((looking-at org-footnote-definition-re) (setq column 0))
21439 ;; Literal examples
21440 ((looking-at "[ \t]*:\\( \\|$\\)")
21441 (setq column (org-get-indentation))) ; do nothing
21442 ;; Lists
21443 ((ignore-errors (goto-char (org-in-item-p)))
21444 (setq column (if itemp
21445 (org-get-indentation)
21446 (org-list-item-body-column (point))))
21447 (goto-char pos))
21448 ;; Drawers
21449 ((and (looking-at "[ \t]*:END:")
21450 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21451 (save-excursion
21452 (goto-char (1- (match-beginning 1)))
21453 (setq column (current-column))))
21454 ;; Special blocks
21455 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21456 (save-excursion
21457 (re-search-backward
21458 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21459 (setq column (org-get-indentation (match-string 0))))
21460 ((and (not (looking-at "[ \t]*#\\+begin_"))
21461 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21462 (save-excursion
21463 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21464 (setq column
21465 (cond ((equal (downcase (match-string 1)) "src")
21466 ;; src blocks: let `org-edit-src-exit' handle them
21467 (org-get-indentation))
21468 ((equal (downcase (match-string 1)) "example")
21469 (max (org-get-indentation)
21470 (org-get-indentation (match-string 0))))
21472 (org-get-indentation (match-string 0))))))
21473 ;; This line has nothing special, look at the previous relevant
21474 ;; line to compute indentation
21476 (beginning-of-line 0)
21477 (while (and (not (bobp))
21478 (not (looking-at org-table-line-regexp))
21479 (not (looking-at org-drawer-regexp))
21480 ;; When point started in an inline task, do not move
21481 ;; above task starting line.
21482 (not (and inline-task-p (looking-at inline-re)))
21483 ;; Skip drawers, blocks, empty lines, verbatim,
21484 ;; comments, tables, footnotes definitions, lists,
21485 ;; inline tasks.
21486 (or (and (looking-at "[ \t]*:END:")
21487 (re-search-backward org-drawer-regexp nil t))
21488 (and (looking-at "[ \t]*#\\+end_")
21489 (re-search-backward "[ \t]*#\\+begin_"nil t))
21490 (looking-at "[ \t]*[\n:#|]")
21491 (looking-at org-footnote-definition-re)
21492 (and (ignore-errors (goto-char (org-in-item-p)))
21493 (goto-char
21494 (org-list-get-top-point (org-list-struct))))
21495 (and (not inline-task-p)
21496 (featurep 'org-inlinetask)
21497 (org-inlinetask-in-task-p)
21498 (or (org-inlinetask-goto-beginning) t))))
21499 (beginning-of-line 0))
21500 (cond
21501 ;; There was an heading above.
21502 ((looking-at "\\*+[ \t]+")
21503 (if (not org-adapt-indentation)
21504 (setq column 0)
21505 (goto-char (match-end 0))
21506 (setq column (current-column))))
21507 ;; A drawer had started and is unfinished
21508 ((looking-at org-drawer-regexp)
21509 (goto-char (1- (match-beginning 1)))
21510 (setq column (current-column)))
21511 ;; Else, nothing noticeable found: get indentation and go on.
21512 (t (setq column (org-get-indentation))))))
21513 ;; Now apply indentation and move cursor accordingly
21514 (goto-char pos)
21515 (if (<= (current-column) (current-indentation))
21516 (org-indent-line-to column)
21517 (save-excursion (org-indent-line-to column)))
21518 ;; Special polishing for properties, see `org-property-format'
21519 (setq column (current-column))
21520 (beginning-of-line 1)
21521 (if (looking-at
21522 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21523 (replace-match (concat (match-string 1)
21524 (format org-property-format
21525 (match-string 2) (match-string 3)))
21526 t t))
21527 (org-move-to-column column))))
21529 (defun org-indent-drawer ()
21530 "Indent the drawer at point."
21531 (interactive)
21532 (let ((p (point))
21533 (e (and (save-excursion (re-search-forward ":END:" nil t))
21534 (match-end 0)))
21535 (folded
21536 (save-excursion
21537 (end-of-line)
21538 (when (overlays-at (point))
21539 (member 'invisible (overlay-properties
21540 (car (overlays-at (point)))))))))
21541 (when folded (org-cycle))
21542 (indent-for-tab-command)
21543 (while (and (move-beginning-of-line 2) (< (point) e))
21544 (indent-for-tab-command))
21545 (goto-char p)
21546 (when folded (org-cycle)))
21547 (message "Drawer at point indented"))
21549 (defun org-indent-block ()
21550 "Indent the block at point."
21551 (interactive)
21552 (let ((p (point))
21553 (case-fold-search t)
21554 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21555 (match-end 0)))
21556 (folded
21557 (save-excursion
21558 (end-of-line)
21559 (when (overlays-at (point))
21560 (member 'invisible (overlay-properties
21561 (car (overlays-at (point)))))))))
21562 (when folded (org-cycle))
21563 (indent-for-tab-command)
21564 (while (and (move-beginning-of-line 2) (< (point) e))
21565 (indent-for-tab-command))
21566 (goto-char p)
21567 (when folded (org-cycle)))
21568 (message "Block at point indented"))
21570 (defun org-indent-region (start end)
21571 "Indent region."
21572 (interactive "r")
21573 (save-excursion
21574 (let ((line-end (org-current-line end)))
21575 (goto-char start)
21576 (while (< (org-current-line) line-end)
21577 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21578 (t (call-interactively 'org-indent-line)))
21579 (move-beginning-of-line 2)))))
21582 ;;; Filling
21584 ;; We use our own fill-paragraph and auto-fill functions.
21586 ;; `org-fill-paragraph' relies on adaptive filling and context
21587 ;; checking. Appropriate `fill-prefix' is computed with
21588 ;; `org-adaptive-fill-function'.
21590 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21591 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21592 ;; `org-adaptive-fill-function' value. Internally,
21593 ;; `org-comment-line-break-function' breaks the line.
21595 ;; `org-setup-filling' installs filling and auto-filling related
21596 ;; variables during `org-mode' initialization.
21598 (defun org-setup-filling ()
21599 (interactive)
21600 ;; Prevent auto-fill from inserting unwanted new items.
21601 (when (boundp 'fill-nobreak-predicate)
21602 (org-set-local
21603 'fill-nobreak-predicate
21604 (org-uniquify
21605 (append fill-nobreak-predicate
21606 '(org-fill-paragraph-separate-nobreak-p
21607 org-fill-line-break-nobreak-p)))))
21608 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21609 (org-set-local 'auto-fill-inhibit-regexp nil)
21610 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21611 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21612 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21614 (defvar org-element-paragraph-separate) ; org-element.el
21615 (defun org-fill-paragraph-separate-nobreak-p ()
21616 "Non-nil when a line break at point would insert a new item."
21617 (looking-at (substring org-element-paragraph-separate 1)))
21619 (defun org-fill-line-break-nobreak-p ()
21620 "Non-nil when a line break at point would create an Org line break."
21621 (save-excursion
21622 (skip-chars-backward "[ \t]")
21623 (skip-chars-backward "\\\\")
21624 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21626 (declare-function message-in-body-p "message" ())
21627 (defvar orgtbl-line-start-regexp) ; From org-table.el
21628 (defun org-adaptive-fill-function ()
21629 "Compute a fill prefix for the current line.
21630 Return fill prefix, as a string, or nil if current line isn't
21631 meant to be filled."
21632 (let (prefix)
21633 (catch 'exit
21634 (when (derived-mode-p 'message-mode)
21635 (save-excursion
21636 (beginning-of-line)
21637 (cond ((or (not (message-in-body-p))
21638 (looking-at orgtbl-line-start-regexp))
21639 (throw 'exit nil))
21640 ((looking-at message-cite-prefix-regexp)
21641 (throw 'exit (match-string-no-properties 0)))
21642 ((looking-at org-outline-regexp)
21643 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21644 (org-with-wide-buffer
21645 (let* ((p (line-beginning-position))
21646 (element (save-excursion (beginning-of-line)
21647 (org-element-at-point)))
21648 (type (org-element-type element))
21649 (post-affiliated (org-element-property :post-affiliated element)))
21650 (unless (and post-affiliated (< p post-affiliated))
21651 (case type
21652 (comment (looking-at "[ \t]*# ?") (match-string 0))
21653 (footnote-definition "")
21654 ((item plain-list)
21655 (make-string (org-list-item-body-column
21656 (or post-affiliated
21657 (org-element-property :begin element)))
21658 ? ))
21659 (paragraph
21660 ;; Fill prefix is usually the same as the current line,
21661 ;; except if the paragraph is at the beginning of an item.
21662 (let ((parent (org-element-property :parent element)))
21663 (cond ((eq (org-element-type parent) 'item)
21664 (make-string (org-list-item-body-column
21665 (org-element-property :begin parent))
21666 ? ))
21667 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21668 (match-string 0))
21669 (t ""))))
21670 (comment-block
21671 ;; Only fill contents if P is within block boundaries.
21672 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21673 (forward-line)
21674 (point)))
21675 (cend (save-excursion
21676 (goto-char (org-element-property :end element))
21677 (skip-chars-backward " \r\t\n")
21678 (line-beginning-position))))
21679 (when (and (>= p cbeg) (< p cend))
21680 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21681 (match-string 0)
21682 "")))))))))))
21684 (declare-function message-goto-body "message" ())
21685 (defvar message-cite-prefix-regexp) ; From message.el
21686 (defvar org-element-all-objects) ; From org-element.el
21687 (defun org-fill-paragraph (&optional justify)
21688 "Fill element at point, when applicable.
21690 This function only applies to comment blocks, comments, example
21691 blocks and paragraphs. Also, as a special case, re-align table
21692 when point is at one.
21694 If JUSTIFY is non-nil (interactively, with prefix argument),
21695 justify as well. If `sentence-end-double-space' is non-nil, then
21696 period followed by one space does not end a sentence, so don't
21697 break a line there. The variable `fill-column' controls the
21698 width for filling.
21700 For convenience, when point is at a plain list, an item or
21701 a footnote definition, try to fill the first paragraph within."
21702 (interactive)
21703 (if (and (derived-mode-p 'message-mode)
21704 (or (not (message-in-body-p))
21705 (save-excursion (move-beginning-of-line 1)
21706 (looking-at message-cite-prefix-regexp))))
21707 ;; First ensure filling is correct in message-mode.
21708 (let ((fill-paragraph-function
21709 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21710 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21711 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21712 (paragraph-separate
21713 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21714 (fill-paragraph nil))
21715 (save-excursion
21716 ;; Move to end of line in order to get the first paragraph
21717 ;; within a plain list or a footnote definition.
21718 (end-of-line)
21719 (let ((element (org-element-at-point)))
21720 ;; First check if point is in a blank line at the beginning of
21721 ;; the buffer. In that case, ignore filling.
21722 (if (< (point) (org-element-property :begin element)) t
21723 (case (org-element-type element)
21724 ;; Use major mode filling function is src blocks.
21725 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21726 ;; Align Org tables, leave table.el tables as-is.
21727 (table-row (org-table-align) t)
21728 (table
21729 (when (eq (org-element-property :type element) 'org)
21730 (org-table-align))
21732 (paragraph
21733 ;; Paragraphs may contain `line-break' type objects.
21734 (let ((beg (max (point-min)
21735 (org-element-property :contents-begin element)))
21736 (end (min (point-max)
21737 (org-element-property :contents-end element))))
21738 ;; Do nothing if point is at an affiliated keyword.
21739 (if (< (point) beg) t
21740 (when (derived-mode-p 'message-mode)
21741 ;; In `message-mode', do not fill following
21742 ;; citation in current paragraph nor text before
21743 ;; message body.
21744 (let ((body-start (save-excursion (message-goto-body))))
21745 (when body-start (setq beg (max body-start beg))))
21746 (when (save-excursion
21747 (re-search-forward
21748 (concat "^" message-cite-prefix-regexp) end t))
21749 (setq end (match-beginning 0))))
21750 ;; Fill paragraph, taking line breaks into
21751 ;; consideration. For that, slice the paragraph
21752 ;; using line breaks as separators, and fill the
21753 ;; parts in reverse order to avoid messing with
21754 ;; markers.
21755 (save-excursion
21756 (goto-char end)
21757 (mapc
21758 (lambda (pos)
21759 (fill-region-as-paragraph pos (point) justify)
21760 (goto-char pos))
21761 ;; Find the list of ending positions for line
21762 ;; breaks in the current paragraph. Add paragraph
21763 ;; beginning to include first slice.
21764 (nreverse
21765 (cons
21767 (org-element-map
21768 (org-element--parse-objects
21769 beg end nil org-element-all-objects)
21770 'line-break
21771 (lambda (lb) (org-element-property :end lb)))))))
21772 t)))
21773 ;; Contents of `comment-block' type elements should be
21774 ;; filled as plain text, but only if point is within block
21775 ;; markers.
21776 (comment-block
21777 (let* ((case-fold-search t)
21778 (beg (save-excursion
21779 (goto-char (org-element-property :begin element))
21780 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21781 (forward-line)
21782 (point)))
21783 (end (save-excursion
21784 (goto-char (org-element-property :end element))
21785 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21786 (line-beginning-position))))
21787 (when (and (>= (point) beg) (< (point) end))
21788 (fill-region-as-paragraph
21789 (save-excursion
21790 (end-of-line)
21791 (re-search-backward "^[ \t]*$" beg 'move)
21792 (line-beginning-position))
21793 (save-excursion
21794 (beginning-of-line)
21795 (re-search-forward "^[ \t]*$" end 'move)
21796 (line-beginning-position))
21797 justify)))
21799 ;; Fill comments.
21800 (comment (fill-comment-paragraph justify))
21801 ;; Ignore every other element.
21802 (otherwise t)))))))
21804 (defun org-auto-fill-function ()
21805 "Auto-fill function."
21806 ;; Check if auto-filling is meaningful.
21807 (let ((fc (current-fill-column)))
21808 (when (and fc (> (current-column) fc))
21809 (let* ((fill-prefix (org-adaptive-fill-function))
21810 ;; Enforce empty fill prefix, if required. Otherwise, it
21811 ;; will be computed again.
21812 (adaptive-fill-mode (not (equal fill-prefix ""))))
21813 (when fill-prefix (do-auto-fill))))))
21815 (defun org-comment-line-break-function (&optional soft)
21816 "Break line at point and indent, continuing comment if within one.
21817 The inserted newline is marked hard if variable
21818 `use-hard-newlines' is true, unless optional argument SOFT is
21819 non-nil."
21820 (if soft (insert-and-inherit ?\n) (newline 1))
21821 (save-excursion (forward-char -1) (delete-horizontal-space))
21822 (delete-horizontal-space)
21823 (indent-to-left-margin)
21824 (insert-before-markers-and-inherit fill-prefix))
21827 ;;; Comments
21829 ;; Org comments syntax is quite complex. It requires the entire line
21830 ;; to be just a comment. Also, even with the right syntax at the
21831 ;; beginning of line, some some elements (i.e. verse-block or
21832 ;; example-block) don't accept comments. Usual Emacs comment commands
21833 ;; cannot cope with those requirements. Therefore, Org replaces them.
21835 ;; Org still relies on `comment-dwim', but cannot trust
21836 ;; `comment-only-p'. So, `comment-region-function' and
21837 ;; `uncomment-region-function' both point
21838 ;; to`org-comment-or-uncomment-region'. Eventually,
21839 ;; `org-insert-comment' takes care of insertion of comments at the
21840 ;; beginning of line.
21842 ;; `org-setup-comments-handling' install comments related variables
21843 ;; during `org-mode' initialization.
21845 (defun org-setup-comments-handling ()
21846 (interactive)
21847 (org-set-local 'comment-use-syntax nil)
21848 (org-set-local 'comment-start "# ")
21849 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21850 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21851 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21852 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21854 (defun org-insert-comment ()
21855 "Insert an empty comment above current line.
21856 If the line is empty, insert comment at its beginning."
21857 (beginning-of-line)
21858 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21859 (org-indent-line)
21860 (insert "# "))
21862 (defvar comment-empty-lines) ; From newcomment.el.
21863 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21864 "Comment or uncomment each non-blank line in the region.
21865 Uncomment each non-blank line between BEG and END if it only
21866 contains commented lines. Otherwise, comment them."
21867 (save-restriction
21868 ;; Restrict region
21869 (narrow-to-region (save-excursion (goto-char beg)
21870 (skip-chars-forward " \r\t\n" end)
21871 (line-beginning-position))
21872 (save-excursion (goto-char end)
21873 (skip-chars-backward " \r\t\n" beg)
21874 (line-end-position)))
21875 (let ((uncommentp
21876 ;; UNCOMMENTP is non-nil when every non blank line between
21877 ;; BEG and END is a comment.
21878 (save-excursion
21879 (goto-char (point-min))
21880 (while (and (not (eobp))
21881 (let ((element (org-element-at-point)))
21882 (and (eq (org-element-type element) 'comment)
21883 (goto-char (min (point-max)
21884 (org-element-property
21885 :end element)))))))
21886 (eobp))))
21887 (if uncommentp
21888 ;; Only blank lines and comments in region: uncomment it.
21889 (save-excursion
21890 (goto-char (point-min))
21891 (while (not (eobp))
21892 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21893 (replace-match "" nil nil nil 1))
21894 (forward-line)))
21895 ;; Comment each line in region.
21896 (let ((min-indent (point-max)))
21897 ;; First find the minimum indentation across all lines.
21898 (save-excursion
21899 (goto-char (point-min))
21900 (while (and (not (eobp)) (not (zerop min-indent)))
21901 (unless (looking-at "[ \t]*$")
21902 (setq min-indent (min min-indent (current-indentation))))
21903 (forward-line)))
21904 ;; Then loop over all lines.
21905 (save-excursion
21906 (goto-char (point-min))
21907 (while (not (eobp))
21908 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21909 (org-move-to-column min-indent t)
21910 (insert comment-start))
21911 (forward-line))))))))
21914 ;;; Planning
21916 ;; This section contains tools to operate on timestamp objects, as
21917 ;; returned by, e.g. `org-element-context'.
21919 (defun org-timestamp-has-time-p (timestamp)
21920 "Non-nil when TIMESTAMP has a time specified."
21921 (org-element-property :hour-start timestamp))
21923 (defun org-timestamp-format (timestamp format &optional end utc)
21924 "Format a TIMESTAMP element into a string.
21926 FORMAT is a format specifier to be passed to
21927 `format-time-string'.
21929 When optional argument END is non-nil, use end of date-range or
21930 time-range, if possible.
21932 When optional argument UTC is non-nil, time will be expressed as
21933 Universal Time."
21934 (format-time-string
21935 format
21936 (apply 'encode-time
21937 (cons 0
21938 (mapcar
21939 (lambda (prop) (or (org-element-property prop timestamp) 0))
21940 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21941 '(:minute-start :hour-start :day-start :month-start
21942 :year-start)))))
21943 utc))
21945 (defun org-timestamp-split-range (timestamp &optional end)
21946 "Extract a timestamp object from a date or time range.
21948 TIMESTAMP is a timestamp object. END, when non-nil, means extract
21949 the end of the range. Otherwise, extract its start.
21951 Return a new timestamp object sharing the same parent as
21952 TIMESTAMP."
21953 (let ((type (org-element-property :type timestamp)))
21954 (if (memq type '(active inactive diary)) timestamp
21955 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
21956 ;; Set new type.
21957 (org-element-put-property
21958 split-ts :type (if (eq type 'active-range) 'active 'inactive))
21959 ;; Copy start properties over end properties if END is
21960 ;; non-nil. Otherwise, copy end properties over `start' ones.
21961 (let ((p-alist '((:minute-start . :minute-end)
21962 (:hour-start . :hour-end)
21963 (:day-start . :day-end)
21964 (:month-start . :month-end)
21965 (:year-start . :year-end))))
21966 (dolist (p-cell p-alist)
21967 (org-element-put-property
21968 split-ts
21969 (funcall (if end 'car 'cdr) p-cell)
21970 (org-element-property
21971 (funcall (if end 'cdr 'car) p-cell) split-ts)))
21972 ;; Eventually refresh `:raw-value'.
21973 (org-element-put-property split-ts :raw-value nil)
21974 (org-element-put-property
21975 split-ts :raw-value (org-element-interpret-data split-ts)))))))
21977 (defun org-timestamp-translate (timestamp &optional boundary)
21978 "Apply `org-translate-time' on a TIMESTAMP object.
21979 When optional argument BOUNDARY is non-nil, it is either the
21980 symbol `start' or `end'. In this case, only translate the
21981 starting or ending part of TIMESTAMP if it is a date or time
21982 range. Otherwise, translate both parts."
21983 (if (and (not boundary)
21984 (memq (org-element-property :type timestamp)
21985 '(active-range inactive-range)))
21986 (concat
21987 (org-translate-time
21988 (org-element-property :raw-value
21989 (org-timestamp-split-range timestamp)))
21990 "--"
21991 (org-translate-time
21992 (org-element-property :raw-value
21993 (org-timestamp-split-range timestamp t))))
21994 (org-translate-time
21995 (org-element-property
21996 :raw-value
21997 (if (not boundary) timestamp
21998 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22002 ;;; Other stuff.
22004 (defun org-toggle-fixed-width-section (arg)
22005 "Toggle the fixed-width export.
22006 If there is no active region, the QUOTE keyword at the current headline is
22007 inserted or removed. When present, it causes the text between this headline
22008 and the next to be exported as fixed-width text, and unmodified.
22009 If there is an active region, this command adds or removes a colon as the
22010 first character of this line. If the first character of a line is a colon,
22011 this line is also exported in fixed-width font."
22012 (interactive "P")
22013 (let* ((cc 0)
22014 (regionp (org-region-active-p))
22015 (beg (if regionp (region-beginning) (point)))
22016 (end (if regionp (region-end)))
22017 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22018 (case-fold-search nil)
22019 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22020 off)
22021 (if regionp
22022 (save-excursion
22023 (goto-char beg)
22024 (setq cc (current-column))
22025 (beginning-of-line 1)
22026 (setq off (looking-at re))
22027 (while (> nlines 0)
22028 (setq nlines (1- nlines))
22029 (beginning-of-line 1)
22030 (cond
22031 (arg
22032 (org-move-to-column cc t)
22033 (insert ": \n")
22034 (forward-line -1))
22035 ((and off (looking-at re))
22036 (replace-match "" t t nil 1))
22037 ((not off) (org-move-to-column cc t) (insert ": ")))
22038 (forward-line 1)))
22039 (save-excursion
22040 (org-back-to-heading)
22041 (cond
22042 ((looking-at (format org-heading-keyword-regexp-format
22043 org-quote-string))
22044 (goto-char (match-end 1))
22045 (looking-at (concat " +" org-quote-string))
22046 (replace-match "" t t)
22047 (when (eolp) (insert " ")))
22048 ((looking-at org-outline-regexp)
22049 (goto-char (match-end 0))
22050 (insert org-quote-string " ")))))))
22052 (defun org-reftex-citation ()
22053 "Use reftex-citation to insert a citation into the buffer.
22054 This looks for a line like
22056 #+BIBLIOGRAPHY: foo plain option:-d
22058 and derives from it that foo.bib is the bibliography file relevant
22059 for this document. It then installs the necessary environment for RefTeX
22060 to work in this buffer and calls `reftex-citation' to insert a citation
22061 into the buffer.
22063 Export of such citations to both LaTeX and HTML is handled by the contributed
22064 package org-exp-bibtex by Taru Karttunen."
22065 (interactive)
22066 (let ((reftex-docstruct-symbol 'rds)
22067 (reftex-cite-format "\\cite{%l}")
22068 rds bib)
22069 (save-excursion
22070 (save-restriction
22071 (widen)
22072 (let ((case-fold-search t)
22073 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22074 (if (not (save-excursion
22075 (or (re-search-forward re nil t)
22076 (re-search-backward re nil t))))
22077 (error "No bibliography defined in file")
22078 (setq bib (concat (match-string 1) ".bib")
22079 rds (list (list 'bib bib)))))))
22080 (call-interactively 'reftex-citation)))
22082 ;;;; Functions extending outline functionality
22084 (defun org-beginning-of-line (&optional arg)
22085 "Go to the beginning of the current line. If that is invisible, continue
22086 to a visible line beginning. This makes the function of C-a more intuitive.
22087 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22088 first attempt, and only move to after the tags when the cursor is already
22089 beyond the end of the headline."
22090 (interactive "P")
22091 (let ((pos (point))
22092 (special (if (consp org-special-ctrl-a/e)
22093 (car org-special-ctrl-a/e)
22094 org-special-ctrl-a/e))
22095 refpos)
22096 (if (org-bound-and-true-p visual-line-mode)
22097 (beginning-of-visual-line 1)
22098 (beginning-of-line 1))
22099 (if (and arg (fboundp 'move-beginning-of-line))
22100 (call-interactively 'move-beginning-of-line)
22101 (if (bobp)
22103 (backward-char 1)
22104 (if (org-truely-invisible-p)
22105 (while (and (not (bobp)) (org-truely-invisible-p))
22106 (backward-char 1)
22107 (beginning-of-line 1))
22108 (forward-char 1))))
22109 (when special
22110 (cond
22111 ((and (looking-at org-complex-heading-regexp)
22112 (= (char-after (match-end 1)) ?\ ))
22113 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22114 (point-at-eol)))
22115 (goto-char
22116 (if (eq special t)
22117 (cond ((> pos refpos) refpos)
22118 ((= pos (point)) refpos)
22119 (t (point)))
22120 (cond ((> pos (point)) (point))
22121 ((not (eq last-command this-command)) (point))
22122 (t refpos)))))
22123 ((org-at-item-p)
22124 ;; Being at an item and not looking at an the item means point
22125 ;; was previously moved to beginning of a visual line, which
22126 ;; doesn't contain the item. Therefore, do nothing special,
22127 ;; just stay here.
22128 (when (looking-at org-list-full-item-re)
22129 ;; Set special position at first white space character after
22130 ;; bullet, and check-box, if any.
22131 (let ((after-bullet
22132 (let ((box (match-end 3)))
22133 (if (not box) (match-end 1)
22134 (let ((after (char-after box)))
22135 (if (and after (= after ? )) (1+ box) box))))))
22136 ;; Special case: Move point to special position when
22137 ;; currently after it or at beginning of line.
22138 (if (eq special t)
22139 (when (or (> pos after-bullet) (= (point) pos))
22140 (goto-char after-bullet))
22141 ;; Reversed case: Move point to special position when
22142 ;; point was already at beginning of line and command is
22143 ;; repeated.
22144 (when (and (= (point) pos) (eq last-command this-command))
22145 (goto-char after-bullet))))))))
22146 (org-no-warnings
22147 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22149 (defun org-end-of-line (&optional arg)
22150 "Go to the end of the line.
22151 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22152 tags on the first attempt, and only move to after the tags when
22153 the cursor is already beyond the end of the headline."
22154 (interactive "P")
22155 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22156 org-special-ctrl-a/e))
22157 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22158 'end-of-visual-line)
22159 ((fboundp 'move-end-of-line) 'move-end-of-line)
22160 (t 'end-of-line))))
22161 (if (or (not special) arg) (call-interactively move-fun)
22162 (let* ((element (save-excursion (beginning-of-line)
22163 (org-element-at-point)))
22164 (type (org-element-type element)))
22165 (cond
22166 ((memq type '(headline inlinetask))
22167 (let ((pos (point)))
22168 (beginning-of-line 1)
22169 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22170 (if (eq special t)
22171 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22172 (goto-char (match-beginning 1))
22173 (goto-char (match-end 0)))
22174 (if (or (< pos (match-end 0))
22175 (not (eq this-command last-command)))
22176 (goto-char (match-end 0))
22177 (goto-char (match-beginning 1))))
22178 (call-interactively move-fun))))
22179 ((org-element-property :hiddenp element)
22180 ;; If element is hidden, `move-end-of-line' would put point
22181 ;; after it. Use `end-of-line' to stay on current line.
22182 (call-interactively 'end-of-line))
22183 (t (call-interactively move-fun)))))
22184 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22186 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22187 (define-key org-mode-map "\C-e" 'org-end-of-line)
22189 (defun org-backward-sentence (&optional arg)
22190 "Go to beginning of sentence, or beginning of table field.
22191 This will call `backward-sentence' or `org-table-beginning-of-field',
22192 depending on context."
22193 (interactive "P")
22194 (cond
22195 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22196 (t (call-interactively 'backward-sentence))))
22198 (defun org-forward-sentence (&optional arg)
22199 "Go to end of sentence, or end of table field.
22200 This will call `forward-sentence' or `org-table-end-of-field',
22201 depending on context."
22202 (interactive "P")
22203 (cond
22204 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22205 (t (call-interactively 'forward-sentence))))
22207 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22208 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22210 (defun org-kill-line (&optional arg)
22211 "Kill line, to tags or end of line."
22212 (interactive "P")
22213 (cond
22214 ((or (not org-special-ctrl-k)
22215 (bolp)
22216 (not (org-at-heading-p)))
22217 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22218 org-ctrl-k-protect-subtree)
22219 (if (or (eq org-ctrl-k-protect-subtree 'error)
22220 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22221 (error "C-k aborted - would kill hidden subtree")))
22222 (call-interactively
22223 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22224 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22225 (kill-region (point) (match-beginning 1))
22226 (org-set-tags nil t))
22227 (t (kill-region (point) (point-at-eol)))))
22229 (define-key org-mode-map "\C-k" 'org-kill-line)
22231 (defun org-yank (&optional arg)
22232 "Yank. If the kill is a subtree, treat it specially.
22233 This command will look at the current kill and check if is a single
22234 subtree, or a series of subtrees[1]. If it passes the test, and if the
22235 cursor is at the beginning of a line or after the stars of a currently
22236 empty headline, then the yank is handled specially. How exactly depends
22237 on the value of the following variables, both set by default.
22239 org-yank-folded-subtrees
22240 When set, the subtree(s) will be folded after insertion, but only
22241 if doing so would now swallow text after the yanked text.
22243 org-yank-adjusted-subtrees
22244 When set, the subtree will be promoted or demoted in order to
22245 fit into the local outline tree structure, which means that the level
22246 will be adjusted so that it becomes the smaller one of the two
22247 *visible* surrounding headings.
22249 Any prefix to this command will cause `yank' to be called directly with
22250 no special treatment. In particular, a simple \\[universal-argument] prefix \
22251 will just
22252 plainly yank the text as it is.
22254 \[1] The test checks if the first non-white line is a heading
22255 and if there are no other headings with fewer stars."
22256 (interactive "P")
22257 (org-yank-generic 'yank arg))
22259 (defun org-yank-generic (command arg)
22260 "Perform some yank-like command.
22262 This function implements the behavior described in the `org-yank'
22263 documentation. However, it has been generalized to work for any
22264 interactive command with similar behavior."
22266 ;; pretend to be command COMMAND
22267 (setq this-command command)
22269 (if arg
22270 (call-interactively command)
22272 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22273 (and (org-kill-is-subtree-p)
22274 (or (bolp)
22275 (and (looking-at "[ \t]*$")
22276 (string-match
22277 "\\`\\*+\\'"
22278 (buffer-substring (point-at-bol) (point)))))))
22279 swallowp)
22280 (cond
22281 ((and subtreep org-yank-folded-subtrees)
22282 (let ((beg (point))
22283 end)
22284 (if (and subtreep org-yank-adjusted-subtrees)
22285 (org-paste-subtree nil nil 'for-yank)
22286 (call-interactively command))
22288 (setq end (point))
22289 (goto-char beg)
22290 (when (and (bolp) subtreep
22291 (not (setq swallowp
22292 (org-yank-folding-would-swallow-text beg end))))
22293 (org-with-limited-levels
22294 (or (looking-at org-outline-regexp)
22295 (re-search-forward org-outline-regexp-bol end t))
22296 (while (and (< (point) end) (looking-at org-outline-regexp))
22297 (hide-subtree)
22298 (org-cycle-show-empty-lines 'folded)
22299 (condition-case nil
22300 (outline-forward-same-level 1)
22301 (error (goto-char end))))))
22302 (when swallowp
22303 (message
22304 "Inserted text not folded because that would swallow text"))
22306 (goto-char end)
22307 (skip-chars-forward " \t\n\r")
22308 (beginning-of-line 1)
22309 (push-mark beg 'nomsg)))
22310 ((and subtreep org-yank-adjusted-subtrees)
22311 (let ((beg (point-at-bol)))
22312 (org-paste-subtree nil nil 'for-yank)
22313 (push-mark beg 'nomsg)))
22315 (call-interactively command))))))
22317 (defun org-yank-folding-would-swallow-text (beg end)
22318 "Would hide-subtree at BEG swallow any text after END?"
22319 (let (level)
22320 (org-with-limited-levels
22321 (save-excursion
22322 (goto-char beg)
22323 (when (or (looking-at org-outline-regexp)
22324 (re-search-forward org-outline-regexp-bol end t))
22325 (setq level (org-outline-level)))
22326 (goto-char end)
22327 (skip-chars-forward " \t\r\n\v\f")
22328 (if (or (eobp)
22329 (and (bolp) (looking-at org-outline-regexp)
22330 (<= (org-outline-level) level)))
22331 nil ; Nothing would be swallowed
22332 t))))) ; something would swallow
22334 (define-key org-mode-map "\C-y" 'org-yank)
22336 (defun org-truely-invisible-p ()
22337 "Check if point is at a character currently not visible.
22338 This version does not only check the character property, but also
22339 `visible-mode'."
22340 ;; Early versions of noutline don't have `outline-invisible-p'.
22341 (if (org-bound-and-true-p visible-mode)
22343 (outline-invisible-p)))
22345 (defun org-invisible-p2 ()
22346 "Check if point is at a character currently not visible."
22347 (save-excursion
22348 (if (and (eolp) (not (bobp))) (backward-char 1))
22349 ;; Early versions of noutline don't have `outline-invisible-p'.
22350 (outline-invisible-p)))
22352 (defun org-back-to-heading (&optional invisible-ok)
22353 "Call `outline-back-to-heading', but provide a better error message."
22354 (condition-case nil
22355 (outline-back-to-heading invisible-ok)
22356 (error (error "Before first headline at position %d in buffer %s"
22357 (point) (current-buffer)))))
22359 (defun org-before-first-heading-p ()
22360 "Before first heading?"
22361 (save-excursion
22362 (end-of-line)
22363 (null (re-search-backward org-outline-regexp-bol nil t))))
22365 (defun org-at-heading-p (&optional ignored)
22366 (outline-on-heading-p t))
22367 ;; Compatibility alias with Org versions < 7.8.03
22368 (defalias 'org-on-heading-p 'org-at-heading-p)
22370 (defun org-at-comment-p nil
22371 "Is cursor in a line starting with a # character?"
22372 (save-excursion
22373 (beginning-of-line)
22374 (looking-at "^#")))
22376 (defun org-at-drawer-p nil
22377 "Is cursor at a drawer keyword?"
22378 (save-excursion
22379 (move-beginning-of-line 1)
22380 (looking-at org-drawer-regexp)))
22382 (defun org-at-block-p nil
22383 "Is cursor at a block keyword?"
22384 (save-excursion
22385 (move-beginning-of-line 1)
22386 (looking-at org-block-regexp)))
22388 (defun org-point-at-end-of-empty-headline ()
22389 "If point is at the end of an empty headline, return t, else nil.
22390 If the heading only contains a TODO keyword, it is still still considered
22391 empty."
22392 (and (looking-at "[ \t]*$")
22393 (when org-todo-line-regexp
22394 (save-excursion
22395 (beginning-of-line 1)
22396 (let ((case-fold-search nil))
22397 (looking-at org-todo-line-regexp)
22398 (string= (match-string 3) ""))))))
22400 (defun org-at-heading-or-item-p ()
22401 (or (org-at-heading-p) (org-at-item-p)))
22403 (defun org-at-target-p ()
22404 (or (org-in-regexp org-radio-target-regexp)
22405 (org-in-regexp org-target-regexp)))
22406 ;; Compatibility alias with Org versions < 7.8.03
22407 (defalias 'org-on-target-p 'org-at-target-p)
22409 (defun org-up-heading-all (arg)
22410 "Move to the heading line of which the present line is a subheading.
22411 This function considers both visible and invisible heading lines.
22412 With argument, move up ARG levels."
22413 (if (fboundp 'outline-up-heading-all)
22414 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22415 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22417 (defun org-up-heading-safe ()
22418 "Move to the heading line of which the present line is a subheading.
22419 This version will not throw an error. It will return the level of the
22420 headline found, or nil if no higher level is found.
22422 Also, this function will be a lot faster than `outline-up-heading',
22423 because it relies on stars being the outline starters. This can really
22424 make a significant difference in outlines with very many siblings."
22425 (let (start-level re)
22426 (org-back-to-heading t)
22427 (setq start-level (funcall outline-level))
22428 (if (equal start-level 1)
22430 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22431 (if (re-search-backward re nil t)
22432 (funcall outline-level)))))
22434 (defun org-first-sibling-p ()
22435 "Is this heading the first child of its parents?"
22436 (interactive)
22437 (let ((re org-outline-regexp-bol)
22438 level l)
22439 (unless (org-at-heading-p t)
22440 (error "Not at a heading"))
22441 (setq level (funcall outline-level))
22442 (save-excursion
22443 (if (not (re-search-backward re nil t))
22445 (setq l (funcall outline-level))
22446 (< l level)))))
22448 (defun org-goto-sibling (&optional previous)
22449 "Goto the next sibling, even if it is invisible.
22450 When PREVIOUS is set, go to the previous sibling instead. Returns t
22451 when a sibling was found. When none is found, return nil and don't
22452 move point."
22453 (let ((fun (if previous 're-search-backward 're-search-forward))
22454 (pos (point))
22455 (re org-outline-regexp-bol)
22456 level l)
22457 (when (condition-case nil (org-back-to-heading t) (error nil))
22458 (setq level (funcall outline-level))
22459 (catch 'exit
22460 (or previous (forward-char 1))
22461 (while (funcall fun re nil t)
22462 (setq l (funcall outline-level))
22463 (when (< l level) (goto-char pos) (throw 'exit nil))
22464 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22465 (goto-char pos)
22466 nil))))
22468 (defun org-show-siblings ()
22469 "Show all siblings of the current headline."
22470 (save-excursion
22471 (while (org-goto-sibling) (org-flag-heading nil)))
22472 (save-excursion
22473 (while (org-goto-sibling 'previous)
22474 (org-flag-heading nil))))
22476 (defun org-goto-first-child ()
22477 "Goto the first child, even if it is invisible.
22478 Return t when a child was found. Otherwise don't move point and
22479 return nil."
22480 (let (level (pos (point)) (re org-outline-regexp-bol))
22481 (when (condition-case nil (org-back-to-heading t) (error nil))
22482 (setq level (outline-level))
22483 (forward-char 1)
22484 (if (and (re-search-forward re nil t) (> (outline-level) level))
22485 (progn (goto-char (match-beginning 0)) t)
22486 (goto-char pos) nil))))
22488 (defun org-show-hidden-entry ()
22489 "Show an entry where even the heading is hidden."
22490 (save-excursion
22491 (org-show-entry)))
22493 (defun org-flag-heading (flag &optional entry)
22494 "Flag the current heading. FLAG non-nil means make invisible.
22495 When ENTRY is non-nil, show the entire entry."
22496 (save-excursion
22497 (org-back-to-heading t)
22498 ;; Check if we should show the entire entry
22499 (if entry
22500 (progn
22501 (org-show-entry)
22502 (save-excursion
22503 (and (outline-next-heading)
22504 (org-flag-heading nil))))
22505 (outline-flag-region (max (point-min) (1- (point)))
22506 (save-excursion (outline-end-of-heading) (point))
22507 flag))))
22509 (defun org-get-next-sibling ()
22510 "Move to next heading of the same level, and return point.
22511 If there is no such heading, return nil.
22512 This is like outline-next-sibling, but invisible headings are ok."
22513 (let ((level (funcall outline-level)))
22514 (outline-next-heading)
22515 (while (and (not (eobp)) (> (funcall outline-level) level))
22516 (outline-next-heading))
22517 (if (or (eobp) (< (funcall outline-level) level))
22519 (point))))
22521 (defun org-get-last-sibling ()
22522 "Move to previous heading of the same level, and return point.
22523 If there is no such heading, return nil."
22524 (let ((opoint (point))
22525 (level (funcall outline-level)))
22526 (outline-previous-heading)
22527 (when (and (/= (point) opoint) (outline-on-heading-p t))
22528 (while (and (> (funcall outline-level) level)
22529 (not (bobp)))
22530 (outline-previous-heading))
22531 (if (< (funcall outline-level) level)
22533 (point)))))
22535 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22536 "Goto to the end of a subtree."
22537 ;; This contains an exact copy of the original function, but it uses
22538 ;; `org-back-to-heading', to make it work also in invisible
22539 ;; trees. And is uses an invisible-ok argument.
22540 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22541 ;; Furthermore, when used inside Org, finding the end of a large subtree
22542 ;; with many children and grandchildren etc, this can be much faster
22543 ;; than the outline version.
22544 (org-back-to-heading invisible-ok)
22545 (let ((first t)
22546 (level (funcall outline-level)))
22547 (if (and (derived-mode-p 'org-mode) (< level 1000))
22548 ;; A true heading (not a plain list item), in Org-mode
22549 ;; This means we can easily find the end by looking
22550 ;; only for the right number of stars. Using a regexp to do
22551 ;; this is so much faster than using a Lisp loop.
22552 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22553 (forward-char 1)
22554 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22555 ;; something else, do it the slow way
22556 (while (and (not (eobp))
22557 (or first (> (funcall outline-level) level)))
22558 (setq first nil)
22559 (outline-next-heading)))
22560 (unless to-heading
22561 (if (memq (preceding-char) '(?\n ?\^M))
22562 (progn
22563 ;; Go to end of line before heading
22564 (forward-char -1)
22565 (if (memq (preceding-char) '(?\n ?\^M))
22566 ;; leave blank line before heading
22567 (forward-char -1))))))
22568 (point))
22570 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22571 "Use Org version in org-mode, for dramatic speed-up."
22572 (if (derived-mode-p 'org-mode)
22573 (progn
22574 (org-end-of-subtree nil t)
22575 (unless (eobp) (backward-char 1)))
22576 ad-do-it))
22578 (defun org-end-of-meta-data-and-drawers ()
22579 "Jump to the first text after meta data and drawers in the current entry.
22580 This will move over empty lines, lines with planning time stamps,
22581 clocking lines, and drawers."
22582 (org-back-to-heading t)
22583 (let ((end (save-excursion (outline-next-heading) (point)))
22584 (re (concat "\\(" org-drawer-regexp "\\)"
22585 "\\|" "[ \t]*" org-keyword-time-regexp)))
22586 (forward-line 1)
22587 (while (re-search-forward re end t)
22588 (if (not (match-end 1))
22589 ;; empty or planning line
22590 (forward-line 1)
22591 ;; a drawer, find the end
22592 (re-search-forward "^[ \t]*:END:" end 'move)
22593 (forward-line 1)))
22594 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22595 (point)))
22597 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22598 "Move forward to the arg'th subheading at same level as this one.
22599 Stop at the first and last subheadings of a superior heading.
22600 Normally this only looks at visible headings, but when INVISIBLE-OK is
22601 non-nil it will also look at invisible ones."
22602 (interactive "p")
22603 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22604 (outline-next-heading)
22605 (org-at-heading-p)
22606 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22607 (re (format "^\\*\\{1,%d\\} " level))
22609 (forward-char 1)
22610 (while (> arg 0)
22611 (while (and (re-search-forward re nil 'move)
22612 (setq l (- (match-end 0) (match-beginning 0) 1))
22613 (= l level)
22614 (not invisible-ok)
22615 (progn (backward-char 1) (outline-invisible-p)))
22616 (if (< l level) (setq arg 1)))
22617 (setq arg (1- arg)))
22618 (beginning-of-line 1))))
22620 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22621 "Move backward to the arg'th subheading at same level as this one.
22622 Stop at the first and last subheadings of a superior heading."
22623 (interactive "p")
22624 (if (not (ignore-errors (org-back-to-heading)))
22625 (goto-char (point-min))
22626 (org-at-heading-p)
22627 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22628 (re (format "^\\*\\{1,%d\\} " level))
22630 (while (> arg 0)
22631 (while (and (re-search-backward re nil 'move)
22632 (setq l (- (match-end 0) (match-beginning 0) 1))
22633 (= l level)
22634 (not invisible-ok)
22635 (outline-invisible-p))
22636 (if (< l level) (setq arg 1)))
22637 (setq arg (1- arg))))))
22639 (defun org-forward-element ()
22640 "Move forward by one element.
22641 Move to the next element at the same level, when possible."
22642 (interactive)
22643 (cond ((eobp) (error "Cannot move further down"))
22644 ((org-with-limited-levels (org-at-heading-p))
22645 (let ((origin (point)))
22646 (org-forward-heading-same-level 1)
22647 (unless (org-with-limited-levels (org-at-heading-p))
22648 (goto-char origin)
22649 (error "Cannot move further down"))))
22651 (let* ((elem (org-element-at-point))
22652 (end (org-element-property :end elem))
22653 (parent (org-element-property :parent elem)))
22654 (if (and parent (= (org-element-property :contents-end parent) end))
22655 (goto-char (org-element-property :end parent))
22656 (goto-char end))))))
22658 (defun org-backward-element ()
22659 "Move backward by one element.
22660 Move to the previous element at the same level, when possible."
22661 (interactive)
22662 (cond ((bobp) (error "Cannot move further up"))
22663 ((org-with-limited-levels (org-at-heading-p))
22664 ;; At an headline, move to the previous one, if any, or stay
22665 ;; here.
22666 (let ((origin (point)))
22667 (org-backward-heading-same-level 1)
22668 (unless (org-with-limited-levels (org-at-heading-p))
22669 (goto-char origin)
22670 (error "Cannot move further up"))))
22672 (let* ((trail (org-element-at-point 'keep-trail))
22673 (elem (car trail))
22674 (prev-elem (nth 1 trail))
22675 (beg (org-element-property :begin elem)))
22676 (cond
22677 ;; Move to beginning of current element if point isn't
22678 ;; there already.
22679 ((/= (point) beg) (goto-char beg))
22680 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22681 ((org-before-first-heading-p) (goto-char (point-min)))
22682 (t (org-back-to-heading)))))))
22684 (defun org-up-element ()
22685 "Move to upper element."
22686 (interactive)
22687 (if (org-with-limited-levels (org-at-heading-p))
22688 (unless (org-up-heading-safe) (error "No surrounding element"))
22689 (let* ((elem (org-element-at-point))
22690 (parent (org-element-property :parent elem)))
22691 (if parent (goto-char (org-element-property :begin parent))
22692 (if (org-with-limited-levels (org-before-first-heading-p))
22693 (error "No surrounding element")
22694 (org-with-limited-levels (org-back-to-heading)))))))
22696 (defvar org-element-greater-elements)
22697 (defun org-down-element ()
22698 "Move to inner element."
22699 (interactive)
22700 (let ((element (org-element-at-point)))
22701 (cond
22702 ((memq (org-element-type element) '(plain-list table))
22703 (goto-char (org-element-property :contents-begin element))
22704 (forward-char))
22705 ((memq (org-element-type element) org-element-greater-elements)
22706 ;; If contents are hidden, first disclose them.
22707 (when (org-element-property :hiddenp element) (org-cycle))
22708 (goto-char (or (org-element-property :contents-begin element)
22709 (error "No content for this element"))))
22710 (t (error "No inner element")))))
22712 (defun org-drag-element-backward ()
22713 "Move backward element at point."
22714 (interactive)
22715 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22716 (let* ((trail (org-element-at-point 'keep-trail))
22717 (elem (car trail))
22718 (prev-elem (nth 1 trail)))
22719 ;; Error out if no previous element or previous element is
22720 ;; a parent of the current one.
22721 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22722 (error "Cannot drag element backward")
22723 (let ((pos (point)))
22724 (org-element-swap-A-B prev-elem elem)
22725 (goto-char (+ (org-element-property :begin prev-elem)
22726 (- pos (org-element-property :begin elem)))))))))
22728 (defun org-drag-element-forward ()
22729 "Move forward element at point."
22730 (interactive)
22731 (let* ((pos (point))
22732 (elem (org-element-at-point)))
22733 (when (= (point-max) (org-element-property :end elem))
22734 (error "Cannot drag element forward"))
22735 (goto-char (org-element-property :end elem))
22736 (let ((next-elem (org-element-at-point)))
22737 (when (or (org-element-nested-p elem next-elem)
22738 (and (eq (org-element-type next-elem) 'headline)
22739 (not (eq (org-element-type elem) 'headline))))
22740 (goto-char pos)
22741 (error "Cannot drag element forward"))
22742 ;; Compute new position of point: it's shifted by NEXT-ELEM
22743 ;; body's length (without final blanks) and by the length of
22744 ;; blanks between ELEM and NEXT-ELEM.
22745 (let ((size-next (- (save-excursion
22746 (goto-char (org-element-property :end next-elem))
22747 (skip-chars-backward " \r\t\n")
22748 (forward-line)
22749 ;; Small correction if buffer doesn't end
22750 ;; with a newline character.
22751 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22752 (org-element-property :begin next-elem)))
22753 (size-blank (- (org-element-property :end elem)
22754 (save-excursion
22755 (goto-char (org-element-property :end elem))
22756 (skip-chars-backward " \r\t\n")
22757 (forward-line)
22758 (point)))))
22759 (org-element-swap-A-B elem next-elem)
22760 (goto-char (+ pos size-next size-blank))))))
22762 (defun org-mark-element ()
22763 "Put point at beginning of this element, mark at end.
22765 Interactively, if this command is repeated or (in Transient Mark
22766 mode) if the mark is active, it marks the next element after the
22767 ones already marked."
22768 (interactive)
22769 (let (deactivate-mark)
22770 (if (and (org-called-interactively-p 'any)
22771 (or (and (eq last-command this-command) (mark t))
22772 (and transient-mark-mode mark-active)))
22773 (set-mark
22774 (save-excursion
22775 (goto-char (mark))
22776 (goto-char (org-element-property :end (org-element-at-point)))))
22777 (let ((element (org-element-at-point)))
22778 (end-of-line)
22779 (push-mark (org-element-property :end element) t t)
22780 (goto-char (org-element-property :begin element))))))
22782 (defun org-narrow-to-element ()
22783 "Narrow buffer to current element."
22784 (interactive)
22785 (let ((elem (org-element-at-point)))
22786 (cond
22787 ((eq (car elem) 'headline)
22788 (narrow-to-region
22789 (org-element-property :begin elem)
22790 (org-element-property :end elem)))
22791 ((memq (car elem) org-element-greater-elements)
22792 (narrow-to-region
22793 (org-element-property :contents-begin elem)
22794 (org-element-property :contents-end elem)))
22796 (narrow-to-region
22797 (org-element-property :begin elem)
22798 (org-element-property :end elem))))))
22800 (defun org-transpose-words ()
22801 "Transpose words, using `org-mode' syntax table."
22802 (interactive)
22803 (with-syntax-table org-syntax-table
22804 (call-interactively 'transpose-words)))
22805 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22807 (defun org-transpose-element ()
22808 "Transpose current and previous elements, keeping blank lines between.
22809 Point is moved after both elements."
22810 (interactive)
22811 (org-skip-whitespace)
22812 (let ((end (org-element-property :end (org-element-at-point))))
22813 (org-drag-element-backward)
22814 (goto-char end)))
22816 (defun org-unindent-buffer ()
22817 "Un-indent the visible part of the buffer.
22818 Relative indentation (between items, inside blocks, etc.) isn't
22819 modified."
22820 (interactive)
22821 (unless (eq major-mode 'org-mode)
22822 (error "Cannot un-indent a buffer not in Org mode"))
22823 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22824 unindent-tree ; For byte-compiler.
22825 (unindent-tree
22826 (function
22827 (lambda (contents)
22828 (mapc
22829 (lambda (element)
22830 (if (memq (org-element-type element) '(headline section))
22831 (funcall unindent-tree (org-element-contents element))
22832 (save-excursion
22833 (save-restriction
22834 (narrow-to-region
22835 (org-element-property :begin element)
22836 (org-element-property :end element))
22837 (org-do-remove-indentation)))))
22838 (reverse contents))))))
22839 (funcall unindent-tree (org-element-contents parse-tree))))
22841 (defun org-show-subtree ()
22842 "Show everything after this heading at deeper levels."
22843 (interactive)
22844 (outline-flag-region
22845 (point)
22846 (save-excursion
22847 (org-end-of-subtree t t))
22848 nil))
22850 (defun org-show-entry ()
22851 "Show the body directly following this heading.
22852 Show the heading too, if it is currently invisible."
22853 (interactive)
22854 (save-excursion
22855 (condition-case nil
22856 (progn
22857 (org-back-to-heading t)
22858 (outline-flag-region
22859 (max (point-min) (1- (point)))
22860 (save-excursion
22861 (if (re-search-forward
22862 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22863 (match-beginning 1)
22864 (point-max)))
22865 nil)
22866 (org-cycle-hide-drawers 'children))
22867 (error nil))))
22869 (defun org-make-options-regexp (kwds &optional extra)
22870 "Make a regular expression for keyword lines."
22871 (concat
22872 "^#\\+\\("
22873 (mapconcat 'regexp-quote kwds "\\|")
22874 (if extra (concat "\\|" extra))
22875 "\\):[ \t]*\\(.*\\)"))
22877 ;; Make isearch reveal the necessary context
22878 (defun org-isearch-end ()
22879 "Reveal context after isearch exits."
22880 (when isearch-success ; only if search was successful
22881 (if (featurep 'xemacs)
22882 ;; Under XEmacs, the hook is run in the correct place,
22883 ;; we directly show the context.
22884 (org-show-context 'isearch)
22885 ;; In Emacs the hook runs *before* restoring the overlays.
22886 ;; So we have to use a one-time post-command-hook to do this.
22887 ;; (Emacs 22 has a special variable, see function `org-mode')
22888 (unless (and (boundp 'isearch-mode-end-hook-quit)
22889 isearch-mode-end-hook-quit)
22890 ;; Only when the isearch was not quitted.
22891 (org-add-hook 'post-command-hook 'org-isearch-post-command
22892 'append 'local)))))
22894 (defun org-isearch-post-command ()
22895 "Remove self from hook, and show context."
22896 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22897 (org-show-context 'isearch))
22900 ;;;; Integration with and fixes for other packages
22902 ;;; Imenu support
22904 (defvar org-imenu-markers nil
22905 "All markers currently used by Imenu.")
22906 (make-variable-buffer-local 'org-imenu-markers)
22908 (defun org-imenu-new-marker (&optional pos)
22909 "Return a new marker for use by Imenu, and remember the marker."
22910 (let ((m (make-marker)))
22911 (move-marker m (or pos (point)))
22912 (push m org-imenu-markers)
22915 (defun org-imenu-get-tree ()
22916 "Produce the index for Imenu."
22917 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22918 (setq org-imenu-markers nil)
22919 (let* ((n org-imenu-depth)
22920 (re (concat "^" (org-get-limited-outline-regexp)))
22921 (subs (make-vector (1+ n) nil))
22922 (last-level 0)
22923 m level head)
22924 (save-excursion
22925 (save-restriction
22926 (widen)
22927 (goto-char (point-max))
22928 (while (re-search-backward re nil t)
22929 (setq level (org-reduced-level (funcall outline-level)))
22930 (when (and (<= level n)
22931 (looking-at org-complex-heading-regexp))
22932 (setq head (org-link-display-format
22933 (org-match-string-no-properties 4))
22934 m (org-imenu-new-marker))
22935 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22936 (if (>= level last-level)
22937 (push (cons head m) (aref subs level))
22938 (push (cons head (aref subs (1+ level))) (aref subs level))
22939 (loop for i from (1+ level) to n do (aset subs i nil)))
22940 (setq last-level level)))))
22941 (aref subs 1)))
22943 (eval-after-load "imenu"
22944 '(progn
22945 (add-hook 'imenu-after-jump-hook
22946 (lambda ()
22947 (if (derived-mode-p 'org-mode)
22948 (org-show-context 'org-goto))))))
22950 (defun org-link-display-format (link)
22951 "Replace a link with either the description, or the link target
22952 if no description is present"
22953 (save-match-data
22954 (if (string-match org-bracket-link-analytic-regexp link)
22955 (replace-match (if (match-end 5)
22956 (match-string 5 link)
22957 (concat (match-string 1 link)
22958 (match-string 3 link)))
22959 nil t link)
22960 link)))
22962 (defun org-toggle-link-display ()
22963 "Toggle the literal or descriptive display of links."
22964 (interactive)
22965 (if org-descriptive-links
22966 (progn (org-remove-from-invisibility-spec '(org-link))
22967 (org-restart-font-lock)
22968 (setq org-descriptive-links nil))
22969 (progn (add-to-invisibility-spec '(org-link))
22970 (org-restart-font-lock)
22971 (setq org-descriptive-links t))))
22973 ;; Speedbar support
22975 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22976 "Overlay marking the agenda restriction line in speedbar.")
22977 (overlay-put org-speedbar-restriction-lock-overlay
22978 'face 'org-agenda-restriction-lock)
22979 (overlay-put org-speedbar-restriction-lock-overlay
22980 'help-echo "Agendas are currently limited to this item.")
22981 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22983 (defun org-speedbar-set-agenda-restriction ()
22984 "Restrict future agenda commands to the location at point in speedbar.
22985 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22986 (interactive)
22987 (require 'org-agenda)
22988 (let (p m tp np dir txt)
22989 (cond
22990 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22991 'org-imenu t))
22992 (setq m (get-text-property p 'org-imenu-marker))
22993 (with-current-buffer (marker-buffer m)
22994 (goto-char m)
22995 (org-agenda-set-restriction-lock 'subtree)))
22996 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22997 'speedbar-function 'speedbar-find-file))
22998 (setq tp (previous-single-property-change
22999 (1+ p) 'speedbar-function)
23000 np (next-single-property-change
23001 tp 'speedbar-function)
23002 dir (speedbar-line-directory)
23003 txt (buffer-substring-no-properties (or tp (point-min))
23004 (or np (point-max))))
23005 (with-current-buffer (find-file-noselect
23006 (let ((default-directory dir))
23007 (expand-file-name txt)))
23008 (unless (derived-mode-p 'org-mode)
23009 (error "Cannot restrict to non-Org-mode file"))
23010 (org-agenda-set-restriction-lock 'file)))
23011 (t (error "Don't know how to restrict Org-mode's agenda")))
23012 (move-overlay org-speedbar-restriction-lock-overlay
23013 (point-at-bol) (point-at-eol))
23014 (setq current-prefix-arg nil)
23015 (org-agenda-maybe-redo)))
23017 (eval-after-load "speedbar"
23018 '(progn
23019 (speedbar-add-supported-extension ".org")
23020 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23021 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23022 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23023 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23024 (add-hook 'speedbar-visiting-tag-hook
23025 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23027 ;;; Fixes and Hacks for problems with other packages
23029 ;; Make flyspell not check words in links, to not mess up our keymap
23030 (defun org-mode-flyspell-verify ()
23031 "Don't let flyspell put overlays at active buttons, or on
23032 {todo,all-time,additional-option-like}-keywords."
23033 (let ((pos (max (1- (point)) (point-min)))
23034 (word (thing-at-point 'word)))
23035 (and (not (get-text-property pos 'keymap))
23036 (not (get-text-property pos 'org-no-flyspell))
23037 (not (member word org-todo-keywords-1))
23038 (not (member word org-all-time-keywords))
23039 (not (member word org-options-keywords))
23040 (not (member word (mapcar 'car org-startup-options)))
23041 (not (member word org-additional-option-like-keywords-for-flyspell)))))
23043 (defun org-remove-flyspell-overlays-in (beg end)
23044 "Remove flyspell overlays in region."
23045 (and (org-bound-and-true-p flyspell-mode)
23046 (fboundp 'flyspell-delete-region-overlays)
23047 (flyspell-delete-region-overlays beg end))
23048 (add-text-properties beg end '(org-no-flyspell t)))
23050 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23051 (eval-after-load "bookmark"
23052 '(if (boundp 'bookmark-after-jump-hook)
23053 ;; We can use the hook
23054 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23055 ;; Hook not available, use advice
23056 (defadvice bookmark-jump (after org-make-visible activate)
23057 "Make the position visible."
23058 (org-bookmark-jump-unhide))))
23060 ;; Make sure saveplace shows the location if it was hidden
23061 (eval-after-load "saveplace"
23062 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23063 "Make the position visible."
23064 (org-bookmark-jump-unhide)))
23066 ;; Make sure ecb shows the location if it was hidden
23067 (eval-after-load "ecb"
23068 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23069 "Make hierarchy visible when jumping into location from ECB tree buffer."
23070 (if (derived-mode-p 'org-mode)
23071 (org-show-context))))
23073 (defun org-bookmark-jump-unhide ()
23074 "Unhide the current position, to show the bookmark location."
23075 (and (derived-mode-p 'org-mode)
23076 (or (outline-invisible-p)
23077 (save-excursion (goto-char (max (point-min) (1- (point))))
23078 (outline-invisible-p)))
23079 (org-show-context 'bookmark-jump)))
23081 ;; Make session.el ignore our circular variable
23082 (eval-after-load "session"
23083 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23085 ;;;; Experimental code
23087 (defun org-closed-in-range ()
23088 "Sparse tree of items closed in a certain time range.
23089 Still experimental, may disappear in the future."
23090 (interactive)
23091 ;; Get the time interval from the user.
23092 (let* ((time1 (org-float-time
23093 (org-read-date nil 'to-time nil "Starting date: ")))
23094 (time2 (org-float-time
23095 (org-read-date nil 'to-time nil "End date:")))
23096 ;; callback function
23097 (callback (lambda ()
23098 (let ((time
23099 (org-float-time
23100 (apply 'encode-time
23101 (org-parse-time-string
23102 (match-string 1))))))
23103 ;; check if time in interval
23104 (and (>= time time1) (<= time time2))))))
23105 ;; make tree, check each match with the callback
23106 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23108 ;;;; Finish up
23110 (provide 'org)
23112 (run-hooks 'org-load-hook)
23114 ;;; org.el ends here