Revert "Compatibility: Use org-define-obsolete-{function,variable}-alias"
[org-mode.git] / lisp / org.el
blob1c6fd5193360a19bfc2945f0c7772543a6525b79
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-map "org-element" (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
151 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
152 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
154 ;; load languages based on value of `org-babel-load-languages'
155 (defvar org-babel-load-languages)
157 ;;;###autoload
158 (defun org-babel-do-load-languages (sym value)
159 "Load the languages defined in `org-babel-load-languages'."
160 (set-default sym value)
161 (mapc (lambda (pair)
162 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
163 (if active
164 (progn
165 (require (intern (concat "ob-" lang))))
166 (progn
167 (funcall 'fmakunbound
168 (intern (concat "org-babel-execute:" lang)))
169 (funcall 'fmakunbound
170 (intern (concat "org-babel-expand-body:" lang)))))))
171 org-babel-load-languages))
173 (defcustom org-babel-load-languages '((emacs-lisp . t))
174 "Languages which can be evaluated in Org-mode buffers.
175 This list can be used to load support for any of the languages
176 below, note that each language will depend on a different set of
177 system executables and/or Emacs modes. When a language is
178 \"loaded\", then code blocks in that language can be evaluated
179 with `org-babel-execute-src-block' bound by default to C-c
180 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
181 be set to remove code block evaluation from the C-c C-c
182 keybinding. By default only Emacs Lisp (which has no
183 requirements) is loaded."
184 :group 'org-babel
185 :set 'org-babel-do-load-languages
186 :version "24.1"
187 :type '(alist :tag "Babel Languages"
188 :key-type
189 (choice
190 (const :tag "Awk" awk)
191 (const :tag "C" C)
192 (const :tag "R" R)
193 (const :tag "Asymptote" asymptote)
194 (const :tag "Calc" calc)
195 (const :tag "Clojure" clojure)
196 (const :tag "CSS" css)
197 (const :tag "Ditaa" ditaa)
198 (const :tag "Dot" dot)
199 (const :tag "Emacs Lisp" emacs-lisp)
200 (const :tag "Fortran" fortran)
201 (const :tag "Gnuplot" gnuplot)
202 (const :tag "Haskell" haskell)
203 (const :tag "IO" io)
204 (const :tag "Java" java)
205 (const :tag "Javascript" js)
206 (const :tag "LaTeX" latex)
207 (const :tag "Ledger" ledger)
208 (const :tag "Lilypond" lilypond)
209 (const :tag "Lisp" lisp)
210 (const :tag "Makefile" makefile)
211 (const :tag "Maxima" maxima)
212 (const :tag "Matlab" matlab)
213 (const :tag "Mscgen" mscgen)
214 (const :tag "Ocaml" ocaml)
215 (const :tag "Octave" octave)
216 (const :tag "Org" org)
217 (const :tag "Perl" perl)
218 (const :tag "Pico Lisp" picolisp)
219 (const :tag "PlantUML" plantuml)
220 (const :tag "Python" python)
221 (const :tag "Ruby" ruby)
222 (const :tag "Sass" sass)
223 (const :tag "Scala" scala)
224 (const :tag "Scheme" scheme)
225 (const :tag "Screen" screen)
226 (const :tag "Shell Script" sh)
227 (const :tag "Shen" shen)
228 (const :tag "Sql" sql)
229 (const :tag "Sqlite" sqlite))
230 :value-type (boolean :tag "Activate" :value t)))
232 ;;;; Customization variables
233 (defcustom org-clone-delete-id nil
234 "Remove ID property of clones of a subtree.
235 When non-nil, clones of a subtree don't inherit the ID property.
236 Otherwise they inherit the ID property with a new unique
237 identifier."
238 :type 'boolean
239 :version "24.1"
240 :group 'org-id)
242 ;;; Version
243 (org-check-version)
245 ;;;###autoload
246 (defun org-version (&optional here full message)
247 "Show the org-mode version in the echo area.
248 With prefix argument HERE, insert it at point.
249 When FULL is non-nil, use a verbose version string.
250 When MESSAGE is non-nil, display a message with the version."
251 (interactive "P")
252 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
253 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
254 (load-suffixes (list ".el"))
255 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
256 (org-trash (or
257 (and (fboundp 'org-release) (fboundp 'org-git-version))
258 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
259 (load-suffixes save-load-suffixes)
260 (org-version (org-release))
261 (git-version (org-git-version))
262 (version (format "Org-mode version %s (%s @ %s)"
263 org-version
264 git-version
265 (if org-install-dir
266 (if (string= org-dir org-install-dir)
267 org-install-dir
268 (concat "mixed installation! " org-install-dir " and " org-dir))
269 "org-loaddefs.el can not be found!")))
270 (_version (if full version org-version)))
271 (if (org-called-interactively-p 'interactive)
272 (if here
273 (insert version)
274 (message version))
275 (if message (message _version))
276 _version)))
278 (defconst org-version (org-version))
280 ;;; Compatibility constants
282 ;;; The custom variables
284 (defgroup org nil
285 "Outline-based notes management and organizer."
286 :tag "Org"
287 :group 'outlines
288 :group 'calendar)
290 (defcustom org-mode-hook nil
291 "Mode hook for Org-mode, run after the mode was turned on."
292 :group 'org
293 :type 'hook)
295 (defcustom org-load-hook nil
296 "Hook that is run after org.el has been loaded."
297 :group 'org
298 :type 'hook)
300 (defcustom org-log-buffer-setup-hook nil
301 "Hook that is run after an Org log buffer is created."
302 :group 'org
303 :version "24.1"
304 :type 'hook)
306 (defvar org-modules) ; defined below
307 (defvar org-modules-loaded nil
308 "Have the modules been loaded already?")
310 (defun org-load-modules-maybe (&optional force)
311 "Load all extensions listed in `org-modules'."
312 (when (or force (not org-modules-loaded))
313 (mapc (lambda (ext)
314 (condition-case nil (require ext)
315 (error (message "Problems while trying to load feature `%s'" ext))))
316 org-modules)
317 (setq org-modules-loaded t)))
319 (defun org-set-modules (var value)
320 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
321 (set var value)
322 (when (featurep 'org)
323 (org-load-modules-maybe 'force)))
325 (when (org-bound-and-true-p org-modules)
326 (let ((a (member 'org-infojs org-modules)))
327 (and a (setcar a 'org-jsinfo))))
329 (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)
330 "Modules that should always be loaded together with org.el.
331 If a description starts with <C>, the file is not part of Emacs
332 and loading it will require that you have downloaded and properly installed
333 the org-mode distribution.
335 You can also use this system to load external packages (i.e. neither Org
336 core modules, nor modules from the CONTRIB directory). Just add symbols
337 to the end of the list. If the package is called org-xyz.el, then you need
338 to add the symbol `xyz', and the package must have a call to
340 (provide 'org-xyz)"
341 :group 'org
342 :set 'org-set-modules
343 :type
344 '(set :greedy t
345 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
346 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
347 (const :tag " crypt: Encryption of subtrees" org-crypt)
348 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
349 (const :tag " docview: Links to doc-view buffers" org-docview)
350 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
351 (const :tag " id: Global IDs for identifying entries" org-id)
352 (const :tag " info: Links to Info nodes" org-info)
353 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
354 (const :tag " habit: Track your consistency with habits" org-habit)
355 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
356 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
357 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
358 (const :tag " mew Links to Mew folders/messages" org-mew)
359 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
360 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
361 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
362 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
363 (const :tag " vm: Links to VM folders/messages" org-vm)
364 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
365 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
366 (const :tag " mouse: Additional mouse support" org-mouse)
367 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
369 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
370 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
371 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
372 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
373 (const :tag "C collector: Collect properties into tables" org-collector)
374 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
375 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
376 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
377 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
378 (const :tag "C eval: Include command output as text" org-eval)
379 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
380 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
381 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
382 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
383 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
385 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
387 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
388 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
389 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
390 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
391 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
392 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
393 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
394 (const :tag "C mtags: Support for muse-like tags" org-mtags)
395 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
396 (const :tag "C registry: A registry for Org-mode links" org-registry)
397 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
398 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
399 (const :tag "C secretary: Team management with org-mode" org-secretary)
400 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
401 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
402 (const :tag "C track: Keep up with Org-mode development" org-track)
403 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
404 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
405 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
407 (defcustom org-support-shift-select nil
408 "Non-nil means make shift-cursor commands select text when possible.
410 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
411 start selecting a region, or enlarge regions started in this way.
412 In Org-mode, in special contexts, these same keys are used for
413 other purposes, important enough to compete with shift selection.
414 Org tries to balance these needs by supporting `shift-select-mode'
415 outside these special contexts, under control of this variable.
417 The default of this variable is nil, to avoid confusing behavior. Shifted
418 cursor keys will then execute Org commands in the following contexts:
419 - on a headline, changing TODO state (left/right) and priority (up/down)
420 - on a time stamp, changing the time
421 - in a plain list item, changing the bullet type
422 - in a property definition line, switching between allowed values
423 - in the BEGIN line of a clock table (changing the time block).
424 Outside these contexts, the commands will throw an error.
426 When this variable is t and the cursor is not in a special
427 context, Org-mode will support shift-selection for making and
428 enlarging regions. To make this more effective, the bullet
429 cycling will no longer happen anywhere in an item line, but only
430 if the cursor is exactly on the bullet.
432 If you set this variable to the symbol `always', then the keys
433 will not be special in headlines, property lines, and item lines,
434 to make shift selection work there as well. If this is what you
435 want, you can use the following alternative commands: `C-c C-t'
436 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
437 can be used to switch TODO sets, `C-c -' to cycle item bullet
438 types, and properties can be edited by hand or in column view.
440 However, when the cursor is on a timestamp, shift-cursor commands
441 will still edit the time stamp - this is just too good to give up.
443 XEmacs user should have this variable set to nil, because
444 `shift-select-mode' is in Emacs 23 or later only."
445 :group 'org
446 :type '(choice
447 (const :tag "Never" nil)
448 (const :tag "When outside special context" t)
449 (const :tag "Everywhere except timestamps" always)))
451 (defcustom org-loop-over-headlines-in-active-region nil
452 "Shall some commands act upon headlines in the active region?
454 When set to `t', some commands will be performed in all headlines
455 within the active region.
457 When set to `start-level', some commands will be performed in all
458 headlines within the active region, provided that these headlines
459 are of the same level than the first one.
461 When set to a string, those commands will be performed on the
462 matching headlines within the active region. Such string must be
463 a tags/property/todo match as it is used in the agenda tags view.
465 The list of commands is: `org-schedule', `org-deadline',
466 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
467 `org-archive-to-archive-sibling'. The archiving commands skip
468 already archived entries."
469 :type '(choice (const :tag "Don't loop" nil)
470 (const :tag "All headlines in active region" t)
471 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
472 (string :tag "Tags/Property/Todo matcher"))
473 :version "24.1"
474 :group 'org-todo
475 :group 'org-archive)
477 (defgroup org-startup nil
478 "Options concerning startup of Org-mode."
479 :tag "Org Startup"
480 :group 'org)
482 (defcustom org-startup-folded t
483 "Non-nil means entering Org-mode will switch to OVERVIEW.
484 This can also be configured on a per-file basis by adding one of
485 the following lines anywhere in the buffer:
487 #+STARTUP: fold (or `overview', this is equivalent)
488 #+STARTUP: nofold (or `showall', this is equivalent)
489 #+STARTUP: content
490 #+STARTUP: showeverything"
491 :group 'org-startup
492 :type '(choice
493 (const :tag "nofold: show all" nil)
494 (const :tag "fold: overview" t)
495 (const :tag "content: all headlines" content)
496 (const :tag "show everything, even drawers" showeverything)))
498 (defcustom org-startup-truncated t
499 "Non-nil means entering Org-mode will set `truncate-lines'.
500 This is useful since some lines containing links can be very long and
501 uninteresting. Also tables look terrible when wrapped."
502 :group 'org-startup
503 :type 'boolean)
505 (defcustom org-startup-indented nil
506 "Non-nil means turn on `org-indent-mode' on startup.
507 This can also be configured on a per-file basis by adding one of
508 the following lines anywhere in the buffer:
510 #+STARTUP: indent
511 #+STARTUP: noindent"
512 :group 'org-structure
513 :type '(choice
514 (const :tag "Not" nil)
515 (const :tag "Globally (slow on startup in large files)" t)))
517 (defcustom org-use-sub-superscripts t
518 "Non-nil means interpret \"_\" and \"^\" for export.
519 When this option is turned on, you can use TeX-like syntax for sub- and
520 superscripts. Several characters after \"_\" or \"^\" will be
521 considered as a single item - so grouping with {} is normally not
522 needed. For example, the following things will be parsed as single
523 sub- or superscripts.
525 10^24 or 10^tau several digits will be considered 1 item.
526 10^-12 or 10^-tau a leading sign with digits or a word
527 x^2-y^3 will be read as x^2 - y^3, because items are
528 terminated by almost any nonword/nondigit char.
529 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
531 Still, ambiguity is possible - so when in doubt use {} to enclose the
532 sub/superscript. If you set this variable to the symbol `{}',
533 the braces are *required* in order to trigger interpretations as
534 sub/superscript. This can be helpful in documents that need \"_\"
535 frequently in plain text.
537 Not all export backends support this, but HTML does.
539 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
540 :group 'org-startup
541 :group 'org-export-translation
542 :version "24.1"
543 :type '(choice
544 (const :tag "Always interpret" t)
545 (const :tag "Only with braces" {})
546 (const :tag "Never interpret" nil)))
548 (if (fboundp 'defvaralias)
549 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
552 (defcustom org-startup-with-beamer-mode nil
553 "Non-nil means turn on `org-beamer-mode' on startup.
554 This can also be configured on a per-file basis by adding one of
555 the following lines anywhere in the buffer:
557 #+STARTUP: beamer"
558 :group 'org-startup
559 :version "24.1"
560 :type 'boolean)
562 (defcustom org-startup-align-all-tables nil
563 "Non-nil means align all tables when visiting a file.
564 This is useful when the column width in tables is forced with <N> cookies
565 in table fields. Such tables will look correct only after the first re-align.
566 This can also be configured on a per-file basis by adding one of
567 the following lines anywhere in the buffer:
568 #+STARTUP: align
569 #+STARTUP: noalign"
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-startup-with-inline-images nil
574 "Non-nil means show inline images when loading a new Org file.
575 This can also be configured on a per-file basis by adding one of
576 the following lines anywhere in the buffer:
577 #+STARTUP: inlineimages
578 #+STARTUP: noinlineimages"
579 :group 'org-startup
580 :version "24.1"
581 :type 'boolean)
583 (defcustom org-insert-mode-line-in-empty-file nil
584 "Non-nil means insert the first line setting Org-mode in empty files.
585 When the function `org-mode' is called interactively in an empty file, this
586 normally means that the file name does not automatically trigger Org-mode.
587 To ensure that the file will always be in Org-mode in the future, a
588 line enforcing Org-mode will be inserted into the buffer, if this option
589 has been set."
590 :group 'org-startup
591 :type 'boolean)
593 (defcustom org-replace-disputed-keys nil
594 "Non-nil means use alternative key bindings for some keys.
595 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
596 These keys are also used by other packages like shift-selection-mode'
597 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
598 If you want to use Org-mode together with one of these other modes,
599 or more generally if you would like to move some Org-mode commands to
600 other keys, set this variable and configure the keys with the variable
601 `org-disputed-keys'.
603 This option is only relevant at load-time of Org-mode, and must be set
604 *before* org.el is loaded. Changing it requires a restart of Emacs to
605 become effective."
606 :group 'org-startup
607 :type 'boolean)
609 (defcustom org-use-extra-keys nil
610 "Non-nil means use extra key sequence definitions for certain commands.
611 This happens automatically if you run XEmacs or if `window-system'
612 is nil. This variable lets you do the same manually. You must
613 set it before loading org.
615 Example: on Carbon Emacs 22 running graphically, with an external
616 keyboard on a Powerbook, the default way of setting M-left might
617 not work for either Alt or ESC. Setting this variable will make
618 it work for ESC."
619 :group 'org-startup
620 :type 'boolean)
622 (if (fboundp 'defvaralias)
623 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
625 (defcustom org-disputed-keys
626 '(([(shift up)] . [(meta p)])
627 ([(shift down)] . [(meta n)])
628 ([(shift left)] . [(meta -)])
629 ([(shift right)] . [(meta +)])
630 ([(control shift right)] . [(meta shift +)])
631 ([(control shift left)] . [(meta shift -)]))
632 "Keys for which Org-mode and other modes compete.
633 This is an alist, cars are the default keys, second element specifies
634 the alternative to use when `org-replace-disputed-keys' is t.
636 Keys can be specified in any syntax supported by `define-key'.
637 The value of this option takes effect only at Org-mode's startup,
638 therefore you'll have to restart Emacs to apply it after changing."
639 :group 'org-startup
640 :type 'alist)
642 (defun org-key (key)
643 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
644 Or return the original if not disputed.
645 Also apply the translations defined in `org-xemacs-key-equivalents'."
646 (when org-replace-disputed-keys
647 (let* ((nkey (key-description key))
648 (x (org-find-if (lambda (x)
649 (equal (key-description (car x)) nkey))
650 org-disputed-keys)))
651 (setq key (if x (cdr x) key))))
652 (when (featurep 'xemacs)
653 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
654 key)
656 (defun org-find-if (predicate seq)
657 (catch 'exit
658 (while seq
659 (if (funcall predicate (car seq))
660 (throw 'exit (car seq))
661 (pop seq)))))
663 (defun org-defkey (keymap key def)
664 "Define a key, possibly translated, as returned by `org-key'."
665 (define-key keymap (org-key key) def))
667 (defcustom org-ellipsis nil
668 "The ellipsis to use in the Org-mode outline.
669 When nil, just use the standard three dots. When a string, use that instead,
670 When a face, use the standard 3 dots, but with the specified face.
671 The change affects only Org-mode (which will then use its own display table).
672 Changing this requires executing `M-x org-mode' in a buffer to become
673 effective."
674 :group 'org-startup
675 :type '(choice (const :tag "Default" nil)
676 (face :tag "Face" :value org-warning)
677 (string :tag "String" :value "...#")))
679 (defvar org-display-table nil
680 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
682 (defgroup org-keywords nil
683 "Keywords in Org-mode."
684 :tag "Org Keywords"
685 :group 'org)
687 (defcustom org-deadline-string "DEADLINE:"
688 "String to mark deadline entries.
689 A deadline is this string, followed by a time stamp. Should be a word,
690 terminated by a colon. You can insert a schedule keyword and
691 a timestamp with \\[org-deadline].
692 Changes become only effective after restarting Emacs."
693 :group 'org-keywords
694 :type 'string)
696 (defcustom org-scheduled-string "SCHEDULED:"
697 "String to mark scheduled TODO entries.
698 A schedule is this string, followed by a time stamp. Should be a word,
699 terminated by a colon. You can insert a schedule keyword and
700 a timestamp with \\[org-schedule].
701 Changes become only effective after restarting Emacs."
702 :group 'org-keywords
703 :type 'string)
705 (defcustom org-closed-string "CLOSED:"
706 "String used as the prefix for timestamps logging closing a TODO entry."
707 :group 'org-keywords
708 :type 'string)
710 (defcustom org-clock-string "CLOCK:"
711 "String used as prefix for timestamps clocking work hours on an item."
712 :group 'org-keywords
713 :type 'string)
715 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
716 org-scheduled-string "\\|"
717 org-deadline-string "\\|"
718 org-closed-string "\\|"
719 org-clock-string "\\)")
720 "Matches a line with planning or clock info.")
722 (defcustom org-comment-string "COMMENT"
723 "Entries starting with this keyword will never be exported.
724 An entry can be toggled between COMMENT and normal with
725 \\[org-toggle-comment].
726 Changes become only effective after restarting Emacs."
727 :group 'org-keywords
728 :type 'string)
730 (defcustom org-quote-string "QUOTE"
731 "Entries starting with this keyword will be exported in fixed-width font.
732 Quoting applies only to the text in the entry following the headline, and does
733 not extend beyond the next headline, even if that is lower level.
734 An entry can be toggled between QUOTE and normal with
735 \\[org-toggle-fixed-width-section]."
736 :group 'org-keywords
737 :type 'string)
739 (defconst org-repeat-re
740 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
741 "Regular expression for specifying repeated events.
742 After a match, group 1 contains the repeat expression.")
744 (defgroup org-structure nil
745 "Options concerning the general structure of Org-mode files."
746 :tag "Org Structure"
747 :group 'org)
749 (defgroup org-reveal-location nil
750 "Options about how to make context of a location visible."
751 :tag "Org Reveal Location"
752 :group 'org-structure)
754 (defconst org-context-choice
755 '(choice
756 (const :tag "Always" t)
757 (const :tag "Never" nil)
758 (repeat :greedy t :tag "Individual contexts"
759 (cons
760 (choice :tag "Context"
761 (const agenda)
762 (const org-goto)
763 (const occur-tree)
764 (const tags-tree)
765 (const link-search)
766 (const mark-goto)
767 (const bookmark-jump)
768 (const isearch)
769 (const default))
770 (boolean))))
771 "Contexts for the reveal options.")
773 (defcustom org-show-hierarchy-above '((default . t))
774 "Non-nil means show full hierarchy when revealing a location.
775 Org-mode often shows locations in an org-mode file which might have
776 been invisible before. When this is set, the hierarchy of headings
777 above the exposed location is shown.
778 Turning this off for example for sparse trees makes them very compact.
779 Instead of t, this can also be an alist specifying this option for different
780 contexts. Valid contexts are
781 agenda when exposing an entry from the agenda
782 org-goto when using the command `org-goto' on key C-c C-j
783 occur-tree when using the command `org-occur' on key C-c /
784 tags-tree when constructing a sparse tree based on tags matches
785 link-search when exposing search matches associated with a link
786 mark-goto when exposing the jump goal of a mark
787 bookmark-jump when exposing a bookmark location
788 isearch when exiting from an incremental search
789 default default for all contexts not set explicitly"
790 :group 'org-reveal-location
791 :type org-context-choice)
793 (defcustom org-show-following-heading '((default . nil))
794 "Non-nil means show following heading when revealing a location.
795 Org-mode often shows locations in an org-mode file which might have
796 been invisible before. When this is set, the heading following the
797 match is shown.
798 Turning this off for example for sparse trees makes them very compact,
799 but makes it harder to edit the location of the match. In such a case,
800 use the command \\[org-reveal] to show more context.
801 Instead of t, this can also be an alist specifying this option for different
802 contexts. See `org-show-hierarchy-above' for valid contexts."
803 :group 'org-reveal-location
804 :type org-context-choice)
806 (defcustom org-show-siblings '((default . nil) (isearch t))
807 "Non-nil means show all sibling heading when revealing a location.
808 Org-mode often shows locations in an org-mode file which might have
809 been invisible before. When this is set, the sibling of the current entry
810 heading are all made visible. If `org-show-hierarchy-above' is t,
811 the same happens on each level of the hierarchy above the current entry.
813 By default this is on for the isearch context, off for all other contexts.
814 Turning this off for example for sparse trees makes them very compact,
815 but makes it harder to edit the location of the match. In such a case,
816 use the command \\[org-reveal] to show more context.
817 Instead of t, this can also be an alist specifying this option for different
818 contexts. See `org-show-hierarchy-above' for valid contexts."
819 :group 'org-reveal-location
820 :type org-context-choice)
822 (defcustom org-show-entry-below '((default . nil))
823 "Non-nil means show the entry below a headline when revealing a location.
824 Org-mode often shows locations in an org-mode file which might have
825 been invisible before. When this is set, the text below the headline that is
826 exposed is also shown.
828 By default this is off for all contexts.
829 Instead of t, this can also be an alist specifying this option for different
830 contexts. See `org-show-hierarchy-above' for valid contexts."
831 :group 'org-reveal-location
832 :type org-context-choice)
834 (defcustom org-indirect-buffer-display 'other-window
835 "How should indirect tree buffers be displayed?
836 This applies to indirect buffers created with the commands
837 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
838 Valid values are:
839 current-window Display in the current window
840 other-window Just display in another window.
841 dedicated-frame Create one new frame, and re-use it each time.
842 new-frame Make a new frame each time. Note that in this case
843 previously-made indirect buffers are kept, and you need to
844 kill these buffers yourself."
845 :group 'org-structure
846 :group 'org-agenda-windows
847 :type '(choice
848 (const :tag "In current window" current-window)
849 (const :tag "In current frame, other window" other-window)
850 (const :tag "Each time a new frame" new-frame)
851 (const :tag "One dedicated frame" dedicated-frame)))
853 (defcustom org-use-speed-commands nil
854 "Non-nil means activate single letter commands at beginning of a headline.
855 This may also be a function to test for appropriate locations where speed
856 commands should be active."
857 :group 'org-structure
858 :type '(choice
859 (const :tag "Never" nil)
860 (const :tag "At beginning of headline stars" t)
861 (function)))
863 (defcustom org-speed-commands-user nil
864 "Alist of additional speed commands.
865 This list will be checked before `org-speed-commands-default'
866 when the variable `org-use-speed-commands' is non-nil
867 and when the cursor is at the beginning of a headline.
868 The car if each entry is a string with a single letter, which must
869 be assigned to `self-insert-command' in the global map.
870 The cdr is either a command to be called interactively, a function
871 to be called, or a form to be evaluated.
872 An entry that is just a list with a single string will be interpreted
873 as a descriptive headline that will be added when listing the speed
874 commands in the Help buffer using the `?' speed command."
875 :group 'org-structure
876 :type '(repeat :value ("k" . ignore)
877 (choice :value ("k" . ignore)
878 (list :tag "Descriptive Headline" (string :tag "Headline"))
879 (cons :tag "Letter and Command"
880 (string :tag "Command letter")
881 (choice
882 (function)
883 (sexp))))))
885 (defgroup org-cycle nil
886 "Options concerning visibility cycling in Org-mode."
887 :tag "Org Cycle"
888 :group 'org-structure)
890 (defcustom org-cycle-skip-children-state-if-no-children t
891 "Non-nil means skip CHILDREN state in entries that don't have any."
892 :group 'org-cycle
893 :type 'boolean)
895 (defcustom org-cycle-max-level nil
896 "Maximum level which should still be subject to visibility cycling.
897 Levels higher than this will, for cycling, be treated as text, not a headline.
898 When `org-odd-levels-only' is set, a value of N in this variable actually
899 means 2N-1 stars as the limiting headline.
900 When nil, cycle all levels.
901 Note that the limiting level of cycling is also influenced by
902 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
903 `org-inlinetask-min-level' is, cycling will be limited to levels one less
904 than its value."
905 :group 'org-cycle
906 :type '(choice
907 (const :tag "No limit" nil)
908 (integer :tag "Maximum level")))
910 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
911 "Names of drawers. Drawers are not opened by cycling on the headline above.
912 Drawers only open with a TAB on the drawer line itself. A drawer looks like
913 this:
914 :DRAWERNAME:
915 .....
916 :END:
917 The drawer \"PROPERTIES\" is special for capturing properties through
918 the property API.
920 Drawers can be defined on the per-file basis with a line like:
922 #+DRAWERS: HIDDEN STATE PROPERTIES"
923 :group 'org-structure
924 :group 'org-cycle
925 :type '(repeat (string :tag "Drawer Name")))
927 (defcustom org-hide-block-startup nil
928 "Non-nil means entering Org-mode will fold all blocks.
929 This can also be set in on a per-file basis with
931 #+STARTUP: hideblocks
932 #+STARTUP: showblocks"
933 :group 'org-startup
934 :group 'org-cycle
935 :type 'boolean)
937 (defcustom org-cycle-global-at-bob nil
938 "Cycle globally if cursor is at beginning of buffer and not at a headline.
939 This makes it possible to do global cycling without having to use S-TAB or
940 \\[universal-argument] TAB. For this special case to work, the first line
941 of the buffer must not be a headline -- it may be empty or some other text.
942 When used in this way, `org-cycle-hook' is disabled temporarily to make
943 sure the cursor stays at the beginning of the buffer. When this option is
944 nil, don't do anything special at the beginning of the buffer."
945 :group 'org-cycle
946 :type 'boolean)
948 (defcustom org-cycle-level-after-item/entry-creation t
949 "Non-nil means cycle entry level or item indentation in new empty entries.
951 When the cursor is at the end of an empty headline, i.e with only stars
952 and maybe a TODO keyword, TAB will then switch the entry to become a child,
953 and then all possible ancestor states, before returning to the original state.
954 This makes data entry extremely fast: M-RET to create a new headline,
955 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
957 When the cursor is at the end of an empty plain list item, one TAB will
958 make it a subitem, two or more tabs will back up to make this an item
959 higher up in the item hierarchy."
960 :group 'org-cycle
961 :type 'boolean)
963 (defcustom org-cycle-emulate-tab t
964 "Where should `org-cycle' emulate TAB.
965 nil Never
966 white Only in completely white lines
967 whitestart Only at the beginning of lines, before the first non-white char
968 t Everywhere except in headlines
969 exc-hl-bol Everywhere except at the start of a headline
970 If TAB is used in a place where it does not emulate TAB, the current subtree
971 visibility is cycled."
972 :group 'org-cycle
973 :type '(choice (const :tag "Never" nil)
974 (const :tag "Only in completely white lines" white)
975 (const :tag "Before first char in a line" whitestart)
976 (const :tag "Everywhere except in headlines" t)
977 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
980 (defcustom org-cycle-separator-lines 2
981 "Number of empty lines needed to keep an empty line between collapsed trees.
982 If you leave an empty line between the end of a subtree and the following
983 headline, this empty line is hidden when the subtree is folded.
984 Org-mode will leave (exactly) one empty line visible if the number of
985 empty lines is equal or larger to the number given in this variable.
986 So the default 2 means at least 2 empty lines after the end of a subtree
987 are needed to produce free space between a collapsed subtree and the
988 following headline.
990 If the number is negative, and the number of empty lines is at least -N,
991 all empty lines are shown.
993 Special case: when 0, never leave empty lines in collapsed view."
994 :group 'org-cycle
995 :type 'integer)
996 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
998 (defcustom org-pre-cycle-hook nil
999 "Hook that is run before visibility cycling is happening.
1000 The function(s) in this hook must accept a single argument which indicates
1001 the new state that will be set right after running this hook. The
1002 argument is a symbol. Before a global state change, it can have the values
1003 `overview', `content', or `all'. Before a local state change, it can have
1004 the values `folded', `children', or `subtree'."
1005 :group 'org-cycle
1006 :type 'hook)
1008 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1009 org-cycle-hide-drawers
1010 org-cycle-hide-inline-tasks
1011 org-cycle-show-empty-lines
1012 org-optimize-window-after-visibility-change)
1013 "Hook that is run after `org-cycle' has changed the buffer visibility.
1014 The function(s) in this hook must accept a single argument which indicates
1015 the new state that was set by the most recent `org-cycle' command. The
1016 argument is a symbol. After a global state change, it can have the values
1017 `overview', `contents', or `all'. After a local state change, it can have
1018 the values `folded', `children', or `subtree'."
1019 :group 'org-cycle
1020 :type 'hook)
1022 (defgroup org-edit-structure nil
1023 "Options concerning structure editing in Org-mode."
1024 :tag "Org Edit Structure"
1025 :group 'org-structure)
1027 (defcustom org-odd-levels-only nil
1028 "Non-nil means skip even levels and only use odd levels for the outline.
1029 This has the effect that two stars are being added/taken away in
1030 promotion/demotion commands. It also influences how levels are
1031 handled by the exporters.
1032 Changing it requires restart of `font-lock-mode' to become effective
1033 for fontification also in regions already fontified.
1034 You may also set this on a per-file basis by adding one of the following
1035 lines to the buffer:
1037 #+STARTUP: odd
1038 #+STARTUP: oddeven"
1039 :group 'org-edit-structure
1040 :group 'org-appearance
1041 :type 'boolean)
1043 (defcustom org-adapt-indentation t
1044 "Non-nil means adapt indentation to outline node level.
1046 When this variable is set, Org assumes that you write outlines by
1047 indenting text in each node to align with the headline (after the stars).
1048 The following issues are influenced by this variable:
1050 - When this is set and the *entire* text in an entry is indented, the
1051 indentation is increased by one space in a demotion command, and
1052 decreased by one in a promotion command. If any line in the entry
1053 body starts with text at column 0, indentation is not changed at all.
1055 - Property drawers and planning information is inserted indented when
1056 this variable s set. When nil, they will not be indented.
1058 - TAB indents a line relative to context. The lines below a headline
1059 will be indented when this variable is set.
1061 Note that this is all about true indentation, by adding and removing
1062 space characters. See also `org-indent.el' which does level-dependent
1063 indentation in a virtual way, i.e. at display time in Emacs."
1064 :group 'org-edit-structure
1065 :type 'boolean)
1067 (defcustom org-special-ctrl-a/e nil
1068 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1070 When t, `C-a' will bring back the cursor to the beginning of the
1071 headline text, i.e. after the stars and after a possible TODO
1072 keyword. In an item, this will be the position after bullet and
1073 check-box, if any. When the cursor is already at that position,
1074 another `C-a' will bring it to the beginning of the line.
1076 `C-e' will jump to the end of the headline, ignoring the presence
1077 of tags in the headline. A second `C-e' will then jump to the
1078 true end of the line, after any tags. This also means that, when
1079 this variable is non-nil, `C-e' also will never jump beyond the
1080 end of the heading of a folded section, i.e. not after the
1081 ellipses.
1083 When set to the symbol `reversed', the first `C-a' or `C-e' works
1084 normally, going to the true line boundary first. Only a directly
1085 following, identical keypress will bring the cursor to the
1086 special positions.
1088 This may also be a cons cell where the behavior for `C-a' and
1089 `C-e' is set separately."
1090 :group 'org-edit-structure
1091 :type '(choice
1092 (const :tag "off" nil)
1093 (const :tag "on: after stars/bullet and before tags first" t)
1094 (const :tag "reversed: true line boundary first" reversed)
1095 (cons :tag "Set C-a and C-e separately"
1096 (choice :tag "Special C-a"
1097 (const :tag "off" nil)
1098 (const :tag "on: after stars/bullet first" t)
1099 (const :tag "reversed: before stars/bullet first" reversed))
1100 (choice :tag "Special C-e"
1101 (const :tag "off" nil)
1102 (const :tag "on: before tags first" t)
1103 (const :tag "reversed: after tags first" reversed)))))
1104 (if (fboundp 'defvaralias)
1105 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1107 (defcustom org-special-ctrl-k nil
1108 "Non-nil means `C-k' will behave specially in headlines.
1109 When nil, `C-k' will call the default `kill-line' command.
1110 When t, the following will happen while the cursor is in the headline:
1112 - When the cursor is at the beginning of a headline, kill the entire
1113 line and possible the folded subtree below the line.
1114 - When in the middle of the headline text, kill the headline up to the tags.
1115 - When after the headline text, kill the tags."
1116 :group 'org-edit-structure
1117 :type 'boolean)
1119 (defcustom org-ctrl-k-protect-subtree nil
1120 "Non-nil means, do not delete a hidden subtree with C-k.
1121 When set to the symbol `error', simply throw an error when C-k is
1122 used to kill (part-of) a headline that has hidden text behind it.
1123 Any other non-nil value will result in a query to the user, if it is
1124 OK to kill that hidden subtree. When nil, kill without remorse."
1125 :group 'org-edit-structure
1126 :version "24.1"
1127 :type '(choice
1128 (const :tag "Do not protect hidden subtrees" nil)
1129 (const :tag "Protect hidden subtrees with a security query" t)
1130 (const :tag "Never kill a hidden subtree with C-k" error)))
1132 (defcustom org-catch-invisible-edits nil
1133 "Check if in invisible region before inserting or deleting a character.
1134 Valid values are:
1136 nil Do not check, so just do invisible edits.
1137 error Throw an error and do nothing.
1138 show Make point visible, and do the requested edit.
1139 show-and-error Make point visible, then throw an error and abort the edit.
1140 smart Make point visible, and do insertion/deletion if it is
1141 adjacent to visible text and the change feels predictable.
1142 Never delete a previously invisible character or add in the
1143 middle or right after an invisible region. Basically, this
1144 allows insertion and backward-delete right before ellipses.
1145 FIXME: maybe in this case we should not even show?"
1146 :group 'org-edit-structure
1147 :version "24.1"
1148 :type '(choice
1149 (const :tag "Do not check" nil)
1150 (const :tag "Throw error when trying to edit" error)
1151 (const :tag "Unhide, but do not do the edit" show-and-error)
1152 (const :tag "Show invisible part and do the edit" show)
1153 (const :tag "Be smart and do the right thing" smart)))
1155 (defcustom org-yank-folded-subtrees t
1156 "Non-nil means when yanking subtrees, fold them.
1157 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1158 it starts with a heading and all other headings in it are either children
1159 or siblings, then fold all the subtrees. However, do this only if no
1160 text after the yank would be swallowed into a folded tree by this action."
1161 :group 'org-edit-structure
1162 :type 'boolean)
1164 (defcustom org-yank-adjusted-subtrees nil
1165 "Non-nil means when yanking subtrees, adjust the level.
1166 With this setting, `org-paste-subtree' is used to insert the subtree, see
1167 this function for details."
1168 :group 'org-edit-structure
1169 :type 'boolean)
1171 (defcustom org-M-RET-may-split-line '((default . t))
1172 "Non-nil means M-RET will split the line at the cursor position.
1173 When nil, it will go to the end of the line before making a
1174 new line.
1175 You may also set this option in a different way for different
1176 contexts. Valid contexts are:
1178 headline when creating a new headline
1179 item when creating a new item
1180 table in a table field
1181 default the value to be used for all contexts not explicitly
1182 customized"
1183 :group 'org-structure
1184 :group 'org-table
1185 :type '(choice
1186 (const :tag "Always" t)
1187 (const :tag "Never" nil)
1188 (repeat :greedy t :tag "Individual contexts"
1189 (cons
1190 (choice :tag "Context"
1191 (const headline)
1192 (const item)
1193 (const table)
1194 (const default))
1195 (boolean)))))
1198 (defcustom org-insert-heading-respect-content nil
1199 "Non-nil means insert new headings after the current subtree.
1200 When nil, the new heading is created directly after the current line.
1201 The commands \\[org-insert-heading-respect-content] and
1202 \\[org-insert-todo-heading-respect-content] turn this variable on
1203 for the duration of the command."
1204 :group 'org-structure
1205 :type 'boolean)
1207 (defcustom org-blank-before-new-entry '((heading . auto)
1208 (plain-list-item . auto))
1209 "Should `org-insert-heading' leave a blank line before new heading/item?
1210 The value is an alist, with `heading' and `plain-list-item' as CAR,
1211 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1212 which case Org will look at the surrounding headings/items and try to
1213 make an intelligent decision whether to insert a blank line or not.
1215 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1216 set, the setting here is ignored and no empty line is inserted, to avoid
1217 breaking the list structure."
1218 :group 'org-edit-structure
1219 :type '(list
1220 (cons (const heading)
1221 (choice (const :tag "Never" nil)
1222 (const :tag "Always" t)
1223 (const :tag "Auto" auto)))
1224 (cons (const plain-list-item)
1225 (choice (const :tag "Never" nil)
1226 (const :tag "Always" t)
1227 (const :tag "Auto" auto)))))
1229 (defcustom org-insert-heading-hook nil
1230 "Hook being run after inserting a new heading."
1231 :group 'org-edit-structure
1232 :type 'hook)
1234 (defcustom org-enable-fixed-width-editor t
1235 "Non-nil means lines starting with \":\" are treated as fixed-width.
1236 This currently only means they are never auto-wrapped.
1237 When nil, such lines will be treated like ordinary lines.
1238 See also the QUOTE keyword."
1239 :group 'org-edit-structure
1240 :type 'boolean)
1242 (defcustom org-goto-auto-isearch t
1243 "Non-nil means typing characters in `org-goto' starts incremental search.
1244 When nil, you can use these keybindings to navigate the buffer:
1246 q Quit the org-goto interface
1247 n Go to the next visible heading
1248 p Go to the previous visible heading
1249 f Go one heading forward on same level
1250 b Go one heading backward on same level
1251 u Go one heading up"
1252 :group 'org-edit-structure
1253 :type 'boolean)
1255 (defgroup org-sparse-trees nil
1256 "Options concerning sparse trees in Org-mode."
1257 :tag "Org Sparse Trees"
1258 :group 'org-structure)
1260 (defcustom org-highlight-sparse-tree-matches t
1261 "Non-nil means highlight all matches that define a sparse tree.
1262 The highlights will automatically disappear the next time the buffer is
1263 changed by an edit command."
1264 :group 'org-sparse-trees
1265 :type 'boolean)
1267 (defcustom org-remove-highlights-with-change t
1268 "Non-nil means any change to the buffer will remove temporary highlights.
1269 Such highlights are created by `org-occur' and `org-clock-display'.
1270 When nil, `C-c C-c needs to be used to get rid of the highlights.
1271 The highlights created by `org-preview-latex-fragment' always need
1272 `C-c C-c' to be removed."
1273 :group 'org-sparse-trees
1274 :group 'org-time
1275 :type 'boolean)
1278 (defcustom org-occur-hook '(org-first-headline-recenter)
1279 "Hook that is run after `org-occur' has constructed a sparse tree.
1280 This can be used to recenter the window to show as much of the structure
1281 as possible."
1282 :group 'org-sparse-trees
1283 :type 'hook)
1285 (defgroup org-imenu-and-speedbar nil
1286 "Options concerning imenu and speedbar in Org-mode."
1287 :tag "Org Imenu and Speedbar"
1288 :group 'org-structure)
1290 (defcustom org-imenu-depth 2
1291 "The maximum level for Imenu access to Org-mode headlines.
1292 This also applied for speedbar access."
1293 :group 'org-imenu-and-speedbar
1294 :type 'integer)
1296 (defgroup org-table nil
1297 "Options concerning tables in Org-mode."
1298 :tag "Org Table"
1299 :group 'org)
1301 (defcustom org-enable-table-editor 'optimized
1302 "Non-nil means lines starting with \"|\" are handled by the table editor.
1303 When nil, such lines will be treated like ordinary lines.
1305 When equal to the symbol `optimized', the table editor will be optimized to
1306 do the following:
1307 - Automatic overwrite mode in front of whitespace in table fields.
1308 This makes the structure of the table stay in tact as long as the edited
1309 field does not exceed the column width.
1310 - Minimize the number of realigns. Normally, the table is aligned each time
1311 TAB or RET are pressed to move to another field. With optimization this
1312 happens only if changes to a field might have changed the column width.
1313 Optimization requires replacing the functions `self-insert-command',
1314 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1315 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1316 very good at guessing when a re-align will be necessary, but you can always
1317 force one with \\[org-ctrl-c-ctrl-c].
1319 If you would like to use the optimized version in Org-mode, but the
1320 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1322 This variable can be used to turn on and off the table editor during a session,
1323 but in order to toggle optimization, a restart is required.
1325 See also the variable `org-table-auto-blank-field'."
1326 :group 'org-table
1327 :type '(choice
1328 (const :tag "off" nil)
1329 (const :tag "on" t)
1330 (const :tag "on, optimized" optimized)))
1332 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1333 (version<= emacs-version "24.1"))
1334 "Non-nil means cluster self-insert commands for undo when possible.
1335 If this is set, then, like in the Emacs command loop, 20 consecutive
1336 characters will be undone together.
1337 This is configurable, because there is some impact on typing performance."
1338 :group 'org-table
1339 :type 'boolean)
1341 (defcustom org-table-tab-recognizes-table.el t
1342 "Non-nil means TAB will automatically notice a table.el table.
1343 When it sees such a table, it moves point into it and - if necessary -
1344 calls `table-recognize-table'."
1345 :group 'org-table-editing
1346 :type 'boolean)
1348 (defgroup org-link nil
1349 "Options concerning links in Org-mode."
1350 :tag "Org Link"
1351 :group 'org)
1353 (defvar org-link-abbrev-alist-local nil
1354 "Buffer-local version of `org-link-abbrev-alist', which see.
1355 The value of this is taken from the #+LINK lines.")
1356 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1358 (defcustom org-link-abbrev-alist nil
1359 "Alist of link abbreviations.
1360 The car of each element is a string, to be replaced at the start of a link.
1361 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1362 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1364 [[linkkey:tag][description]]
1366 The 'linkkey' must be a word word, starting with a letter, followed
1367 by letters, numbers, '-' or '_'.
1369 If REPLACE is a string, the tag will simply be appended to create the link.
1370 If the string contains \"%s\", the tag will be inserted there. If the string
1371 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1372 at that point (see the function `url-hexify-string'). If the string contains
1373 the specifier \"%(my-function)\", then the custom function `my-function' will
1374 be invoked: this function takes the tag as its only argument and must return
1375 a string.
1377 REPLACE may also be a function that will be called with the tag as the
1378 only argument to create the link, which should be returned as a string.
1380 See the manual for examples."
1381 :group 'org-link
1382 :type '(repeat
1383 (cons
1384 (string :tag "Protocol")
1385 (choice
1386 (string :tag "Format")
1387 (function)))))
1389 (defcustom org-descriptive-links t
1390 "Non-nil means Org will display descriptive links.
1391 E.g. [[http://orgmode.org][Org website]] will be displayed as
1392 \"Org Website\", hiding the link itself and just displaying its
1393 description. When set to `nil', Org will display the full links
1394 literally.
1396 You can interactively set the value of this variable by calling
1397 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1398 :group 'org-link
1399 :type 'boolean)
1401 (defcustom org-link-file-path-type 'adaptive
1402 "How the path name in file links should be stored.
1403 Valid values are:
1405 relative Relative to the current directory, i.e. the directory of the file
1406 into which the link is being inserted.
1407 absolute Absolute path, if possible with ~ for home directory.
1408 noabbrev Absolute path, no abbreviation of home directory.
1409 adaptive Use relative path for files in the current directory and sub-
1410 directories of it. For other files, use an absolute path."
1411 :group 'org-link
1412 :type '(choice
1413 (const relative)
1414 (const absolute)
1415 (const noabbrev)
1416 (const adaptive)))
1418 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1419 "Types of links that should be activated in Org-mode files.
1420 This is a list of symbols, each leading to the activation of a certain link
1421 type. In principle, it does not hurt to turn on most link types - there may
1422 be a small gain when turning off unused link types. The types are:
1424 bracket The recommended [[link][description]] or [[link]] links with hiding.
1425 angle Links in angular brackets that may contain whitespace like
1426 <bbdb:Carsten Dominik>.
1427 plain Plain links in normal text, no whitespace, like http://google.com.
1428 radio Text that is matched by a radio target, see manual for details.
1429 tag Tag settings in a headline (link to tag search).
1430 date Time stamps (link to calendar).
1431 footnote Footnote labels.
1433 Changing this variable requires a restart of Emacs to become effective."
1434 :group 'org-link
1435 :type '(set :greedy t
1436 (const :tag "Double bracket links" bracket)
1437 (const :tag "Angular bracket links" angle)
1438 (const :tag "Plain text links" plain)
1439 (const :tag "Radio target matches" radio)
1440 (const :tag "Tags" tag)
1441 (const :tag "Timestamps" date)
1442 (const :tag "Footnotes" footnote)))
1444 (defcustom org-make-link-description-function nil
1445 "Function to use for generating link descriptions from links.
1446 When nil, the link location will be used. This function must take
1447 two parameters: the first one is the link, the second one is the
1448 description generated by `org-insert-link'. The function should
1449 return the description to use."
1450 :group 'org-link
1451 :type 'function)
1453 (defgroup org-link-store nil
1454 "Options concerning storing links in Org-mode."
1455 :tag "Org Store Link"
1456 :group 'org-link)
1458 (defcustom org-url-hexify-p t
1459 "When non-nil, hexify URL when creating a link."
1460 :type 'boolean
1461 :version "24.3"
1462 :group 'org-link-store)
1464 (defcustom org-email-link-description-format "Email %c: %.30s"
1465 "Format of the description part of a link to an email or usenet message.
1466 The following %-escapes will be replaced by corresponding information:
1468 %F full \"From\" field
1469 %f name, taken from \"From\" field, address if no name
1470 %T full \"To\" field
1471 %t first name in \"To\" field, address if no name
1472 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1473 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1474 %s subject
1475 %d date
1476 %m message-id.
1478 You may use normal field width specification between the % and the letter.
1479 This is for example useful to limit the length of the subject.
1481 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1482 :group 'org-link-store
1483 :type 'string)
1485 (defcustom org-from-is-user-regexp
1486 (let (r1 r2)
1487 (when (and user-mail-address (not (string= user-mail-address "")))
1488 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1489 (when (and user-full-name (not (string= user-full-name "")))
1490 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1491 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1492 "Regexp matched against the \"From:\" header of an email or usenet message.
1493 It should match if the message is from the user him/herself."
1494 :group 'org-link-store
1495 :type 'regexp)
1497 (defcustom org-context-in-file-links t
1498 "Non-nil means file links from `org-store-link' contain context.
1499 A search string will be added to the file name with :: as separator and
1500 used to find the context when the link is activated by the command
1501 `org-open-at-point'. When this option is t, the entire active region
1502 will be placed in the search string of the file link. If set to a
1503 positive integer, only the first n lines of context will be stored.
1505 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1506 negates this setting for the duration of the command."
1507 :group 'org-link-store
1508 :type '(choice boolean integer))
1510 (defcustom org-keep-stored-link-after-insertion nil
1511 "Non-nil means keep link in list for entire session.
1513 The command `org-store-link' adds a link pointing to the current
1514 location to an internal list. These links accumulate during a session.
1515 The command `org-insert-link' can be used to insert links into any
1516 Org-mode file (offering completion for all stored links). When this
1517 option is nil, every link which has been inserted once using \\[org-insert-link]
1518 will be removed from the list, to make completing the unused links
1519 more efficient."
1520 :group 'org-link-store
1521 :type 'boolean)
1523 (defgroup org-link-follow nil
1524 "Options concerning following links in Org-mode."
1525 :tag "Org Follow Link"
1526 :group 'org-link)
1528 (defcustom org-link-translation-function nil
1529 "Function to translate links with different syntax to Org syntax.
1530 This can be used to translate links created for example by the Planner
1531 or emacs-wiki packages to Org syntax.
1532 The function must accept two parameters, a TYPE containing the link
1533 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1534 which is everything after the link protocol. It should return a cons
1535 with possibly modified values of type and path.
1536 Org contains a function for this, so if you set this variable to
1537 `org-translate-link-from-planner', you should be able follow many
1538 links created by planner."
1539 :group 'org-link-follow
1540 :type 'function)
1542 (defcustom org-follow-link-hook nil
1543 "Hook that is run after a link has been followed."
1544 :group 'org-link-follow
1545 :type 'hook)
1547 (defcustom org-tab-follows-link nil
1548 "Non-nil means on links TAB will follow the link.
1549 Needs to be set before org.el is loaded.
1550 This really should not be used, it does not make sense, and the
1551 implementation is bad."
1552 :group 'org-link-follow
1553 :type 'boolean)
1555 (defcustom org-return-follows-link nil
1556 "Non-nil means on links RET will follow the link."
1557 :group 'org-link-follow
1558 :type 'boolean)
1560 (defcustom org-mouse-1-follows-link
1561 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1562 "Non-nil means mouse-1 on a link will follow the link.
1563 A longer mouse click will still set point. Does not work on XEmacs.
1564 Needs to be set before org.el is loaded."
1565 :group 'org-link-follow
1566 :type 'boolean)
1568 (defcustom org-mark-ring-length 4
1569 "Number of different positions to be recorded in the ring.
1570 Changing this requires a restart of Emacs to work correctly."
1571 :group 'org-link-follow
1572 :type 'integer)
1574 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1575 "Non-nil means internal links in Org files must exactly match a headline.
1576 When nil, the link search tries to match a phrase with all words
1577 in the search text."
1578 :group 'org-link-follow
1579 :version "24.1"
1580 :type '(choice
1581 (const :tag "Use fuzzy text search" nil)
1582 (const :tag "Match only exact headline" t)
1583 (const :tag "Match exact headline or query to create it"
1584 query-to-create)))
1586 (defcustom org-link-frame-setup
1587 '((vm . vm-visit-folder-other-frame)
1588 (vm-imap . vm-visit-imap-folder-other-frame)
1589 (gnus . org-gnus-no-new-news)
1590 (file . find-file-other-window)
1591 (wl . wl-other-frame))
1592 "Setup the frame configuration for following links.
1593 When following a link with Emacs, it may often be useful to display
1594 this link in another window or frame. This variable can be used to
1595 set this up for the different types of links.
1596 For VM, use any of
1597 `vm-visit-folder'
1598 `vm-visit-folder-other-window'
1599 `vm-visit-folder-other-frame'
1600 For Gnus, use any of
1601 `gnus'
1602 `gnus-other-frame'
1603 `org-gnus-no-new-news'
1604 For FILE, use any of
1605 `find-file'
1606 `find-file-other-window'
1607 `find-file-other-frame'
1608 For Wanderlust use any of
1609 `wl'
1610 `wl-other-frame'
1611 For the calendar, use the variable `calendar-setup'.
1612 For BBDB, it is currently only possible to display the matches in
1613 another window."
1614 :group 'org-link-follow
1615 :type '(list
1616 (cons (const vm)
1617 (choice
1618 (const vm-visit-folder)
1619 (const vm-visit-folder-other-window)
1620 (const vm-visit-folder-other-frame)))
1621 (cons (const gnus)
1622 (choice
1623 (const gnus)
1624 (const gnus-other-frame)
1625 (const org-gnus-no-new-news)))
1626 (cons (const file)
1627 (choice
1628 (const find-file)
1629 (const find-file-other-window)
1630 (const find-file-other-frame)))
1631 (cons (const wl)
1632 (choice
1633 (const wl)
1634 (const wl-other-frame)))))
1636 (defcustom org-display-internal-link-with-indirect-buffer nil
1637 "Non-nil means use indirect buffer to display infile links.
1638 Activating internal links (from one location in a file to another location
1639 in the same file) normally just jumps to the location. When the link is
1640 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1641 is displayed in
1642 another window. When this option is set, the other window actually displays
1643 an indirect buffer clone of the current buffer, to avoid any visibility
1644 changes to the current buffer."
1645 :group 'org-link-follow
1646 :type 'boolean)
1648 (defcustom org-open-non-existing-files nil
1649 "Non-nil means `org-open-file' will open non-existing files.
1650 When nil, an error will be generated.
1651 This variable applies only to external applications because they
1652 might choke on non-existing files. If the link is to a file that
1653 will be opened in Emacs, the variable is ignored."
1654 :group 'org-link-follow
1655 :type 'boolean)
1657 (defcustom org-open-directory-means-index-dot-org nil
1658 "Non-nil means a link to a directory really means to index.org.
1659 When nil, following a directory link will run dired or open a finder/explorer
1660 window on that directory."
1661 :group 'org-link-follow
1662 :type 'boolean)
1664 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1665 "Function and arguments to call for following mailto links.
1666 This is a list with the first element being a Lisp function, and the
1667 remaining elements being arguments to the function. In string arguments,
1668 %a will be replaced by the address, and %s will be replaced by the subject
1669 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1670 :group 'org-link-follow
1671 :type '(choice
1672 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1673 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1674 (const :tag "message-mail" (message-mail "%a" "%s"))
1675 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1677 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1678 "Non-nil means ask for confirmation before executing shell links.
1679 Shell links can be dangerous: just think about a link
1681 [[shell:rm -rf ~/*][Google Search]]
1683 This link would show up in your Org-mode document as \"Google Search\",
1684 but really it would remove your entire home directory.
1685 Therefore we advise against setting this variable to nil.
1686 Just change it to `y-or-n-p' if you want to confirm with a
1687 single keystroke rather than having to type \"yes\"."
1688 :group 'org-link-follow
1689 :type '(choice
1690 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1691 (const :tag "with y-or-n (faster)" y-or-n-p)
1692 (const :tag "no confirmation (dangerous)" nil)))
1693 (put 'org-confirm-shell-link-function
1694 'safe-local-variable
1695 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1697 (defcustom org-confirm-shell-link-not-regexp ""
1698 "A regexp to skip confirmation for shell links."
1699 :group 'org-link-follow
1700 :version "24.1"
1701 :type 'regexp)
1703 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1704 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1705 Elisp links can be dangerous: just think about a link
1707 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1709 This link would show up in your Org-mode document as \"Google Search\",
1710 but really it would remove your entire home directory.
1711 Therefore we advise against setting this variable to nil.
1712 Just change it to `y-or-n-p' if you want to confirm with a
1713 single keystroke rather than having to type \"yes\"."
1714 :group 'org-link-follow
1715 :type '(choice
1716 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1717 (const :tag "with y-or-n (faster)" y-or-n-p)
1718 (const :tag "no confirmation (dangerous)" nil)))
1719 (put 'org-confirm-shell-link-function
1720 'safe-local-variable
1721 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1723 (defcustom org-confirm-elisp-link-not-regexp ""
1724 "A regexp to skip confirmation for Elisp links."
1725 :group 'org-link-follow
1726 :version "24.1"
1727 :type 'regexp)
1729 (defconst org-file-apps-defaults-gnu
1730 '((remote . emacs)
1731 (system . mailcap)
1732 (t . mailcap))
1733 "Default file applications on a UNIX or GNU/Linux system.
1734 See `org-file-apps'.")
1736 (defconst org-file-apps-defaults-macosx
1737 '((remote . emacs)
1738 (t . "open %s")
1739 (system . "open %s")
1740 ("ps.gz" . "gv %s")
1741 ("eps.gz" . "gv %s")
1742 ("dvi" . "xdvi %s")
1743 ("fig" . "xfig %s"))
1744 "Default file applications on a MacOS X system.
1745 The system \"open\" is known as a default, but we use X11 applications
1746 for some files for which the OS does not have a good default.
1747 See `org-file-apps'.")
1749 (defconst org-file-apps-defaults-windowsnt
1750 (list
1751 '(remote . emacs)
1752 (cons t
1753 (list (if (featurep 'xemacs)
1754 'mswindows-shell-execute
1755 'w32-shell-execute)
1756 "open" 'file))
1757 (cons 'system
1758 (list (if (featurep 'xemacs)
1759 'mswindows-shell-execute
1760 'w32-shell-execute)
1761 "open" 'file)))
1762 "Default file applications on a Windows NT system.
1763 The system \"open\" is used for most files.
1764 See `org-file-apps'.")
1766 (defcustom org-file-apps
1768 (auto-mode . emacs)
1769 ("\\.mm\\'" . default)
1770 ("\\.x?html?\\'" . default)
1771 ("\\.pdf\\'" . default)
1773 "External applications for opening `file:path' items in a document.
1774 Org-mode uses system defaults for different file types, but
1775 you can use this variable to set the application for a given file
1776 extension. The entries in this list are cons cells where the car identifies
1777 files and the cdr the corresponding command. Possible values for the
1778 file identifier are
1779 \"string\" A string as a file identifier can be interpreted in different
1780 ways, depending on its contents:
1782 - Alphanumeric characters only:
1783 Match links with this file extension.
1784 Example: (\"pdf\" . \"evince %s\")
1785 to open PDFs with evince.
1787 - Regular expression: Match links where the
1788 filename matches the regexp. If you want to
1789 use groups here, use shy groups.
1791 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1792 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1793 to open *.html and *.xhtml with firefox.
1795 - Regular expression which contains (non-shy) groups:
1796 Match links where the whole link, including \"::\", and
1797 anything after that, matches the regexp.
1798 In a custom command string, %1, %2, etc. are replaced with
1799 the parts of the link that were matched by the groups.
1800 For backwards compatibility, if a command string is given
1801 that does not use any of the group matches, this case is
1802 handled identically to the second one (i.e. match against
1803 file name only).
1804 In a custom lisp form, you can access the group matches with
1805 (match-string n link).
1807 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1808 to open [[file:document.pdf::5]] with evince at page 5.
1810 `directory' Matches a directory
1811 `remote' Matches a remote file, accessible through tramp or efs.
1812 Remote files most likely should be visited through Emacs
1813 because external applications cannot handle such paths.
1814 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1815 so all files Emacs knows how to handle. Using this with
1816 command `emacs' will open most files in Emacs. Beware that this
1817 will also open html files inside Emacs, unless you add
1818 (\"html\" . default) to the list as well.
1819 t Default for files not matched by any of the other options.
1820 `system' The system command to open files, like `open' on Windows
1821 and Mac OS X, and mailcap under GNU/Linux. This is the command
1822 that will be selected if you call `C-c C-o' with a double
1823 \\[universal-argument] \\[universal-argument] prefix.
1825 Possible values for the command are:
1826 `emacs' The file will be visited by the current Emacs process.
1827 `default' Use the default application for this file type, which is the
1828 association for t in the list, most likely in the system-specific
1829 part.
1830 This can be used to overrule an unwanted setting in the
1831 system-specific variable.
1832 `system' Use the system command for opening files, like \"open\".
1833 This command is specified by the entry whose car is `system'.
1834 Most likely, the system-specific version of this variable
1835 does define this command, but you can overrule/replace it
1836 here.
1837 string A command to be executed by a shell; %s will be replaced
1838 by the path to the file.
1839 sexp A Lisp form which will be evaluated. The file path will
1840 be available in the Lisp variable `file'.
1841 For more examples, see the system specific constants
1842 `org-file-apps-defaults-macosx'
1843 `org-file-apps-defaults-windowsnt'
1844 `org-file-apps-defaults-gnu'."
1845 :group 'org-link-follow
1846 :type '(repeat
1847 (cons (choice :value ""
1848 (string :tag "Extension")
1849 (const :tag "System command to open files" system)
1850 (const :tag "Default for unrecognized files" t)
1851 (const :tag "Remote file" remote)
1852 (const :tag "Links to a directory" directory)
1853 (const :tag "Any files that have Emacs modes"
1854 auto-mode))
1855 (choice :value ""
1856 (const :tag "Visit with Emacs" emacs)
1857 (const :tag "Use default" default)
1858 (const :tag "Use the system command" system)
1859 (string :tag "Command")
1860 (sexp :tag "Lisp form")))))
1862 (defcustom org-doi-server-url "http://dx.doi.org/"
1863 "The URL of the DOI server."
1864 :type 'string
1865 :version "24.3"
1866 :group 'org-link-follow)
1868 (defgroup org-refile nil
1869 "Options concerning refiling entries in Org-mode."
1870 :tag "Org Refile"
1871 :group 'org)
1873 (defcustom org-directory "~/org"
1874 "Directory with org files.
1875 This is just a default location to look for Org files. There is no need
1876 at all to put your files into this directory. It is only used in the
1877 following situations:
1879 1. When a capture template specifies a target file that is not an
1880 absolute path. The path will then be interpreted relative to
1881 `org-directory'
1882 2. When a capture note is filed away in an interactive way (when exiting the
1883 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1884 with `org-directory' as the default path."
1885 :group 'org-refile
1886 :group 'org-remember
1887 :group 'org-capture
1888 :type 'directory)
1890 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1891 "Default target for storing notes.
1892 Used as a fall back file for org-remember.el and org-capture.el, for
1893 templates that do not specify a target file."
1894 :group 'org-refile
1895 :group 'org-remember
1896 :group 'org-capture
1897 :type '(choice
1898 (const :tag "Default from remember-data-file" nil)
1899 file))
1901 (defcustom org-goto-interface 'outline
1902 "The default interface to be used for `org-goto'.
1903 Allowed values are:
1904 outline The interface shows an outline of the relevant file
1905 and the correct heading is found by moving through
1906 the outline or by searching with incremental search.
1907 outline-path-completion Headlines in the current buffer are offered via
1908 completion. This is the interface also used by
1909 the refile command."
1910 :group 'org-refile
1911 :type '(choice
1912 (const :tag "Outline" outline)
1913 (const :tag "Outline-path-completion" outline-path-completion)))
1915 (defcustom org-goto-max-level 5
1916 "Maximum target level when running `org-goto' with refile interface."
1917 :group 'org-refile
1918 :type 'integer)
1920 (defcustom org-reverse-note-order nil
1921 "Non-nil means store new notes at the beginning of a file or entry.
1922 When nil, new notes will be filed to the end of a file or entry.
1923 This can also be a list with cons cells of regular expressions that
1924 are matched against file names, and values."
1925 :group 'org-remember
1926 :group 'org-capture
1927 :group 'org-refile
1928 :type '(choice
1929 (const :tag "Reverse always" t)
1930 (const :tag "Reverse never" nil)
1931 (repeat :tag "By file name regexp"
1932 (cons regexp boolean))))
1934 (defcustom org-log-refile nil
1935 "Information to record when a task is refiled.
1937 Possible values are:
1939 nil Don't add anything
1940 time Add a time stamp to the task
1941 note Prompt for a note and add it with template `org-log-note-headings'
1943 This option can also be set with on a per-file-basis with
1945 #+STARTUP: nologrefile
1946 #+STARTUP: logrefile
1947 #+STARTUP: lognoterefile
1949 You can have local logging settings for a subtree by setting the LOGGING
1950 property to one or more of these keywords.
1952 When bulk-refiling from the agenda, the value `note' is forbidden and
1953 will temporarily be changed to `time'."
1954 :group 'org-refile
1955 :group 'org-progress
1956 :version "24.1"
1957 :type '(choice
1958 (const :tag "No logging" nil)
1959 (const :tag "Record timestamp" time)
1960 (const :tag "Record timestamp with note." note)))
1962 (defcustom org-refile-targets nil
1963 "Targets for refiling entries with \\[org-refile].
1964 This is a list of cons cells. Each cell contains:
1965 - a specification of the files to be considered, either a list of files,
1966 or a symbol whose function or variable value will be used to retrieve
1967 a file name or a list of file names. If you use `org-agenda-files' for
1968 that, all agenda files will be scanned for targets. Nil means consider
1969 headings in the current buffer.
1970 - A specification of how to find candidate refile targets. This may be
1971 any of:
1972 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1973 This tag has to be present in all target headlines, inheritance will
1974 not be considered.
1975 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1976 todo keyword.
1977 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1978 headlines that are refiling targets.
1979 - a cons cell (:level . N). Any headline of level N is considered a target.
1980 Note that, when `org-odd-levels-only' is set, level corresponds to
1981 order in hierarchy, not to the number of stars.
1982 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1983 Note that, when `org-odd-levels-only' is set, level corresponds to
1984 order in hierarchy, not to the number of stars.
1986 Each element of this list generates a set of possible targets.
1987 The union of these sets is presented (with completion) to
1988 the user by `org-refile'.
1990 You can set the variable `org-refile-target-verify-function' to a function
1991 to verify each headline found by the simple criteria above.
1993 When this variable is nil, all top-level headlines in the current buffer
1994 are used, equivalent to the value `((nil . (:level . 1))'."
1995 :group 'org-refile
1996 :type '(repeat
1997 (cons
1998 (choice :value org-agenda-files
1999 (const :tag "All agenda files" org-agenda-files)
2000 (const :tag "Current buffer" nil)
2001 (function) (variable) (file))
2002 (choice :tag "Identify target headline by"
2003 (cons :tag "Specific tag" (const :value :tag) (string))
2004 (cons :tag "TODO keyword" (const :value :todo) (string))
2005 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2006 (cons :tag "Level number" (const :value :level) (integer))
2007 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2009 (defcustom org-refile-target-verify-function nil
2010 "Function to verify if the headline at point should be a refile target.
2011 The function will be called without arguments, with point at the
2012 beginning of the headline. It should return t and leave point
2013 where it is if the headline is a valid target for refiling.
2015 If the target should not be selected, the function must return nil.
2016 In addition to this, it may move point to a place from where the search
2017 should be continued. For example, the function may decide that the entire
2018 subtree of the current entry should be excluded and move point to the end
2019 of the subtree."
2020 :group 'org-refile
2021 :type 'function)
2023 (defcustom org-refile-use-cache nil
2024 "Non-nil means cache refile targets to speed up the process.
2025 The cache for a particular file will be updated automatically when
2026 the buffer has been killed, or when any of the marker used for flagging
2027 refile targets no longer points at a live buffer.
2028 If you have added new entries to a buffer that might themselves be targets,
2029 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2030 find that easier, `C-u C-u C-u C-c C-w'."
2031 :group 'org-refile
2032 :version "24.1"
2033 :type 'boolean)
2035 (defcustom org-refile-use-outline-path nil
2036 "Non-nil means provide refile targets as paths.
2037 So a level 3 headline will be available as level1/level2/level3.
2039 When the value is `file', also include the file name (without directory)
2040 into the path. In this case, you can also stop the completion after
2041 the file name, to get entries inserted as top level in the file.
2043 When `full-file-path', include the full file path."
2044 :group 'org-refile
2045 :type '(choice
2046 (const :tag "Not" nil)
2047 (const :tag "Yes" t)
2048 (const :tag "Start with file name" file)
2049 (const :tag "Start with full file path" full-file-path)))
2051 (defcustom org-outline-path-complete-in-steps t
2052 "Non-nil means complete the outline path in hierarchical steps.
2053 When Org-mode uses the refile interface to select an outline path
2054 \(see variable `org-refile-use-outline-path'), the completion of
2055 the path can be done is a single go, or if can be done in steps down
2056 the headline hierarchy. Going in steps is probably the best if you
2057 do not use a special completion package like `ido' or `icicles'.
2058 However, when using these packages, going in one step can be very
2059 fast, while still showing the whole path to the entry."
2060 :group 'org-refile
2061 :type 'boolean)
2063 (defcustom org-refile-allow-creating-parent-nodes nil
2064 "Non-nil means allow to create new nodes as refile targets.
2065 New nodes are then created by adding \"/new node name\" to the completion
2066 of an existing node. When the value of this variable is `confirm',
2067 new node creation must be confirmed by the user (recommended)
2068 When nil, the completion must match an existing entry.
2070 Note that, if the new heading is not seen by the criteria
2071 listed in `org-refile-targets', multiple instances of the same
2072 heading would be created by trying again to file under the new
2073 heading."
2074 :group 'org-refile
2075 :type '(choice
2076 (const :tag "Never" nil)
2077 (const :tag "Always" t)
2078 (const :tag "Prompt for confirmation" confirm)))
2080 (defcustom org-refile-active-region-within-subtree nil
2081 "Non-nil means also refile active region within a subtree.
2083 By default `org-refile' doesn't allow refiling regions if they
2084 don't contain a set of subtrees, but it might be convenient to
2085 do so sometimes: in that case, the first line of the region is
2086 converted to a headline before refiling."
2087 :group 'org-refile
2088 :version "24.1"
2089 :type 'boolean)
2091 (defgroup org-todo nil
2092 "Options concerning TODO items in Org-mode."
2093 :tag "Org TODO"
2094 :group 'org)
2096 (defgroup org-progress nil
2097 "Options concerning Progress logging in Org-mode."
2098 :tag "Org Progress"
2099 :group 'org-time)
2101 (defvar org-todo-interpretation-widgets
2102 '((:tag "Sequence (cycling hits every state)" sequence)
2103 (:tag "Type (cycling directly to DONE)" type))
2104 "The available interpretation symbols for customizing `org-todo-keywords'.
2105 Interested libraries should add to this list.")
2107 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2108 "List of TODO entry keyword sequences and their interpretation.
2109 \\<org-mode-map>This is a list of sequences.
2111 Each sequence starts with a symbol, either `sequence' or `type',
2112 indicating if the keywords should be interpreted as a sequence of
2113 action steps, or as different types of TODO items. The first
2114 keywords are states requiring action - these states will select a headline
2115 for inclusion into the global TODO list Org-mode produces. If one of
2116 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2117 signify that no further action is necessary. If \"|\" is not found,
2118 the last keyword is treated as the only DONE state of the sequence.
2120 The command \\[org-todo] cycles an entry through these states, and one
2121 additional state where no keyword is present. For details about this
2122 cycling, see the manual.
2124 TODO keywords and interpretation can also be set on a per-file basis with
2125 the special #+SEQ_TODO and #+TYP_TODO lines.
2127 Each keyword can optionally specify a character for fast state selection
2128 \(in combination with the variable `org-use-fast-todo-selection')
2129 and specifiers for state change logging, using the same syntax that
2130 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2131 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2132 indicates to record a time stamp each time this state is selected.
2134 Each keyword may also specify if a timestamp or a note should be
2135 recorded when entering or leaving the state, by adding additional
2136 characters in the parenthesis after the keyword. This looks like this:
2137 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2138 record only the time of the state change. With X and Y being either
2139 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2140 Y when leaving the state if and only if the *target* state does not
2141 define X. You may omit any of the fast-selection key or X or /Y,
2142 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2144 For backward compatibility, this variable may also be just a list
2145 of keywords. In this case the interpretation (sequence or type) will be
2146 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2147 :group 'org-todo
2148 :group 'org-keywords
2149 :type '(choice
2150 (repeat :tag "Old syntax, just keywords"
2151 (string :tag "Keyword"))
2152 (repeat :tag "New syntax"
2153 (cons
2154 (choice
2155 :tag "Interpretation"
2156 ;;Quick and dirty way to see
2157 ;;`org-todo-interpretations'. This takes the
2158 ;;place of item arguments
2159 :convert-widget
2160 (lambda (widget)
2161 (widget-put widget
2162 :args (mapcar
2163 #'(lambda (x)
2164 (widget-convert
2165 (cons 'const x)))
2166 org-todo-interpretation-widgets))
2167 widget))
2168 (repeat
2169 (string :tag "Keyword"))))))
2171 (defvar org-todo-keywords-1 nil
2172 "All TODO and DONE keywords active in a buffer.")
2173 (make-variable-buffer-local 'org-todo-keywords-1)
2174 (defvar org-todo-keywords-for-agenda nil)
2175 (defvar org-done-keywords-for-agenda nil)
2176 (defvar org-drawers-for-agenda nil)
2177 (defvar org-todo-keyword-alist-for-agenda nil)
2178 (defvar org-tag-alist-for-agenda nil)
2179 (defvar org-agenda-contributing-files nil)
2180 (defvar org-not-done-keywords nil)
2181 (make-variable-buffer-local 'org-not-done-keywords)
2182 (defvar org-done-keywords nil)
2183 (make-variable-buffer-local 'org-done-keywords)
2184 (defvar org-todo-heads nil)
2185 (make-variable-buffer-local 'org-todo-heads)
2186 (defvar org-todo-sets nil)
2187 (make-variable-buffer-local 'org-todo-sets)
2188 (defvar org-todo-log-states nil)
2189 (make-variable-buffer-local 'org-todo-log-states)
2190 (defvar org-todo-kwd-alist nil)
2191 (make-variable-buffer-local 'org-todo-kwd-alist)
2192 (defvar org-todo-key-alist nil)
2193 (make-variable-buffer-local 'org-todo-key-alist)
2194 (defvar org-todo-key-trigger nil)
2195 (make-variable-buffer-local 'org-todo-key-trigger)
2197 (defcustom org-todo-interpretation 'sequence
2198 "Controls how TODO keywords are interpreted.
2199 This variable is in principle obsolete and is only used for
2200 backward compatibility, if the interpretation of todo keywords is
2201 not given already in `org-todo-keywords'. See that variable for
2202 more information."
2203 :group 'org-todo
2204 :group 'org-keywords
2205 :type '(choice (const sequence)
2206 (const type)))
2208 (defcustom org-use-fast-todo-selection t
2209 "Non-nil means use the fast todo selection scheme with C-c C-t.
2210 This variable describes if and under what circumstances the cycling
2211 mechanism for TODO keywords will be replaced by a single-key, direct
2212 selection scheme.
2214 When nil, fast selection is never used.
2216 When the symbol `prefix', it will be used when `org-todo' is called
2217 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2218 `C-u t' in an agenda buffer.
2220 When t, fast selection is used by default. In this case, the prefix
2221 argument forces cycling instead.
2223 In all cases, the special interface is only used if access keys have
2224 actually been assigned by the user, i.e. if keywords in the configuration
2225 are followed by a letter in parenthesis, like TODO(t)."
2226 :group 'org-todo
2227 :type '(choice
2228 (const :tag "Never" nil)
2229 (const :tag "By default" t)
2230 (const :tag "Only with C-u C-c C-t" prefix)))
2232 (defcustom org-provide-todo-statistics t
2233 "Non-nil means update todo statistics after insert and toggle.
2234 ALL-HEADLINES means update todo statistics by including headlines
2235 with no TODO keyword as well, counting them as not done.
2236 A list of TODO keywords means the same, but skip keywords that are
2237 not in this list.
2239 When this is set, todo statistics is updated in the parent of the
2240 current entry each time a todo state is changed."
2241 :group 'org-todo
2242 :type '(choice
2243 (const :tag "Yes, only for TODO entries" t)
2244 (const :tag "Yes, including all entries" 'all-headlines)
2245 (repeat :tag "Yes, for TODOs in this list"
2246 (string :tag "TODO keyword"))
2247 (other :tag "No TODO statistics" nil)))
2249 (defcustom org-hierarchical-todo-statistics t
2250 "Non-nil means TODO statistics covers just direct children.
2251 When nil, all entries in the subtree are considered.
2252 This has only an effect if `org-provide-todo-statistics' is set.
2253 To set this to nil for only a single subtree, use a COOKIE_DATA
2254 property and include the word \"recursive\" into the value."
2255 :group 'org-todo
2256 :type 'boolean)
2258 (defcustom org-after-todo-state-change-hook nil
2259 "Hook which is run after the state of a TODO item was changed.
2260 The new state (a string with a TODO keyword, or nil) is available in the
2261 Lisp variable `org-state'."
2262 :group 'org-todo
2263 :type 'hook)
2265 (defvar org-blocker-hook nil
2266 "Hook for functions that are allowed to block a state change.
2268 Functions in this hook should not modify the buffer.
2269 Each function gets as its single argument a property list,
2270 see `org-trigger-hook' for more information about this list.
2272 If any of the functions in this hook returns nil, the state change
2273 is blocked.")
2275 (defvar org-trigger-hook nil
2276 "Hook for functions that are triggered by a state change.
2278 Each function gets as its single argument a property list with at
2279 least the following elements:
2281 (:type type-of-change :position pos-at-entry-start
2282 :from old-state :to new-state)
2284 Depending on the type, more properties may be present.
2286 This mechanism is currently implemented for:
2288 TODO state changes
2289 ------------------
2290 :type todo-state-change
2291 :from previous state (keyword as a string), or nil, or a symbol
2292 'todo' or 'done', to indicate the general type of state.
2293 :to new state, like in :from")
2295 (defcustom org-enforce-todo-dependencies nil
2296 "Non-nil means undone TODO entries will block switching the parent to DONE.
2297 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2298 be blocked if any prior sibling is not yet done.
2299 Finally, if the parent is blocked because of ordered siblings of its own,
2300 the child will also be blocked."
2301 :set (lambda (var val)
2302 (set var val)
2303 (if val
2304 (add-hook 'org-blocker-hook
2305 'org-block-todo-from-children-or-siblings-or-parent)
2306 (remove-hook 'org-blocker-hook
2307 'org-block-todo-from-children-or-siblings-or-parent)))
2308 :group 'org-todo
2309 :type 'boolean)
2311 (defcustom org-enforce-todo-checkbox-dependencies nil
2312 "Non-nil means unchecked boxes will block switching the parent to DONE.
2313 When this is nil, checkboxes have no influence on switching TODO states.
2314 When non-nil, you first need to check off all check boxes before the TODO
2315 entry can be switched to DONE.
2316 This variable needs to be set before org.el is loaded, and you need to
2317 restart Emacs after a change to make the change effective. The only way
2318 to change is while Emacs is running is through the customize interface."
2319 :set (lambda (var val)
2320 (set var val)
2321 (if val
2322 (add-hook 'org-blocker-hook
2323 'org-block-todo-from-checkboxes)
2324 (remove-hook 'org-blocker-hook
2325 'org-block-todo-from-checkboxes)))
2326 :group 'org-todo
2327 :type 'boolean)
2329 (defcustom org-treat-insert-todo-heading-as-state-change nil
2330 "Non-nil means inserting a TODO heading is treated as state change.
2331 So when the command \\[org-insert-todo-heading] is used, state change
2332 logging will apply if appropriate. When nil, the new TODO item will
2333 be inserted directly, and no logging will take place."
2334 :group 'org-todo
2335 :type 'boolean)
2337 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2338 "Non-nil means switching TODO states with S-cursor counts as state change.
2339 This is the default behavior. However, setting this to nil allows a
2340 convenient way to select a TODO state and bypass any logging associated
2341 with that."
2342 :group 'org-todo
2343 :type 'boolean)
2345 (defcustom org-todo-state-tags-triggers nil
2346 "Tag changes that should be triggered by TODO state changes.
2347 This is a list. Each entry is
2349 (state-change (tag . flag) .......)
2351 State-change can be a string with a state, and empty string to indicate the
2352 state that has no TODO keyword, or it can be one of the symbols `todo'
2353 or `done', meaning any not-done or done state, respectively."
2354 :group 'org-todo
2355 :group 'org-tags
2356 :type '(repeat
2357 (cons (choice :tag "When changing to"
2358 (const :tag "Not-done state" todo)
2359 (const :tag "Done state" done)
2360 (string :tag "State"))
2361 (repeat
2362 (cons :tag "Tag action"
2363 (string :tag "Tag")
2364 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2366 (defcustom org-log-done nil
2367 "Information to record when a task moves to the DONE state.
2369 Possible values are:
2371 nil Don't add anything, just change the keyword
2372 time Add a time stamp to the task
2373 note Prompt for a note and add it with template `org-log-note-headings'
2375 This option can also be set with on a per-file-basis with
2377 #+STARTUP: nologdone
2378 #+STARTUP: logdone
2379 #+STARTUP: lognotedone
2381 You can have local logging settings for a subtree by setting the LOGGING
2382 property to one or more of these keywords."
2383 :group 'org-todo
2384 :group 'org-progress
2385 :type '(choice
2386 (const :tag "No logging" nil)
2387 (const :tag "Record CLOSED timestamp" time)
2388 (const :tag "Record CLOSED timestamp with note." note)))
2390 ;; Normalize old uses of org-log-done.
2391 (cond
2392 ((eq org-log-done t) (setq org-log-done 'time))
2393 ((and (listp org-log-done) (memq 'done org-log-done))
2394 (setq org-log-done 'note)))
2396 (defcustom org-log-reschedule nil
2397 "Information to record when the scheduling date of a tasks is modified.
2399 Possible values are:
2401 nil Don't add anything, just change the date
2402 time Add a time stamp to the task
2403 note Prompt for a note and add it with template `org-log-note-headings'
2405 This option can also be set with on a per-file-basis with
2407 #+STARTUP: nologreschedule
2408 #+STARTUP: logreschedule
2409 #+STARTUP: lognotereschedule"
2410 :group 'org-todo
2411 :group 'org-progress
2412 :type '(choice
2413 (const :tag "No logging" nil)
2414 (const :tag "Record timestamp" time)
2415 (const :tag "Record timestamp with note." note)))
2417 (defcustom org-log-redeadline nil
2418 "Information to record when the deadline date of a tasks is modified.
2420 Possible values are:
2422 nil Don't add anything, just change the date
2423 time Add a time stamp to the task
2424 note Prompt for a note and add it with template `org-log-note-headings'
2426 This option can also be set with on a per-file-basis with
2428 #+STARTUP: nologredeadline
2429 #+STARTUP: logredeadline
2430 #+STARTUP: lognoteredeadline
2432 You can have local logging settings for a subtree by setting the LOGGING
2433 property to one or more of these keywords."
2434 :group 'org-todo
2435 :group 'org-progress
2436 :type '(choice
2437 (const :tag "No logging" nil)
2438 (const :tag "Record timestamp" time)
2439 (const :tag "Record timestamp with note." note)))
2441 (defcustom org-log-note-clock-out nil
2442 "Non-nil means record a note when clocking out of an item.
2443 This can also be configured on a per-file basis by adding one of
2444 the following lines anywhere in the buffer:
2446 #+STARTUP: lognoteclock-out
2447 #+STARTUP: nolognoteclock-out"
2448 :group 'org-todo
2449 :group 'org-progress
2450 :type 'boolean)
2452 (defcustom org-log-done-with-time t
2453 "Non-nil means the CLOSED time stamp will contain date and time.
2454 When nil, only the date will be recorded."
2455 :group 'org-progress
2456 :type 'boolean)
2458 (defcustom org-log-note-headings
2459 '((done . "CLOSING NOTE %t")
2460 (state . "State %-12s from %-12S %t")
2461 (note . "Note taken on %t")
2462 (reschedule . "Rescheduled from %S on %t")
2463 (delschedule . "Not scheduled, was %S on %t")
2464 (redeadline . "New deadline from %S on %t")
2465 (deldeadline . "Removed deadline, was %S on %t")
2466 (refile . "Refiled on %t")
2467 (clock-out . ""))
2468 "Headings for notes added to entries.
2469 The value is an alist, with the car being a symbol indicating the note
2470 context, and the cdr is the heading to be used. The heading may also be the
2471 empty string.
2472 %t in the heading will be replaced by a time stamp.
2473 %T will be an active time stamp instead the default inactive one
2474 %d will be replaced by a short-format time stamp.
2475 %D will be replaced by an active short-format time stamp.
2476 %s will be replaced by the new TODO state, in double quotes.
2477 %S will be replaced by the old TODO state, in double quotes.
2478 %u will be replaced by the user name.
2479 %U will be replaced by the full user name.
2481 In fact, it is not a good idea to change the `state' entry, because
2482 agenda log mode depends on the format of these entries."
2483 :group 'org-todo
2484 :group 'org-progress
2485 :type '(list :greedy t
2486 (cons (const :tag "Heading when closing an item" done) string)
2487 (cons (const :tag
2488 "Heading when changing todo state (todo sequence only)"
2489 state) string)
2490 (cons (const :tag "Heading when just taking a note" note) string)
2491 (cons (const :tag "Heading when clocking out" clock-out) string)
2492 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2493 (cons (const :tag "Heading when rescheduling" reschedule) string)
2494 (cons (const :tag "Heading when changing deadline" redeadline) string)
2495 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2496 (cons (const :tag "Heading when refiling" refile) string)))
2498 (unless (assq 'note org-log-note-headings)
2499 (push '(note . "%t") org-log-note-headings))
2501 (defcustom org-log-into-drawer nil
2502 "Non-nil means insert state change notes and time stamps into a drawer.
2503 When nil, state changes notes will be inserted after the headline and
2504 any scheduling and clock lines, but not inside a drawer.
2506 The value of this variable should be the name of the drawer to use.
2507 LOGBOOK is proposed as the default drawer for this purpose, you can
2508 also set this to a string to define the drawer of your choice.
2510 A value of t is also allowed, representing \"LOGBOOK\".
2512 A value of t or nil can also be set with on a per-file-basis with
2514 #+STARTUP: logdrawer
2515 #+STARTUP: nologdrawer
2517 If this variable is set, `org-log-state-notes-insert-after-drawers'
2518 will be ignored.
2520 You can set the property LOG_INTO_DRAWER to overrule this setting for
2521 a subtree."
2522 :group 'org-todo
2523 :group 'org-progress
2524 :type '(choice
2525 (const :tag "Not into a drawer" nil)
2526 (const :tag "LOGBOOK" t)
2527 (string :tag "Other")))
2529 (if (fboundp 'defvaralias)
2530 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2532 (defun org-log-into-drawer ()
2533 "Return the value of `org-log-into-drawer', but let properties overrule.
2534 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2535 used instead of the default value."
2536 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2537 (cond
2538 ((not p) org-log-into-drawer)
2539 ((equal p "nil") nil)
2540 ((equal p "t") "LOGBOOK")
2541 (t p))))
2543 (defcustom org-log-state-notes-insert-after-drawers nil
2544 "Non-nil means insert state change notes after any drawers in entry.
2545 Only the drawers that *immediately* follow the headline and the
2546 deadline/scheduled line are skipped.
2547 When nil, insert notes right after the heading and perhaps the line
2548 with deadline/scheduling if present.
2550 This variable will have no effect if `org-log-into-drawer' is
2551 set."
2552 :group 'org-todo
2553 :group 'org-progress
2554 :type 'boolean)
2556 (defcustom org-log-states-order-reversed t
2557 "Non-nil means the latest state note will be directly after heading.
2558 When nil, the state change notes will be ordered according to time.
2560 This option can also be set with on a per-file-basis with
2562 #+STARTUP: logstatesreversed
2563 #+STARTUP: nologstatesreversed"
2564 :group 'org-todo
2565 :group 'org-progress
2566 :type 'boolean)
2568 (defcustom org-todo-repeat-to-state nil
2569 "The TODO state to which a repeater should return the repeating task.
2570 By default this is the first task in a TODO sequence, or the previous state
2571 in a TODO_TYP set. But you can specify another task here.
2572 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2573 :group 'org-todo
2574 :version "24.1"
2575 :type '(choice (const :tag "Head of sequence" nil)
2576 (string :tag "Specific state")))
2578 (defcustom org-log-repeat 'time
2579 "Non-nil means record moving through the DONE state when triggering repeat.
2580 An auto-repeating task is immediately switched back to TODO when
2581 marked DONE. If you are not logging state changes (by adding \"@\"
2582 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2583 record a closing note, there will be no record of the task moving
2584 through DONE. This variable forces taking a note anyway.
2586 nil Don't force a record
2587 time Record a time stamp
2588 note Prompt for a note and add it with template `org-log-note-headings'
2590 This option can also be set with on a per-file-basis with
2592 #+STARTUP: nologrepeat
2593 #+STARTUP: logrepeat
2594 #+STARTUP: lognoterepeat
2596 You can have local logging settings for a subtree by setting the LOGGING
2597 property to one or more of these keywords."
2598 :group 'org-todo
2599 :group 'org-progress
2600 :type '(choice
2601 (const :tag "Don't force a record" nil)
2602 (const :tag "Force recording the DONE state" time)
2603 (const :tag "Force recording a note with the DONE state" note)))
2606 (defgroup org-priorities nil
2607 "Priorities in Org-mode."
2608 :tag "Org Priorities"
2609 :group 'org-todo)
2611 (defcustom org-enable-priority-commands t
2612 "Non-nil means priority commands are active.
2613 When nil, these commands will be disabled, so that you never accidentally
2614 set a priority."
2615 :group 'org-priorities
2616 :type 'boolean)
2618 (defcustom org-highest-priority ?A
2619 "The highest priority of TODO items. A character like ?A, ?B etc.
2620 Must have a smaller ASCII number than `org-lowest-priority'."
2621 :group 'org-priorities
2622 :type 'character)
2624 (defcustom org-lowest-priority ?C
2625 "The lowest priority of TODO items. A character like ?A, ?B etc.
2626 Must have a larger ASCII number than `org-highest-priority'."
2627 :group 'org-priorities
2628 :type 'character)
2630 (defcustom org-default-priority ?B
2631 "The default priority of TODO items.
2632 This is the priority an item gets if no explicit priority is given.
2633 When starting to cycle on an empty priority the first step in the cycle
2634 depends on `org-priority-start-cycle-with-default'. The resulting first
2635 step priority must not exceed the range from `org-highest-priority' to
2636 `org-lowest-priority' which means that `org-default-priority' has to be
2637 in this range exclusive or inclusive the range boundaries. Else the
2638 first step refuses to set the default and the second will fall back
2639 to (depending on the command used) the highest or lowest priority."
2640 :group 'org-priorities
2641 :type 'character)
2643 (defcustom org-priority-start-cycle-with-default t
2644 "Non-nil means start with default priority when starting to cycle.
2645 When this is nil, the first step in the cycle will be (depending on the
2646 command used) one higher or lower than the default priority.
2647 See also `org-default-priority'."
2648 :group 'org-priorities
2649 :type 'boolean)
2651 (defcustom org-get-priority-function nil
2652 "Function to extract the priority from a string.
2653 The string is normally the headline. If this is nil Org computes the
2654 priority from the priority cookie like [#A] in the headline. It returns
2655 an integer, increasing by 1000 for each priority level.
2656 The user can set a different function here, which should take a string
2657 as an argument and return the numeric priority."
2658 :group 'org-priorities
2659 :version "24.1"
2660 :type 'function)
2662 (defgroup org-time nil
2663 "Options concerning time stamps and deadlines in Org-mode."
2664 :tag "Org Time"
2665 :group 'org)
2667 (defcustom org-insert-labeled-timestamps-at-point nil
2668 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2669 When nil, these labeled time stamps are forces into the second line of an
2670 entry, just after the headline. When scheduling from the global TODO list,
2671 the time stamp will always be forced into the second line."
2672 :group 'org-time
2673 :type 'boolean)
2675 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2676 "Formats for `format-time-string' which are used for time stamps.
2677 It is not recommended to change this constant.")
2679 (defcustom org-time-stamp-rounding-minutes '(0 5)
2680 "Number of minutes to round time stamps to.
2681 These are two values, the first applies when first creating a time stamp.
2682 The second applies when changing it with the commands `S-up' and `S-down'.
2683 When changing the time stamp, this means that it will change in steps
2684 of N minutes, as given by the second value.
2686 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2687 numbers should be factors of 60, so for example 5, 10, 15.
2689 When this is larger than 1, you can still force an exact time stamp by using
2690 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2691 and by using a prefix arg to `S-up/down' to specify the exact number
2692 of minutes to shift."
2693 :group 'org-time
2694 :get #'(lambda (var) ; Make sure both elements are there
2695 (if (integerp (default-value var))
2696 (list (default-value var) 5)
2697 (default-value var)))
2698 :type '(list
2699 (integer :tag "when inserting times")
2700 (integer :tag "when modifying times")))
2702 ;; Normalize old customizations of this variable.
2703 (when (integerp org-time-stamp-rounding-minutes)
2704 (setq org-time-stamp-rounding-minutes
2705 (list org-time-stamp-rounding-minutes
2706 org-time-stamp-rounding-minutes)))
2708 (defcustom org-display-custom-times nil
2709 "Non-nil means overlay custom formats over all time stamps.
2710 The formats are defined through the variable `org-time-stamp-custom-formats'.
2711 To turn this on on a per-file basis, insert anywhere in the file:
2712 #+STARTUP: customtime"
2713 :group 'org-time
2714 :set 'set-default
2715 :type 'sexp)
2716 (make-variable-buffer-local 'org-display-custom-times)
2718 (defcustom org-time-stamp-custom-formats
2719 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2720 "Custom formats for time stamps. See `format-time-string' for the syntax.
2721 These are overlaid over the default ISO format if the variable
2722 `org-display-custom-times' is set. Time like %H:%M should be at the
2723 end of the second format. The custom formats are also honored by export
2724 commands, if custom time display is turned on at the time of export."
2725 :group 'org-time
2726 :type 'sexp)
2728 (defun org-time-stamp-format (&optional long inactive)
2729 "Get the right format for a time string."
2730 (let ((f (if long (cdr org-time-stamp-formats)
2731 (car org-time-stamp-formats))))
2732 (if inactive
2733 (concat "[" (substring f 1 -1) "]")
2734 f)))
2736 (defcustom org-time-clocksum-format
2737 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2738 "The format string used when creating CLOCKSUM lines.
2739 This is also used when Org mode generates a time duration.
2741 The value can be a single format string containing two
2742 %-sequences, which will be filled with the number of hours and
2743 minutes in that order.
2745 Alternatively, the value can be a plist associating any of the
2746 keys :years, :months, :weeks, :days, :hours or :minutes with
2747 format strings. The time duration is formatted using only the
2748 time components that are needed and concatenating the results.
2749 If a time unit in absent, it falls back to the next smallest
2750 unit.
2752 The keys :require-years, :require-months, :require-days,
2753 :require-weeks, :require-hours, :require-minutes are also
2754 meaningful. A non-nil value for these keys indicates that the
2755 corresponding time component should always be included, even if
2756 its value is 0.
2759 For example,
2761 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2762 :require-minutes t)
2764 means durations longer than a day will be expressed in days,
2765 hours and minutes, and durations less than a day will always be
2766 expressed in hours and minutes (even for durations less than an
2767 hour).
2769 The value
2771 \(:days \"%dd\" :minutes \"%dm\")
2773 means durations longer than a day will be expressed in days and
2774 minutes, and durations less than a day will be expressed entirely
2775 in minutes (even for durations longer than an hour)."
2776 :group 'org-time
2777 :group 'org-clock
2778 :version "24.3"
2779 :type '(choice (string :tag "Format string")
2780 (set :tag "Plist"
2781 (group :inline t (const :tag "Years" :years)
2782 (string :tag "Format string"))
2783 (group :inline t
2784 (const :tag "Always show years" :require-years)
2785 (const t))
2786 (group :inline t (const :tag "Months" :months)
2787 (string :tag "Format string"))
2788 (group :inline t
2789 (const :tag "Always show months" :require-months)
2790 (const t))
2791 (group :inline t (const :tag "Weeks" :weeks)
2792 (string :tag "Format string"))
2793 (group :inline t
2794 (const :tag "Always show weeks" :require-weeks)
2795 (const t))
2796 (group :inline t (const :tag "Days" :days)
2797 (string :tag "Format string"))
2798 (group :inline t
2799 (const :tag "Always show days" :require-days)
2800 (const t))
2801 (group :inline t (const :tag "Hours" :hours)
2802 (string :tag "Format string"))
2803 (group :inline t
2804 (const :tag "Always show hours" :require-hours)
2805 (const t))
2806 (group :inline t (const :tag "Minutes" :minutes)
2807 (string :tag "Format string"))
2808 (group :inline t
2809 (const :tag "Always show minutes" :require-minutes)
2810 (const t)))))
2812 (defcustom org-time-clocksum-use-fractional nil
2813 "When non-nil, \\[org-clock-display] uses fractional times.
2814 See `org-time-clocksum-format' for more on time clock formats."
2815 :group 'org-time
2816 :group 'org-clock
2817 :version "24.3"
2818 :type 'boolean)
2820 (defcustom org-time-clocksum-use-effort-durations t
2821 "When non-nil, \\[org-clock-display] uses effort durations.
2822 E.g. by default, one day is considered to be a 8 hours effort,
2823 so a task that has been clocked for 16 hours will be displayed
2824 as during 2 days in the clock display or in the clocktable.
2826 See `org-effort-durations' on how to set effort durations
2827 and `org-time-clocksum-format' for more on time clock formats."
2828 :group 'org-time
2829 :group 'org-clock
2830 :version "24.3"
2831 :type 'boolean)
2833 (defcustom org-time-clocksum-fractional-format "%.2f"
2834 "The format string used when creating CLOCKSUM lines,
2835 or when Org mode generates a time duration, if
2836 `org-time-clocksum-use-fractional' is enabled.
2838 The value can be a single format string containing one
2839 %-sequence, which will be filled with the number of hours as
2840 a float.
2842 Alternatively, the value can be a plist associating any of the
2843 keys :years, :months, :weeks, :days, :hours or :minutes with
2844 a format string. The time duration is formatted using the
2845 largest time unit which gives a non-zero integer part. If all
2846 specified formats have zero integer part, the smallest time unit
2847 is used."
2848 :group 'org-time
2849 :type '(choice (string :tag "Format string")
2850 (set (group :inline t (const :tag "Years" :years)
2851 (string :tag "Format string"))
2852 (group :inline t (const :tag "Months" :months)
2853 (string :tag "Format string"))
2854 (group :inline t (const :tag "Weeks" :weeks)
2855 (string :tag "Format string"))
2856 (group :inline t (const :tag "Days" :days)
2857 (string :tag "Format string"))
2858 (group :inline t (const :tag "Hours" :hours)
2859 (string :tag "Format string"))
2860 (group :inline t (const :tag "Minutes" :minutes)
2861 (string :tag "Format string")))))
2863 (defcustom org-deadline-warning-days 14
2864 "No. of days before expiration during which a deadline becomes active.
2865 This variable governs the display in sparse trees and in the agenda.
2866 When 0 or negative, it means use this number (the absolute value of it)
2867 even if a deadline has a different individual lead time specified.
2869 Custom commands can set this variable in the options section."
2870 :group 'org-time
2871 :group 'org-agenda-daily/weekly
2872 :type 'integer)
2874 (defcustom org-read-date-prefer-future t
2875 "Non-nil means assume future for incomplete date input from user.
2876 This affects the following situations:
2877 1. The user gives a month but not a year.
2878 For example, if it is April and you enter \"feb 2\", this will be read
2879 as Feb 2, *next* year. \"May 5\", however, will be this year.
2880 2. The user gives a day, but no month.
2881 For example, if today is the 15th, and you enter \"3\", Org-mode will
2882 read this as the third of *next* month. However, if you enter \"17\",
2883 it will be considered as *this* month.
2885 If you set this variable to the symbol `time', then also the following
2886 will work:
2888 3. If the user gives a time.
2889 If the time is before now, it will be interpreted as tomorrow.
2891 Currently none of this works for ISO week specifications.
2893 When this option is nil, the current day, month and year will always be
2894 used as defaults.
2896 See also `org-agenda-jump-prefer-future'."
2897 :group 'org-time
2898 :type '(choice
2899 (const :tag "Never" nil)
2900 (const :tag "Check month and day" t)
2901 (const :tag "Check month, day, and time" time)))
2903 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2904 "Should the agenda jump command prefer the future for incomplete dates?
2905 The default is to do the same as configured in `org-read-date-prefer-future'.
2906 But you can also set a deviating value here.
2907 This may t or nil, or the symbol `org-read-date-prefer-future'."
2908 :group 'org-agenda
2909 :group 'org-time
2910 :version "24.1"
2911 :type '(choice
2912 (const :tag "Use org-read-date-prefer-future"
2913 org-read-date-prefer-future)
2914 (const :tag "Never" nil)
2915 (const :tag "Always" t)))
2917 (defcustom org-read-date-force-compatible-dates t
2918 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2920 Depending on the system Emacs is running on, certain dates cannot
2921 be represented with the type used internally to represent time.
2922 Dates between 1970-1-1 and 2038-1-1 can always be represented
2923 correctly. Some systems allow for earlier dates, some for later,
2924 some for both. One way to find out it to insert any date into an
2925 Org buffer, putting the cursor on the year and hitting S-up and
2926 S-down to test the range.
2928 When this variable is set to t, the date/time prompt will not let
2929 you specify dates outside the 1970-2037 range, so it is certain that
2930 these dates will work in whatever version of Emacs you are
2931 running, and also that you can move a file from one Emacs implementation
2932 to another. WHenever Org is forcing the year for you, it will display
2933 a message and beep.
2935 When this variable is nil, Org will check if the date is
2936 representable in the specific Emacs implementation you are using.
2937 If not, it will force a year, usually the current year, and beep
2938 to remind you. Currently this setting is not recommended because
2939 the likelihood that you will open your Org files in an Emacs that
2940 has limited date range is not negligible.
2942 A workaround for this problem is to use diary sexp dates for time
2943 stamps outside of this range."
2944 :group 'org-time
2945 :version "24.1"
2946 :type 'boolean)
2948 (defcustom org-read-date-display-live t
2949 "Non-nil means display current interpretation of date prompt live.
2950 This display will be in an overlay, in the minibuffer."
2951 :group 'org-time
2952 :type 'boolean)
2954 (defcustom org-read-date-popup-calendar t
2955 "Non-nil means pop up a calendar when prompting for a date.
2956 In the calendar, the date can be selected with mouse-1. However, the
2957 minibuffer will also be active, and you can simply enter the date as well.
2958 When nil, only the minibuffer will be available."
2959 :group 'org-time
2960 :type 'boolean)
2961 (if (fboundp 'defvaralias)
2962 (defvaralias 'org-popup-calendar-for-date-prompt
2963 'org-read-date-popup-calendar))
2965 (defcustom org-read-date-minibuffer-setup-hook nil
2966 "Hook to be used to set up keys for the date/time interface.
2967 Add key definitions to `minibuffer-local-map', which will be a temporary
2968 copy."
2969 :group 'org-time
2970 :type 'hook)
2972 (defcustom org-extend-today-until 0
2973 "The hour when your day really ends. Must be an integer.
2974 This has influence for the following applications:
2975 - When switching the agenda to \"today\". It it is still earlier than
2976 the time given here, the day recognized as TODAY is actually yesterday.
2977 - When a date is read from the user and it is still before the time given
2978 here, the current date and time will be assumed to be yesterday, 23:59.
2979 Also, timestamps inserted in capture templates follow this rule.
2981 IMPORTANT: This is a feature whose implementation is and likely will
2982 remain incomplete. Really, it is only here because past midnight seems to
2983 be the favorite working time of John Wiegley :-)"
2984 :group 'org-time
2985 :type 'integer)
2987 (defcustom org-use-effective-time nil
2988 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2989 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2990 \"effective time\" of any timestamps between midnight and 8am will be
2991 23:59 of the previous day."
2992 :group 'org-time
2993 :version "24.1"
2994 :type 'boolean)
2996 (defcustom org-use-last-clock-out-time-as-effective-time nil
2997 "When non-nil, use the last clock out time for `org-todo'.
2998 Note that this option has precedence over the combined use of
2999 `org-use-effective-time' and `org-extend-today-until'."
3000 :group 'org-time
3001 ;; :version "24.3"
3002 :type 'boolean)
3004 (defcustom org-edit-timestamp-down-means-later nil
3005 "Non-nil means S-down will increase the time in a time stamp.
3006 When nil, S-up will increase."
3007 :group 'org-time
3008 :type 'boolean)
3010 (defcustom org-calendar-follow-timestamp-change t
3011 "Non-nil means make the calendar window follow timestamp changes.
3012 When a timestamp is modified and the calendar window is visible, it will be
3013 moved to the new date."
3014 :group 'org-time
3015 :type 'boolean)
3017 (defgroup org-tags nil
3018 "Options concerning tags in Org-mode."
3019 :tag "Org Tags"
3020 :group 'org)
3022 (defcustom org-tag-alist nil
3023 "List of tags allowed in Org-mode files.
3024 When this list is nil, Org-mode will base TAG input on what is already in the
3025 buffer.
3026 The value of this variable is an alist, the car of each entry must be a
3027 keyword as a string, the cdr may be a character that is used to select
3028 that tag through the fast-tag-selection interface.
3029 See the manual for details."
3030 :group 'org-tags
3031 :type '(repeat
3032 (choice
3033 (cons (string :tag "Tag name")
3034 (character :tag "Access char"))
3035 (list :tag "Start radio group"
3036 (const :startgroup)
3037 (option (string :tag "Group description")))
3038 (list :tag "End radio group"
3039 (const :endgroup)
3040 (option (string :tag "Group description")))
3041 (const :tag "New line" (:newline)))))
3043 (defcustom org-tag-persistent-alist nil
3044 "List of tags that will always appear in all Org-mode files.
3045 This is in addition to any in buffer settings or customizations
3046 of `org-tag-alist'.
3047 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3048 The value of this variable is an alist, the car of each entry must be a
3049 keyword as a string, the cdr may be a character that is used to select
3050 that tag through the fast-tag-selection interface.
3051 See the manual for details.
3052 To disable these tags on a per-file basis, insert anywhere in the file:
3053 #+STARTUP: noptag"
3054 :group 'org-tags
3055 :type '(repeat
3056 (choice
3057 (cons (string :tag "Tag name")
3058 (character :tag "Access char"))
3059 (const :tag "Start radio group" (:startgroup))
3060 (const :tag "End radio group" (:endgroup))
3061 (const :tag "New line" (:newline)))))
3063 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3064 "If non-nil, always offer completion for all tags of all agenda files.
3065 Instead of customizing this variable directly, you might want to
3066 set it locally for capture buffers, because there no list of
3067 tags in that file can be created dynamically (there are none).
3069 (add-hook 'org-capture-mode-hook
3070 (lambda ()
3071 (set (make-local-variable
3072 'org-complete-tags-always-offer-all-agenda-tags)
3073 t)))"
3074 :group 'org-tags
3075 :version "24.1"
3076 :type 'boolean)
3078 (defvar org-file-tags nil
3079 "List of tags that can be inherited by all entries in the file.
3080 The tags will be inherited if the variable `org-use-tag-inheritance'
3081 says they should be.
3082 This variable is populated from #+FILETAGS lines.")
3084 (defcustom org-use-fast-tag-selection 'auto
3085 "Non-nil means use fast tag selection scheme.
3086 This is a special interface to select and deselect tags with single keys.
3087 When nil, fast selection is never used.
3088 When the symbol `auto', fast selection is used if and only if selection
3089 characters for tags have been configured, either through the variable
3090 `org-tag-alist' or through a #+TAGS line in the buffer.
3091 When t, fast selection is always used and selection keys are assigned
3092 automatically if necessary."
3093 :group 'org-tags
3094 :type '(choice
3095 (const :tag "Always" t)
3096 (const :tag "Never" nil)
3097 (const :tag "When selection characters are configured" 'auto)))
3099 (defcustom org-fast-tag-selection-single-key nil
3100 "Non-nil means fast tag selection exits after first change.
3101 When nil, you have to press RET to exit it.
3102 During fast tag selection, you can toggle this flag with `C-c'.
3103 This variable can also have the value `expert'. In this case, the window
3104 displaying the tags menu is not even shown, until you press C-c again."
3105 :group 'org-tags
3106 :type '(choice
3107 (const :tag "No" nil)
3108 (const :tag "Yes" t)
3109 (const :tag "Expert" expert)))
3111 (defvar org-fast-tag-selection-include-todo nil
3112 "Non-nil means fast tags selection interface will also offer TODO states.
3113 This is an undocumented feature, you should not rely on it.")
3115 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3116 "The column to which tags should be indented in a headline.
3117 If this number is positive, it specifies the column. If it is negative,
3118 it means that the tags should be flushright to that column. For example,
3119 -80 works well for a normal 80 character screen.
3120 When 0, place tags directly after headline text, with only one space in
3121 between."
3122 :group 'org-tags
3123 :type 'integer)
3125 (defcustom org-auto-align-tags t
3126 "Non-nil keeps tags aligned when modifying headlines.
3127 Some operations (i.e. demoting) change the length of a headline and
3128 therefore shift the tags around. With this option turned on, after
3129 each such operation the tags are again aligned to `org-tags-column'."
3130 :group 'org-tags
3131 :type 'boolean)
3133 (defcustom org-use-tag-inheritance t
3134 "Non-nil means tags in levels apply also for sublevels.
3135 When nil, only the tags directly given in a specific line apply there.
3136 This may also be a list of tags that should be inherited, or a regexp that
3137 matches tags that should be inherited. Additional control is possible
3138 with the variable `org-tags-exclude-from-inheritance' which gives an
3139 explicit list of tags to be excluded from inheritance, even if the value of
3140 `org-use-tag-inheritance' would select it for inheritance.
3142 If this option is t, a match early-on in a tree can lead to a large
3143 number of matches in the subtree when constructing the agenda or creating
3144 a sparse tree. If you only want to see the first match in a tree during
3145 a search, check out the variable `org-tags-match-list-sublevels'."
3146 :group 'org-tags
3147 :type '(choice
3148 (const :tag "Not" nil)
3149 (const :tag "Always" t)
3150 (repeat :tag "Specific tags" (string :tag "Tag"))
3151 (regexp :tag "Tags matched by regexp")))
3153 (defcustom org-tags-exclude-from-inheritance nil
3154 "List of tags that should never be inherited.
3155 This is a way to exclude a few tags from inheritance. For way to do
3156 the opposite, to actively allow inheritance for selected tags,
3157 see the variable `org-use-tag-inheritance'."
3158 :group 'org-tags
3159 :type '(repeat (string :tag "Tag")))
3161 (defun org-tag-inherit-p (tag)
3162 "Check if TAG is one that should be inherited."
3163 (cond
3164 ((member tag org-tags-exclude-from-inheritance) nil)
3165 ((eq org-use-tag-inheritance t) t)
3166 ((not org-use-tag-inheritance) nil)
3167 ((stringp org-use-tag-inheritance)
3168 (string-match org-use-tag-inheritance tag))
3169 ((listp org-use-tag-inheritance)
3170 (member tag org-use-tag-inheritance))
3171 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3173 (defcustom org-tags-match-list-sublevels t
3174 "Non-nil means list also sublevels of headlines matching a search.
3175 This variable applies to tags/property searches, and also to stuck
3176 projects because this search is based on a tags match as well.
3178 When set to the symbol `indented', sublevels are indented with
3179 leading dots.
3181 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3182 the sublevels of a headline matching a tag search often also match
3183 the same search. Listing all of them can create very long lists.
3184 Setting this variable to nil causes subtrees of a match to be skipped.
3186 This variable is semi-obsolete and probably should always be true. It
3187 is better to limit inheritance to certain tags using the variables
3188 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3189 :group 'org-tags
3190 :type '(choice
3191 (const :tag "No, don't list them" nil)
3192 (const :tag "Yes, do list them" t)
3193 (const :tag "List them, indented with leading dots" indented)))
3195 (defcustom org-tags-sort-function nil
3196 "When set, tags are sorted using this function as a comparator."
3197 :group 'org-tags
3198 :type '(choice
3199 (const :tag "No sorting" nil)
3200 (const :tag "Alphabetical" string<)
3201 (const :tag "Reverse alphabetical" string>)
3202 (function :tag "Custom function" nil)))
3204 (defvar org-tags-history nil
3205 "History of minibuffer reads for tags.")
3206 (defvar org-last-tags-completion-table nil
3207 "The last used completion table for tags.")
3208 (defvar org-after-tags-change-hook nil
3209 "Hook that is run after the tags in a line have changed.")
3211 (defgroup org-properties nil
3212 "Options concerning properties in Org-mode."
3213 :tag "Org Properties"
3214 :group 'org)
3216 (defcustom org-property-format "%-10s %s"
3217 "How property key/value pairs should be formatted by `indent-line'.
3218 When `indent-line' hits a property definition, it will format the line
3219 according to this format, mainly to make sure that the values are
3220 lined-up with respect to each other."
3221 :group 'org-properties
3222 :type 'string)
3224 (defcustom org-properties-postprocess-alist nil
3225 "Alist of properties and functions to adjust inserted values.
3226 Elements of this alist must be of the form
3228 ([string] [function])
3230 where [string] must be a property name and [function] must be a
3231 lambda expression: this lambda expression must take one argument,
3232 the value to adjust, and return the new value as a string.
3234 For example, this element will allow the property \"Remaining\"
3235 to be updated wrt the relation between the \"Effort\" property
3236 and the clock summary:
3238 ((\"Remaining\" (lambda(value)
3239 (let ((clocksum (org-clock-sum-current-item))
3240 (effort (org-duration-string-to-minutes
3241 (org-entry-get (point) \"Effort\"))))
3242 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3243 :group 'org-properties
3244 :version "24.1"
3245 :type '(alist :key-type (string :tag "Property")
3246 :value-type (function :tag "Function")))
3248 (defcustom org-use-property-inheritance nil
3249 "Non-nil means properties apply also for sublevels.
3251 This setting is chiefly used during property searches. Turning it on can
3252 cause significant overhead when doing a search, which is why it is not
3253 on by default.
3255 When nil, only the properties directly given in the current entry count.
3256 When t, every property is inherited. The value may also be a list of
3257 properties that should have inheritance, or a regular expression matching
3258 properties that should be inherited.
3260 However, note that some special properties use inheritance under special
3261 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3262 and the properties ending in \"_ALL\" when they are used as descriptor
3263 for valid values of a property.
3265 Note for programmers:
3266 When querying an entry with `org-entry-get', you can control if inheritance
3267 should be used. By default, `org-entry-get' looks only at the local
3268 properties. You can request inheritance by setting the inherit argument
3269 to t (to force inheritance) or to `selective' (to respect the setting
3270 in this variable)."
3271 :group 'org-properties
3272 :type '(choice
3273 (const :tag "Not" nil)
3274 (const :tag "Always" t)
3275 (repeat :tag "Specific properties" (string :tag "Property"))
3276 (regexp :tag "Properties matched by regexp")))
3278 (defun org-property-inherit-p (property)
3279 "Check if PROPERTY is one that should be inherited."
3280 (cond
3281 ((eq org-use-property-inheritance t) t)
3282 ((not org-use-property-inheritance) nil)
3283 ((stringp org-use-property-inheritance)
3284 (string-match org-use-property-inheritance property))
3285 ((listp org-use-property-inheritance)
3286 (member property org-use-property-inheritance))
3287 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3289 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3290 "The default column format, if no other format has been defined.
3291 This variable can be set on the per-file basis by inserting a line
3293 #+COLUMNS: %25ITEM ....."
3294 :group 'org-properties
3295 :type 'string)
3297 (defcustom org-columns-ellipses ".."
3298 "The ellipses to be used when a field in column view is truncated.
3299 When this is the empty string, as many characters as possible are shown,
3300 but then there will be no visual indication that the field has been truncated.
3301 When this is a string of length N, the last N characters of a truncated
3302 field are replaced by this string. If the column is narrower than the
3303 ellipses string, only part of the ellipses string will be shown."
3304 :group 'org-properties
3305 :type 'string)
3307 (defcustom org-columns-modify-value-for-display-function nil
3308 "Function that modifies values for display in column view.
3309 For example, it can be used to cut out a certain part from a time stamp.
3310 The function must take 2 arguments:
3312 column-title The title of the column (*not* the property name)
3313 value The value that should be modified.
3315 The function should return the value that should be displayed,
3316 or nil if the normal value should be used."
3317 :group 'org-properties
3318 :type 'function)
3320 (defcustom org-effort-property "Effort"
3321 "The property that is being used to keep track of effort estimates.
3322 Effort estimates given in this property need to have the format H:MM."
3323 :group 'org-properties
3324 :group 'org-progress
3325 :type '(string :tag "Property"))
3327 (defconst org-global-properties-fixed
3328 '(("VISIBILITY_ALL" . "folded children content all")
3329 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3330 "List of property/value pairs that can be inherited by any entry.
3332 These are fixed values, for the preset properties. The user variable
3333 that can be used to add to this list is `org-global-properties'.
3335 The entries in this list are cons cells where the car is a property
3336 name and cdr is a string with the value. If the value represents
3337 multiple items like an \"_ALL\" property, separate the items by
3338 spaces.")
3340 (defcustom org-global-properties nil
3341 "List of property/value pairs that can be inherited by any entry.
3343 This list will be combined with the constant `org-global-properties-fixed'.
3345 The entries in this list are cons cells where the car is a property
3346 name and cdr is a string with the value.
3348 You can set buffer-local values for the same purpose in the variable
3349 `org-file-properties' this by adding lines like
3351 #+PROPERTY: NAME VALUE"
3352 :group 'org-properties
3353 :type '(repeat
3354 (cons (string :tag "Property")
3355 (string :tag "Value"))))
3357 (defvar org-file-properties nil
3358 "List of property/value pairs that can be inherited by any entry.
3359 Valid for the current buffer.
3360 This variable is populated from #+PROPERTY lines.")
3361 (make-variable-buffer-local 'org-file-properties)
3363 (defgroup org-agenda nil
3364 "Options concerning agenda views in Org-mode."
3365 :tag "Org Agenda"
3366 :group 'org)
3368 (defvar org-category nil
3369 "Variable used by org files to set a category for agenda display.
3370 Such files should use a file variable to set it, for example
3372 # -*- mode: org; org-category: \"ELisp\"
3374 or contain a special line
3376 #+CATEGORY: ELisp
3378 If the file does not specify a category, then file's base name
3379 is used instead.")
3380 (make-variable-buffer-local 'org-category)
3381 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3383 (defcustom org-agenda-files nil
3384 "The files to be used for agenda display.
3385 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3386 \\[org-remove-file]. You can also use customize to edit the list.
3388 If an entry is a directory, all files in that directory that are matched by
3389 `org-agenda-file-regexp' will be part of the file list.
3391 If the value of the variable is not a list but a single file name, then
3392 the list of agenda files is actually stored and maintained in that file, one
3393 agenda file per line. In this file paths can be given relative to
3394 `org-directory'. Tilde expansion and environment variable substitution
3395 are also made."
3396 :group 'org-agenda
3397 :type '(choice
3398 (repeat :tag "List of files and directories" file)
3399 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3401 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3402 "Regular expression to match files for `org-agenda-files'.
3403 If any element in the list in that variable contains a directory instead
3404 of a normal file, all files in that directory that are matched by this
3405 regular expression will be included."
3406 :group 'org-agenda
3407 :type 'regexp)
3409 (defcustom org-agenda-text-search-extra-files nil
3410 "List of extra files to be searched by text search commands.
3411 These files will be search in addition to the agenda files by the
3412 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3413 Note that these files will only be searched for text search commands,
3414 not for the other agenda views like todo lists, tag searches or the weekly
3415 agenda. This variable is intended to list notes and possibly archive files
3416 that should also be searched by these two commands.
3417 In fact, if the first element in the list is the symbol `agenda-archives',
3418 than all archive files of all agenda files will be added to the search
3419 scope."
3420 :group 'org-agenda
3421 :type '(set :greedy t
3422 (const :tag "Agenda Archives" agenda-archives)
3423 (repeat :inline t (file))))
3425 (if (fboundp 'defvaralias)
3426 (defvaralias 'org-agenda-multi-occur-extra-files
3427 'org-agenda-text-search-extra-files))
3429 (defcustom org-agenda-skip-unavailable-files nil
3430 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3431 A nil value means to remove them, after a query, from the list."
3432 :group 'org-agenda
3433 :type 'boolean)
3435 (defcustom org-calendar-to-agenda-key [?c]
3436 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3437 The command `org-calendar-goto-agenda' will be bound to this key. The
3438 default is the character `c' because then `c' can be used to switch back and
3439 forth between agenda and calendar."
3440 :group 'org-agenda
3441 :type 'sexp)
3443 (defcustom org-calendar-insert-diary-entry-key [?i]
3444 "The key to be installed in `calendar-mode-map' for adding diary entries.
3445 This option is irrelevant until `org-agenda-diary-file' has been configured
3446 to point to an Org-mode file. When that is the case, the command
3447 `org-agenda-diary-entry' will be bound to the key given here, by default
3448 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3449 if you want to continue doing this, you need to change this to a different
3450 key."
3451 :group 'org-agenda
3452 :type 'sexp)
3454 (defcustom org-agenda-diary-file 'diary-file
3455 "File to which to add new entries with the `i' key in agenda and calendar.
3456 When this is the symbol `diary-file', the functionality in the Emacs
3457 calendar will be used to add entries to the `diary-file'. But when this
3458 points to a file, `org-agenda-diary-entry' will be used instead."
3459 :group 'org-agenda
3460 :type '(choice
3461 (const :tag "The standard Emacs diary file" diary-file)
3462 (file :tag "Special Org file diary entries")))
3464 (eval-after-load "calendar"
3465 '(progn
3466 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3467 'org-calendar-goto-agenda)
3468 (add-hook 'calendar-mode-hook
3469 (lambda ()
3470 (unless (eq org-agenda-diary-file 'diary-file)
3471 (define-key calendar-mode-map
3472 org-calendar-insert-diary-entry-key
3473 'org-agenda-diary-entry))))))
3475 (defgroup org-latex nil
3476 "Options for embedding LaTeX code into Org-mode."
3477 :tag "Org LaTeX"
3478 :group 'org)
3480 (defcustom org-format-latex-options
3481 '(:foreground default :background default :scale 1.0
3482 :html-foreground "Black" :html-background "Transparent"
3483 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3484 "Options for creating images from LaTeX fragments.
3485 This is a property list with the following properties:
3486 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3487 `default' means use the foreground of the default face.
3488 `auto' means use the foreground from the text face.
3489 :background the background color, or \"Transparent\".
3490 `default' means use the background of the default face.
3491 `auto' means use the background from the text face.
3492 :scale a scaling factor for the size of the images, to get more pixels
3493 :html-foreground, :html-background, :html-scale
3494 the same numbers for HTML export.
3495 :matchers a list indicating which matchers should be used to
3496 find LaTeX fragments. Valid members of this list are:
3497 \"begin\" find environments
3498 \"$1\" find single characters surrounded by $.$
3499 \"$\" find math expressions surrounded by $...$
3500 \"$$\" find math expressions surrounded by $$....$$
3501 \"\\(\" find math expressions surrounded by \\(...\\)
3502 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3503 :group 'org-latex
3504 :type 'plist)
3506 (defcustom org-format-latex-signal-error t
3507 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3508 When nil, just push out a message."
3509 :group 'org-latex
3510 :version "24.1"
3511 :type 'boolean)
3513 (defcustom org-latex-to-mathml-jar-file nil
3514 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3515 Use this to specify additional executable file say a jar file.
3517 When using MathToWeb as the converter, specify the full-path to
3518 your mathtoweb.jar file."
3519 :group 'org-latex
3520 :version "24.1"
3521 :type '(choice
3522 (const :tag "None" nil)
3523 (file :tag "JAR file" :must-match t)))
3525 (defcustom org-latex-to-mathml-convert-command nil
3526 "Command to convert LaTeX fragments to MathML.
3527 Replace format-specifiers in the command as noted below and use
3528 `shell-command' to convert LaTeX to MathML.
3529 %j: Executable file in fully expanded form as specified by
3530 `org-latex-to-mathml-jar-file'.
3531 %I: Input LaTeX file in fully expanded form
3532 %o: Output MathML file
3533 This command is used by `org-create-math-formula'.
3535 When using MathToWeb as the converter, set this to
3536 \"java -jar %j -unicode -force -df %o %I\"."
3537 :group 'org-latex
3538 :version "24.1"
3539 :type '(choice
3540 (const :tag "None" nil)
3541 (string :tag "\nShell command")))
3543 (defcustom org-latex-create-formula-image-program 'dvipng
3544 "Program to convert LaTeX fragments with.
3546 dvipng Process the LaTeX fragments to dvi file, then convert
3547 dvi files to png files using dvipng.
3548 This will also include processing of non-math environments.
3549 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3550 to convert pdf files to png files"
3551 :group 'org-latex
3552 :version "24.1"
3553 :type '(choice
3554 (const :tag "dvipng" dvipng)
3555 (const :tag "imagemagick" imagemagick)))
3557 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3558 "Path to store latex preview images.
3559 A relative path here creates many directories relative to the
3560 processed org files paths. An absolute path puts all preview
3561 images at the same place."
3562 :group 'org-latex
3563 :version "24.3"
3564 :type 'string)
3566 (defun org-format-latex-mathml-available-p ()
3567 "Return t if `org-latex-to-mathml-convert-command' is usable."
3568 (save-match-data
3569 (when (and (boundp 'org-latex-to-mathml-convert-command)
3570 org-latex-to-mathml-convert-command)
3571 (let ((executable (car (split-string
3572 org-latex-to-mathml-convert-command))))
3573 (when (executable-find executable)
3574 (if (string-match
3575 "%j" org-latex-to-mathml-convert-command)
3576 (file-readable-p org-latex-to-mathml-jar-file)
3577 t))))))
3579 (defcustom org-format-latex-header "\\documentclass{article}
3580 \\usepackage[usenames]{color}
3581 \\usepackage{amsmath}
3582 \\usepackage[mathscr]{eucal}
3583 \\pagestyle{empty} % do not remove
3584 \[PACKAGES]
3585 \[DEFAULT-PACKAGES]
3586 % The settings below are copied from fullpage.sty
3587 \\setlength{\\textwidth}{\\paperwidth}
3588 \\addtolength{\\textwidth}{-3cm}
3589 \\setlength{\\oddsidemargin}{1.5cm}
3590 \\addtolength{\\oddsidemargin}{-2.54cm}
3591 \\setlength{\\evensidemargin}{\\oddsidemargin}
3592 \\setlength{\\textheight}{\\paperheight}
3593 \\addtolength{\\textheight}{-\\headheight}
3594 \\addtolength{\\textheight}{-\\headsep}
3595 \\addtolength{\\textheight}{-\\footskip}
3596 \\addtolength{\\textheight}{-3cm}
3597 \\setlength{\\topmargin}{1.5cm}
3598 \\addtolength{\\topmargin}{-2.54cm}"
3599 "The document header used for processing LaTeX fragments.
3600 It is imperative that this header make sure that no page number
3601 appears on the page. The package defined in the variables
3602 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3603 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3604 will be appended."
3605 :group 'org-latex
3606 :type 'string)
3608 (defvar org-format-latex-header-extra nil)
3610 (defun org-set-packages-alist (var val)
3611 "Set the packages alist and make sure it has 3 elements per entry."
3612 (set var (mapcar (lambda (x)
3613 (if (and (consp x) (= (length x) 2))
3614 (list (car x) (nth 1 x) t)
3616 val)))
3618 (defun org-get-packages-alist (var)
3620 "Get the packages alist and make sure it has 3 elements per entry."
3621 (mapcar (lambda (x)
3622 (if (and (consp x) (= (length x) 2))
3623 (list (car x) (nth 1 x) t)
3625 (default-value var)))
3627 ;; The following variables are defined here because is it also used
3628 ;; when formatting latex fragments. Originally it was part of the
3629 ;; LaTeX exporter, which is why the name includes "export".
3630 (defcustom org-export-latex-default-packages-alist
3631 '(("AUTO" "inputenc" t)
3632 ("T1" "fontenc" t)
3633 ("" "fixltx2e" nil)
3634 ("" "graphicx" t)
3635 ("" "longtable" nil)
3636 ("" "float" nil)
3637 ("" "wrapfig" nil)
3638 ("" "soul" t)
3639 ("" "textcomp" t)
3640 ("" "marvosym" t)
3641 ("" "wasysym" t)
3642 ("" "latexsym" t)
3643 ("" "amssymb" t)
3644 ("" "hyperref" nil)
3645 "\\tolerance=1000"
3647 "Alist of default packages to be inserted in the header.
3648 Change this only if one of the packages here causes an incompatibility
3649 with another package you are using.
3650 The packages in this list are needed by one part or another of Org-mode
3651 to function properly.
3653 - inputenc, fontenc: for basic font and character selection
3654 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3655 for interpreting the entities in `org-entities'. You can skip some of these
3656 packages if you don't use any of the symbols in it.
3657 - graphicx: for including images
3658 - float, wrapfig: for figure placement
3659 - longtable: for long tables
3660 - hyperref: for cross references
3662 Therefore you should not modify this variable unless you know what you
3663 are doing. The one reason to change it anyway is that you might be loading
3664 some other package that conflicts with one of the default packages.
3665 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3666 If SNIPPET-FLAG is t, the package also needs to be included when
3667 compiling LaTeX snippets into images for inclusion into HTML."
3668 :group 'org-export-latex
3669 :set 'org-set-packages-alist
3670 :get 'org-get-packages-alist
3671 :version "24.1"
3672 :type '(repeat
3673 (choice
3674 (list :tag "options/package pair"
3675 (string :tag "options")
3676 (string :tag "package")
3677 (boolean :tag "Snippet"))
3678 (string :tag "A line of LaTeX"))))
3680 (defcustom org-export-latex-packages-alist nil
3681 "Alist of packages to be inserted in every LaTeX header.
3682 These will be inserted after `org-export-latex-default-packages-alist'.
3683 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3684 SNIPPET-FLAG, when t, indicates that this package is also needed when
3685 turning LaTeX snippets into images for inclusion into HTML.
3686 Make sure that you only list packages here which:
3687 - you want in every file
3688 - do not conflict with the default packages in
3689 `org-export-latex-default-packages-alist'
3690 - do not conflict with the setup in `org-format-latex-header'."
3691 :group 'org-export-latex
3692 :set 'org-set-packages-alist
3693 :get 'org-get-packages-alist
3694 :type '(repeat
3695 (choice
3696 (list :tag "options/package pair"
3697 (string :tag "options")
3698 (string :tag "package")
3699 (boolean :tag "Snippet"))
3700 (string :tag "A line of LaTeX"))))
3703 (defgroup org-appearance nil
3704 "Settings for Org-mode appearance."
3705 :tag "Org Appearance"
3706 :group 'org)
3708 (defcustom org-level-color-stars-only nil
3709 "Non-nil means fontify only the stars in each headline.
3710 When nil, the entire headline is fontified.
3711 Changing it requires restart of `font-lock-mode' to become effective
3712 also in regions already fontified."
3713 :group 'org-appearance
3714 :type 'boolean)
3716 (defcustom org-hide-leading-stars nil
3717 "Non-nil means hide the first N-1 stars in a headline.
3718 This works by using the face `org-hide' for these stars. This
3719 face is white for a light background, and black for a dark
3720 background. You may have to customize the face `org-hide' to
3721 make this work.
3722 Changing it requires restart of `font-lock-mode' to become effective
3723 also in regions already fontified.
3724 You may also set this on a per-file basis by adding one of the following
3725 lines to the buffer:
3727 #+STARTUP: hidestars
3728 #+STARTUP: showstars"
3729 :group 'org-appearance
3730 :type 'boolean)
3732 (defcustom org-hidden-keywords nil
3733 "List of symbols corresponding to keywords to be hidden the org buffer.
3734 For example, a value '(title) for this list will make the document's title
3735 appear in the buffer without the initial #+TITLE: keyword."
3736 :group 'org-appearance
3737 :version "24.1"
3738 :type '(set (const :tag "#+AUTHOR" author)
3739 (const :tag "#+DATE" date)
3740 (const :tag "#+EMAIL" email)
3741 (const :tag "#+TITLE" title)))
3743 (defcustom org-custom-properties nil
3744 "List of properties (as strings) with a special meaning.
3745 The default use of these custom properties is to let the user
3746 hide them with `org-toggle-custom-properties-visibility'."
3747 :group 'org-properties
3748 :group 'org-appearance
3749 :version "24.3"
3750 :type '(repeat (string :tag "Property Name")))
3752 (defcustom org-fontify-done-headline nil
3753 "Non-nil means change the face of a headline if it is marked DONE.
3754 Normally, only the TODO/DONE keyword indicates the state of a headline.
3755 When this is non-nil, the headline after the keyword is set to the
3756 `org-headline-done' as an additional indication."
3757 :group 'org-appearance
3758 :type 'boolean)
3760 (defcustom org-fontify-emphasized-text t
3761 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3762 Changing this variable requires a restart of Emacs to take effect."
3763 :group 'org-appearance
3764 :type 'boolean)
3766 (defcustom org-fontify-whole-heading-line nil
3767 "Non-nil means fontify the whole line for headings.
3768 This is useful when setting a background color for the
3769 org-level-* faces."
3770 :group 'org-appearance
3771 :type 'boolean)
3773 (defcustom org-highlight-latex-fragments-and-specials nil
3774 "Non-nil means fontify what is treated specially by the exporters."
3775 :group 'org-appearance
3776 :type 'boolean)
3778 (defcustom org-hide-emphasis-markers nil
3779 "Non-nil mean font-lock should hide the emphasis marker characters."
3780 :group 'org-appearance
3781 :type 'boolean)
3783 (defcustom org-pretty-entities nil
3784 "Non-nil means show entities as UTF8 characters.
3785 When nil, the \\name form remains in the buffer."
3786 :group 'org-appearance
3787 :version "24.1"
3788 :type 'boolean)
3790 (defcustom org-pretty-entities-include-sub-superscripts t
3791 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3792 :group 'org-appearance
3793 :version "24.1"
3794 :type 'boolean)
3796 (defvar org-emph-re nil
3797 "Regular expression for matching emphasis.
3798 After a match, the match groups contain these elements:
3799 0 The match of the full regular expression, including the characters
3800 before and after the proper match
3801 1 The character before the proper match, or empty at beginning of line
3802 2 The proper match, including the leading and trailing markers
3803 3 The leading marker like * or /, indicating the type of highlighting
3804 4 The text between the emphasis markers, not including the markers
3805 5 The character after the match, empty at the end of a line")
3806 (defvar org-verbatim-re nil
3807 "Regular expression for matching verbatim text.")
3808 (defvar org-emphasis-regexp-components) ; defined just below
3809 (defvar org-emphasis-alist) ; defined just below
3810 (defun org-set-emph-re (var val)
3811 "Set variable and compute the emphasis regular expression."
3812 (set var val)
3813 (when (and (boundp 'org-emphasis-alist)
3814 (boundp 'org-emphasis-regexp-components)
3815 org-emphasis-alist org-emphasis-regexp-components)
3816 (let* ((e org-emphasis-regexp-components)
3817 (pre (car e))
3818 (post (nth 1 e))
3819 (border (nth 2 e))
3820 (body (nth 3 e))
3821 (nl (nth 4 e))
3822 (body1 (concat body "*?"))
3823 (markers (mapconcat 'car org-emphasis-alist ""))
3824 (vmarkers (mapconcat
3825 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3826 org-emphasis-alist "")))
3827 ;; make sure special characters appear at the right position in the class
3828 (if (string-match "\\^" markers)
3829 (setq markers (concat (replace-match "" t t markers) "^")))
3830 (if (string-match "-" markers)
3831 (setq markers (concat (replace-match "" t t markers) "-")))
3832 (if (string-match "\\^" vmarkers)
3833 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3834 (if (string-match "-" vmarkers)
3835 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3836 (if (> nl 0)
3837 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3838 (int-to-string nl) "\\}")))
3839 ;; Make the regexp
3840 (setq org-emph-re
3841 (concat "\\([" pre "]\\|^\\)"
3842 "\\("
3843 "\\([" markers "]\\)"
3844 "\\("
3845 "[^" border "]\\|"
3846 "[^" border "]"
3847 body1
3848 "[^" border "]"
3849 "\\)"
3850 "\\3\\)"
3851 "\\([" post "]\\|$\\)"))
3852 (setq org-verbatim-re
3853 (concat "\\([" pre "]\\|^\\)"
3854 "\\("
3855 "\\([" vmarkers "]\\)"
3856 "\\("
3857 "[^" border "]\\|"
3858 "[^" border "]"
3859 body1
3860 "[^" border "]"
3861 "\\)"
3862 "\\3\\)"
3863 "\\([" post "]\\|$\\)")))))
3865 (defcustom org-emphasis-regexp-components
3866 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3867 "Components used to build the regular expression for emphasis.
3868 This is a list with five entries. Terminology: In an emphasis string
3869 like \" *strong word* \", we call the initial space PREMATCH, the final
3870 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3871 and \"trong wor\" is the body. The different components in this variable
3872 specify what is allowed/forbidden in each part:
3874 pre Chars allowed as prematch. Beginning of line will be allowed too.
3875 post Chars allowed as postmatch. End of line will be allowed too.
3876 border The chars *forbidden* as border characters.
3877 body-regexp A regexp like \".\" to match a body character. Don't use
3878 non-shy groups here, and don't allow newline here.
3879 newline The maximum number of newlines allowed in an emphasis exp.
3881 Use customize to modify this, or restart Emacs after changing it."
3882 :group 'org-appearance
3883 :set 'org-set-emph-re
3884 :type '(list
3885 (sexp :tag "Allowed chars in pre ")
3886 (sexp :tag "Allowed chars in post ")
3887 (sexp :tag "Forbidden chars in border ")
3888 (sexp :tag "Regexp for body ")
3889 (integer :tag "number of newlines allowed")
3890 (option (boolean :tag "Please ignore this button"))))
3892 (defcustom org-emphasis-alist
3893 `(("*" bold "<b>" "</b>")
3894 ("/" italic "<i>" "</i>")
3895 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3896 ("=" org-code "<code>" "</code>" verbatim)
3897 ("~" org-verbatim "<code>" "</code>" verbatim)
3898 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3899 "<del>" "</del>")
3901 "Special syntax for emphasized text.
3902 Text starting and ending with a special character will be emphasized, for
3903 example *bold*, _underlined_ and /italic/. This variable sets the marker
3904 characters, the face to be used by font-lock for highlighting in Org-mode
3905 Emacs buffers, and the HTML tags to be used for this.
3906 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3907 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3908 Use customize to modify this, or restart Emacs after changing it."
3909 :group 'org-appearance
3910 :set 'org-set-emph-re
3911 :type '(repeat
3912 (list
3913 (string :tag "Marker character")
3914 (choice
3915 (face :tag "Font-lock-face")
3916 (plist :tag "Face property list"))
3917 (string :tag "HTML start tag")
3918 (string :tag "HTML end tag")
3919 (option (const verbatim)))))
3921 (defvar org-syntax-table
3922 (let ((st (make-syntax-table)))
3923 (mapc (lambda(c) (modify-syntax-entry
3924 (string-to-char (car c)) "w p" st))
3925 org-emphasis-alist)
3926 st))
3928 (defvar org-protecting-blocks
3929 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3930 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3931 This is needed for font-lock setup.")
3933 ;;; Miscellaneous options
3935 (defgroup org-completion nil
3936 "Completion in Org-mode."
3937 :tag "Org Completion"
3938 :group 'org)
3940 (defcustom org-completion-use-ido nil
3941 "Non-nil means use ido completion wherever possible.
3942 Note that `ido-mode' must be active for this variable to be relevant.
3943 If you decide to turn this variable on, you might well want to turn off
3944 `org-outline-path-complete-in-steps'.
3945 See also `org-completion-use-iswitchb'."
3946 :group 'org-completion
3947 :type 'boolean)
3949 (defcustom org-completion-use-iswitchb nil
3950 "Non-nil means use iswitchb completion wherever possible.
3951 Note that `iswitchb-mode' must be active for this variable to be relevant.
3952 If you decide to turn this variable on, you might well want to turn off
3953 `org-outline-path-complete-in-steps'.
3954 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3955 :group 'org-completion
3956 :type 'boolean)
3958 (defcustom org-completion-fallback-command 'hippie-expand
3959 "The expansion command called by \\[pcomplete] in normal context.
3960 Normal means, no org-mode-specific context."
3961 :group 'org-completion
3962 :type 'function)
3964 ;;; Functions and variables from their packages
3965 ;; Declared here to avoid compiler warnings
3967 ;; XEmacs only
3968 (defvar outline-mode-menu-heading)
3969 (defvar outline-mode-menu-show)
3970 (defvar outline-mode-menu-hide)
3971 (defvar zmacs-regions) ; XEmacs regions
3973 ;; Emacs only
3974 (defvar mark-active)
3976 ;; Various packages
3977 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3978 (declare-function calendar-forward-day "cal-move" (arg))
3979 (declare-function calendar-goto-date "cal-move" (date))
3980 (declare-function calendar-goto-today "cal-move" ())
3981 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3982 (defvar calc-embedded-close-formula)
3983 (defvar calc-embedded-open-formula)
3984 (declare-function cdlatex-tab "ext:cdlatex" ())
3985 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3986 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3987 (defvar font-lock-unfontify-region-function)
3988 (declare-function iswitchb-read-buffer "iswitchb"
3989 (prompt &optional default require-match start matches-set))
3990 (defvar iswitchb-temp-buflist)
3991 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3992 (defvar org-agenda-tags-todo-honor-ignore-options)
3993 (declare-function org-agenda-skip "org-agenda" ())
3994 (declare-function
3995 org-agenda-format-item "org-agenda"
3996 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3997 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3998 (declare-function org-agenda-change-all-lines "org-agenda"
3999 (newhead hdmarker &optional fixface just-this))
4000 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4001 (declare-function org-agenda-maybe-redo "org-agenda" ())
4002 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4003 (beg end))
4004 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4005 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4006 "org-agenda" (&optional end))
4007 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4008 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4009 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4010 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4011 (declare-function org-indent-mode "org-indent" (&optional arg))
4012 (declare-function parse-time-string "parse-time" (string))
4013 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4014 (declare-function org-export-latex-fix-inputenc "org-latex" ())
4015 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4016 (defvar remember-data-file)
4017 (defvar texmathp-why)
4018 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4019 (declare-function table--at-cell-p "table" (position &optional object at-column))
4021 (defvar org-latex-regexps)
4023 ;;; Autoload and prepare some org modules
4025 ;; Some table stuff that needs to be defined here, because it is used
4026 ;; by the functions setting up org-mode or checking for table context.
4028 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4029 "Detect an org-type or table-type table.")
4030 (defconst org-table-line-regexp "^[ \t]*|"
4031 "Detect an org-type table line.")
4032 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4033 "Detect an org-type table line.")
4034 (defconst org-table-hline-regexp "^[ \t]*|-"
4035 "Detect an org-type table hline.")
4036 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4037 "Detect a table-type table hline.")
4038 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4039 "Detect the first line outside a table when searching from within it.
4040 This works for both table types.")
4042 ;; Autoload the functions in org-table.el that are needed by functions here.
4044 (eval-and-compile
4045 (org-autoload "org-table"
4046 '(org-table-begin org-table-blank-field org-table-end)))
4048 ;;;###autoload
4049 (defun turn-on-orgtbl ()
4050 "Unconditionally turn on `orgtbl-mode'."
4051 (require 'org-table)
4052 (orgtbl-mode 1))
4054 (defun org-at-table-p (&optional table-type)
4055 "Return t if the cursor is inside an org-type table.
4056 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4057 (if org-enable-table-editor
4058 (save-excursion
4059 (beginning-of-line 1)
4060 (looking-at (if table-type org-table-any-line-regexp
4061 org-table-line-regexp)))
4062 nil))
4063 (defsubst org-table-p () (org-at-table-p))
4065 (defun org-at-table.el-p ()
4066 "Return t if and only if we are at a table.el table."
4067 (and (org-at-table-p 'any)
4068 (save-excursion
4069 (goto-char (org-table-begin 'any))
4070 (looking-at org-table1-hline-regexp))))
4071 (defun org-table-recognize-table.el ()
4072 "If there is a table.el table nearby, recognize it and move into it."
4073 (if org-table-tab-recognizes-table.el
4074 (if (org-at-table.el-p)
4075 (progn
4076 (beginning-of-line 1)
4077 (if (looking-at org-table-dataline-regexp)
4079 (if (looking-at org-table1-hline-regexp)
4080 (progn
4081 (beginning-of-line 2)
4082 (if (looking-at org-table-any-border-regexp)
4083 (beginning-of-line -1)))))
4084 (if (re-search-forward "|" (org-table-end t) t)
4085 (progn
4086 (require 'table)
4087 (if (table--at-cell-p (point))
4089 (message "recognizing table.el table...")
4090 (table-recognize-table)
4091 (message "recognizing table.el table...done")))
4092 (error "This should not happen"))
4094 nil)
4095 nil))
4097 (defun org-at-table-hline-p ()
4098 "Return t if the cursor is inside a hline in a table."
4099 (if org-enable-table-editor
4100 (save-excursion
4101 (beginning-of-line 1)
4102 (looking-at org-table-hline-regexp))
4103 nil))
4105 (defvar org-table-clean-did-remove-column nil)
4107 (defun org-table-map-tables (function &optional quietly)
4108 "Apply FUNCTION to the start of all tables in the buffer."
4109 (save-excursion
4110 (save-restriction
4111 (widen)
4112 (goto-char (point-min))
4113 (while (re-search-forward org-table-any-line-regexp nil t)
4114 (unless quietly
4115 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4116 (beginning-of-line 1)
4117 (when (and (looking-at org-table-line-regexp)
4118 ;; Exclude tables in src/example/verbatim/clocktable blocks
4119 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4120 (save-excursion (funcall function))
4121 (or (looking-at org-table-line-regexp)
4122 (forward-char 1)))
4123 (re-search-forward org-table-any-border-regexp nil 1))))
4124 (unless quietly (message "Mapping tables: done")))
4126 ;; Declare and autoload functions from org-exp.el & Co
4128 (declare-function org-default-export-plist "org-exp")
4129 (declare-function org-infile-export-plist "org-exp")
4130 (declare-function org-get-current-options "org-exp")
4132 ;; Declare and autoload functions from org-agenda.el
4134 (eval-and-compile
4135 (org-autoload "org-agenda"
4136 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4138 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4139 (declare-function org-clock-update-mode-line "org-clock" ())
4140 (declare-function org-resolve-clocks "org-clock"
4141 (&optional also-non-dangling-p prompt last-valid))
4142 (defvar org-clock-start-time)
4143 (defvar org-clock-marker (make-marker)
4144 "Marker recording the last clock-in.")
4145 (defvar org-clock-hd-marker (make-marker)
4146 "Marker recording the last clock-in, but the headline position.")
4147 (defvar org-clock-heading ""
4148 "The heading of the current clock entry.")
4149 (defun org-clock-is-active ()
4150 "Return non-nil if clock is currently running.
4151 The return value is actually the clock marker."
4152 (marker-buffer org-clock-marker))
4154 (eval-and-compile
4155 (org-autoload "org-clock" '(org-clock-remove-overlays
4156 org-clock-update-time-maybe
4157 org-clocktable-shift)))
4159 (defun org-check-running-clock ()
4160 "Check if the current buffer contains the running clock.
4161 If yes, offer to stop it and to save the buffer with the changes."
4162 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4163 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4164 (buffer-name))))
4165 (org-clock-out)
4166 (when (y-or-n-p "Save changed buffer?")
4167 (save-buffer))))
4169 (defun org-clocktable-try-shift (dir n)
4170 "Check if this line starts a clock table, if yes, shift the time block."
4171 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4172 (org-clocktable-shift dir n)))
4174 ;;;###autoload
4175 (defun org-clock-persistence-insinuate ()
4176 "Set up hooks for clock persistence."
4177 (require 'org-clock)
4178 (add-hook 'org-mode-hook 'org-clock-load)
4179 (add-hook 'kill-emacs-hook 'org-clock-save))
4181 ;; Define the variable already here, to make sure we have it.
4182 (defvar org-indent-mode nil
4183 "Non-nil if Org-Indent mode is enabled.
4184 Use the command `org-indent-mode' to change this variable.")
4186 ;; Autoload archiving code
4187 ;; The stuff that is needed for cycling and tags has to be defined here.
4189 (defgroup org-archive nil
4190 "Options concerning archiving in Org-mode."
4191 :tag "Org Archive"
4192 :group 'org-structure)
4194 (defcustom org-archive-location "%s_archive::"
4195 "The location where subtrees should be archived.
4197 The value of this variable is a string, consisting of two parts,
4198 separated by a double-colon. The first part is a filename and
4199 the second part is a headline.
4201 When the filename is omitted, archiving happens in the same file.
4202 %s in the filename will be replaced by the current file
4203 name (without the directory part). Archiving to a different file
4204 is useful to keep archived entries from contributing to the
4205 Org-mode Agenda.
4207 The archived entries will be filed as subtrees of the specified
4208 headline. When the headline is omitted, the subtrees are simply
4209 filed away at the end of the file, as top-level entries. Also in
4210 the heading you can use %s to represent the file name, this can be
4211 useful when using the same archive for a number of different files.
4213 Here are a few examples:
4214 \"%s_archive::\"
4215 If the current file is Projects.org, archive in file
4216 Projects.org_archive, as top-level trees. This is the default.
4218 \"::* Archived Tasks\"
4219 Archive in the current file, under the top-level headline
4220 \"* Archived Tasks\".
4222 \"~/org/archive.org::\"
4223 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4225 \"~/org/archive.org::* From %s\"
4226 Archive in file ~/org/archive.org (absolute path), under headlines
4227 \"From FILENAME\" where file name is the current file name.
4229 \"~/org/datetree.org::datetree/* Finished Tasks\"
4230 The \"datetree/\" string is special, signifying to archive
4231 items to the datetree. Items are placed in either the CLOSED
4232 date of the item, or the current date if there is no CLOSED date.
4233 The heading will be a subentry to the current date. There doesn't
4234 need to be a heading, but there always needs to be a slash after
4235 datetree. For example, to store archived items directly in the
4236 datetree, use \"~/org/datetree.org::datetree/\".
4238 \"basement::** Finished Tasks\"
4239 Archive in file ./basement (relative path), as level 3 trees
4240 below the level 2 heading \"** Finished Tasks\".
4242 You may set this option on a per-file basis by adding to the buffer a
4243 line like
4245 #+ARCHIVE: basement::** Finished Tasks
4247 You may also define it locally for a subtree by setting an ARCHIVE property
4248 in the entry. If such a property is found in an entry, or anywhere up
4249 the hierarchy, it will be used."
4250 :group 'org-archive
4251 :type 'string)
4253 (defcustom org-archive-tag "ARCHIVE"
4254 "The tag that marks a subtree as archived.
4255 An archived subtree does not open during visibility cycling, and does
4256 not contribute to the agenda listings.
4257 After changing this, font-lock must be restarted in the relevant buffers to
4258 get the proper fontification."
4259 :group 'org-archive
4260 :group 'org-keywords
4261 :type 'string)
4263 (defcustom org-agenda-skip-archived-trees t
4264 "Non-nil means the agenda will skip any items located in archived trees.
4265 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4266 variable is no longer recommended, you should leave it at the value t.
4267 Instead, use the key `v' to cycle the archives-mode in the agenda."
4268 :group 'org-archive
4269 :group 'org-agenda-skip
4270 :type 'boolean)
4272 (defcustom org-columns-skip-archived-trees t
4273 "Non-nil means ignore archived trees when creating column view."
4274 :group 'org-archive
4275 :group 'org-properties
4276 :type 'boolean)
4278 (defcustom org-cycle-open-archived-trees nil
4279 "Non-nil means `org-cycle' will open archived trees.
4280 An archived tree is a tree marked with the tag ARCHIVE.
4281 When nil, archived trees will stay folded. You can still open them with
4282 normal outline commands like `show-all', but not with the cycling commands."
4283 :group 'org-archive
4284 :group 'org-cycle
4285 :type 'boolean)
4287 (defcustom org-sparse-tree-open-archived-trees nil
4288 "Non-nil means sparse tree construction shows matches in archived trees.
4289 When nil, matches in these trees are highlighted, but the trees are kept in
4290 collapsed state."
4291 :group 'org-archive
4292 :group 'org-sparse-trees
4293 :type 'boolean)
4295 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4296 "The default date type when building a sparse tree.
4297 When this is nil, a date is a scheduled or a deadline timestamp.
4298 Otherwise, these types are allowed:
4300 all: all timestamps
4301 active: only active timestamps (<...>)
4302 inactive: only inactive timestamps (<...)
4303 scheduled: only scheduled timestamps
4304 deadline: only deadline timestamps"
4305 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4306 (const :tag "All timestamps" all)
4307 (const :tag "Only active timestamps" active)
4308 (const :tag "Only inactive timestamps" inactive)
4309 (const :tag "Only scheduled timestamps" scheduled)
4310 (const :tag "Only deadline timestamps" deadline))
4311 :version "24.3"
4312 :group 'org-sparse-trees)
4314 (defun org-cycle-hide-archived-subtrees (state)
4315 "Re-hide all archived subtrees after a visibility state change."
4316 (when (and (not org-cycle-open-archived-trees)
4317 (not (memq state '(overview folded))))
4318 (save-excursion
4319 (let* ((globalp (memq state '(contents all)))
4320 (beg (if globalp (point-min) (point)))
4321 (end (if globalp (point-max) (org-end-of-subtree t))))
4322 (org-hide-archived-subtrees beg end)
4323 (goto-char beg)
4324 (if (looking-at (concat ".*:" org-archive-tag ":"))
4325 (message "%s" (substitute-command-keys
4326 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4328 (defun org-force-cycle-archived ()
4329 "Cycle subtree even if it is archived."
4330 (interactive)
4331 (setq this-command 'org-cycle)
4332 (let ((org-cycle-open-archived-trees t))
4333 (call-interactively 'org-cycle)))
4335 (defun org-hide-archived-subtrees (beg end)
4336 "Re-hide all archived subtrees after a visibility state change."
4337 (save-excursion
4338 (let* ((re (concat ":" org-archive-tag ":")))
4339 (goto-char beg)
4340 (while (re-search-forward re end t)
4341 (when (org-at-heading-p)
4342 (org-flag-subtree t)
4343 (org-end-of-subtree t))))))
4345 (declare-function outline-end-of-heading "outline" ())
4346 (declare-function outline-flag-region "outline" (from to flag))
4347 (defun org-flag-subtree (flag)
4348 (save-excursion
4349 (org-back-to-heading t)
4350 (outline-end-of-heading)
4351 (outline-flag-region (point)
4352 (progn (org-end-of-subtree t) (point))
4353 flag)))
4355 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4357 (eval-and-compile
4358 (org-autoload "org-archive"
4359 '(org-add-archive-files)))
4361 ;; Autoload Column View Code
4363 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4364 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4365 (declare-function org-columns-compute "org-colview" (property))
4367 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4368 '(org-columns-number-to-string
4369 org-columns-get-format-and-top-level
4370 org-columns-compute
4371 org-columns-remove-overlays))
4373 ;; Autoload ID code
4375 (declare-function org-id-store-link "org-id")
4376 (declare-function org-id-locations-load "org-id")
4377 (declare-function org-id-locations-save "org-id")
4378 (defvar org-id-track-globally)
4379 (org-autoload "org-id"
4380 '(org-id-new
4381 org-id-copy
4382 org-id-get-with-outline-path-completion
4383 org-id-get-with-outline-drilling))
4385 ;;; Variables for pre-computed regular expressions, all buffer local
4387 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4388 "Matches first line of a hidden block.")
4389 (make-variable-buffer-local 'org-drawer-regexp)
4390 (defvar org-todo-regexp nil
4391 "Matches any of the TODO state keywords.")
4392 (make-variable-buffer-local 'org-todo-regexp)
4393 (defvar org-not-done-regexp nil
4394 "Matches any of the TODO state keywords except the last one.")
4395 (make-variable-buffer-local 'org-not-done-regexp)
4396 (defvar org-not-done-heading-regexp nil
4397 "Matches a TODO headline that is not done.")
4398 (make-variable-buffer-local 'org-not-done-regexp)
4399 (defvar org-todo-line-regexp nil
4400 "Matches a headline and puts TODO state into group 2 if present.")
4401 (make-variable-buffer-local 'org-todo-line-regexp)
4402 (defvar org-complex-heading-regexp nil
4403 "Matches a headline and puts everything into groups:
4404 group 1: the stars
4405 group 2: The todo keyword, maybe
4406 group 3: Priority cookie
4407 group 4: True headline
4408 group 5: Tags")
4409 (make-variable-buffer-local 'org-complex-heading-regexp)
4410 (defvar org-complex-heading-regexp-format nil
4411 "Printf format to make regexp to match an exact headline.
4412 This regexp will match the headline of any node which has the
4413 exact headline text that is put into the format, but may have any
4414 TODO state, priority and tags.")
4415 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4416 (defvar org-todo-line-tags-regexp nil
4417 "Matches a headline and puts TODO state into group 2 if present.
4418 Also put tags into group 4 if tags are present.")
4419 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4420 (defvar org-ds-keyword-length 12
4421 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4422 (make-variable-buffer-local 'org-ds-keyword-length)
4423 (defvar org-deadline-regexp nil
4424 "Matches the DEADLINE keyword.")
4425 (make-variable-buffer-local 'org-deadline-regexp)
4426 (defvar org-deadline-time-regexp nil
4427 "Matches the DEADLINE keyword together with a time stamp.")
4428 (make-variable-buffer-local 'org-deadline-time-regexp)
4429 (defvar org-deadline-line-regexp nil
4430 "Matches the DEADLINE keyword and the rest of the line.")
4431 (make-variable-buffer-local 'org-deadline-line-regexp)
4432 (defvar org-scheduled-regexp nil
4433 "Matches the SCHEDULED keyword.")
4434 (make-variable-buffer-local 'org-scheduled-regexp)
4435 (defvar org-scheduled-time-regexp nil
4436 "Matches the SCHEDULED keyword together with a time stamp.")
4437 (make-variable-buffer-local 'org-scheduled-time-regexp)
4438 (defvar org-closed-time-regexp nil
4439 "Matches the CLOSED keyword together with a time stamp.")
4440 (make-variable-buffer-local 'org-closed-time-regexp)
4442 (defvar org-keyword-time-regexp nil
4443 "Matches any of the 4 keywords, together with the time stamp.")
4444 (make-variable-buffer-local 'org-keyword-time-regexp)
4445 (defvar org-keyword-time-not-clock-regexp nil
4446 "Matches any of the 3 keywords, together with the time stamp.")
4447 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4448 (defvar org-maybe-keyword-time-regexp nil
4449 "Matches a timestamp, possibly preceded by a keyword.")
4450 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4451 (defvar org-all-time-keywords nil
4452 "List of time keywords.")
4453 (make-variable-buffer-local 'org-all-time-keywords)
4455 (defconst org-plain-time-of-day-regexp
4456 (concat
4457 "\\(\\<[012]?[0-9]"
4458 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4459 "\\(--?"
4460 "\\(\\<[012]?[0-9]"
4461 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4462 "\\)?")
4463 "Regular expression to match a plain time or time range.
4464 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4465 groups carry important information:
4466 0 the full match
4467 1 the first time, range or not
4468 8 the second time, if it is a range.")
4470 (defconst org-plain-time-extension-regexp
4471 (concat
4472 "\\(\\<[012]?[0-9]"
4473 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4474 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4475 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4476 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4477 groups carry important information:
4478 0 the full match
4479 7 hours of duration
4480 9 minutes of duration")
4482 (defconst org-stamp-time-of-day-regexp
4483 (concat
4484 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4485 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4486 "\\(--?"
4487 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4488 "Regular expression to match a timestamp time or time range.
4489 After a match, the following groups carry important information:
4490 0 the full match
4491 1 date plus weekday, for back referencing to make sure both times are on the same day
4492 2 the first time, range or not
4493 4 the second time, if it is a range.")
4495 (defconst org-startup-options
4496 '(("fold" org-startup-folded t)
4497 ("overview" org-startup-folded t)
4498 ("nofold" org-startup-folded nil)
4499 ("showall" org-startup-folded nil)
4500 ("showeverything" org-startup-folded showeverything)
4501 ("content" org-startup-folded content)
4502 ("indent" org-startup-indented t)
4503 ("noindent" org-startup-indented nil)
4504 ("hidestars" org-hide-leading-stars t)
4505 ("showstars" org-hide-leading-stars nil)
4506 ("odd" org-odd-levels-only t)
4507 ("oddeven" org-odd-levels-only nil)
4508 ("align" org-startup-align-all-tables t)
4509 ("noalign" org-startup-align-all-tables nil)
4510 ("inlineimages" org-startup-with-inline-images t)
4511 ("noinlineimages" org-startup-with-inline-images nil)
4512 ("customtime" org-display-custom-times t)
4513 ("logdone" org-log-done time)
4514 ("lognotedone" org-log-done note)
4515 ("nologdone" org-log-done nil)
4516 ("lognoteclock-out" org-log-note-clock-out t)
4517 ("nolognoteclock-out" org-log-note-clock-out nil)
4518 ("logrepeat" org-log-repeat state)
4519 ("lognoterepeat" org-log-repeat note)
4520 ("logdrawer" org-log-into-drawer t)
4521 ("nologdrawer" org-log-into-drawer nil)
4522 ("logstatesreversed" org-log-states-order-reversed t)
4523 ("nologstatesreversed" org-log-states-order-reversed nil)
4524 ("nologrepeat" org-log-repeat nil)
4525 ("logreschedule" org-log-reschedule time)
4526 ("lognotereschedule" org-log-reschedule note)
4527 ("nologreschedule" org-log-reschedule nil)
4528 ("logredeadline" org-log-redeadline time)
4529 ("lognoteredeadline" org-log-redeadline note)
4530 ("nologredeadline" org-log-redeadline nil)
4531 ("logrefile" org-log-refile time)
4532 ("lognoterefile" org-log-refile note)
4533 ("nologrefile" org-log-refile nil)
4534 ("fninline" org-footnote-define-inline t)
4535 ("nofninline" org-footnote-define-inline nil)
4536 ("fnlocal" org-footnote-section nil)
4537 ("fnauto" org-footnote-auto-label t)
4538 ("fnprompt" org-footnote-auto-label nil)
4539 ("fnconfirm" org-footnote-auto-label confirm)
4540 ("fnplain" org-footnote-auto-label plain)
4541 ("fnadjust" org-footnote-auto-adjust t)
4542 ("nofnadjust" org-footnote-auto-adjust nil)
4543 ("constcgs" constants-unit-system cgs)
4544 ("constSI" constants-unit-system SI)
4545 ("noptag" org-tag-persistent-alist nil)
4546 ("hideblocks" org-hide-block-startup t)
4547 ("nohideblocks" org-hide-block-startup nil)
4548 ("beamer" org-startup-with-beamer-mode t)
4549 ("entitiespretty" org-pretty-entities t)
4550 ("entitiesplain" org-pretty-entities nil))
4551 "Variable associated with STARTUP options for org-mode.
4552 Each element is a list of three items: the startup options (as written
4553 in the #+STARTUP line), the corresponding variable, and the value to set
4554 this variable to if the option is found. An optional forth element PUSH
4555 means to push this value onto the list in the variable.")
4557 (defun org-update-property-plist (key val props)
4558 "Update PROPS with KEY and VAL."
4559 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4560 (key (if appending (substring key 0 (- (length key) 1)) key))
4561 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4562 (previous (cdr (assoc key props))))
4563 (if appending
4564 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4565 (cons (cons key val) remainder))))
4567 (defconst org-block-regexp
4568 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4569 "Regular expression for hiding blocks.")
4570 (defconst org-heading-keyword-regexp-format
4571 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4572 "Printf format for a regexp matching an headline with some keyword.
4573 This regexp will match the headline of any node which has the
4574 exact keyword that is put into the format. The keyword isn't in
4575 any group by default, but the stars and the body are.")
4576 (defconst org-heading-keyword-maybe-regexp-format
4577 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4578 "Printf format for a regexp matching an headline, possibly with some keyword.
4579 This regexp can match any headline with the specified keyword, or
4580 without a keyword. The keyword isn't in any group by default,
4581 but the stars and the body are.")
4583 (defun org-set-regexps-and-options ()
4584 "Precompute regular expressions for current buffer."
4585 (when (derived-mode-p 'org-mode)
4586 (org-set-local 'org-todo-kwd-alist nil)
4587 (org-set-local 'org-todo-key-alist nil)
4588 (org-set-local 'org-todo-key-trigger nil)
4589 (org-set-local 'org-todo-keywords-1 nil)
4590 (org-set-local 'org-done-keywords nil)
4591 (org-set-local 'org-todo-heads nil)
4592 (org-set-local 'org-todo-sets nil)
4593 (org-set-local 'org-todo-log-states nil)
4594 (org-set-local 'org-file-properties nil)
4595 (org-set-local 'org-file-tags nil)
4596 (let ((re (org-make-options-regexp
4597 '("CATEGORY" "TODO" "COLUMNS"
4598 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4599 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4600 "OPTIONS")
4601 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4602 (splitre "[ \t]+")
4603 (scripts org-use-sub-superscripts)
4604 kwds kws0 kwsa key log value cat arch tags const links hw dws
4605 tail sep kws1 prio props ftags drawers beamer-p
4606 ext-setup-or-nil setup-contents (start 0))
4607 (save-excursion
4608 (save-restriction
4609 (widen)
4610 (goto-char (point-min))
4611 (while (or (and ext-setup-or-nil
4612 (string-match re ext-setup-or-nil start)
4613 (setq start (match-end 0)))
4614 (and (setq ext-setup-or-nil nil start 0)
4615 (re-search-forward re nil t)))
4616 (setq key (upcase (match-string 1 ext-setup-or-nil))
4617 value (org-match-string-no-properties 2 ext-setup-or-nil))
4618 (if (stringp value) (setq value (org-trim value)))
4619 (cond
4620 ((equal key "CATEGORY")
4621 (setq cat value))
4622 ((member key '("SEQ_TODO" "TODO"))
4623 (push (cons 'sequence (org-split-string value splitre)) kwds))
4624 ((equal key "TYP_TODO")
4625 (push (cons 'type (org-split-string value splitre)) kwds))
4626 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4627 ;; general TODO-like setup
4628 (push (cons (intern (downcase (match-string 1 key)))
4629 (org-split-string value splitre)) kwds))
4630 ((equal key "TAGS")
4631 (setq tags (append tags (if tags '("\\n") nil)
4632 (org-split-string value splitre))))
4633 ((equal key "COLUMNS")
4634 (org-set-local 'org-columns-default-format value))
4635 ((equal key "LINK")
4636 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4637 (push (cons (match-string 1 value)
4638 (org-trim (match-string 2 value)))
4639 links)))
4640 ((equal key "PRIORITIES")
4641 (setq prio (org-split-string value " +")))
4642 ((equal key "PROPERTY")
4643 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4644 (setq props (org-update-property-plist (match-string 1 value)
4645 (match-string 2 value)
4646 props))))
4647 ((equal key "FILETAGS")
4648 (when (string-match "\\S-" value)
4649 (setq ftags
4650 (append
4651 ftags
4652 (apply 'append
4653 (mapcar (lambda (x) (org-split-string x ":"))
4654 (org-split-string value)))))))
4655 ((equal key "DRAWERS")
4656 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4657 ((equal key "CONSTANTS")
4658 (setq const (append const (org-split-string value splitre))))
4659 ((equal key "STARTUP")
4660 (let ((opts (org-split-string value splitre))
4661 l var val)
4662 (while (setq l (pop opts))
4663 (when (setq l (assoc l org-startup-options))
4664 (setq var (nth 1 l) val (nth 2 l))
4665 (if (not (nth 3 l))
4666 (set (make-local-variable var) val)
4667 (if (not (listp (symbol-value var)))
4668 (set (make-local-variable var) nil))
4669 (set (make-local-variable var) (symbol-value var))
4670 (add-to-list var val))))))
4671 ((equal key "ARCHIVE")
4672 (setq arch value)
4673 (remove-text-properties 0 (length arch)
4674 '(face t fontified t) arch))
4675 ((equal key "LATEX_CLASS")
4676 (setq beamer-p (equal value "beamer")))
4677 ((equal key "OPTIONS")
4678 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4679 (setq scripts (read (match-string 2 value)))))
4680 ((equal key "SETUPFILE")
4681 (setq setup-contents (org-file-contents
4682 (expand-file-name
4683 (org-remove-double-quotes value))
4684 'noerror))
4685 (if (not ext-setup-or-nil)
4686 (setq ext-setup-or-nil setup-contents start 0)
4687 (setq ext-setup-or-nil
4688 (concat (substring ext-setup-or-nil 0 start)
4689 "\n" setup-contents "\n"
4690 (substring ext-setup-or-nil start)))))))
4691 ;; search for property blocks
4692 (goto-char (point-min))
4693 (while (re-search-forward org-block-regexp nil t)
4694 (when (equal "PROPERTY" (upcase (match-string 1)))
4695 (setq value (replace-regexp-in-string
4696 "[\n\r]" " " (match-string 4)))
4697 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4698 (setq props (org-update-property-plist (match-string 1 value)
4699 (match-string 2 value)
4700 props)))))))
4701 (org-set-local 'org-use-sub-superscripts scripts)
4702 (when cat
4703 (org-set-local 'org-category (intern cat))
4704 (push (cons "CATEGORY" cat) props))
4705 (when prio
4706 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4707 (setq prio (mapcar 'string-to-char prio))
4708 (org-set-local 'org-highest-priority (nth 0 prio))
4709 (org-set-local 'org-lowest-priority (nth 1 prio))
4710 (org-set-local 'org-default-priority (nth 2 prio)))
4711 (and props (org-set-local 'org-file-properties (nreverse props)))
4712 (and ftags (org-set-local 'org-file-tags
4713 (mapcar 'org-add-prop-inherited ftags)))
4714 (and drawers (org-set-local 'org-drawers drawers))
4715 (and arch (org-set-local 'org-archive-location arch))
4716 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4717 ;; Process the TODO keywords
4718 (unless kwds
4719 ;; Use the global values as if they had been given locally.
4720 (setq kwds (default-value 'org-todo-keywords))
4721 (if (stringp (car kwds))
4722 (setq kwds (list (cons org-todo-interpretation
4723 (default-value 'org-todo-keywords)))))
4724 (setq kwds (reverse kwds)))
4725 (setq kwds (nreverse kwds))
4726 (let (inter kws kw)
4727 (while (setq kws (pop kwds))
4728 (let ((kws (or
4729 (run-hook-with-args-until-success
4730 'org-todo-setup-filter-hook kws)
4731 kws)))
4732 (setq inter (pop kws) sep (member "|" kws)
4733 kws0 (delete "|" (copy-sequence kws))
4734 kwsa nil
4735 kws1 (mapcar
4736 (lambda (x)
4737 ;; 1 2
4738 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4739 (progn
4740 (setq kw (match-string 1 x)
4741 key (and (match-end 2) (match-string 2 x))
4742 log (org-extract-log-state-settings x))
4743 (push (cons kw (and key (string-to-char key))) kwsa)
4744 (and log (push log org-todo-log-states))
4746 (error "Invalid TODO keyword %s" x)))
4747 kws0)
4748 kwsa (if kwsa (append '((:startgroup))
4749 (nreverse kwsa)
4750 '((:endgroup))))
4751 hw (car kws1)
4752 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4753 tail (list inter hw (car dws) (org-last dws))))
4754 (add-to-list 'org-todo-heads hw 'append)
4755 (push kws1 org-todo-sets)
4756 (setq org-done-keywords (append org-done-keywords dws nil))
4757 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4758 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4759 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4760 (setq org-todo-sets (nreverse org-todo-sets)
4761 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4762 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4763 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4764 ;; Process the constants
4765 (when const
4766 (let (e cst)
4767 (while (setq e (pop const))
4768 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4769 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4770 (setq org-table-formula-constants-local cst)))
4772 ;; Process the tags.
4773 (when tags
4774 (let (e tgs)
4775 (while (setq e (pop tags))
4776 (cond
4777 ((equal e "{") (push '(:startgroup) tgs))
4778 ((equal e "}") (push '(:endgroup) tgs))
4779 ((equal e "\\n") (push '(:newline) tgs))
4780 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4781 (push (cons (match-string 1 e)
4782 (string-to-char (match-string 2 e)))
4783 tgs))
4784 (t (push (list e) tgs))))
4785 (org-set-local 'org-tag-alist nil)
4786 (while (setq e (pop tgs))
4787 (or (and (stringp (car e))
4788 (assoc (car e) org-tag-alist))
4789 (push e org-tag-alist)))))
4791 ;; Compute the regular expressions and other local variables.
4792 ;; Using `org-outline-regexp-bol' would complicate them much,
4793 ;; because of the fixed white space at the end of that string.
4794 (if (not org-done-keywords)
4795 (setq org-done-keywords (and org-todo-keywords-1
4796 (list (org-last org-todo-keywords-1)))))
4797 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4798 (length org-scheduled-string)
4799 (length org-clock-string)
4800 (length org-closed-string)))
4801 org-drawer-regexp
4802 (concat "^[ \t]*:\\("
4803 (mapconcat 'regexp-quote org-drawers "\\|")
4804 "\\):[ \t]*$")
4805 org-not-done-keywords
4806 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4807 org-todo-regexp
4808 (concat "\\("
4809 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4810 "\\)")
4811 org-not-done-regexp
4812 (concat "\\("
4813 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4814 "\\)")
4815 org-not-done-heading-regexp
4816 (format org-heading-keyword-regexp-format org-not-done-regexp)
4817 org-todo-line-regexp
4818 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4819 org-complex-heading-regexp
4820 (concat "^\\(\\*+\\)"
4821 "\\(?: +" org-todo-regexp "\\)?"
4822 "\\(?: +\\(\\[#.\\]\\)\\)?"
4823 "\\(?: +\\(.*?\\)\\)??"
4824 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4825 "[ \t]*$")
4826 org-complex-heading-regexp-format
4827 (concat "^\\(\\*+\\)"
4828 "\\(?: +" org-todo-regexp "\\)?"
4829 "\\(?: +\\(\\[#.\\]\\)\\)?"
4830 "\\(?: +"
4831 ;; Stats cookies can be stuck to body.
4832 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4833 "\\(%s\\)"
4834 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4835 "\\)"
4836 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4837 "[ \t]*$")
4838 org-todo-line-tags-regexp
4839 (concat "^\\(\\*+\\)"
4840 "\\(?: +" org-todo-regexp "\\)?"
4841 "\\(?: +\\(.*?\\)\\)??"
4842 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4843 "[ \t]*$")
4844 org-deadline-regexp (concat "\\<" org-deadline-string)
4845 org-deadline-time-regexp
4846 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4847 org-deadline-line-regexp
4848 (concat "\\<\\(" org-deadline-string "\\).*")
4849 org-scheduled-regexp
4850 (concat "\\<" org-scheduled-string)
4851 org-scheduled-time-regexp
4852 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4853 org-closed-time-regexp
4854 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4855 org-keyword-time-regexp
4856 (concat "\\<\\(" org-scheduled-string
4857 "\\|" org-deadline-string
4858 "\\|" org-closed-string
4859 "\\|" org-clock-string "\\)"
4860 " *[[<]\\([^]>]+\\)[]>]")
4861 org-keyword-time-not-clock-regexp
4862 (concat "\\<\\(" org-scheduled-string
4863 "\\|" org-deadline-string
4864 "\\|" org-closed-string
4865 "\\)"
4866 " *[[<]\\([^]>]+\\)[]>]")
4867 org-maybe-keyword-time-regexp
4868 (concat "\\(\\<\\(" org-scheduled-string
4869 "\\|" org-deadline-string
4870 "\\|" org-closed-string
4871 "\\|" org-clock-string "\\)\\)?"
4872 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4873 org-all-time-keywords
4874 (mapcar (lambda (w) (substring w 0 -1))
4875 (list org-scheduled-string org-deadline-string
4876 org-clock-string org-closed-string))
4878 (org-compute-latex-and-specials-regexp)
4879 (org-set-font-lock-defaults))))
4881 (defun org-file-contents (file &optional noerror)
4882 "Return the contents of FILE, as a string."
4883 (if (or (not file)
4884 (not (file-readable-p file)))
4885 (if noerror
4886 (progn
4887 (message "Cannot read file \"%s\"" file)
4888 (ding) (sit-for 2)
4890 (error "Cannot read file \"%s\"" file))
4891 (with-temp-buffer
4892 (insert-file-contents file)
4893 (buffer-string))))
4895 (defun org-extract-log-state-settings (x)
4896 "Extract the log state setting from a TODO keyword string.
4897 This will extract info from a string like \"WAIT(w@/!)\"."
4898 (let (kw key log1 log2)
4899 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4900 (setq kw (match-string 1 x)
4901 key (and (match-end 2) (match-string 2 x))
4902 log1 (and (match-end 3) (match-string 3 x))
4903 log2 (and (match-end 4) (match-string 4 x)))
4904 (and (or log1 log2)
4905 (list kw
4906 (and log1 (if (equal log1 "!") 'time 'note))
4907 (and log2 (if (equal log2 "!") 'time 'note)))))))
4909 (defun org-remove-keyword-keys (list)
4910 "Remove a pair of parenthesis at the end of each string in LIST."
4911 (mapcar (lambda (x)
4912 (if (string-match "(.*)$" x)
4913 (substring x 0 (match-beginning 0))
4915 list))
4917 (defun org-assign-fast-keys (alist)
4918 "Assign fast keys to a keyword-key alist.
4919 Respect keys that are already there."
4920 (let (new e (alt ?0))
4921 (while (setq e (pop alist))
4922 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4923 (cdr e)) ;; Key already assigned.
4924 (push e new)
4925 (let ((clist (string-to-list (downcase (car e))))
4926 (used (append new alist)))
4927 (when (= (car clist) ?@)
4928 (pop clist))
4929 (while (and clist (rassoc (car clist) used))
4930 (pop clist))
4931 (unless clist
4932 (while (rassoc alt used)
4933 (incf alt)))
4934 (push (cons (car e) (or (car clist) alt)) new))))
4935 (nreverse new)))
4937 ;;; Some variables used in various places
4939 (defvar org-window-configuration nil
4940 "Used in various places to store a window configuration.")
4941 (defvar org-selected-window nil
4942 "Used in various places to store a window configuration.")
4943 (defvar org-finish-function nil
4944 "Function to be called when `C-c C-c' is used.
4945 This is for getting out of special buffers like capture.")
4948 ;; FIXME: Occasionally check by commenting these, to make sure
4949 ;; no other functions uses these, forgetting to let-bind them.
4950 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4951 (defvar org-last-state)
4952 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4954 ;; Defined somewhere in this file, but used before definition.
4955 (defvar org-entities) ;; defined in org-entities.el
4956 (defvar org-struct-menu)
4957 (defvar org-org-menu)
4958 (defvar org-tbl-menu)
4960 ;;;; Define the Org-mode
4962 ;; We use a before-change function to check if a table might need
4963 ;; an update.
4964 (defvar org-table-may-need-update t
4965 "Indicates that a table might need an update.
4966 This variable is set by `org-before-change-function'.
4967 `org-table-align' sets it back to nil.")
4968 (defun org-before-change-function (beg end)
4969 "Every change indicates that a table might need an update."
4970 (setq org-table-may-need-update t))
4971 (defvar org-mode-map)
4972 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4973 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4974 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4975 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4976 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4977 (defvar org-table-buffer-is-an nil)
4979 (defvar bidi-paragraph-direction)
4980 (defvar buffer-face-mode-face)
4982 (require 'outline)
4983 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4984 (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"))
4985 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4987 ;; Other stuff we need.
4988 (require 'time-date)
4989 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4990 (require 'easymenu)
4991 (require 'overlay)
4993 ;; (require 'org-macs) moved higher up in the file before it is first used
4994 (require 'org-entities)
4995 ;; (require 'org-compat) moved higher up in the file before it is first used
4996 (require 'org-faces)
4997 (require 'org-list)
4998 (require 'org-pcomplete)
4999 (require 'org-src)
5000 (require 'org-footnote)
5002 ;; babel
5003 (require 'ob)
5005 ;;;###autoload
5006 (define-derived-mode org-mode outline-mode "Org"
5007 "Outline-based notes management and organizer, alias
5008 \"Carsten's outline-mode for keeping track of everything.\"
5010 Org-mode develops organizational tasks around a NOTES file which
5011 contains information about projects as plain text. Org-mode is
5012 implemented on top of outline-mode, which is ideal to keep the content
5013 of large files well structured. It supports ToDo items, deadlines and
5014 time stamps, which magically appear in the diary listing of the Emacs
5015 calendar. Tables are easily created with a built-in table editor.
5016 Plain text URL-like links connect to websites, emails (VM), Usenet
5017 messages (Gnus), BBDB entries, and any files related to the project.
5018 For printing and sharing of notes, an Org-mode file (or a part of it)
5019 can be exported as a structured ASCII or HTML file.
5021 The following commands are available:
5023 \\{org-mode-map}"
5025 ;; Get rid of Outline menus, they are not needed
5026 ;; Need to do this here because define-derived-mode sets up
5027 ;; the keymap so late. Still, it is a waste to call this each time
5028 ;; we switch another buffer into org-mode.
5029 (if (featurep 'xemacs)
5030 (when (boundp 'outline-mode-menu-heading)
5031 ;; Assume this is Greg's port, it uses easymenu
5032 (easy-menu-remove outline-mode-menu-heading)
5033 (easy-menu-remove outline-mode-menu-show)
5034 (easy-menu-remove outline-mode-menu-hide))
5035 (define-key org-mode-map [menu-bar headings] 'undefined)
5036 (define-key org-mode-map [menu-bar hide] 'undefined)
5037 (define-key org-mode-map [menu-bar show] 'undefined))
5039 (org-load-modules-maybe)
5040 (easy-menu-add org-org-menu)
5041 (easy-menu-add org-tbl-menu)
5042 (org-install-agenda-files-menu)
5043 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5044 (add-to-invisibility-spec '(org-cwidth))
5045 (add-to-invisibility-spec '(org-hide-block . t))
5046 (when (featurep 'xemacs)
5047 (org-set-local 'line-move-ignore-invisible t))
5048 (org-set-local 'outline-regexp org-outline-regexp)
5049 (org-set-local 'outline-level 'org-outline-level)
5050 (setq bidi-paragraph-direction 'left-to-right)
5051 (when (and org-ellipsis
5052 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5053 (fboundp 'make-glyph-code))
5054 (unless org-display-table
5055 (setq org-display-table (make-display-table)))
5056 (set-display-table-slot
5057 org-display-table 4
5058 (vconcat (mapcar
5059 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5060 org-ellipsis)))
5061 (if (stringp org-ellipsis) org-ellipsis "..."))))
5062 (setq buffer-display-table org-display-table))
5063 (org-set-regexps-and-options)
5064 (when (and org-tag-faces (not org-tags-special-faces-re))
5065 ;; tag faces set outside customize.... force initialization.
5066 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5067 ;; Calc embedded
5068 (org-set-local 'calc-embedded-open-mode "# ")
5069 (modify-syntax-entry ?@ "w")
5070 (modify-syntax-entry ?\" "\"")
5071 (if org-startup-truncated (setq truncate-lines t))
5072 (org-set-local 'font-lock-unfontify-region-function
5073 'org-unfontify-region)
5074 ;; Activate before-change-function
5075 (org-set-local 'org-table-may-need-update t)
5076 (org-add-hook 'before-change-functions 'org-before-change-function nil
5077 'local)
5078 ;; Check for running clock before killing a buffer
5079 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5080 ;; Initialize macros templates.
5081 (org-macro-initialize-templates)
5082 ;; Initialize radio targets.
5083 (org-update-radio-target-regexp)
5084 ;; Indentation.
5085 (org-set-local 'indent-line-function 'org-indent-line)
5086 (org-set-local 'indent-region-function 'org-indent-region)
5087 ;; Filling and auto-filling.
5088 (org-setup-filling)
5089 ;; Comments.
5090 (org-setup-comments-handling)
5091 ;; Beginning/end of defun
5092 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5093 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5094 ;; Next error for sparse trees
5095 (org-set-local 'next-error-function 'org-occur-next-match)
5096 ;; Make sure dependence stuff works reliably, even for users who set it
5097 ;; too late :-(
5098 (if org-enforce-todo-dependencies
5099 (add-hook 'org-blocker-hook
5100 'org-block-todo-from-children-or-siblings-or-parent)
5101 (remove-hook 'org-blocker-hook
5102 'org-block-todo-from-children-or-siblings-or-parent))
5103 (if org-enforce-todo-checkbox-dependencies
5104 (add-hook 'org-blocker-hook
5105 'org-block-todo-from-checkboxes)
5106 (remove-hook 'org-blocker-hook
5107 'org-block-todo-from-checkboxes))
5109 ;; Align options lines
5110 (org-set-local
5111 'align-mode-rules-list
5112 '((org-in-buffer-settings
5113 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5114 (modes . '(org-mode)))))
5116 ;; Imenu
5117 (org-set-local 'imenu-create-index-function
5118 'org-imenu-get-tree)
5120 ;; Make isearch reveal context
5121 (if (or (featurep 'xemacs)
5122 (not (boundp 'outline-isearch-open-invisible-function)))
5123 ;; Emacs 21 and XEmacs make use of the hook
5124 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5125 ;; Emacs 22 deals with this through a special variable
5126 (org-set-local 'outline-isearch-open-invisible-function
5127 (lambda (&rest ignore) (org-show-context 'isearch))))
5129 ;; Turn on org-beamer-mode?
5130 (and org-startup-with-beamer-mode (org-beamer-mode))
5132 ;; Setup the pcomplete hooks
5133 (set (make-local-variable 'pcomplete-command-completion-function)
5134 'org-pcomplete-initial)
5135 (set (make-local-variable 'pcomplete-command-name-function)
5136 'org-command-at-point)
5137 (set (make-local-variable 'pcomplete-default-completion-function)
5138 'ignore)
5139 (set (make-local-variable 'pcomplete-parse-arguments-function)
5140 'org-parse-arguments)
5141 (set (make-local-variable 'pcomplete-termination-string) "")
5142 (when (>= emacs-major-version 23)
5143 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5145 ;; If empty file that did not turn on org-mode automatically, make it to.
5146 (if (and org-insert-mode-line-in-empty-file
5147 (org-called-interactively-p 'any)
5148 (= (point-min) (point-max)))
5149 (insert "# -*- mode: org -*-\n\n"))
5150 (unless org-inhibit-startup
5151 (when org-startup-align-all-tables
5152 (let ((bmp (buffer-modified-p)))
5153 (org-table-map-tables 'org-table-align 'quietly)
5154 (set-buffer-modified-p bmp)))
5155 (when org-startup-with-inline-images
5156 (org-display-inline-images))
5157 (when org-startup-indented
5158 (require 'org-indent)
5159 (org-indent-mode 1))
5160 (unless org-inhibit-startup-visibility-stuff
5161 (org-set-startup-visibility)))
5162 ;; Try to set org-hide correctly
5163 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5165 (when (fboundp 'abbrev-table-put)
5166 (abbrev-table-put org-mode-abbrev-table
5167 :parents (list text-mode-abbrev-table)))
5169 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5172 (defun org-find-invisible-foreground ()
5173 (let ((candidates (remove
5174 "unspecified-bg"
5175 (nconc
5176 (list (face-background 'default)
5177 (face-background 'org-default))
5178 (mapcar
5179 (lambda (alist)
5180 (when (boundp alist)
5181 (cdr (assoc 'background-color (symbol-value alist)))))
5182 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5183 (list (face-foreground 'org-hide))))))
5184 (car (remove nil candidates))))
5186 (defun org-current-time (&optional rounding-minutes)
5187 "Current time, possibly rounded to ROUNDING-MINUTES.
5188 When ROUNDING-MINUTES is not an integer, fall back on the car of
5189 `org-time-stamp-rounding-minutes'."
5190 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5191 (car org-time-stamp-rounding-minutes)))
5192 (time (decode-time)))
5193 (if (> r 1)
5194 (apply 'encode-time
5195 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5196 (nthcdr 2 time)))
5197 (current-time))))
5199 (defun org-today ()
5200 "Return today date, considering `org-extend-today-until'."
5201 (time-to-days
5202 (time-subtract (current-time)
5203 (list 0 (* 3600 org-extend-today-until) 0))))
5205 ;;;; Font-Lock stuff, including the activators
5207 (defvar org-mouse-map (make-sparse-keymap))
5208 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5209 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5210 (when org-mouse-1-follows-link
5211 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5212 (when org-tab-follows-link
5213 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5214 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5216 (require 'font-lock)
5218 (defconst org-non-link-chars "]\t\n\r<>")
5219 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5220 "shell" "elisp" "doi" "message"))
5221 (defvar org-link-types-re nil
5222 "Matches a link that has a url-like prefix like \"http:\"")
5223 (defvar org-link-re-with-space nil
5224 "Matches a link with spaces, optional angular brackets around it.")
5225 (defvar org-link-re-with-space2 nil
5226 "Matches a link with spaces, optional angular brackets around it.")
5227 (defvar org-link-re-with-space3 nil
5228 "Matches a link with spaces, only for internal part in bracket links.")
5229 (defvar org-angle-link-re nil
5230 "Matches link with angular brackets, spaces are allowed.")
5231 (defvar org-plain-link-re nil
5232 "Matches plain link, without spaces.")
5233 (defvar org-bracket-link-regexp nil
5234 "Matches a link in double brackets.")
5235 (defvar org-bracket-link-analytic-regexp nil
5236 "Regular expression used to analyze links.
5237 Here is what the match groups contain after a match:
5238 1: http:
5239 2: http
5240 3: path
5241 4: [desc]
5242 5: desc")
5243 (defvar org-bracket-link-analytic-regexp++ nil
5244 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5245 (defvar org-any-link-re nil
5246 "Regular expression matching any link.")
5248 (defcustom org-match-sexp-depth 3
5249 "Number of stacked braces for sub/superscript matching.
5250 This has to be set before loading org.el to be effective."
5251 :group 'org-export-translation ; ??????????????????????????/
5252 :type 'integer)
5254 (defun org-create-multibrace-regexp (left right n)
5255 "Create a regular expression which will match a balanced sexp.
5256 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5257 as single character strings.
5258 The regexp returned will match the entire expression including the
5259 delimiters. It will also define a single group which contains the
5260 match except for the outermost delimiters. The maximum depth of
5261 stacked delimiters is N. Escaping delimiters is not possible."
5262 (let* ((nothing (concat "[^" left right "]*?"))
5263 (or "\\|")
5264 (re nothing)
5265 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5266 (while (> n 1)
5267 (setq n (1- n)
5268 re (concat re or next)
5269 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5270 (concat left "\\(" re "\\)" right)))
5272 (defvar org-match-substring-regexp
5273 (concat
5274 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5275 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5276 "\\|"
5277 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5278 "\\|"
5279 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5280 "The regular expression matching a sub- or superscript.")
5282 (defvar org-match-substring-with-braces-regexp
5283 (concat
5284 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5285 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5286 "\\)")
5287 "The regular expression matching a sub- or superscript, forcing braces.")
5289 (defun org-make-link-regexps ()
5290 "Update the link regular expressions.
5291 This should be called after the variable `org-link-types' has changed."
5292 (setq org-link-types-re
5293 (concat
5294 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5295 org-link-re-with-space
5296 (concat
5297 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5298 "\\([^" org-non-link-chars " ]"
5299 "[^" org-non-link-chars "]*"
5300 "[^" org-non-link-chars " ]\\)>?")
5301 org-link-re-with-space2
5302 (concat
5303 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5304 "\\([^" org-non-link-chars " ]"
5305 "[^\t\n\r]*"
5306 "[^" org-non-link-chars " ]\\)>?")
5307 org-link-re-with-space3
5308 (concat
5309 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5310 "\\([^" org-non-link-chars " ]"
5311 "[^\t\n\r]*\\)")
5312 org-angle-link-re
5313 (concat
5314 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5315 "\\([^" org-non-link-chars " ]"
5316 "[^" org-non-link-chars "]*"
5317 "\\)>")
5318 org-plain-link-re
5319 (concat
5320 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5321 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5322 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5323 org-bracket-link-regexp
5324 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5325 org-bracket-link-analytic-regexp
5326 (concat
5327 "\\[\\["
5328 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5329 "\\([^]]+\\)"
5330 "\\]"
5331 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5332 "\\]")
5333 org-bracket-link-analytic-regexp++
5334 (concat
5335 "\\[\\["
5336 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5337 "\\([^]]+\\)"
5338 "\\]"
5339 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5340 "\\]")
5341 org-any-link-re
5342 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5343 org-angle-link-re "\\)\\|\\("
5344 org-plain-link-re "\\)")))
5346 (org-make-link-regexps)
5348 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5349 "Regular expression for fast time stamp matching.")
5350 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5351 "Regular expression for fast time stamp matching.")
5352 (defconst org-ts-regexp0
5353 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5354 "Regular expression matching time strings for analysis.
5355 This one does not require the space after the date, so it can be used
5356 on a string that terminates immediately after the date.")
5357 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5358 "Regular expression matching time strings for analysis.")
5359 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5360 "Regular expression matching time stamps, with groups.")
5361 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5362 "Regular expression matching time stamps (also [..]), with groups.")
5363 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5364 "Regular expression matching a time stamp range.")
5365 (defconst org-tr-regexp-both
5366 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5367 "Regular expression matching a time stamp range.")
5368 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5369 org-ts-regexp "\\)?")
5370 "Regular expression matching a time stamp or time stamp range.")
5371 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5372 org-ts-regexp-both "\\)?")
5373 "Regular expression matching a time stamp or time stamp range.
5374 The time stamps may be either active or inactive.")
5376 (defvar org-emph-face nil)
5378 (defun org-do-emphasis-faces (limit)
5379 "Run through the buffer and add overlays to emphasized strings."
5380 (let (rtn a)
5381 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5382 (if (not (= (char-after (match-beginning 3))
5383 (char-after (match-beginning 4))))
5384 (progn
5385 (setq rtn t)
5386 (setq a (assoc (match-string 3) org-emphasis-alist))
5387 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5388 'face
5389 (nth 1 a))
5390 (and (nth 4 a)
5391 (org-remove-flyspell-overlays-in
5392 (match-beginning 0) (match-end 0)))
5393 (add-text-properties (match-beginning 2) (match-end 2)
5394 '(font-lock-multiline t org-emphasis t))
5395 (when org-hide-emphasis-markers
5396 (add-text-properties (match-end 4) (match-beginning 5)
5397 '(invisible org-link))
5398 (add-text-properties (match-beginning 3) (match-end 3)
5399 '(invisible org-link)))))
5400 (backward-char 1))
5401 rtn))
5403 (defun org-emphasize (&optional char)
5404 "Insert or change an emphasis, i.e. a font like bold or italic.
5405 If there is an active region, change that region to a new emphasis.
5406 If there is no region, just insert the marker characters and position
5407 the cursor between them.
5408 CHAR should be either the marker character, or the first character of the
5409 HTML tag associated with that emphasis. If CHAR is a space, the means
5410 to remove the emphasis of the selected region.
5411 If char is not given (for example in an interactive call) it
5412 will be prompted for."
5413 (interactive)
5414 (let ((eal org-emphasis-alist) e det
5415 (erc org-emphasis-regexp-components)
5416 (prompt "")
5417 (string "") beg end move tag c s)
5418 (if (org-region-active-p)
5419 (setq beg (region-beginning) end (region-end)
5420 string (buffer-substring beg end))
5421 (setq move t))
5423 (while (setq e (pop eal))
5424 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5425 c (aref tag 0))
5426 (push (cons c (string-to-char (car e))) det)
5427 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5428 (substring tag 1)))))
5429 (setq det (nreverse det))
5430 (unless char
5431 (message "%s" (concat "Emphasis marker or tag:" prompt))
5432 (setq char (read-char-exclusive)))
5433 (setq char (or (cdr (assoc char det)) char))
5434 (if (equal char ?\ )
5435 (setq s "" move nil)
5436 (unless (assoc (char-to-string char) org-emphasis-alist)
5437 (error "No such emphasis marker: \"%c\"" char))
5438 (setq s (char-to-string char)))
5439 (while (and (> (length string) 1)
5440 (equal (substring string 0 1) (substring string -1))
5441 (assoc (substring string 0 1) org-emphasis-alist))
5442 (setq string (substring string 1 -1)))
5443 (setq string (concat s string s))
5444 (if beg (delete-region beg end))
5445 (unless (or (bolp)
5446 (string-match (concat "[" (nth 0 erc) "\n]")
5447 (char-to-string (char-before (point)))))
5448 (insert " "))
5449 (unless (or (eobp)
5450 (string-match (concat "[" (nth 1 erc) "\n]")
5451 (char-to-string (char-after (point)))))
5452 (insert " ") (backward-char 1))
5453 (insert string)
5454 (and move (backward-char 1))))
5456 (defconst org-nonsticky-props
5457 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5459 (defsubst org-rear-nonsticky-at (pos)
5460 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5462 (defun org-activate-plain-links (limit)
5463 "Run through the buffer and add overlays to links."
5464 (catch 'exit
5465 (let (f hl)
5466 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5467 (not (org-in-src-block-p)))
5468 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5469 (setq f (get-text-property (match-beginning 0) 'face))
5470 (setq hl (org-match-string-no-properties 0))
5471 (if (or (eq f 'org-tag)
5472 (and (listp f) (memq 'org-tag f)))
5474 (add-text-properties (match-beginning 0) (match-end 0)
5475 (list 'mouse-face 'highlight
5476 'face 'org-link
5477 'htmlize-link `(:uri ,hl)
5478 'keymap org-mouse-map))
5479 (org-rear-nonsticky-at (match-end 0)))
5480 t))))
5482 (defun org-activate-code (limit)
5483 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5484 (progn
5485 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5486 (remove-text-properties (match-beginning 0) (match-end 0)
5487 '(display t invisible t intangible t))
5488 t)))
5490 (defcustom org-src-fontify-natively nil
5491 "When non-nil, fontify code in code blocks."
5492 :type 'boolean
5493 :version "24.1"
5494 :group 'org-appearance
5495 :group 'org-babel)
5497 (defcustom org-allow-promoting-top-level-subtree nil
5498 "When non-nil, allow promoting a top level subtree.
5499 The leading star of the top level headline will be replaced
5500 by a #."
5501 :type 'boolean
5502 :version "24.1"
5503 :group 'org-appearance)
5505 (defun org-fontify-meta-lines-and-blocks (limit)
5506 (condition-case nil
5507 (org-fontify-meta-lines-and-blocks-1 limit)
5508 (error (message "org-mode fontification error"))))
5510 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5511 "Fontify #+ lines and blocks, in the correct ways."
5512 (let ((case-fold-search t))
5513 (if (re-search-forward
5514 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5515 limit t)
5516 (let ((beg (match-beginning 0))
5517 (block-start (match-end 0))
5518 (block-end nil)
5519 (lang (match-string 7))
5520 (beg1 (line-beginning-position 2))
5521 (dc1 (downcase (match-string 2)))
5522 (dc3 (downcase (match-string 3)))
5523 end end1 quoting block-type ovl)
5524 (cond
5525 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5526 ;; a single line of backend-specific content
5527 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5528 (remove-text-properties (match-beginning 0) (match-end 0)
5529 '(display t invisible t intangible t))
5530 (add-text-properties (match-beginning 1) (match-end 3)
5531 '(font-lock-fontified t face org-meta-line))
5532 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5533 '(font-lock-fontified t face org-block))
5534 ; for backend-specific code
5536 ((and (match-end 4) (equal dc3 "+begin"))
5537 ;; Truly a block
5538 (setq block-type (downcase (match-string 5))
5539 quoting (member block-type org-protecting-blocks))
5540 (when (re-search-forward
5541 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5542 nil t) ;; on purpose, we look further than LIMIT
5543 (setq end (min (point-max) (match-end 0))
5544 end1 (min (point-max) (1- (match-beginning 0))))
5545 (setq block-end (match-beginning 0))
5546 (when quoting
5547 (remove-text-properties beg end
5548 '(display t invisible t intangible t)))
5549 (add-text-properties
5550 beg end
5551 '(font-lock-fontified t font-lock-multiline t))
5552 (add-text-properties beg beg1 '(face org-meta-line))
5553 (add-text-properties end1 (min (point-max) (1+ end))
5554 '(face org-meta-line)) ; for end_src
5555 (cond
5556 ((and lang (not (string= lang "")) org-src-fontify-natively)
5557 (org-src-font-lock-fontify-block lang block-start block-end)
5558 ;; remove old background overlays
5559 (mapc (lambda (ov)
5560 (if (eq (overlay-get ov 'face) 'org-block-background)
5561 (delete-overlay ov)))
5562 (overlays-at (/ (+ beg1 block-end) 2)))
5563 ;; add a background overlay
5564 (setq ovl (make-overlay beg1 block-end))
5565 (overlay-put ovl 'face 'org-block-background)
5566 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5567 (quoting
5568 (add-text-properties beg1 (min (point-max) (1+ end1))
5569 '(face org-block))) ; end of source block
5570 ((not org-fontify-quote-and-verse-blocks))
5571 ((string= block-type "quote")
5572 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5573 ((string= block-type "verse")
5574 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5575 (add-text-properties beg beg1 '(face org-block-begin-line))
5576 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5577 '(face org-block-end-line))
5579 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5580 (add-text-properties
5581 beg (match-end 3)
5582 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5583 '(font-lock-fontified t invisible t)
5584 '(font-lock-fontified t face org-document-info-keyword)))
5585 (add-text-properties
5586 (match-beginning 6) (1+ (match-end 6))
5587 (if (string-equal dc1 "+title:")
5588 '(font-lock-fontified t face org-document-title)
5589 '(font-lock-fontified t face org-document-info))))
5590 ((or (equal dc1 "+results")
5591 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5592 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5593 "+call:" "+header:" "+headers:" "+name:"))
5594 (and (match-end 4) (equal dc3 "+attr")))
5595 (add-text-properties
5596 beg (match-end 0)
5597 '(font-lock-fontified t face org-meta-line))
5599 ((member dc3 '(" " ""))
5600 (add-text-properties
5601 beg (match-end 0)
5602 '(font-lock-fontified t face font-lock-comment-face)))
5603 ((not (member (char-after beg) '(?\ ?\t)))
5604 ;; just any other in-buffer setting, but not indented
5605 (add-text-properties
5606 beg (match-end 0)
5607 '(font-lock-fontified t face org-meta-line))
5609 (t nil))))))
5611 (defun org-activate-angle-links (limit)
5612 "Run through the buffer and add overlays to links."
5613 (if (and (re-search-forward org-angle-link-re limit t)
5614 (not (org-in-src-block-p)))
5615 (progn
5616 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5617 (add-text-properties (match-beginning 0) (match-end 0)
5618 (list 'mouse-face 'highlight
5619 'keymap org-mouse-map))
5620 (org-rear-nonsticky-at (match-end 0))
5621 t)))
5623 (defun org-activate-footnote-links (limit)
5624 "Run through the buffer and add overlays to footnotes."
5625 (let ((fn (org-footnote-next-reference-or-definition limit)))
5626 (when fn
5627 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5628 (org-remove-flyspell-overlays-in beg end)
5629 (add-text-properties beg end
5630 (list 'mouse-face 'highlight
5631 'keymap org-mouse-map
5632 'help-echo
5633 (if (= (point-at-bol) beg)
5634 "Footnote definition"
5635 "Footnote reference")
5636 'font-lock-fontified t
5637 'font-lock-multiline t
5638 'face 'org-footnote))))))
5640 (defun org-activate-bracket-links (limit)
5641 "Run through the buffer and add overlays to bracketed links."
5642 (if (and (re-search-forward org-bracket-link-regexp limit t)
5643 (not (org-in-src-block-p)))
5644 (let* ((hl (org-match-string-no-properties 1))
5645 (help (concat "LINK: " hl))
5646 ;; FIXME: Above we should remove the escapes. But that
5647 ;; requires another match, protecting match data, a lot
5648 ;; of overhead for font-lock.
5649 (ip (org-maybe-intangible
5650 (list 'invisible 'org-link
5651 'keymap org-mouse-map 'mouse-face 'highlight
5652 'font-lock-multiline t 'help-echo help
5653 'htmlize-link `(:uri ,hl))))
5654 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5655 'font-lock-multiline t 'help-echo help
5656 'htmlize-link `(:uri ,hl))))
5657 ;; We need to remove the invisible property here. Table narrowing
5658 ;; may have made some of this invisible.
5659 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5660 (remove-text-properties (match-beginning 0) (match-end 0)
5661 '(invisible nil))
5662 (if (match-end 3)
5663 (progn
5664 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5665 (org-rear-nonsticky-at (match-beginning 3))
5666 (add-text-properties (match-beginning 3) (match-end 3) vp)
5667 (org-rear-nonsticky-at (match-end 3))
5668 (add-text-properties (match-end 3) (match-end 0) ip)
5669 (org-rear-nonsticky-at (match-end 0)))
5670 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5671 (org-rear-nonsticky-at (match-beginning 1))
5672 (add-text-properties (match-beginning 1) (match-end 1) vp)
5673 (org-rear-nonsticky-at (match-end 1))
5674 (add-text-properties (match-end 1) (match-end 0) ip)
5675 (org-rear-nonsticky-at (match-end 0)))
5676 t)))
5678 (defun org-activate-dates (limit)
5679 "Run through the buffer and add overlays to dates."
5680 (if (re-search-forward org-tsr-regexp-both limit t)
5681 (progn
5682 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5683 (add-text-properties (match-beginning 0) (match-end 0)
5684 (list 'mouse-face 'highlight
5685 'keymap org-mouse-map))
5686 (org-rear-nonsticky-at (match-end 0))
5687 (when org-display-custom-times
5688 (if (match-end 3)
5689 (org-display-custom-time (match-beginning 3) (match-end 3)))
5690 (org-display-custom-time (match-beginning 1) (match-end 1)))
5691 t)))
5693 (defvar org-target-link-regexp nil
5694 "Regular expression matching radio targets in plain text.")
5695 (make-variable-buffer-local 'org-target-link-regexp)
5696 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5697 "Regular expression matching a link target.")
5698 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5699 "Regular expression matching a radio target.")
5700 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5701 "Regular expression matching any target.")
5703 (defun org-activate-target-links (limit)
5704 "Run through the buffer and add overlays to target matches."
5705 (when org-target-link-regexp
5706 (let ((case-fold-search t))
5707 (if (re-search-forward org-target-link-regexp limit t)
5708 (progn
5709 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5710 (add-text-properties (match-beginning 0) (match-end 0)
5711 (list 'mouse-face 'highlight
5712 'keymap org-mouse-map
5713 'help-echo "Radio target link"
5714 'org-linked-text t))
5715 (org-rear-nonsticky-at (match-end 0))
5716 t)))))
5718 (defun org-update-radio-target-regexp ()
5719 "Find all radio targets in this file and update the regular expression."
5720 (interactive)
5721 (when (memq 'radio org-activate-links)
5722 (setq org-target-link-regexp
5723 (org-make-target-link-regexp (org-all-targets 'radio)))
5724 (org-restart-font-lock)))
5726 (defun org-hide-wide-columns (limit)
5727 (let (s e)
5728 (setq s (text-property-any (point) (or limit (point-max))
5729 'org-cwidth t))
5730 (when s
5731 (setq e (next-single-property-change s 'org-cwidth))
5732 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5733 (goto-char e)
5734 t)))
5736 (defvar org-latex-and-specials-regexp nil
5737 "Regular expression for highlighting export special stuff.")
5738 (defvar org-match-substring-regexp)
5739 (defvar org-match-substring-with-braces-regexp)
5741 ;; This should be with the exporter code, but we also use if for font-locking
5742 (defconst org-export-html-special-string-regexps
5743 '(("\\\\-" . "&shy;")
5744 ("---\\([^-]\\)" . "&mdash;\\1")
5745 ("--\\([^-]\\)" . "&ndash;\\1")
5746 ("\\.\\.\\." . "&hellip;"))
5747 "Regular expressions for special string conversion.")
5750 (defun org-compute-latex-and-specials-regexp ()
5751 "Compute regular expression for stuff treated specially by exporters."
5752 (if (not org-highlight-latex-fragments-and-specials)
5753 (org-set-local 'org-latex-and-specials-regexp nil)
5754 (require 'org-exp)
5755 (let*
5756 ((matchers (plist-get org-format-latex-options :matchers))
5757 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5758 org-latex-regexps)))
5759 (org-export-allow-BIND nil)
5760 (options (org-combine-plists (org-default-export-plist)
5761 (org-infile-export-plist)))
5762 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5763 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5764 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5765 (org-export-html-expand (plist-get options :expand-quoted-html))
5766 (org-export-with-special-strings (plist-get options :special-strings))
5767 (re-sub
5768 (cond
5769 ((equal org-export-with-sub-superscripts '{})
5770 (list org-match-substring-with-braces-regexp))
5771 (org-export-with-sub-superscripts
5772 (list org-match-substring-regexp))))
5773 (re-latex
5774 (if org-export-with-LaTeX-fragments
5775 (mapcar (lambda (x) (nth 1 x)) latexs)))
5776 (re-macros
5777 (if org-export-with-TeX-macros
5778 (list (concat "\\\\"
5779 (regexp-opt
5780 (append
5782 (delq nil
5783 (mapcar 'car-safe
5784 (append org-entities-user
5785 org-entities)))
5786 (if (boundp 'org-latex-entities)
5787 (mapcar (lambda (x)
5788 (or (car-safe x) x))
5789 org-latex-entities)
5790 nil))
5791 'words))) ; FIXME
5793 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5794 (re-special (if org-export-with-special-strings
5795 (mapcar (lambda (x) (car x))
5796 org-export-html-special-string-regexps)))
5797 (re-rest
5798 (delq nil
5799 (list
5800 (if org-export-html-expand "@<[^>\n]+>")
5801 ))))
5802 (org-set-local
5803 'org-latex-and-specials-regexp
5804 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5805 re-rest) "\\|")))))
5807 (defun org-do-latex-and-special-faces (limit)
5808 "Run through the buffer and add overlays to links."
5809 (when org-latex-and-specials-regexp
5810 (let (rtn d)
5811 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5812 limit t))
5813 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5814 'face))
5815 '(org-code org-verbatim underline)))
5816 (progn
5817 (setq rtn t
5818 d (cond ((member (char-after (1+ (match-beginning 0)))
5819 '(?_ ?^)) 1)
5820 (t 0)))
5821 (font-lock-prepend-text-property
5822 (+ d (match-beginning 0)) (match-end 0)
5823 'face 'org-latex-and-export-specials)
5824 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5825 '(font-lock-multiline t)))))
5826 rtn)))
5828 (defun org-restart-font-lock ()
5829 "Restart `font-lock-mode', to force refontification."
5830 (when (and (boundp 'font-lock-mode) font-lock-mode)
5831 (font-lock-mode -1)
5832 (font-lock-mode 1)))
5834 (defun org-all-targets (&optional radio)
5835 "Return a list of all targets in this file.
5836 When optional argument RADIO is non-nil, only find radio
5837 targets."
5838 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5839 (save-excursion
5840 (goto-char (point-min))
5841 (while (re-search-forward re nil t)
5842 ;; Make sure point is really within the object.
5843 (backward-char)
5844 (let ((obj (org-element-context)))
5845 (when (memq (org-element-type obj) '(radio-target target))
5846 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5847 rtn)))
5849 (defun org-make-target-link-regexp (targets)
5850 "Make regular expression matching all strings in TARGETS.
5851 The regular expression finds the targets also if there is a line break
5852 between words."
5853 (and targets
5854 (concat
5855 "\\<\\("
5856 (mapconcat
5857 (lambda (x)
5858 (setq x (regexp-quote x))
5859 (while (string-match " +" x)
5860 (setq x (replace-match "\\s-+" t t x)))
5862 targets
5863 "\\|")
5864 "\\)\\>")))
5866 (defun org-activate-tags (limit)
5867 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5868 (progn
5869 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5870 (add-text-properties (match-beginning 1) (match-end 1)
5871 (list 'mouse-face 'highlight
5872 'keymap org-mouse-map))
5873 (org-rear-nonsticky-at (match-end 1))
5874 t)))
5876 (defun org-outline-level ()
5877 "Compute the outline level of the heading at point.
5878 If this is called at a normal headline, the level is the number of stars.
5879 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5880 (save-excursion
5881 (if (not (condition-case nil
5882 (org-back-to-heading t)
5883 (error nil)))
5885 (looking-at org-outline-regexp)
5886 (1- (- (match-end 0) (match-beginning 0))))))
5888 (defvar org-font-lock-keywords nil)
5890 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5891 "Regular expression matching a property line.")
5893 (defvar org-font-lock-hook nil
5894 "Functions to be called for special font lock stuff.")
5896 (defvar org-font-lock-set-keywords-hook nil
5897 "Functions that can manipulate `org-font-lock-extra-keywords'.
5898 This is called after `org-font-lock-extra-keywords' is defined, but before
5899 it is installed to be used by font lock. This can be useful if something
5900 needs to be inserted at a specific position in the font-lock sequence.")
5902 (defun org-font-lock-hook (limit)
5903 "Run `org-font-lock-hook' within LIMIT."
5904 (run-hook-with-args 'org-font-lock-hook limit))
5906 (defun org-set-font-lock-defaults ()
5907 "Set font lock defaults for the current buffer."
5908 (let* ((em org-fontify-emphasized-text)
5909 (lk org-activate-links)
5910 (org-font-lock-extra-keywords
5911 (list
5912 ;; Call the hook
5913 '(org-font-lock-hook)
5914 ;; Headlines
5915 `(,(if org-fontify-whole-heading-line
5916 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5917 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5918 (1 (org-get-level-face 1))
5919 (2 (org-get-level-face 2))
5920 (3 (org-get-level-face 3)))
5921 ;; Table lines
5922 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5923 (1 'org-table t))
5924 ;; Table internals
5925 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5926 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5927 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5928 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5929 ;; Drawers
5930 (list org-drawer-regexp '(0 'org-special-keyword t))
5931 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5932 ;; Properties
5933 (list org-property-re
5934 '(1 'org-special-keyword t)
5935 '(3 'org-property-value t))
5936 ;; Links
5937 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5938 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5939 (if (memq 'plain lk) '(org-activate-plain-links))
5940 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5941 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5942 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5943 (if (memq 'footnote lk) '(org-activate-footnote-links))
5944 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5945 '(org-hide-wide-columns (0 nil append))
5946 ;; TODO keyword
5947 (list (format org-heading-keyword-regexp-format
5948 org-todo-regexp)
5949 '(2 (org-get-todo-face 2) t))
5950 ;; DONE
5951 (if org-fontify-done-headline
5952 (list (format org-heading-keyword-regexp-format
5953 (concat
5954 "\\(?:"
5955 (mapconcat 'regexp-quote org-done-keywords "\\|")
5956 "\\)"))
5957 '(2 'org-headline-done t))
5958 nil)
5959 ;; Priorities
5960 '(org-font-lock-add-priority-faces)
5961 ;; Tags
5962 '(org-font-lock-add-tag-faces)
5963 ;; Special keywords
5964 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5965 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5966 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5967 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5968 ;; Emphasis
5969 (if em
5970 (if (featurep 'xemacs)
5971 '(org-do-emphasis-faces (0 nil append))
5972 '(org-do-emphasis-faces)))
5973 ;; Checkboxes
5974 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5975 1 'org-checkbox prepend)
5976 (if (cdr (assq 'checkbox org-list-automatic-rules))
5977 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5978 (0 (org-get-checkbox-statistics-face) t)))
5979 ;; Description list items
5980 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5981 1 'org-list-dt prepend)
5982 ;; ARCHIVEd headings
5983 (list (concat
5984 org-outline-regexp-bol
5985 "\\(.*:" org-archive-tag ":.*\\)")
5986 '(1 'org-archived prepend))
5987 ;; Specials
5988 '(org-do-latex-and-special-faces)
5989 '(org-fontify-entities)
5990 '(org-raise-scripts)
5991 ;; Code
5992 '(org-activate-code (1 'org-code t))
5993 ;; COMMENT
5994 (list (format org-heading-keyword-regexp-format
5995 (concat "\\("
5996 org-comment-string "\\|" org-quote-string
5997 "\\)"))
5998 '(2 'org-special-keyword t))
5999 ;; Blocks and meta lines
6000 '(org-fontify-meta-lines-and-blocks)
6002 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6003 (run-hooks 'org-font-lock-set-keywords-hook)
6004 ;; Now set the full font-lock-keywords
6005 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6006 (org-set-local 'font-lock-defaults
6007 '(org-font-lock-keywords t nil nil backward-paragraph))
6008 (kill-local-variable 'font-lock-keywords) nil))
6010 (defun org-toggle-pretty-entities ()
6011 "Toggle the composition display of entities as UTF8 characters."
6012 (interactive)
6013 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6014 (org-restart-font-lock)
6015 (if org-pretty-entities
6016 (message "Entities are displayed as UTF8 characters")
6017 (save-restriction
6018 (widen)
6019 (org-decompose-region (point-min) (point-max))
6020 (message "Entities are displayed plain"))))
6022 (defvar org-custom-properties-overlays nil
6023 "List of overlays used for custom properties.")
6024 (make-variable-buffer-local 'org-custom-properties-overlays)
6026 (defun org-toggle-custom-properties-visibility ()
6027 "Display or hide properties in `org-custom-properties'."
6028 (interactive)
6029 (if org-custom-properties-overlays
6030 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6031 (setq org-custom-properties-overlays nil))
6032 (unless (not org-custom-properties)
6033 (save-excursion
6034 (save-restriction
6035 (widen)
6036 (goto-char (point-min))
6037 (while (re-search-forward org-property-re nil t)
6038 (mapc (lambda(p)
6039 (when (equal p (substring (match-string 1) 1 -1))
6040 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6041 (overlay-put o 'invisible t)
6042 (overlay-put o 'org-custom-property t)
6043 (push o org-custom-properties-overlays))))
6044 org-custom-properties)))))))
6046 (defun org-fontify-entities (limit)
6047 "Find an entity to fontify."
6048 (let (ee)
6049 (when org-pretty-entities
6050 (catch 'match
6051 (while (re-search-forward
6052 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6053 limit t)
6054 (if (and (not (org-in-indented-comment-line))
6055 (setq ee (org-entity-get (match-string 1)))
6056 (= (length (nth 6 ee)) 1))
6057 (let*
6058 ((end (if (equal (match-string 2) "{}")
6059 (match-end 2)
6060 (match-end 1))))
6061 (add-text-properties
6062 (match-beginning 0) end
6063 (list 'font-lock-fontified t))
6064 (compose-region (match-beginning 0) end
6065 (nth 6 ee) nil)
6066 (backward-char 1)
6067 (throw 'match t))))
6068 nil))))
6070 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6071 "Fontify string S like in Org-mode."
6072 (with-temp-buffer
6073 (insert s)
6074 (let ((org-odd-levels-only odd-levels))
6075 (org-mode)
6076 (font-lock-fontify-buffer)
6077 (buffer-string))))
6079 (defvar org-m nil)
6080 (defvar org-l nil)
6081 (defvar org-f nil)
6082 (defun org-get-level-face (n)
6083 "Get the right face for match N in font-lock matching of headlines."
6084 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6085 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6086 (if org-cycle-level-faces
6087 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6088 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6089 (cond
6090 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6091 ((eq n 2) org-f)
6092 (t (if org-level-color-stars-only nil org-f))))
6095 (defun org-get-todo-face (kwd)
6096 "Get the right face for a TODO keyword KWD.
6097 If KWD is a number, get the corresponding match group."
6098 (if (numberp kwd) (setq kwd (match-string kwd)))
6099 (or (org-face-from-face-or-color
6100 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6101 (and (member kwd org-done-keywords) 'org-done)
6102 'org-todo))
6104 (defun org-face-from-face-or-color (context inherit face-or-color)
6105 "Create a face list that inherits INHERIT, but sets the foreground color.
6106 When FACE-OR-COLOR is not a string, just return it."
6107 (if (stringp face-or-color)
6108 (list :inherit inherit
6109 (cdr (assoc context org-faces-easy-properties))
6110 face-or-color)
6111 face-or-color))
6113 (defun org-font-lock-add-tag-faces (limit)
6114 "Add the special tag faces."
6115 (when (and org-tag-faces org-tags-special-faces-re)
6116 (while (re-search-forward org-tags-special-faces-re limit t)
6117 (add-text-properties (match-beginning 1) (match-end 1)
6118 (list 'face (org-get-tag-face 1)
6119 'font-lock-fontified t))
6120 (backward-char 1))))
6122 (defun org-font-lock-add-priority-faces (limit)
6123 "Add the special priority faces."
6124 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6125 (when (save-match-data (org-at-heading-p))
6126 (add-text-properties
6127 (match-beginning 0) (match-end 0)
6128 (list 'face (or (org-face-from-face-or-color
6129 'priority 'org-special-keyword
6130 (cdr (assoc (char-after (match-beginning 1))
6131 org-priority-faces)))
6132 'org-special-keyword)
6133 'font-lock-fontified t)))))
6135 (defun org-get-tag-face (kwd)
6136 "Get the right face for a TODO keyword KWD.
6137 If KWD is a number, get the corresponding match group."
6138 (if (numberp kwd) (setq kwd (match-string kwd)))
6139 (or (org-face-from-face-or-color
6140 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6141 'org-tag))
6143 (defun org-unfontify-region (beg end &optional maybe_loudly)
6144 "Remove fontification and activation overlays from links."
6145 (font-lock-default-unfontify-region beg end)
6146 (let* ((buffer-undo-list t)
6147 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6148 (inhibit-modification-hooks t)
6149 deactivate-mark buffer-file-name buffer-file-truename)
6150 (org-decompose-region beg end)
6151 (remove-text-properties beg end
6152 '(mouse-face t keymap t org-linked-text t
6153 invisible t intangible t
6154 org-no-flyspell t org-emphasis t))
6155 (org-remove-font-lock-display-properties beg end)))
6157 (defconst org-script-display '(((raise -0.3) (height 0.7))
6158 ((raise 0.3) (height 0.7))
6159 ((raise -0.5))
6160 ((raise 0.5)))
6161 "Display properties for showing superscripts and subscripts.")
6163 (defun org-remove-font-lock-display-properties (beg end)
6164 "Remove specific display properties that have been added by font lock.
6165 The will remove the raise properties that are used to show superscripts
6166 and subscripts."
6167 (let (next prop)
6168 (while (< beg end)
6169 (setq next (next-single-property-change beg 'display nil end)
6170 prop (get-text-property beg 'display))
6171 (if (member prop org-script-display)
6172 (put-text-property beg next 'display nil))
6173 (setq beg next))))
6175 (defun org-raise-scripts (limit)
6176 "Add raise properties to sub/superscripts."
6177 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6178 (if (re-search-forward
6179 (if (eq org-use-sub-superscripts t)
6180 org-match-substring-regexp
6181 org-match-substring-with-braces-regexp)
6182 limit t)
6183 (let* ((pos (point)) table-p comment-p
6184 (mpos (match-beginning 3))
6185 (emph-p (get-text-property mpos 'org-emphasis))
6186 (link-p (get-text-property mpos 'mouse-face))
6187 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6188 (goto-char (point-at-bol))
6189 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6190 comment-p (org-looking-at-p "[ \t]*#"))
6191 (goto-char pos)
6192 ;; FIXME: Should we go back one character here, for a_b^c
6193 ;; (goto-char (1- pos)) ;????????????????????
6194 (if (or comment-p emph-p link-p keyw-p)
6196 (put-text-property (match-beginning 3) (match-end 0)
6197 'display
6198 (if (equal (char-after (match-beginning 2)) ?^)
6199 (nth (if table-p 3 1) org-script-display)
6200 (nth (if table-p 2 0) org-script-display)))
6201 (add-text-properties (match-beginning 2) (match-end 2)
6202 (list 'invisible t
6203 'org-dwidth t 'org-dwidth-n 1))
6204 (if (and (eq (char-after (match-beginning 3)) ?{)
6205 (eq (char-before (match-end 3)) ?}))
6206 (progn
6207 (add-text-properties
6208 (match-beginning 3) (1+ (match-beginning 3))
6209 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6210 (add-text-properties
6211 (1- (match-end 3)) (match-end 3)
6212 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6213 t)))))
6215 ;;;; Visibility cycling, including org-goto and indirect buffer
6217 ;;; Cycling
6219 (defvar org-cycle-global-status nil)
6220 (make-variable-buffer-local 'org-cycle-global-status)
6221 (defvar org-cycle-subtree-status nil)
6222 (make-variable-buffer-local 'org-cycle-subtree-status)
6224 (defvar org-inlinetask-min-level)
6226 ;;;###autoload
6227 (defun org-cycle (&optional arg)
6228 "TAB-action and visibility cycling for Org-mode.
6230 This is the command invoked in Org-mode by the TAB key. Its main purpose
6231 is outline visibility cycling, but it also invokes other actions
6232 in special contexts.
6234 - When this function is called with a prefix argument, rotate the entire
6235 buffer through 3 states (global cycling)
6236 1. OVERVIEW: Show only top-level headlines.
6237 2. CONTENTS: Show all headlines of all levels, but no body text.
6238 3. SHOW ALL: Show everything.
6239 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6240 determined by the variable `org-startup-folded', and by any VISIBILITY
6241 properties in the buffer.
6242 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6243 including any drawers.
6245 - When inside a table, re-align the table and move to the next field.
6247 - When point is at the beginning of a headline, rotate the subtree started
6248 by this line through 3 different states (local cycling)
6249 1. FOLDED: Only the main headline is shown.
6250 2. CHILDREN: The main headline and the direct children are shown.
6251 From this state, you can move to one of the children
6252 and zoom in further.
6253 3. SUBTREE: Show the entire subtree, including body text.
6254 If there is no subtree, switch directly from CHILDREN to FOLDED.
6256 - When point is at the beginning of an empty headline and the variable
6257 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6258 of the headline by demoting and promoting it to likely levels. This
6259 speeds up creation document structure by pressing TAB once or several
6260 times right after creating a new headline.
6262 - When there is a numeric prefix, go up to a heading with level ARG, do
6263 a `show-subtree' and return to the previous cursor position. If ARG
6264 is negative, go up that many levels.
6266 - When point is not at the beginning of a headline, execute the global
6267 binding for TAB, which is re-indenting the line. See the option
6268 `org-cycle-emulate-tab' for details.
6270 - Special case: if point is at the beginning of the buffer and there is
6271 no headline in line 1, this function will act as if called with prefix arg
6272 (C-u TAB, same as S-TAB) also when called without prefix arg.
6273 But only if also the variable `org-cycle-global-at-bob' is t."
6274 (interactive "P")
6275 (org-load-modules-maybe)
6276 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6277 (and org-cycle-level-after-item/entry-creation
6278 (or (org-cycle-level)
6279 (org-cycle-item-indentation))))
6280 (let* (message-log-max ; Don't populate the *Messages* buffer
6281 (limit-level
6282 (or org-cycle-max-level
6283 (and (boundp 'org-inlinetask-min-level)
6284 org-inlinetask-min-level
6285 (1- org-inlinetask-min-level))))
6286 (nstars (and limit-level
6287 (if org-odd-levels-only
6288 (and limit-level (1- (* limit-level 2)))
6289 limit-level)))
6290 (org-outline-regexp
6291 (if (not (derived-mode-p 'org-mode))
6292 outline-regexp
6293 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6294 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6295 (not (looking-at org-outline-regexp))))
6296 (org-cycle-hook
6297 (if bob-special
6298 (delq 'org-optimize-window-after-visibility-change
6299 (copy-sequence org-cycle-hook))
6300 org-cycle-hook))
6301 (pos (point)))
6303 (if (or bob-special (equal arg '(4)))
6304 ;; special case: use global cycling
6305 (setq arg t))
6307 (cond
6309 ((equal arg '(16))
6310 (setq last-command 'dummy)
6311 (org-set-startup-visibility)
6312 (message "Startup visibility, plus VISIBILITY properties"))
6314 ((equal arg '(64))
6315 (show-all)
6316 (message "Entire buffer visible, including drawers"))
6318 ;; Table: enter it or move to the next field.
6319 ((org-at-table-p 'any)
6320 (if (org-at-table.el-p)
6321 (message "Use C-c ' to edit table.el tables")
6322 (if arg (org-table-edit-field t)
6323 (org-table-justify-field-maybe)
6324 (call-interactively 'org-table-next-field))))
6326 ((run-hook-with-args-until-success
6327 'org-tab-after-check-for-table-hook))
6329 ;; Global cycling: delegate to `org-cycle-internal-global'.
6330 ((eq arg t) (org-cycle-internal-global))
6332 ;; Drawers: delegate to `org-flag-drawer'.
6333 ((and org-drawers org-drawer-regexp
6334 (save-excursion
6335 (beginning-of-line 1)
6336 (looking-at org-drawer-regexp)))
6337 (org-flag-drawer ; toggle block visibility
6338 (not (get-char-property (match-end 0) 'invisible))))
6340 ;; Show-subtree, ARG levels up from here.
6341 ((integerp arg)
6342 (save-excursion
6343 (org-back-to-heading)
6344 (outline-up-heading (if (< arg 0) (- arg)
6345 (- (funcall outline-level) arg)))
6346 (org-show-subtree)))
6348 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6349 ((and (featurep 'org-inlinetask)
6350 (org-inlinetask-at-task-p)
6351 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6352 (org-inlinetask-toggle-visibility))
6354 ((org-try-cdlatex-tab))
6356 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6357 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6358 (save-excursion (beginning-of-line 1)
6359 (looking-at org-outline-regexp)))
6360 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6361 (org-cycle-internal-local))
6363 ;; From there: TAB emulation and template completion.
6364 (buffer-read-only (org-back-to-heading))
6366 ((run-hook-with-args-until-success
6367 'org-tab-after-check-for-cycling-hook))
6369 ((org-try-structure-completion))
6371 ((run-hook-with-args-until-success
6372 'org-tab-before-tab-emulation-hook))
6374 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6375 (or (not (bolp))
6376 (not (looking-at org-outline-regexp))))
6377 (call-interactively (global-key-binding "\t")))
6379 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6380 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6381 (or (and (eq org-cycle-emulate-tab 'white)
6382 (= (match-end 0) (point-at-eol)))
6383 (and (eq org-cycle-emulate-tab 'whitestart)
6384 (>= (match-end 0) pos))))
6386 (eq org-cycle-emulate-tab t))
6387 (call-interactively (global-key-binding "\t")))
6389 (t (save-excursion
6390 (org-back-to-heading)
6391 (org-cycle)))))))
6393 (defun org-cycle-internal-global ()
6394 "Do the global cycling action."
6395 ;; Hack to avoid display of messages for .org attachments in Gnus
6396 (let (message-log-max ; Don't populate the *Messages* buffer
6397 (ga (string-match "\\*fontification" (buffer-name))))
6398 (cond
6399 ((and (eq last-command this-command)
6400 (eq org-cycle-global-status 'overview))
6401 ;; We just created the overview - now do table of contents
6402 ;; This can be slow in very large buffers, so indicate action
6403 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6404 (unless ga (message "CONTENTS..."))
6405 (org-content)
6406 (unless ga (message "CONTENTS...done"))
6407 (setq org-cycle-global-status 'contents)
6408 (run-hook-with-args 'org-cycle-hook 'contents))
6410 ((and (eq last-command this-command)
6411 (eq org-cycle-global-status 'contents))
6412 ;; We just showed the table of contents - now show everything
6413 (run-hook-with-args 'org-pre-cycle-hook 'all)
6414 (show-all)
6415 (unless ga (message "SHOW ALL"))
6416 (setq org-cycle-global-status 'all)
6417 (run-hook-with-args 'org-cycle-hook 'all))
6420 ;; Default action: go to overview
6421 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6422 (org-overview)
6423 (unless ga (message "OVERVIEW"))
6424 (setq org-cycle-global-status 'overview)
6425 (run-hook-with-args 'org-cycle-hook 'overview)))))
6427 (defun org-cycle-internal-local ()
6428 "Do the local cycling action."
6429 (let (message-log-max ; Don't populate the *Messages* buffer
6430 (goal-column 0) eoh eol eos has-children children-skipped struct)
6431 ;; First, determine end of headline (EOH), end of subtree or item
6432 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6433 (save-excursion
6434 (if (org-at-item-p)
6435 (progn
6436 (beginning-of-line)
6437 (setq struct (org-list-struct))
6438 (setq eoh (point-at-eol))
6439 (setq eos (org-list-get-item-end-before-blank (point) struct))
6440 (setq has-children (org-list-has-child-p (point) struct)))
6441 (org-back-to-heading)
6442 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6443 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6444 (setq has-children
6445 (or (save-excursion
6446 (let ((level (funcall outline-level)))
6447 (outline-next-heading)
6448 (and (org-at-heading-p t)
6449 (> (funcall outline-level) level))))
6450 (save-excursion
6451 (org-list-search-forward (org-item-beginning-re) eos t)))))
6452 ;; Determine end invisible part of buffer (EOL)
6453 (beginning-of-line 2)
6454 ;; XEmacs doesn't have `next-single-char-property-change'
6455 (if (featurep 'xemacs)
6456 (while (and (not (eobp)) ;; this is like `next-line'
6457 (get-char-property (1- (point)) 'invisible))
6458 (beginning-of-line 2))
6459 (while (and (not (eobp)) ;; this is like `next-line'
6460 (get-char-property (1- (point)) 'invisible))
6461 (goto-char (next-single-char-property-change (point) 'invisible))
6462 (and (eolp) (beginning-of-line 2))))
6463 (setq eol (point)))
6464 ;; Find out what to do next and set `this-command'
6465 (cond
6466 ((= eos eoh)
6467 ;; Nothing is hidden behind this heading
6468 (unless (org-before-first-heading-p)
6469 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6470 (message "EMPTY ENTRY")
6471 (setq org-cycle-subtree-status nil)
6472 (save-excursion
6473 (goto-char eos)
6474 (outline-next-heading)
6475 (if (outline-invisible-p) (org-flag-heading nil))))
6476 ((and (or (>= eol eos)
6477 (not (string-match "\\S-" (buffer-substring eol eos))))
6478 (or has-children
6479 (not (setq children-skipped
6480 org-cycle-skip-children-state-if-no-children))))
6481 ;; Entire subtree is hidden in one line: children view
6482 (unless (org-before-first-heading-p)
6483 (run-hook-with-args 'org-pre-cycle-hook 'children))
6484 (if (org-at-item-p)
6485 (org-list-set-item-visibility (point-at-bol) struct 'children)
6486 (org-show-entry)
6487 (org-with-limited-levels (show-children))
6488 ;; FIXME: This slows down the func way too much.
6489 ;; How keep drawers hidden in subtree anyway?
6490 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6491 ;; (org-cycle-hide-drawers 'subtree))
6493 ;; Fold every list in subtree to top-level items.
6494 (when (eq org-cycle-include-plain-lists 'integrate)
6495 (save-excursion
6496 (org-back-to-heading)
6497 (while (org-list-search-forward (org-item-beginning-re) eos t)
6498 (beginning-of-line 1)
6499 (let* ((struct (org-list-struct))
6500 (prevs (org-list-prevs-alist struct))
6501 (end (org-list-get-bottom-point struct)))
6502 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6503 (org-list-get-all-items (point) struct prevs))
6504 (goto-char end))))))
6505 (message "CHILDREN")
6506 (save-excursion
6507 (goto-char eos)
6508 (outline-next-heading)
6509 (if (outline-invisible-p) (org-flag-heading nil)))
6510 (setq org-cycle-subtree-status 'children)
6511 (unless (org-before-first-heading-p)
6512 (run-hook-with-args 'org-cycle-hook 'children)))
6513 ((or children-skipped
6514 (and (eq last-command this-command)
6515 (eq org-cycle-subtree-status 'children)))
6516 ;; We just showed the children, or no children are there,
6517 ;; now show everything.
6518 (unless (org-before-first-heading-p)
6519 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6520 (outline-flag-region eoh eos nil)
6521 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6522 (setq org-cycle-subtree-status 'subtree)
6523 (unless (org-before-first-heading-p)
6524 (run-hook-with-args 'org-cycle-hook 'subtree)))
6526 ;; Default action: hide the subtree.
6527 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6528 (outline-flag-region eoh eos t)
6529 (message "FOLDED")
6530 (setq org-cycle-subtree-status 'folded)
6531 (unless (org-before-first-heading-p)
6532 (run-hook-with-args 'org-cycle-hook 'folded))))))
6534 ;;;###autoload
6535 (defun org-global-cycle (&optional arg)
6536 "Cycle the global visibility. For details see `org-cycle'.
6537 With \\[universal-argument] prefix arg, switch to startup visibility.
6538 With a numeric prefix, show all headlines up to that level."
6539 (interactive "P")
6540 (let ((org-cycle-include-plain-lists
6541 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6542 (cond
6543 ((integerp arg)
6544 (show-all)
6545 (hide-sublevels arg)
6546 (setq org-cycle-global-status 'contents))
6547 ((equal arg '(4))
6548 (org-set-startup-visibility)
6549 (message "Startup visibility, plus VISIBILITY properties."))
6551 (org-cycle '(4))))))
6553 (defun org-set-startup-visibility ()
6554 "Set the visibility required by startup options and properties."
6555 (cond
6556 ((eq org-startup-folded t)
6557 (org-cycle '(4)))
6558 ((eq org-startup-folded 'content)
6559 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6560 (org-cycle '(4)) (org-cycle '(4)))))
6561 (unless (eq org-startup-folded 'showeverything)
6562 (if org-hide-block-startup (org-hide-block-all))
6563 (org-set-visibility-according-to-property 'no-cleanup)
6564 (org-cycle-hide-archived-subtrees 'all)
6565 (org-cycle-hide-drawers 'all)
6566 (org-cycle-show-empty-lines t)))
6568 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6569 "Switch subtree visibilities according to :VISIBILITY: property."
6570 (interactive)
6571 (let (org-show-entry-below state)
6572 (save-excursion
6573 (goto-char (point-min))
6574 (while (re-search-forward
6575 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6576 nil t)
6577 (setq state (match-string 1))
6578 (save-excursion
6579 (org-back-to-heading t)
6580 (hide-subtree)
6581 (org-reveal)
6582 (cond
6583 ((equal state '("fold" "folded"))
6584 (hide-subtree))
6585 ((equal state "children")
6586 (org-show-hidden-entry)
6587 (show-children))
6588 ((equal state "content")
6589 (save-excursion
6590 (save-restriction
6591 (org-narrow-to-subtree)
6592 (org-content))))
6593 ((member state '("all" "showall"))
6594 (show-subtree)))))
6595 (unless no-cleanup
6596 (org-cycle-hide-archived-subtrees 'all)
6597 (org-cycle-hide-drawers 'all)
6598 (org-cycle-show-empty-lines 'all)))))
6600 ;; This function uses outline-regexp instead of the more fundamental
6601 ;; org-outline-regexp so that org-cycle-global works outside of Org
6602 ;; buffers, where outline-regexp is needed.
6603 (defun org-overview ()
6604 "Switch to overview mode, showing only top-level headlines.
6605 Really, this shows all headlines with level equal or greater than the level
6606 of the first headline in the buffer. This is important, because if the
6607 first headline is not level one, then (hide-sublevels 1) gives confusing
6608 results."
6609 (interactive)
6610 (let ((level (save-excursion
6611 (goto-char (point-min))
6612 (if (re-search-forward (concat "^" outline-regexp) nil t)
6613 (progn
6614 (goto-char (match-beginning 0))
6615 (funcall outline-level))))))
6616 (and level (hide-sublevels level))))
6618 (defun org-content (&optional arg)
6619 "Show all headlines in the buffer, like a table of contents.
6620 With numerical argument N, show content up to level N."
6621 (interactive "P")
6622 (save-excursion
6623 ;; Visit all headings and show their offspring
6624 (and (integerp arg) (org-overview))
6625 (goto-char (point-max))
6626 (catch 'exit
6627 (while (and (progn (condition-case nil
6628 (outline-previous-visible-heading 1)
6629 (error (goto-char (point-min))))
6631 (looking-at org-outline-regexp))
6632 (if (integerp arg)
6633 (show-children (1- arg))
6634 (show-branches))
6635 (if (bobp) (throw 'exit nil))))))
6638 (defun org-optimize-window-after-visibility-change (state)
6639 "Adjust the window after a change in outline visibility.
6640 This function is the default value of the hook `org-cycle-hook'."
6641 (when (get-buffer-window (current-buffer))
6642 (cond
6643 ((eq state 'content) nil)
6644 ((eq state 'all) nil)
6645 ((eq state 'folded) nil)
6646 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6647 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6649 (defun org-remove-empty-overlays-at (pos)
6650 "Remove outline overlays that do not contain non-white stuff."
6651 (mapc
6652 (lambda (o)
6653 (and (eq 'outline (overlay-get o 'invisible))
6654 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6655 (overlay-end o))))
6656 (delete-overlay o)))
6657 (overlays-at pos)))
6659 (defun org-clean-visibility-after-subtree-move ()
6660 "Fix visibility issues after moving a subtree."
6661 ;; First, find a reasonable region to look at:
6662 ;; Start two siblings above, end three below
6663 (let* ((beg (save-excursion
6664 (and (org-get-last-sibling)
6665 (org-get-last-sibling))
6666 (point)))
6667 (end (save-excursion
6668 (and (org-get-next-sibling)
6669 (org-get-next-sibling)
6670 (org-get-next-sibling))
6671 (if (org-at-heading-p)
6672 (point-at-eol)
6673 (point))))
6674 (level (looking-at "\\*+"))
6675 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6676 (save-excursion
6677 (save-restriction
6678 (narrow-to-region beg end)
6679 (when re
6680 ;; Properly fold already folded siblings
6681 (goto-char (point-min))
6682 (while (re-search-forward re nil t)
6683 (if (and (not (outline-invisible-p))
6684 (save-excursion
6685 (goto-char (point-at-eol)) (outline-invisible-p)))
6686 (hide-entry))))
6687 (org-cycle-show-empty-lines 'overview)
6688 (org-cycle-hide-drawers 'overview)))))
6690 (defun org-cycle-show-empty-lines (state)
6691 "Show empty lines above all visible headlines.
6692 The region to be covered depends on STATE when called through
6693 `org-cycle-hook'. Lisp program can use t for STATE to get the
6694 entire buffer covered. Note that an empty line is only shown if there
6695 are at least `org-cycle-separator-lines' empty lines before the headline."
6696 (when (not (= org-cycle-separator-lines 0))
6697 (save-excursion
6698 (let* ((n (abs org-cycle-separator-lines))
6699 (re (cond
6700 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6701 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6702 (t (let ((ns (number-to-string (- n 2))))
6703 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6704 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6705 beg end b e)
6706 (cond
6707 ((memq state '(overview contents t))
6708 (setq beg (point-min) end (point-max)))
6709 ((memq state '(children folded))
6710 (setq beg (point) end (progn (org-end-of-subtree t t)
6711 (beginning-of-line 2)
6712 (point)))))
6713 (when beg
6714 (goto-char beg)
6715 (while (re-search-forward re end t)
6716 (unless (get-char-property (match-end 1) 'invisible)
6717 (setq e (match-end 1))
6718 (if (< org-cycle-separator-lines 0)
6719 (setq b (save-excursion
6720 (goto-char (match-beginning 0))
6721 (org-back-over-empty-lines)
6722 (if (save-excursion
6723 (goto-char (max (point-min) (1- (point))))
6724 (org-at-heading-p))
6725 (1- (point))
6726 (point))))
6727 (setq b (match-beginning 1)))
6728 (outline-flag-region b e nil)))))))
6729 ;; Never hide empty lines at the end of the file.
6730 (save-excursion
6731 (goto-char (point-max))
6732 (outline-previous-heading)
6733 (outline-end-of-heading)
6734 (if (and (looking-at "[ \t\n]+")
6735 (= (match-end 0) (point-max)))
6736 (outline-flag-region (point) (match-end 0) nil))))
6738 (defun org-show-empty-lines-in-parent ()
6739 "Move to the parent and re-show empty lines before visible headlines."
6740 (save-excursion
6741 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6742 (org-cycle-show-empty-lines context))))
6744 (defun org-files-list ()
6745 "Return `org-agenda-files' list, plus all open org-mode files.
6746 This is useful for operations that need to scan all of a user's
6747 open and agenda-wise Org files."
6748 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6749 (dolist (buf (buffer-list))
6750 (with-current-buffer buf
6751 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6752 (let ((file (expand-file-name (buffer-file-name))))
6753 (unless (member file files)
6754 (push file files))))))
6755 files))
6757 (defsubst org-entry-beginning-position ()
6758 "Return the beginning position of the current entry."
6759 (save-excursion (outline-back-to-heading t) (point)))
6761 (defsubst org-entry-end-position ()
6762 "Return the end position of the current entry."
6763 (save-excursion (outline-next-heading) (point)))
6765 (defun org-cycle-hide-drawers (state)
6766 "Re-hide all drawers after a visibility state change."
6767 (when (and (derived-mode-p 'org-mode)
6768 (not (memq state '(overview folded contents))))
6769 (save-excursion
6770 (let* ((globalp (memq state '(contents all)))
6771 (beg (if globalp (point-min) (point)))
6772 (end (if globalp (point-max)
6773 (if (eq state 'children)
6774 (save-excursion (outline-next-heading) (point))
6775 (org-end-of-subtree t)))))
6776 (goto-char beg)
6777 (while (re-search-forward org-drawer-regexp end t)
6778 (org-flag-drawer t))))))
6780 (defun org-cycle-hide-inline-tasks (state)
6781 "Re-hide inline task when switching to 'contents visibility state."
6782 (when (and (eq state 'contents)
6783 (boundp 'org-inlinetask-min-level)
6784 org-inlinetask-min-level)
6785 (hide-sublevels (1- org-inlinetask-min-level))))
6787 (defun org-flag-drawer (flag)
6788 "When FLAG is non-nil, hide the drawer we are within.
6789 Otherwise make it visible."
6790 (save-excursion
6791 (beginning-of-line 1)
6792 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6793 (let ((b (match-end 0)))
6794 (if (re-search-forward
6795 "^[ \t]*:END:"
6796 (save-excursion (outline-next-heading) (point)) t)
6797 (outline-flag-region b (point-at-eol) flag)
6798 (error ":END: line missing at position %s" b))))))
6800 (defun org-subtree-end-visible-p ()
6801 "Is the end of the current subtree visible?"
6802 (pos-visible-in-window-p
6803 (save-excursion (org-end-of-subtree t) (point))))
6805 (defun org-first-headline-recenter (&optional N)
6806 "Move cursor to the first headline and recenter the headline.
6807 Optional argument N means put the headline into the Nth line of the window."
6808 (goto-char (point-min))
6809 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6810 (beginning-of-line)
6811 (recenter (prefix-numeric-value N))))
6813 ;;; Saving and restoring visibility
6815 (defun org-outline-overlay-data (&optional use-markers)
6816 "Return a list of the locations of all outline overlays.
6817 These are overlays with the `invisible' property value `outline'.
6818 The return value is a list of cons cells, with start and stop
6819 positions for each overlay.
6820 If USE-MARKERS is set, return the positions as markers."
6821 (let (beg end)
6822 (save-excursion
6823 (save-restriction
6824 (widen)
6825 (delq nil
6826 (mapcar (lambda (o)
6827 (when (eq (overlay-get o 'invisible) 'outline)
6828 (setq beg (overlay-start o)
6829 end (overlay-end o))
6830 (and beg end (> end beg)
6831 (if use-markers
6832 (cons (move-marker (make-marker) beg)
6833 (move-marker (make-marker) end))
6834 (cons beg end)))))
6835 (overlays-in (point-min) (point-max))))))))
6837 (defun org-set-outline-overlay-data (data)
6838 "Create visibility overlays for all positions in DATA.
6839 DATA should have been made by `org-outline-overlay-data'."
6840 (let (o)
6841 (save-excursion
6842 (save-restriction
6843 (widen)
6844 (show-all)
6845 (mapc (lambda (c)
6846 (outline-flag-region (car c) (cdr c) t))
6847 data)))))
6849 ;;; Folding of blocks
6851 (defvar org-hide-block-overlays nil
6852 "Overlays hiding blocks.")
6853 (make-variable-buffer-local 'org-hide-block-overlays)
6855 (defun org-block-map (function &optional start end)
6856 "Call FUNCTION at the head of all source blocks in the current buffer.
6857 Optional arguments START and END can be used to limit the range."
6858 (let ((start (or start (point-min)))
6859 (end (or end (point-max))))
6860 (save-excursion
6861 (goto-char start)
6862 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6863 (save-excursion
6864 (save-match-data
6865 (goto-char (match-beginning 0))
6866 (funcall function)))))))
6868 (defun org-hide-block-toggle-all ()
6869 "Toggle the visibility of all blocks in the current buffer."
6870 (org-block-map #'org-hide-block-toggle))
6872 (defun org-hide-block-all ()
6873 "Fold all blocks in the current buffer."
6874 (interactive)
6875 (org-show-block-all)
6876 (org-block-map #'org-hide-block-toggle-maybe))
6878 (defun org-show-block-all ()
6879 "Unfold all blocks in the current buffer."
6880 (interactive)
6881 (mapc 'delete-overlay org-hide-block-overlays)
6882 (setq org-hide-block-overlays nil))
6884 (defun org-hide-block-toggle-maybe ()
6885 "Toggle visibility of block at point."
6886 (interactive)
6887 (let ((case-fold-search t))
6888 (if (save-excursion
6889 (beginning-of-line 1)
6890 (looking-at org-block-regexp))
6891 (progn (org-hide-block-toggle)
6892 t) ;; to signal that we took action
6893 nil))) ;; to signal that we did not
6895 (defun org-hide-block-toggle (&optional force)
6896 "Toggle the visibility of the current block."
6897 (interactive)
6898 (save-excursion
6899 (beginning-of-line)
6900 (if (re-search-forward org-block-regexp nil t)
6901 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6902 (end (match-end 0)) ;; end of entire body
6904 (if (memq t (mapcar (lambda (overlay)
6905 (eq (overlay-get overlay 'invisible)
6906 'org-hide-block))
6907 (overlays-at start)))
6908 (if (or (not force) (eq force 'off))
6909 (mapc (lambda (ov)
6910 (when (member ov org-hide-block-overlays)
6911 (setq org-hide-block-overlays
6912 (delq ov org-hide-block-overlays)))
6913 (when (eq (overlay-get ov 'invisible)
6914 'org-hide-block)
6915 (delete-overlay ov)))
6916 (overlays-at start)))
6917 (setq ov (make-overlay start end))
6918 (overlay-put ov 'invisible 'org-hide-block)
6919 ;; make the block accessible to isearch
6920 (overlay-put
6921 ov 'isearch-open-invisible
6922 (lambda (ov)
6923 (when (member ov org-hide-block-overlays)
6924 (setq org-hide-block-overlays
6925 (delq ov org-hide-block-overlays)))
6926 (when (eq (overlay-get ov 'invisible)
6927 'org-hide-block)
6928 (delete-overlay ov))))
6929 (push ov org-hide-block-overlays)))
6930 (error "Not looking at a source block"))))
6932 ;; org-tab-after-check-for-cycling-hook
6933 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6934 ;; Remove overlays when changing major mode
6935 (add-hook 'org-mode-hook
6936 (lambda () (org-add-hook 'change-major-mode-hook
6937 'org-show-block-all 'append 'local)))
6939 ;;; Org-goto
6941 (defvar org-goto-window-configuration nil)
6942 (defvar org-goto-marker nil)
6943 (defvar org-goto-map)
6944 (defun org-goto-map ()
6945 "Set the keymap `org-goto'."
6946 (setq org-goto-map
6947 (let ((map (make-sparse-keymap)))
6948 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6949 mouse-drag-region universal-argument org-occur))
6950 cmd)
6951 (while (setq cmd (pop cmds))
6952 (substitute-key-definition cmd cmd map global-map)))
6953 (suppress-keymap map)
6954 (org-defkey map "\C-m" 'org-goto-ret)
6955 (org-defkey map [(return)] 'org-goto-ret)
6956 (org-defkey map [(left)] 'org-goto-left)
6957 (org-defkey map [(right)] 'org-goto-right)
6958 (org-defkey map [(control ?g)] 'org-goto-quit)
6959 (org-defkey map "\C-i" 'org-cycle)
6960 (org-defkey map [(tab)] 'org-cycle)
6961 (org-defkey map [(down)] 'outline-next-visible-heading)
6962 (org-defkey map [(up)] 'outline-previous-visible-heading)
6963 (if org-goto-auto-isearch
6964 (if (fboundp 'define-key-after)
6965 (define-key-after map [t] 'org-goto-local-auto-isearch)
6966 nil)
6967 (org-defkey map "q" 'org-goto-quit)
6968 (org-defkey map "n" 'outline-next-visible-heading)
6969 (org-defkey map "p" 'outline-previous-visible-heading)
6970 (org-defkey map "f" 'outline-forward-same-level)
6971 (org-defkey map "b" 'outline-backward-same-level)
6972 (org-defkey map "u" 'outline-up-heading))
6973 (org-defkey map "/" 'org-occur)
6974 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6975 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6976 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6977 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6978 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6979 map)))
6981 (defconst org-goto-help
6982 "Browse buffer copy, to find location or copy text.%s
6983 RET=jump to location C-g=quit and return to previous location
6984 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6986 (defvar org-goto-start-pos) ; dynamically scoped parameter
6988 ;; FIXME: Docstring does not mention both interfaces
6989 (defun org-goto (&optional alternative-interface)
6990 "Look up a different location in the current file, keeping current visibility.
6992 When you want look-up or go to a different location in a
6993 document, the fastest way is often to fold the entire buffer and
6994 then dive into the tree. This method has the disadvantage, that
6995 the previous location will be folded, which may not be what you
6996 want.
6998 This command works around this by showing a copy of the current
6999 buffer in an indirect buffer, in overview mode. You can dive
7000 into the tree in that copy, use org-occur and incremental search
7001 to find a location. When pressing RET or `Q', the command
7002 returns to the original buffer in which the visibility is still
7003 unchanged. After RET it will also jump to the location selected
7004 in the indirect buffer and expose the headline hierarchy above.
7006 With a prefix argument, use the alternative interface: e.g. if
7007 `org-goto-interface' is 'outline use 'outline-path-completion."
7008 (interactive "P")
7009 (org-goto-map)
7010 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7011 (org-refile-use-outline-path t)
7012 (org-refile-target-verify-function nil)
7013 (interface
7014 (if (not alternative-interface)
7015 org-goto-interface
7016 (if (eq org-goto-interface 'outline)
7017 'outline-path-completion
7018 'outline)))
7019 (org-goto-start-pos (point))
7020 (selected-point
7021 (if (eq interface 'outline)
7022 (car (org-get-location (current-buffer) org-goto-help))
7023 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7024 (org-refile-check-position pa)
7025 (nth 3 pa)))))
7026 (if selected-point
7027 (progn
7028 (org-mark-ring-push org-goto-start-pos)
7029 (goto-char selected-point)
7030 (if (or (outline-invisible-p) (org-invisible-p2))
7031 (org-show-context 'org-goto)))
7032 (message "Quit"))))
7034 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7035 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7036 (defvar org-goto-local-auto-isearch-map) ; defined below
7038 (defun org-get-location (buf help)
7039 "Let the user select a location in the Org-mode buffer BUF.
7040 This function uses a recursive edit. It returns the selected position
7041 or nil."
7042 (org-no-popups
7043 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7044 (isearch-hide-immediately nil)
7045 (isearch-search-fun-function
7046 (lambda () 'org-goto-local-search-headings))
7047 (org-goto-selected-point org-goto-exit-command))
7048 (save-excursion
7049 (save-window-excursion
7050 (delete-other-windows)
7051 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7052 (org-pop-to-buffer-same-window
7053 (condition-case nil
7054 (make-indirect-buffer (current-buffer) "*org-goto*")
7055 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7056 (with-output-to-temp-buffer "*Org Help*"
7057 (princ (format help (if org-goto-auto-isearch
7058 " Just type for auto-isearch."
7059 " n/p/f/b/u to navigate, q to quit."))))
7060 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7061 (setq buffer-read-only nil)
7062 (let ((org-startup-truncated t)
7063 (org-startup-folded nil)
7064 (org-startup-align-all-tables nil))
7065 (org-mode)
7066 (org-overview))
7067 (setq buffer-read-only t)
7068 (if (and (boundp 'org-goto-start-pos)
7069 (integer-or-marker-p org-goto-start-pos))
7070 (let ((org-show-hierarchy-above t)
7071 (org-show-siblings t)
7072 (org-show-following-heading t))
7073 (goto-char org-goto-start-pos)
7074 (and (outline-invisible-p) (org-show-context)))
7075 (goto-char (point-min)))
7076 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7077 (message "Select location and press RET")
7078 (use-local-map org-goto-map)
7079 (recursive-edit)))
7080 (kill-buffer "*org-goto*")
7081 (cons org-goto-selected-point org-goto-exit-command))))
7083 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7084 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7085 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7086 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7088 (defun org-goto-local-search-headings (string bound noerror)
7089 "Search and make sure that any matches are in headlines."
7090 (catch 'return
7091 (while (if isearch-forward
7092 (search-forward string bound noerror)
7093 (search-backward string bound noerror))
7094 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7095 (and (member :headline context)
7096 (not (member :tags context))))
7097 (throw 'return (point))))))
7099 (defun org-goto-local-auto-isearch ()
7100 "Start isearch."
7101 (interactive)
7102 (goto-char (point-min))
7103 (let ((keys (this-command-keys)))
7104 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7105 (isearch-mode t)
7106 (isearch-process-search-char (string-to-char keys)))))
7108 (defun org-goto-ret (&optional arg)
7109 "Finish `org-goto' by going to the new location."
7110 (interactive "P")
7111 (setq org-goto-selected-point (point)
7112 org-goto-exit-command 'return)
7113 (throw 'exit nil))
7115 (defun org-goto-left ()
7116 "Finish `org-goto' by going to the new location."
7117 (interactive)
7118 (if (org-at-heading-p)
7119 (progn
7120 (beginning-of-line 1)
7121 (setq org-goto-selected-point (point)
7122 org-goto-exit-command 'left)
7123 (throw 'exit nil))
7124 (error "Not on a heading")))
7126 (defun org-goto-right ()
7127 "Finish `org-goto' by going to the new location."
7128 (interactive)
7129 (if (org-at-heading-p)
7130 (progn
7131 (setq org-goto-selected-point (point)
7132 org-goto-exit-command 'right)
7133 (throw 'exit nil))
7134 (error "Not on a heading")))
7136 (defun org-goto-quit ()
7137 "Finish `org-goto' without cursor motion."
7138 (interactive)
7139 (setq org-goto-selected-point nil)
7140 (setq org-goto-exit-command 'quit)
7141 (throw 'exit nil))
7143 ;;; Indirect buffer display of subtrees
7145 (defvar org-indirect-dedicated-frame nil
7146 "This is the frame being used for indirect tree display.")
7147 (defvar org-last-indirect-buffer nil)
7149 (defun org-tree-to-indirect-buffer (&optional arg)
7150 "Create indirect buffer and narrow it to current subtree.
7151 With a numerical prefix ARG, go up to this level and then take that tree.
7152 If ARG is negative, go up that many levels.
7154 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7155 indirect buffer previously made with this command, to avoid proliferation of
7156 indirect buffers. However, when you call the command with a \
7157 \\[universal-argument] prefix, or
7158 when `org-indirect-buffer-display' is `new-frame', the last buffer
7159 is kept so that you can work with several indirect buffers at the same time.
7160 If `org-indirect-buffer-display' is `dedicated-frame', the \
7161 \\[universal-argument] prefix also
7162 requests that a new frame be made for the new buffer, so that the dedicated
7163 frame is not changed."
7164 (interactive "P")
7165 (let ((cbuf (current-buffer))
7166 (cwin (selected-window))
7167 (pos (point))
7168 beg end level heading ibuf)
7169 (save-excursion
7170 (org-back-to-heading t)
7171 (when (numberp arg)
7172 (setq level (org-outline-level))
7173 (if (< arg 0) (setq arg (+ level arg)))
7174 (while (> (setq level (org-outline-level)) arg)
7175 (org-up-heading-safe)))
7176 (setq beg (point)
7177 heading (org-get-heading))
7178 (org-end-of-subtree t t)
7179 (if (org-at-heading-p) (backward-char 1))
7180 (setq end (point)))
7181 (if (and (buffer-live-p org-last-indirect-buffer)
7182 (not (eq org-indirect-buffer-display 'new-frame))
7183 (not arg))
7184 (kill-buffer org-last-indirect-buffer))
7185 (setq ibuf (org-get-indirect-buffer cbuf)
7186 org-last-indirect-buffer ibuf)
7187 (cond
7188 ((or (eq org-indirect-buffer-display 'new-frame)
7189 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7190 (select-frame (make-frame))
7191 (delete-other-windows)
7192 (org-pop-to-buffer-same-window ibuf)
7193 (org-set-frame-title heading))
7194 ((eq org-indirect-buffer-display 'dedicated-frame)
7195 (raise-frame
7196 (select-frame (or (and org-indirect-dedicated-frame
7197 (frame-live-p org-indirect-dedicated-frame)
7198 org-indirect-dedicated-frame)
7199 (setq org-indirect-dedicated-frame (make-frame)))))
7200 (delete-other-windows)
7201 (org-pop-to-buffer-same-window ibuf)
7202 (org-set-frame-title (concat "Indirect: " heading)))
7203 ((eq org-indirect-buffer-display 'current-window)
7204 (org-pop-to-buffer-same-window ibuf))
7205 ((eq org-indirect-buffer-display 'other-window)
7206 (pop-to-buffer ibuf))
7207 (t (error "Invalid value")))
7208 (if (featurep 'xemacs)
7209 (save-excursion (org-mode) (turn-on-font-lock)))
7210 (narrow-to-region beg end)
7211 (show-all)
7212 (goto-char pos)
7213 (run-hook-with-args 'org-cycle-hook 'all)
7214 (and (window-live-p cwin) (select-window cwin))))
7216 (defun org-get-indirect-buffer (&optional buffer)
7217 (setq buffer (or buffer (current-buffer)))
7218 (let ((n 1) (base (buffer-name buffer)) bname)
7219 (while (buffer-live-p
7220 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7221 (setq n (1+ n)))
7222 (condition-case nil
7223 (make-indirect-buffer buffer bname 'clone)
7224 (error (make-indirect-buffer buffer bname)))))
7226 (defun org-set-frame-title (title)
7227 "Set the title of the current frame to the string TITLE."
7228 ;; FIXME: how to name a single frame in XEmacs???
7229 (unless (featurep 'xemacs)
7230 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7232 ;;;; Structure editing
7234 ;;; Inserting headlines
7236 (defun org-previous-line-empty-p ()
7237 (save-excursion
7238 (and (not (bobp))
7239 (or (beginning-of-line 0) t)
7240 (save-match-data
7241 (looking-at "[ \t]*$")))))
7243 (defun org-insert-heading (&optional force-heading invisible-ok)
7244 "Insert a new heading or item with same depth at point.
7245 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7246 If point is at the beginning of a headline, insert a sibling before the
7247 current headline. If point is not at the beginning, split the line,
7248 create the new headline with the text in the current line after point
7249 \(but see also the variable `org-M-RET-may-split-line').
7251 With a double prefix arg, force the heading to be inserted at the
7252 end of the parent subtree.
7254 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7255 This is important for non-interactive uses of the command."
7256 (interactive "P")
7257 (if (or (= (buffer-size) 0)
7258 (and (not (save-excursion
7259 (and (ignore-errors (org-back-to-heading invisible-ok))
7260 (org-at-heading-p))))
7261 (or force-heading (not (org-in-item-p)))))
7262 (progn
7263 (insert "\n* ")
7264 (run-hooks 'org-insert-heading-hook))
7265 (when (or force-heading (not (org-insert-item)))
7266 (let* ((empty-line-p nil)
7267 (level nil)
7268 (on-heading (org-at-heading-p))
7269 (head (save-excursion
7270 (condition-case nil
7271 (progn
7272 (org-back-to-heading invisible-ok)
7273 (when (and (not on-heading)
7274 (featurep 'org-inlinetask)
7275 (integerp org-inlinetask-min-level)
7276 (>= (length (match-string 0))
7277 org-inlinetask-min-level))
7278 ;; Find a heading level before the inline task
7279 (while (and (setq level (org-up-heading-safe))
7280 (>= level org-inlinetask-min-level)))
7281 (if (org-at-heading-p)
7282 (org-back-to-heading invisible-ok)
7283 (error "This should not happen")))
7284 (setq empty-line-p (org-previous-line-empty-p))
7285 (match-string 0))
7286 (error "*"))))
7287 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7288 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7289 pos hide-previous previous-pos)
7290 (cond
7291 ((and (org-at-heading-p) (bolp)
7292 (or (bobp)
7293 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7294 ;; insert before the current line
7295 (open-line (if blank 2 1)))
7296 ((and (bolp)
7297 (not org-insert-heading-respect-content)
7298 (or (bobp)
7299 (save-excursion
7300 (backward-char 1) (not (outline-invisible-p)))))
7301 ;; insert right here
7302 nil)
7304 ;; somewhere in the line
7305 (save-excursion
7306 (setq previous-pos (point-at-bol))
7307 (end-of-line)
7308 (setq hide-previous (outline-invisible-p)))
7309 (and org-insert-heading-respect-content (org-show-subtree))
7310 (let ((split
7311 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7312 (save-excursion
7313 (let ((p (point)))
7314 (goto-char (point-at-bol))
7315 (and (looking-at org-complex-heading-regexp)
7316 (match-beginning 4)
7317 (> p (match-beginning 4)))))))
7318 tags pos)
7319 (cond
7320 (org-insert-heading-respect-content
7321 (if (not (equal force-heading '(16)))
7322 (org-end-of-subtree nil t)
7323 (org-up-heading-safe)
7324 (org-end-of-subtree nil t))
7325 (when (featurep 'org-inlinetask)
7326 (while (and (not (eobp))
7327 (looking-at "\\(\\*+\\)[ \t]+")
7328 (>= (length (match-string 1))
7329 org-inlinetask-min-level))
7330 (org-end-of-subtree nil t)))
7331 (or (bolp) (newline))
7332 (or (org-previous-line-empty-p)
7333 (and blank (newline)))
7334 (open-line 1))
7335 ((org-at-heading-p)
7336 (when hide-previous
7337 (show-children)
7338 (org-show-entry))
7339 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7340 (setq tags (and (match-end 2) (match-string 2)))
7341 (and (match-end 1)
7342 (delete-region (match-beginning 1) (match-end 1)))
7343 (setq pos (point-at-bol))
7344 (or split (end-of-line 1))
7345 (delete-horizontal-space)
7346 (if (string-match "\\`\\*+\\'"
7347 (buffer-substring (point-at-bol) (point)))
7348 (insert " "))
7349 (newline (if blank 2 1))
7350 (when tags
7351 (save-excursion
7352 (goto-char pos)
7353 (end-of-line 1)
7354 (insert " " tags)
7355 (org-set-tags nil 'align))))
7357 (or split (end-of-line 1))
7358 (newline (if blank 2 1)))))))
7359 (insert head) (just-one-space)
7360 (setq pos (point))
7361 (end-of-line 1)
7362 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7363 (when (and org-insert-heading-respect-content hide-previous)
7364 (save-excursion
7365 (goto-char previous-pos)
7366 (hide-subtree)))
7367 (run-hooks 'org-insert-heading-hook)))))
7369 (defun org-get-heading (&optional no-tags no-todo)
7370 "Return the heading of the current entry, without the stars.
7371 When NO-TAGS is non-nil, don't include tags.
7372 When NO-TODO is non-nil, don't include TODO keywords."
7373 (save-excursion
7374 (org-back-to-heading t)
7375 (cond
7376 ((and no-tags no-todo)
7377 (looking-at org-complex-heading-regexp)
7378 (match-string 4))
7379 (no-tags
7380 (looking-at (concat org-outline-regexp
7381 "\\(.*?\\)"
7382 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7383 (match-string 1))
7384 (no-todo
7385 (looking-at org-todo-line-regexp)
7386 (match-string 3))
7387 (t (looking-at org-heading-regexp)
7388 (match-string 2)))))
7390 (defun org-heading-components ()
7391 "Return the components of the current heading.
7392 This is a list with the following elements:
7393 - the level as an integer
7394 - the reduced level, different if `org-odd-levels-only' is set.
7395 - the TODO keyword, or nil
7396 - the priority character, like ?A, or nil if no priority is given
7397 - the headline text itself, or the tags string if no headline text
7398 - the tags string, or nil."
7399 (save-excursion
7400 (org-back-to-heading t)
7401 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7402 (list (length (match-string 1))
7403 (org-reduced-level (length (match-string 1)))
7404 (org-match-string-no-properties 2)
7405 (and (match-end 3) (aref (match-string 3) 2))
7406 (org-match-string-no-properties 4)
7407 (org-match-string-no-properties 5)))))
7409 (defun org-get-entry ()
7410 "Get the entry text, after heading, entire subtree."
7411 (save-excursion
7412 (org-back-to-heading t)
7413 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7415 (defun org-insert-heading-after-current ()
7416 "Insert a new heading with same level as current, after current subtree."
7417 (interactive)
7418 (org-back-to-heading)
7419 (org-insert-heading)
7420 (org-move-subtree-down)
7421 (end-of-line 1))
7423 (defun org-insert-heading-respect-content ()
7424 (interactive)
7425 (let ((org-insert-heading-respect-content t))
7426 (org-insert-heading t)))
7428 (defun org-insert-todo-heading-respect-content (&optional force-state)
7429 (interactive "P")
7430 (let ((org-insert-heading-respect-content t))
7431 (org-insert-todo-heading force-state t)))
7433 (defun org-insert-todo-heading (arg &optional force-heading)
7434 "Insert a new heading with the same level and TODO state as current heading.
7435 If the heading has no TODO state, or if the state is DONE, use the first
7436 state (TODO by default). Also one prefix arg, force first state. With two
7437 prefix args, force inserting at the end of the parent subtree."
7438 (interactive "P")
7439 (when (or force-heading (not (org-insert-item 'checkbox)))
7440 (org-insert-heading (or (and (equal arg '(16)) '(16))
7441 force-heading))
7442 (save-excursion
7443 (org-back-to-heading)
7444 (outline-previous-heading)
7445 (looking-at org-todo-line-regexp))
7446 (let*
7447 ((new-mark-x
7448 (if (or arg
7449 (not (match-beginning 2))
7450 (member (match-string 2) org-done-keywords))
7451 (car org-todo-keywords-1)
7452 (match-string 2)))
7453 (new-mark
7455 (run-hook-with-args-until-success
7456 'org-todo-get-default-hook new-mark-x nil)
7457 new-mark-x)))
7458 (beginning-of-line 1)
7459 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7460 (if org-treat-insert-todo-heading-as-state-change
7461 (org-todo new-mark)
7462 (insert new-mark " "))))
7463 (when org-provide-todo-statistics
7464 (org-update-parent-todo-statistics))))
7466 (defun org-insert-subheading (arg)
7467 "Insert a new subheading and demote it.
7468 Works for outline headings and for plain lists alike."
7469 (interactive "P")
7470 (org-insert-heading arg)
7471 (cond
7472 ((org-at-heading-p) (org-do-demote))
7473 ((org-at-item-p) (org-indent-item))))
7475 (defun org-insert-todo-subheading (arg)
7476 "Insert a new subheading with TODO keyword or checkbox and demote it.
7477 Works for outline headings and for plain lists alike."
7478 (interactive "P")
7479 (org-insert-todo-heading arg)
7480 (cond
7481 ((org-at-heading-p) (org-do-demote))
7482 ((org-at-item-p) (org-indent-item))))
7484 ;;; Promotion and Demotion
7486 (defvar org-after-demote-entry-hook nil
7487 "Hook run after an entry has been demoted.
7488 The cursor will be at the beginning of the entry.
7489 When a subtree is being demoted, the hook will be called for each node.")
7491 (defvar org-after-promote-entry-hook nil
7492 "Hook run after an entry has been promoted.
7493 The cursor will be at the beginning of the entry.
7494 When a subtree is being promoted, the hook will be called for each node.")
7496 (defun org-promote-subtree ()
7497 "Promote the entire subtree.
7498 See also `org-promote'."
7499 (interactive)
7500 (save-excursion
7501 (org-with-limited-levels (org-map-tree 'org-promote)))
7502 (org-fix-position-after-promote))
7504 (defun org-demote-subtree ()
7505 "Demote the entire subtree. See `org-demote'.
7506 See also `org-promote'."
7507 (interactive)
7508 (save-excursion
7509 (org-with-limited-levels (org-map-tree 'org-demote)))
7510 (org-fix-position-after-promote))
7513 (defun org-do-promote ()
7514 "Promote the current heading higher up the tree.
7515 If the region is active in `transient-mark-mode', promote all headings
7516 in the region."
7517 (interactive)
7518 (save-excursion
7519 (if (org-region-active-p)
7520 (org-map-region 'org-promote (region-beginning) (region-end))
7521 (org-promote)))
7522 (org-fix-position-after-promote))
7524 (defun org-do-demote ()
7525 "Demote the current heading lower down the tree.
7526 If the region is active in `transient-mark-mode', demote all headings
7527 in the region."
7528 (interactive)
7529 (save-excursion
7530 (if (org-region-active-p)
7531 (org-map-region 'org-demote (region-beginning) (region-end))
7532 (org-demote)))
7533 (org-fix-position-after-promote))
7535 (defun org-fix-position-after-promote ()
7536 "Make sure that after pro/demotion cursor position is right."
7537 (let ((pos (point)))
7538 (when (save-excursion
7539 (beginning-of-line 1)
7540 (looking-at org-todo-line-regexp)
7541 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7542 (cond ((eobp) (insert " "))
7543 ((eolp) (insert " "))
7544 ((equal (char-after) ?\ ) (forward-char 1))))))
7546 (defun org-current-level ()
7547 "Return the level of the current entry, or nil if before the first headline.
7548 The level is the number of stars at the beginning of the headline."
7549 (save-excursion
7550 (org-with-limited-levels
7551 (if (ignore-errors (org-back-to-heading t))
7552 (funcall outline-level)))))
7554 (defun org-get-previous-line-level ()
7555 "Return the outline depth of the last headline before the current line.
7556 Returns 0 for the first headline in the buffer, and nil if before the
7557 first headline."
7558 (let ((current-level (org-current-level))
7559 (prev-level (when (> (line-number-at-pos) 1)
7560 (save-excursion
7561 (beginning-of-line 0)
7562 (org-current-level)))))
7563 (cond ((null current-level) nil) ; Before first headline
7564 ((null prev-level) 0) ; At first headline
7565 (prev-level))))
7567 (defun org-reduced-level (l)
7568 "Compute the effective level of a heading.
7569 This takes into account the setting of `org-odd-levels-only'."
7570 (cond
7571 ((zerop l) 0)
7572 (org-odd-levels-only (1+ (floor (/ l 2))))
7573 (t l)))
7575 (defun org-level-increment ()
7576 "Return the number of stars that will be added or removed at a
7577 time to headlines when structure editing, based on the value of
7578 `org-odd-levels-only'."
7579 (if org-odd-levels-only 2 1))
7581 (defun org-get-valid-level (level &optional change)
7582 "Rectify a level change under the influence of `org-odd-levels-only'
7583 LEVEL is a current level, CHANGE is by how much the level should be
7584 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7585 even level numbers will become the next higher odd number."
7586 (if org-odd-levels-only
7587 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7588 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7589 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7590 (max 1 (+ level (or change 0)))))
7592 (if (boundp 'define-obsolete-function-alias)
7593 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7594 (define-obsolete-function-alias 'org-get-legal-level
7595 'org-get-valid-level)
7596 (define-obsolete-function-alias 'org-get-legal-level
7597 'org-get-valid-level "23.1")))
7599 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7600 ;; ̀org-with-limited-levels'
7601 (defun org-promote ()
7602 "Promote the current heading higher up the tree.
7603 If the region is active in `transient-mark-mode', promote all headings
7604 in the region."
7605 (org-back-to-heading t)
7606 (let* ((level (save-match-data (funcall outline-level)))
7607 (after-change-functions (remove 'flyspell-after-change-function
7608 after-change-functions))
7609 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7610 (diff (abs (- level (length up-head) -1))))
7611 (cond ((and (= level 1) org-called-with-limited-levels
7612 org-allow-promoting-top-level-subtree)
7613 (replace-match "# " nil t))
7614 ((= level 1)
7615 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7616 (t (replace-match up-head nil t)))
7617 ;; Fixup tag positioning
7618 (unless (= level 1)
7619 (and org-auto-align-tags (org-set-tags nil t))
7620 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7621 (run-hooks 'org-after-promote-entry-hook)))
7623 (defun org-demote ()
7624 "Demote the current heading lower down the tree.
7625 If the region is active in `transient-mark-mode', demote all headings
7626 in the region."
7627 (org-back-to-heading t)
7628 (let* ((level (save-match-data (funcall outline-level)))
7629 (after-change-functions (remove 'flyspell-after-change-function
7630 after-change-functions))
7631 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7632 (diff (abs (- level (length down-head) -1))))
7633 (replace-match down-head nil t)
7634 ;; Fixup tag positioning
7635 (and org-auto-align-tags (org-set-tags nil t))
7636 (if org-adapt-indentation (org-fixup-indentation diff))
7637 (run-hooks 'org-after-demote-entry-hook)))
7639 (defun org-cycle-level ()
7640 "Cycle the level of an empty headline through possible states.
7641 This goes first to child, then to parent, level, then up the hierarchy.
7642 After top level, it switches back to sibling level."
7643 (interactive)
7644 (let ((org-adapt-indentation nil))
7645 (when (org-point-at-end-of-empty-headline)
7646 (setq this-command 'org-cycle-level) ; Only needed for caching
7647 (let ((cur-level (org-current-level))
7648 (prev-level (org-get-previous-line-level)))
7649 (cond
7650 ;; If first headline in file, promote to top-level.
7651 ((= prev-level 0)
7652 (loop repeat (/ (- cur-level 1) (org-level-increment))
7653 do (org-do-promote)))
7654 ;; If same level as prev, demote one.
7655 ((= prev-level cur-level)
7656 (org-do-demote))
7657 ;; If parent is top-level, promote to top level if not already.
7658 ((= prev-level 1)
7659 (loop repeat (/ (- cur-level 1) (org-level-increment))
7660 do (org-do-promote)))
7661 ;; If top-level, return to prev-level.
7662 ((= cur-level 1)
7663 (loop repeat (/ (- prev-level 1) (org-level-increment))
7664 do (org-do-demote)))
7665 ;; If less than prev-level, promote one.
7666 ((< cur-level prev-level)
7667 (org-do-promote))
7668 ;; If deeper than prev-level, promote until higher than
7669 ;; prev-level.
7670 ((> cur-level prev-level)
7671 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7672 do (org-do-promote))))
7673 t))))
7675 (defun org-map-tree (fun)
7676 "Call FUN for every heading underneath the current one."
7677 (org-back-to-heading)
7678 (let ((level (funcall outline-level)))
7679 (save-excursion
7680 (funcall fun)
7681 (while (and (progn
7682 (outline-next-heading)
7683 (> (funcall outline-level) level))
7684 (not (eobp)))
7685 (funcall fun)))))
7687 (defun org-map-region (fun beg end)
7688 "Call FUN for every heading between BEG and END."
7689 (let ((org-ignore-region t))
7690 (save-excursion
7691 (setq end (copy-marker end))
7692 (goto-char beg)
7693 (if (and (re-search-forward org-outline-regexp-bol nil t)
7694 (< (point) end))
7695 (funcall fun))
7696 (while (and (progn
7697 (outline-next-heading)
7698 (< (point) end))
7699 (not (eobp)))
7700 (funcall fun)))))
7702 (defvar org-property-end-re) ; silence byte-compiler
7703 (defun org-fixup-indentation (diff)
7704 "Change the indentation in the current entry by DIFF.
7705 However, if any line in the current entry has no indentation, or if it
7706 would end up with no indentation after the change, nothing at all is done."
7707 (save-excursion
7708 (let ((end (save-excursion (outline-next-heading)
7709 (point-marker)))
7710 (prohibit (if (> diff 0)
7711 "^\\S-"
7712 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7713 col)
7714 (unless (save-excursion (end-of-line 1)
7715 (re-search-forward prohibit end t))
7716 (while (and (< (point) end)
7717 (re-search-forward "^[ \t]+" end t))
7718 (goto-char (match-end 0))
7719 (setq col (current-column))
7720 (if (< diff 0) (replace-match ""))
7721 (org-indent-to-column (+ diff col))))
7722 (move-marker end nil))))
7724 (defun org-convert-to-odd-levels ()
7725 "Convert an org-mode file with all levels allowed to one with odd levels.
7726 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7727 level 5 etc."
7728 (interactive)
7729 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7730 (let ((outline-level 'org-outline-level)
7731 (org-odd-levels-only nil) n)
7732 (save-excursion
7733 (goto-char (point-min))
7734 (while (re-search-forward "^\\*\\*+ " nil t)
7735 (setq n (- (length (match-string 0)) 2))
7736 (while (>= (setq n (1- n)) 0)
7737 (org-demote))
7738 (end-of-line 1))))))
7740 (defun org-convert-to-oddeven-levels ()
7741 "Convert an org-mode file with only odd levels to one with odd/even levels.
7742 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7743 file contains a section with an even level, conversion would
7744 destroy the structure of the file. An error is signaled in this
7745 case."
7746 (interactive)
7747 (goto-char (point-min))
7748 ;; First check if there are no even levels
7749 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7750 (org-show-context t)
7751 (error "Not all levels are odd in this file. Conversion not possible"))
7752 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7753 (let ((outline-regexp org-outline-regexp)
7754 (outline-level 'org-outline-level)
7755 (org-odd-levels-only nil) n)
7756 (save-excursion
7757 (goto-char (point-min))
7758 (while (re-search-forward "^\\*\\*+ " nil t)
7759 (setq n (/ (1- (length (match-string 0))) 2))
7760 (while (>= (setq n (1- n)) 0)
7761 (org-promote))
7762 (end-of-line 1))))))
7764 (defun org-tr-level (n)
7765 "Make N odd if required."
7766 (if org-odd-levels-only (1+ (/ n 2)) n))
7768 ;;; Vertical tree motion, cutting and pasting of subtrees
7770 (defun org-move-subtree-up (&optional arg)
7771 "Move the current subtree up past ARG headlines of the same level."
7772 (interactive "p")
7773 (org-move-subtree-down (- (prefix-numeric-value arg))))
7775 (defun org-move-subtree-down (&optional arg)
7776 "Move the current subtree down past ARG headlines of the same level."
7777 (interactive "p")
7778 (setq arg (prefix-numeric-value arg))
7779 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7780 'org-get-last-sibling))
7781 (ins-point (make-marker))
7782 (cnt (abs arg))
7783 (col (current-column))
7784 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7785 ;; Select the tree
7786 (org-back-to-heading)
7787 (setq beg0 (point))
7788 (save-excursion
7789 (setq ne-beg (org-back-over-empty-lines))
7790 (setq beg (point)))
7791 (save-match-data
7792 (save-excursion (outline-end-of-heading)
7793 (setq folded (outline-invisible-p)))
7794 (outline-end-of-subtree))
7795 (outline-next-heading)
7796 (setq ne-end (org-back-over-empty-lines))
7797 (setq end (point))
7798 (goto-char beg0)
7799 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7800 ;; include less whitespace
7801 (save-excursion
7802 (goto-char beg)
7803 (forward-line (- ne-beg ne-end))
7804 (setq beg (point))))
7805 ;; Find insertion point, with error handling
7806 (while (> cnt 0)
7807 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7808 (progn (goto-char beg0)
7809 (error "Cannot move past superior level or buffer limit")))
7810 (setq cnt (1- cnt)))
7811 (if (> arg 0)
7812 ;; Moving forward - still need to move over subtree
7813 (progn (org-end-of-subtree t t)
7814 (save-excursion
7815 (org-back-over-empty-lines)
7816 (or (bolp) (newline)))))
7817 (setq ne-ins (org-back-over-empty-lines))
7818 (move-marker ins-point (point))
7819 (setq txt (buffer-substring beg end))
7820 (org-save-markers-in-region beg end)
7821 (delete-region beg end)
7822 (org-remove-empty-overlays-at beg)
7823 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7824 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7825 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7826 (let ((bbb (point)))
7827 (insert-before-markers txt)
7828 (org-reinstall-markers-in-region bbb)
7829 (move-marker ins-point bbb))
7830 (or (bolp) (insert "\n"))
7831 (setq ins-end (point))
7832 (goto-char ins-point)
7833 (org-skip-whitespace)
7834 (when (and (< arg 0)
7835 (org-first-sibling-p)
7836 (> ne-ins ne-beg))
7837 ;; Move whitespace back to beginning
7838 (save-excursion
7839 (goto-char ins-end)
7840 (let ((kill-whole-line t))
7841 (kill-line (- ne-ins ne-beg)) (point)))
7842 (insert (make-string (- ne-ins ne-beg) ?\n)))
7843 (move-marker ins-point nil)
7844 (if folded
7845 (hide-subtree)
7846 (org-show-entry)
7847 (show-children)
7848 (org-cycle-hide-drawers 'children))
7849 (org-clean-visibility-after-subtree-move)
7850 ;; move back to the initial column we were at
7851 (move-to-column col)))
7853 (defvar org-subtree-clip ""
7854 "Clipboard for cut and paste of subtrees.
7855 This is actually only a copy of the kill, because we use the normal kill
7856 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7858 (defvar org-subtree-clip-folded nil
7859 "Was the last copied subtree folded?
7860 This is used to fold the tree back after pasting.")
7862 (defun org-cut-subtree (&optional n)
7863 "Cut the current subtree into the clipboard.
7864 With prefix arg N, cut this many sequential subtrees.
7865 This is a short-hand for marking the subtree and then cutting it."
7866 (interactive "p")
7867 (org-copy-subtree n 'cut))
7869 (defun org-copy-subtree (&optional n cut force-store-markers)
7870 "Cut the current subtree into the clipboard.
7871 With prefix arg N, cut this many sequential subtrees.
7872 This is a short-hand for marking the subtree and then copying it.
7873 If CUT is non-nil, actually cut the subtree.
7874 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7875 of some markers in the region, even if CUT is non-nil. This is
7876 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7877 (interactive "p")
7878 (let (beg end folded (beg0 (point)))
7879 (if (org-called-interactively-p 'any)
7880 (org-back-to-heading nil) ; take what looks like a subtree
7881 (org-back-to-heading t)) ; take what is really there
7882 (setq beg (point))
7883 (skip-chars-forward " \t\r\n")
7884 (save-match-data
7885 (save-excursion (outline-end-of-heading)
7886 (setq folded (outline-invisible-p)))
7887 (condition-case nil
7888 (org-forward-heading-same-level (1- n) t)
7889 (error nil))
7890 (org-end-of-subtree t t))
7891 (setq end (point))
7892 (goto-char beg0)
7893 (when (> end beg)
7894 (setq org-subtree-clip-folded folded)
7895 (when (or cut force-store-markers)
7896 (org-save-markers-in-region beg end))
7897 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7898 (setq org-subtree-clip (current-kill 0))
7899 (message "%s: Subtree(s) with %d characters"
7900 (if cut "Cut" "Copied")
7901 (length org-subtree-clip)))))
7903 (defun org-paste-subtree (&optional level tree for-yank)
7904 "Paste the clipboard as a subtree, with modification of headline level.
7905 The entire subtree is promoted or demoted in order to match a new headline
7906 level.
7908 If the cursor is at the beginning of a headline, the same level as
7909 that headline is used to paste the tree
7911 If not, the new level is derived from the *visible* headings
7912 before and after the insertion point, and taken to be the inferior headline
7913 level of the two. So if the previous visible heading is level 3 and the
7914 next is level 4 (or vice versa), level 4 will be used for insertion.
7915 This makes sure that the subtree remains an independent subtree and does
7916 not swallow low level entries.
7918 You can also force a different level, either by using a numeric prefix
7919 argument, or by inserting the heading marker by hand. For example, if the
7920 cursor is after \"*****\", then the tree will be shifted to level 5.
7922 If optional TREE is given, use this text instead of the kill ring.
7924 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7925 move back over whitespace before inserting, and move point to the end of
7926 the inserted text when done."
7927 (interactive "P")
7928 (setq tree (or tree (and kill-ring (current-kill 0))))
7929 (unless (org-kill-is-subtree-p tree)
7930 (error "%s"
7931 (substitute-command-keys
7932 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7933 (org-with-limited-levels
7934 (let* ((visp (not (outline-invisible-p)))
7935 (txt tree)
7936 (^re_ "\\(\\*+\\)[ \t]*")
7937 (old-level (if (string-match org-outline-regexp-bol txt)
7938 (- (match-end 0) (match-beginning 0) 1)
7939 -1))
7940 (force-level (cond (level (prefix-numeric-value level))
7941 ((and (looking-at "[ \t]*$")
7942 (string-match
7943 "^\\*+$" (buffer-substring
7944 (point-at-bol) (point))))
7945 (- (match-end 1) (match-beginning 1)))
7946 ((and (bolp)
7947 (looking-at org-outline-regexp))
7948 (- (match-end 0) (point) 1))))
7949 (previous-level (save-excursion
7950 (condition-case nil
7951 (progn
7952 (outline-previous-visible-heading 1)
7953 (if (looking-at ^re_)
7954 (- (match-end 0) (match-beginning 0) 1)
7956 (error 1))))
7957 (next-level (save-excursion
7958 (condition-case nil
7959 (progn
7960 (or (looking-at org-outline-regexp)
7961 (outline-next-visible-heading 1))
7962 (if (looking-at ^re_)
7963 (- (match-end 0) (match-beginning 0) 1)
7965 (error 1))))
7966 (new-level (or force-level (max previous-level next-level)))
7967 (shift (if (or (= old-level -1)
7968 (= new-level -1)
7969 (= old-level new-level))
7971 (- new-level old-level)))
7972 (delta (if (> shift 0) -1 1))
7973 (func (if (> shift 0) 'org-demote 'org-promote))
7974 (org-odd-levels-only nil)
7975 beg end newend)
7976 ;; Remove the forced level indicator
7977 (if force-level
7978 (delete-region (point-at-bol) (point)))
7979 ;; Paste
7980 (beginning-of-line (if (bolp) 1 2))
7981 (setq beg (point))
7982 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7983 (insert-before-markers txt)
7984 (unless (string-match "\n\\'" txt) (insert "\n"))
7985 (setq newend (point))
7986 (org-reinstall-markers-in-region beg)
7987 (setq end (point))
7988 (goto-char beg)
7989 (skip-chars-forward " \t\n\r")
7990 (setq beg (point))
7991 (if (and (outline-invisible-p) visp)
7992 (save-excursion (outline-show-heading)))
7993 ;; Shift if necessary
7994 (unless (= shift 0)
7995 (save-restriction
7996 (narrow-to-region beg end)
7997 (while (not (= shift 0))
7998 (org-map-region func (point-min) (point-max))
7999 (setq shift (+ delta shift)))
8000 (goto-char (point-min))
8001 (setq newend (point-max))))
8002 (when (or (org-called-interactively-p 'interactive) for-yank)
8003 (message "Clipboard pasted as level %d subtree" new-level))
8004 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8005 kill-ring
8006 (eq org-subtree-clip (current-kill 0))
8007 org-subtree-clip-folded)
8008 ;; The tree was folded before it was killed/copied
8009 (hide-subtree))
8010 (and for-yank (goto-char newend)))))
8012 (defun org-kill-is-subtree-p (&optional txt)
8013 "Check if the current kill is an outline subtree, or a set of trees.
8014 Returns nil if kill does not start with a headline, or if the first
8015 headline level is not the largest headline level in the tree.
8016 So this will actually accept several entries of equal levels as well,
8017 which is OK for `org-paste-subtree'.
8018 If optional TXT is given, check this string instead of the current kill."
8019 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8020 (re (org-get-limited-outline-regexp))
8021 (^re (concat "^" re))
8022 (start-level (and kill
8023 (string-match
8024 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8025 kill)
8026 (- (match-end 2) (match-beginning 2) 1)))
8027 (start (1+ (or (match-beginning 2) -1))))
8028 (if (not start-level)
8029 (progn
8030 nil) ;; does not even start with a heading
8031 (catch 'exit
8032 (while (setq start (string-match ^re kill (1+ start)))
8033 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8034 (throw 'exit nil)))
8035 t))))
8037 (defvar org-markers-to-move nil
8038 "Markers that should be moved with a cut-and-paste operation.
8039 Those markers are stored together with their positions relative to
8040 the start of the region.")
8042 (defun org-save-markers-in-region (beg end)
8043 "Check markers in region.
8044 If these markers are between BEG and END, record their position relative
8045 to BEG, so that after moving the block of text, we can put the markers back
8046 into place.
8047 This function gets called just before an entry or tree gets cut from the
8048 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8049 called immediately, to move the markers with the entries."
8050 (setq org-markers-to-move nil)
8051 (when (featurep 'org-clock)
8052 (org-clock-save-markers-for-cut-and-paste beg end))
8053 (when (featurep 'org-agenda)
8054 (org-agenda-save-markers-for-cut-and-paste beg end)))
8056 (defun org-check-and-save-marker (marker beg end)
8057 "Check if MARKER is between BEG and END.
8058 If yes, remember the marker and the distance to BEG."
8059 (when (and (marker-buffer marker)
8060 (equal (marker-buffer marker) (current-buffer)))
8061 (if (and (>= marker beg) (< marker end))
8062 (push (cons marker (- marker beg)) org-markers-to-move))))
8064 (defun org-reinstall-markers-in-region (beg)
8065 "Move all remembered markers to their position relative to BEG."
8066 (mapc (lambda (x)
8067 (move-marker (car x) (+ beg (cdr x))))
8068 org-markers-to-move)
8069 (setq org-markers-to-move nil))
8071 (defun org-narrow-to-subtree ()
8072 "Narrow buffer to the current subtree."
8073 (interactive)
8074 (save-excursion
8075 (save-match-data
8076 (org-with-limited-levels
8077 (narrow-to-region
8078 (progn (org-back-to-heading t) (point))
8079 (progn (org-end-of-subtree t t)
8080 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8081 (point)))))))
8083 (defun org-narrow-to-block ()
8084 "Narrow buffer to the current block."
8085 (interactive)
8086 (let* ((case-fold-search t)
8087 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8088 "^[ \t]*#\\+end_.*")))
8089 (if blockp
8090 (narrow-to-region (car blockp) (cdr blockp))
8091 (error "Not in a block"))))
8093 (eval-when-compile
8094 (defvar org-property-drawer-re))
8096 (defvar org-property-start-re) ;; defined below
8097 (defun org-clone-subtree-with-time-shift (n &optional shift)
8098 "Clone the task (subtree) at point N times.
8099 The clones will be inserted as siblings.
8101 In interactive use, the user will be prompted for the number of
8102 clones to be produced, and for a time SHIFT, which may be a
8103 repeater as used in time stamps, for example `+3d'.
8105 When a valid repeater is given and the entry contains any time
8106 stamps, the clones will become a sequence in time, with time
8107 stamps in the subtree shifted for each clone produced. If SHIFT
8108 is nil or the empty string, time stamps will be left alone. The
8109 ID property of the original subtree is removed.
8111 If the original subtree did contain time stamps with a repeater,
8112 the following will happen:
8113 - the repeater will be removed in each clone
8114 - an additional clone will be produced, with the current, unshifted
8115 date(s) in the entry.
8116 - the original entry will be placed *after* all the clones, with
8117 repeater intact.
8118 - the start days in the repeater in the original entry will be shifted
8119 to past the last clone.
8120 In this way you can spell out a number of instances of a repeating task,
8121 and still retain the repeater to cover future instances of the task."
8122 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8123 (let (beg end template task idprop
8124 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8125 (drawer-re org-drawer-regexp))
8126 (if (not (and (integerp n) (> n 0)))
8127 (error "Invalid number of replications %s" n))
8128 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8129 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8130 shift)))
8131 (error "Invalid shift specification %s" shift))
8132 (when doshift
8133 (setq shift-n (string-to-number (match-string 1 shift))
8134 shift-what (cdr (assoc (match-string 2 shift)
8135 '(("d" . day) ("w" . week)
8136 ("m" . month) ("y" . year))))))
8137 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8138 (setq nmin 1 nmax n)
8139 (org-back-to-heading t)
8140 (setq beg (point))
8141 (setq idprop (org-entry-get nil "ID"))
8142 (org-end-of-subtree t t)
8143 (or (bolp) (insert "\n"))
8144 (setq end (point))
8145 (setq template (buffer-substring beg end))
8146 (when (and doshift
8147 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8148 (delete-region beg end)
8149 (setq end beg)
8150 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8151 (goto-char end)
8152 (loop for n from nmin to nmax do
8153 ;; prepare clone
8154 (with-temp-buffer
8155 (insert template)
8156 (org-mode)
8157 (goto-char (point-min))
8158 (org-show-subtree)
8159 (and idprop (if org-clone-delete-id
8160 (org-entry-delete nil "ID")
8161 (org-id-get-create t)))
8162 (unless (= n 0)
8163 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8164 (kill-whole-line))
8165 (goto-char (point-min))
8166 (while (re-search-forward drawer-re nil t)
8167 (mapc (lambda (d)
8168 (org-remove-empty-drawer-at d (point))) org-drawers)))
8169 (goto-char (point-min))
8170 (when doshift
8171 (while (re-search-forward org-ts-regexp-both nil t)
8172 (org-timestamp-change (* n shift-n) shift-what))
8173 (unless (= n n-no-remove)
8174 (goto-char (point-min))
8175 (while (re-search-forward org-ts-regexp nil t)
8176 (save-excursion
8177 (goto-char (match-beginning 0))
8178 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8179 (delete-region (match-beginning 1) (match-end 1)))))))
8180 (setq task (buffer-string)))
8181 (insert task))
8182 (goto-char beg)))
8184 ;;; Outline Sorting
8186 (defun org-sort (with-case)
8187 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8188 Optional argument WITH-CASE means sort case-sensitively."
8189 (interactive "P")
8190 (cond
8191 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8192 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8194 (org-call-with-arg 'org-sort-entries with-case))))
8196 (defun org-sort-remove-invisible (s)
8197 (remove-text-properties 0 (length s) org-rm-props s)
8198 (while (string-match org-bracket-link-regexp s)
8199 (setq s (replace-match (if (match-end 2)
8200 (match-string 3 s)
8201 (match-string 1 s)) t t s)))
8204 (defvar org-priority-regexp) ; defined later in the file
8206 (defvar org-after-sorting-entries-or-items-hook nil
8207 "Hook that is run after a bunch of entries or items have been sorted.
8208 When children are sorted, the cursor is in the parent line when this
8209 hook gets called. When a region or a plain list is sorted, the cursor
8210 will be in the first entry of the sorted region/list.")
8212 (defun org-sort-entries
8213 (&optional with-case sorting-type getkey-func compare-func property)
8214 "Sort entries on a certain level of an outline tree.
8215 If there is an active region, the entries in the region are sorted.
8216 Else, if the cursor is before the first entry, sort the top-level items.
8217 Else, the children of the entry at point are sorted.
8219 Sorting can be alphabetically, numerically, by date/time as given by
8220 a time stamp, by a property or by priority.
8222 The command prompts for the sorting type unless it has been given to the
8223 function through the SORTING-TYPE argument, which needs to be a character,
8224 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8225 precise meaning of each character:
8227 n Numerically, by converting the beginning of the entry/item to a number.
8228 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8229 o By order of TODO keywords.
8230 t By date/time, either the first active time stamp in the entry, or, if
8231 none exist, by the first inactive one.
8232 s By the scheduled date/time.
8233 d By deadline date/time.
8234 c By creation time, which is assumed to be the first inactive time stamp
8235 at the beginning of a line.
8236 p By priority according to the cookie.
8237 r By the value of a property.
8239 Capital letters will reverse the sort order.
8241 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8242 called with point at the beginning of the record. It must return either
8243 a string or a number that should serve as the sorting key for that record.
8245 Comparing entries ignores case by default. However, with an optional argument
8246 WITH-CASE, the sorting considers case as well."
8247 (interactive "P")
8248 (let ((case-func (if with-case 'identity 'downcase))
8249 (cmstr
8250 ;; The clock marker is lost when using `sort-subr', let's
8251 ;; store the clocking string.
8252 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8253 (save-excursion
8254 (goto-char org-clock-marker)
8255 (looking-back "^.*") (match-string-no-properties 0))))
8256 start beg end stars re re2
8257 txt what tmp)
8258 ;; Find beginning and end of region to sort
8259 (cond
8260 ((org-region-active-p)
8261 ;; we will sort the region
8262 (setq end (region-end)
8263 what "region")
8264 (goto-char (region-beginning))
8265 (if (not (org-at-heading-p)) (outline-next-heading))
8266 (setq start (point)))
8267 ((or (org-at-heading-p)
8268 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8269 ;; we will sort the children of the current headline
8270 (org-back-to-heading)
8271 (setq start (point)
8272 end (progn (org-end-of-subtree t t)
8273 (or (bolp) (insert "\n"))
8274 (org-back-over-empty-lines)
8275 (point))
8276 what "children")
8277 (goto-char start)
8278 (show-subtree)
8279 (outline-next-heading))
8281 ;; we will sort the top-level entries in this file
8282 (goto-char (point-min))
8283 (or (org-at-heading-p) (outline-next-heading))
8284 (setq start (point))
8285 (goto-char (point-max))
8286 (beginning-of-line 1)
8287 (when (looking-at ".*?\\S-")
8288 ;; File ends in a non-white line
8289 (end-of-line 1)
8290 (insert "\n"))
8291 (setq end (point-max))
8292 (setq what "top-level")
8293 (goto-char start)
8294 (show-all)))
8296 (setq beg (point))
8297 (if (>= beg end) (error "Nothing to sort"))
8299 (looking-at "\\(\\*+\\)")
8300 (setq stars (match-string 1)
8301 re (concat "^" (regexp-quote stars) " +")
8302 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8303 txt (buffer-substring beg end))
8304 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8305 (if (and (not (equal stars "*")) (string-match re2 txt))
8306 (error "Region to sort contains a level above the first entry"))
8308 (unless sorting-type
8309 (message
8310 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8311 [t]ime [s]cheduled [d]eadline [c]reated
8312 A/N/P/R/O/F/T/S/D/C means reversed:"
8313 what)
8314 (setq sorting-type (read-char-exclusive))
8316 (unless getkey-func
8317 (and (= (downcase sorting-type) ?f)
8318 (setq getkey-func
8319 (org-icompleting-read "Sort using function: "
8320 obarray 'fboundp t nil nil))
8321 (setq getkey-func (intern getkey-func))))
8323 (and (= (downcase sorting-type) ?r)
8324 (not property)
8325 (setq property
8326 (org-icompleting-read "Property: "
8327 (mapcar 'list (org-buffer-property-keys t))
8328 nil t))))
8330 (message "Sorting entries...")
8332 (save-restriction
8333 (narrow-to-region start end)
8334 (let ((dcst (downcase sorting-type))
8335 (case-fold-search nil)
8336 (now (current-time)))
8337 (sort-subr
8338 (/= dcst sorting-type)
8339 ;; This function moves to the beginning character of the "record" to
8340 ;; be sorted.
8341 (lambda nil
8342 (if (re-search-forward re nil t)
8343 (goto-char (match-beginning 0))
8344 (goto-char (point-max))))
8345 ;; This function moves to the last character of the "record" being
8346 ;; sorted.
8347 (lambda nil
8348 (save-match-data
8349 (condition-case nil
8350 (outline-forward-same-level 1)
8351 (error
8352 (goto-char (point-max))))))
8353 ;; This function returns the value that gets sorted against.
8354 (lambda nil
8355 (cond
8356 ((= dcst ?n)
8357 (if (looking-at org-complex-heading-regexp)
8358 (string-to-number (match-string 4))
8359 nil))
8360 ((= dcst ?a)
8361 (if (looking-at org-complex-heading-regexp)
8362 (funcall case-func (match-string 4))
8363 nil))
8364 ((= dcst ?t)
8365 (let ((end (save-excursion (outline-next-heading) (point))))
8366 (if (or (re-search-forward org-ts-regexp end t)
8367 (re-search-forward org-ts-regexp-both end t))
8368 (org-time-string-to-seconds (match-string 0))
8369 (org-float-time now))))
8370 ((= dcst ?c)
8371 (let ((end (save-excursion (outline-next-heading) (point))))
8372 (if (re-search-forward
8373 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8374 end t)
8375 (org-time-string-to-seconds (match-string 0))
8376 (org-float-time now))))
8377 ((= dcst ?s)
8378 (let ((end (save-excursion (outline-next-heading) (point))))
8379 (if (re-search-forward org-scheduled-time-regexp end t)
8380 (org-time-string-to-seconds (match-string 1))
8381 (org-float-time now))))
8382 ((= dcst ?d)
8383 (let ((end (save-excursion (outline-next-heading) (point))))
8384 (if (re-search-forward org-deadline-time-regexp end t)
8385 (org-time-string-to-seconds (match-string 1))
8386 (org-float-time now))))
8387 ((= dcst ?p)
8388 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8389 (string-to-char (match-string 2))
8390 org-default-priority))
8391 ((= dcst ?r)
8392 (or (org-entry-get nil property) ""))
8393 ((= dcst ?o)
8394 (if (looking-at org-complex-heading-regexp)
8395 (- 9999 (length (member (match-string 2)
8396 org-todo-keywords-1)))))
8397 ((= dcst ?f)
8398 (if getkey-func
8399 (progn
8400 (setq tmp (funcall getkey-func))
8401 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8402 tmp)
8403 (error "Invalid key function `%s'" getkey-func)))
8404 (t (error "Invalid sorting type `%c'" sorting-type))))
8406 (cond
8407 ((= dcst ?a) 'string<)
8408 ((= dcst ?f) compare-func)
8409 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8410 (run-hooks 'org-after-sorting-entries-or-items-hook)
8411 ;; Reset the clock marker if needed
8412 (when cmstr
8413 (save-excursion
8414 (goto-char start)
8415 (search-forward cmstr nil t)
8416 (move-marker org-clock-marker (point))))
8417 (message "Sorting entries...done")))
8419 (defun org-do-sort (table what &optional with-case sorting-type)
8420 "Sort TABLE of WHAT according to SORTING-TYPE.
8421 The user will be prompted for the SORTING-TYPE if the call to this
8422 function does not specify it. WHAT is only for the prompt, to indicate
8423 what is being sorted. The sorting key will be extracted from
8424 the car of the elements of the table.
8425 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8426 (unless sorting-type
8427 (message
8428 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8429 what)
8430 (setq sorting-type (read-char-exclusive)))
8431 (let ((dcst (downcase sorting-type))
8432 extractfun comparefun)
8433 ;; Define the appropriate functions
8434 (cond
8435 ((= dcst ?n)
8436 (setq extractfun 'string-to-number
8437 comparefun (if (= dcst sorting-type) '< '>)))
8438 ((= dcst ?a)
8439 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8440 (lambda(x) (downcase (org-sort-remove-invisible x))))
8441 comparefun (if (= dcst sorting-type)
8442 'string<
8443 (lambda (a b) (and (not (string< a b))
8444 (not (string= a b)))))))
8445 ((= dcst ?t)
8446 (setq extractfun
8447 (lambda (x)
8448 (if (or (string-match org-ts-regexp x)
8449 (string-match org-ts-regexp-both x))
8450 (org-float-time
8451 (org-time-string-to-time (match-string 0 x)))
8453 comparefun (if (= dcst sorting-type) '< '>)))
8454 (t (error "Invalid sorting type `%c'" sorting-type)))
8456 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8457 table)
8458 (lambda (a b) (funcall comparefun (car a) (car b))))))
8461 ;;; The orgstruct minor mode
8463 ;; Define a minor mode which can be used in other modes in order to
8464 ;; integrate the org-mode structure editing commands.
8466 ;; This is really a hack, because the org-mode structure commands use
8467 ;; keys which normally belong to the major mode. Here is how it
8468 ;; works: The minor mode defines all the keys necessary to operate the
8469 ;; structure commands, but wraps the commands into a function which
8470 ;; tests if the cursor is currently at a headline or a plain list
8471 ;; item. If that is the case, the structure command is used,
8472 ;; temporarily setting many Org-mode variables like regular
8473 ;; expressions for filling etc. However, when any of those keys is
8474 ;; used at a different location, function uses `key-binding' to look
8475 ;; up if the key has an associated command in another currently active
8476 ;; keymap (minor modes, major mode, global), and executes that
8477 ;; command. There might be problems if any of the keys is otherwise
8478 ;; used as a prefix key.
8480 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8481 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8482 ;; addresses this by checking explicitly for both bindings.
8484 (defvar orgstruct-mode-map (make-sparse-keymap)
8485 "Keymap for the minor `orgstruct-mode'.")
8487 (defvar org-local-vars nil
8488 "List of local variables, for use by `orgstruct-mode'.")
8490 ;;;###autoload
8491 (define-minor-mode orgstruct-mode
8492 "Toggle the minor mode `orgstruct-mode'.
8493 This mode is for using Org-mode structure commands in other
8494 modes. The following keys behave as if Org-mode were active, if
8495 the cursor is on a headline, or on a plain list item (both as
8496 defined by Org-mode).
8498 M-up Move entry/item up
8499 M-down Move entry/item down
8500 M-left Promote
8501 M-right Demote
8502 M-S-up Move entry/item up
8503 M-S-down Move entry/item down
8504 M-S-left Promote subtree
8505 M-S-right Demote subtree
8506 M-q Fill paragraph and items like in Org-mode
8507 C-c ^ Sort entries
8508 C-c - Cycle list bullet
8509 TAB Cycle item visibility
8510 M-RET Insert new heading/item
8511 S-M-RET Insert new TODO heading / Checkbox item
8512 C-c C-c Set tags / toggle checkbox"
8513 nil " OrgStruct" nil
8514 (org-load-modules-maybe)
8515 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8517 ;;;###autoload
8518 (defun turn-on-orgstruct ()
8519 "Unconditionally turn on `orgstruct-mode'."
8520 (orgstruct-mode 1))
8522 (defvar org-fb-vars nil)
8523 (make-variable-buffer-local 'org-fb-vars)
8524 (defun orgstruct++-mode (&optional arg)
8525 "Toggle `orgstruct-mode', the enhanced version of it.
8526 In addition to setting orgstruct-mode, this also exports all
8527 indentation and autofilling variables from org-mode into the
8528 buffer. It will also recognize item context in multiline items."
8529 (interactive "P")
8530 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8531 (if (< arg 1)
8532 (progn (orgstruct-mode -1)
8533 (mapc (lambda(v)
8534 (org-set-local (car v)
8535 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8536 org-fb-vars))
8537 (orgstruct-mode 1)
8538 (setq org-fb-vars nil)
8539 (let (var val)
8540 (mapc
8541 (lambda (x)
8542 (when (string-match
8543 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8544 (symbol-name (car x)))
8545 (setq var (car x) val (nth 1 x))
8546 (push (list var `(quote ,(eval var))) org-fb-vars)
8547 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8548 org-local-vars)
8549 (org-set-local 'orgstruct-is-++ t))))
8551 (defvar orgstruct-is-++ nil
8552 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8553 (make-variable-buffer-local 'orgstruct-is-++)
8555 ;;;###autoload
8556 (defun turn-on-orgstruct++ ()
8557 "Unconditionally turn on `orgstruct++-mode'."
8558 (orgstruct++-mode 1))
8560 (defun orgstruct-error ()
8561 "Error when there is no default binding for a structure key."
8562 (interactive)
8563 (error "This key has no function outside structure elements"))
8565 (defun orgstruct-setup ()
8566 "Setup orgstruct keymaps."
8567 (let ((nfunc 0)
8568 (bindings
8569 (list
8570 '([(meta up)] org-metaup)
8571 '([(meta down)] org-metadown)
8572 '([(meta left)] org-metaleft)
8573 '([(meta right)] org-metaright)
8574 '([(meta shift up)] org-shiftmetaup)
8575 '([(meta shift down)] org-shiftmetadown)
8576 '([(meta shift left)] org-shiftmetaleft)
8577 '([(meta shift right)] org-shiftmetaright)
8578 '([?\e (up)] org-metaup)
8579 '([?\e (down)] org-metadown)
8580 '([?\e (left)] org-metaleft)
8581 '([?\e (right)] org-metaright)
8582 '([?\e (shift up)] org-shiftmetaup)
8583 '([?\e (shift down)] org-shiftmetadown)
8584 '([?\e (shift left)] org-shiftmetaleft)
8585 '([?\e (shift right)] org-shiftmetaright)
8586 '([(shift up)] org-shiftup)
8587 '([(shift down)] org-shiftdown)
8588 '([(shift left)] org-shiftleft)
8589 '([(shift right)] org-shiftright)
8590 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8591 '("\M-q" fill-paragraph)
8592 '("\C-c^" org-sort)
8593 '("\C-c-" org-cycle-list-bullet)))
8594 elt key fun cmd)
8595 (while (setq elt (pop bindings))
8596 (setq nfunc (1+ nfunc))
8597 (setq key (org-key (car elt))
8598 fun (nth 1 elt)
8599 cmd (orgstruct-make-binding fun nfunc key))
8600 (org-defkey orgstruct-mode-map key cmd))
8602 ;; Prevent an error for users who forgot to make autoloads
8603 (require 'org-element)
8605 ;; Special treatment needed for TAB and RET
8606 (org-defkey orgstruct-mode-map [(tab)]
8607 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8608 (org-defkey orgstruct-mode-map "\C-i"
8609 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8611 (org-defkey orgstruct-mode-map "\M-\C-m"
8612 (orgstruct-make-binding 'org-insert-heading 105
8613 "\M-\C-m" [(meta return)]))
8614 (org-defkey orgstruct-mode-map [(meta return)]
8615 (orgstruct-make-binding 'org-insert-heading 106
8616 [(meta return)] "\M-\C-m"))
8618 (org-defkey orgstruct-mode-map [(shift meta return)]
8619 (orgstruct-make-binding 'org-insert-todo-heading 107
8620 [(meta return)] "\M-\C-m"))
8622 (org-defkey orgstruct-mode-map "\e\C-m"
8623 (orgstruct-make-binding 'org-insert-heading 108
8624 "\e\C-m" [?\e (return)]))
8625 (org-defkey orgstruct-mode-map [?\e (return)]
8626 (orgstruct-make-binding 'org-insert-heading 109
8627 [?\e (return)] "\e\C-m"))
8628 (org-defkey orgstruct-mode-map [?\e (shift return)]
8629 (orgstruct-make-binding 'org-insert-todo-heading 110
8630 [?\e (return)] "\e\C-m"))
8632 (unless org-local-vars
8633 (setq org-local-vars (org-get-local-variables)))
8637 (defun orgstruct-make-binding (fun n &rest keys)
8638 "Create a function for binding in the structure minor mode.
8639 FUN is the command to call inside a table. N is used to create a unique
8640 command name. KEYS are keys that should be checked in for a command
8641 to execute outside of tables."
8642 (eval
8643 (list 'defun
8644 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8645 '(arg)
8646 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8647 "Outside of structure, run the binding of `"
8648 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8649 "'.")
8650 '(interactive "p")
8651 (list 'if
8652 `(org-context-p 'headline 'item
8653 (and orgstruct-is-++
8654 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8655 'item-body))
8656 (list 'org-run-like-in-org-mode (list 'quote fun))
8657 (list 'let '(orgstruct-mode)
8658 (list 'call-interactively
8659 (append '(or)
8660 (mapcar (lambda (k)
8661 (list 'key-binding k))
8662 keys)
8663 '('orgstruct-error))))))))
8665 (defun org-contextualize-keys (alist contexts)
8666 "Return valid elements in ALIST depending on CONTEXTS.
8668 `org-agenda-custom-commands' or `org-capture-templates' are the
8669 values used for ALIST, and `org-agenda-custom-commands-contexts'
8670 or `org-capture-templates-contexts' are the associated contexts
8671 definitions."
8672 (let ((contexts
8673 ;; normalize contexts
8674 (mapcar
8675 (lambda(c) (cond ((listp (cadr c))
8676 (list (car c) (car c) (cadr c)))
8677 ((string= "" (cadr c))
8678 (list (car c) (car c) (caddr c)))
8679 (t c))) contexts))
8680 (a alist) c r s)
8681 ;; loop over all commands or templates
8682 (while (setq c (pop a))
8683 (let (vrules repl)
8684 (cond
8685 ((not (assoc (car c) contexts))
8686 (push c r))
8687 ((and (assoc (car c) contexts)
8688 (setq vrules (org-contextualize-validate-key
8689 (car c) contexts)))
8690 (mapc (lambda (vr)
8691 (when (not (equal (car vr) (cadr vr)))
8692 (setq repl vr))) vrules)
8693 (if (not repl) (push c r)
8694 (push (cadr repl) s)
8695 (push
8696 (cons (car c)
8697 (cdr (or (assoc (cadr repl) alist)
8698 (error "Undefined key `%s' as contextual replacement for `%s'"
8699 (cadr repl) (car c)))))
8700 r))))))
8701 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8702 (delq
8704 (delete-dups
8705 (mapcar (lambda (x)
8706 (let ((tpl (car x)))
8707 (when (not (delq
8709 (mapcar (lambda(y)
8710 (equal y tpl)) s))) x)))
8711 (reverse r))))))
8713 (defun org-contextualize-validate-key (key contexts)
8714 "Check CONTEXTS for agenda or capture KEY."
8715 (let (r rr res)
8716 (while (setq r (pop contexts))
8717 (mapc
8718 (lambda (rr)
8719 (when
8720 (and (equal key (car r))
8721 (if (functionp rr) (funcall rr)
8722 (or (and (eq (car rr) 'in-file)
8723 (buffer-file-name)
8724 (string-match (cdr rr) (buffer-file-name)))
8725 (and (eq (car rr) 'in-mode)
8726 (string-match (cdr rr) (symbol-name major-mode)))
8727 (when (and (eq (car rr) 'not-in-file)
8728 (buffer-file-name))
8729 (not (string-match (cdr rr) (buffer-file-name))))
8730 (when (eq (car rr) 'not-in-mode)
8731 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8732 (push r res)))
8733 (car (last r))))
8734 (delete-dups (delq nil res))))
8736 (defun org-context-p (&rest contexts)
8737 "Check if local context is any of CONTEXTS.
8738 Possible values in the list of contexts are `table', `headline', and `item'."
8739 (let ((pos (point)))
8740 (goto-char (point-at-bol))
8741 (prog1 (or (and (memq 'table contexts)
8742 (looking-at "[ \t]*|"))
8743 (and (memq 'headline contexts)
8744 (looking-at org-outline-regexp))
8745 (and (memq 'item contexts)
8746 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8747 (and (memq 'item-body contexts)
8748 (org-in-item-p)))
8749 (goto-char pos))))
8751 (defun org-get-local-variables ()
8752 "Return a list of all local variables in an Org mode buffer."
8753 (let (varlist)
8754 (with-current-buffer (get-buffer-create "*Org tmp*")
8755 (erase-buffer)
8756 (org-mode)
8757 (setq varlist (buffer-local-variables)))
8758 (kill-buffer "*Org tmp*")
8759 (delq nil
8760 (mapcar
8761 (lambda (x)
8762 (setq x
8763 (if (symbolp x)
8764 (list x)
8765 (list (car x) (list 'quote (cdr x)))))
8766 (if (string-match
8767 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8768 (symbol-name (car x)))
8769 x nil))
8770 varlist))))
8772 (defun org-clone-local-variables (from-buffer &optional regexp)
8773 "Clone local variables from FROM-BUFFER.
8774 Optional argument REGEXP selects variables to clone."
8775 (mapc
8776 (lambda (pair)
8777 (and (symbolp (car pair))
8778 (or (null regexp)
8779 (string-match regexp (symbol-name (car pair))))
8780 (set (make-local-variable (car pair))
8781 (cdr pair))))
8782 (buffer-local-variables from-buffer)))
8784 ;;;###autoload
8785 (defun org-run-like-in-org-mode (cmd)
8786 "Run a command, pretending that the current buffer is in Org-mode.
8787 This will temporarily bind local variables that are typically bound in
8788 Org-mode to the values they have in Org-mode, and then interactively
8789 call CMD."
8790 (org-load-modules-maybe)
8791 (unless org-local-vars
8792 (setq org-local-vars (org-get-local-variables)))
8793 (eval (list 'let org-local-vars
8794 (list 'call-interactively (list 'quote cmd)))))
8796 ;;;; Archiving
8798 (defun org-get-category (&optional pos force-refresh)
8799 "Get the category applying to position POS."
8800 (save-match-data
8801 (if force-refresh (org-refresh-category-properties))
8802 (let ((pos (or pos (point))))
8803 (or (get-text-property pos 'org-category)
8804 (progn (org-refresh-category-properties)
8805 (get-text-property pos 'org-category))))))
8807 (defun org-refresh-category-properties ()
8808 "Refresh category text properties in the buffer."
8809 (let ((case-fold-search t)
8810 (inhibit-read-only t)
8811 (def-cat (cond
8812 ((null org-category)
8813 (if buffer-file-name
8814 (file-name-sans-extension
8815 (file-name-nondirectory buffer-file-name))
8816 "???"))
8817 ((symbolp org-category) (symbol-name org-category))
8818 (t org-category)))
8819 beg end cat pos optionp)
8820 (org-unmodified
8821 (save-excursion
8822 (save-restriction
8823 (widen)
8824 (goto-char (point-min))
8825 (put-text-property (point) (point-max) 'org-category def-cat)
8826 (while (re-search-forward
8827 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8828 (setq pos (match-end 0)
8829 optionp (equal (char-after (match-beginning 0)) ?#)
8830 cat (org-trim (match-string 2)))
8831 (if optionp
8832 (setq beg (point-at-bol) end (point-max))
8833 (org-back-to-heading t)
8834 (setq beg (point) end (org-end-of-subtree t t)))
8835 (put-text-property beg end 'org-category cat)
8836 (put-text-property beg end 'org-category-position beg)
8837 (goto-char pos)))))))
8839 (defun org-refresh-properties (dprop tprop)
8840 "Refresh buffer text properties.
8841 DPROP is the drawer property and TPROP is the corresponding text
8842 property to set."
8843 (let ((case-fold-search t)
8844 (inhibit-read-only t) p)
8845 (org-unmodified
8846 (save-excursion
8847 (save-restriction
8848 (widen)
8849 (goto-char (point-min))
8850 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8851 (setq p (org-match-string-no-properties 1))
8852 (save-excursion
8853 (org-back-to-heading t)
8854 (put-text-property
8855 (point-at-bol) (point-at-eol) tprop p))))))))
8858 ;;;; Link Stuff
8860 ;;; Link abbreviations
8862 (defun org-link-expand-abbrev (link)
8863 "Apply replacements as defined in `org-link-abbrev-alist'."
8864 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8865 (let* ((key (match-string 1 link))
8866 (as (or (assoc key org-link-abbrev-alist-local)
8867 (assoc key org-link-abbrev-alist)))
8868 (tag (and (match-end 2) (match-string 3 link)))
8869 rpl)
8870 (if (not as)
8871 link
8872 (setq rpl (cdr as))
8873 (cond
8874 ((symbolp rpl) (funcall rpl tag))
8875 ((string-match "%(\\([^)]+\\))" rpl)
8876 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8877 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8878 ((string-match "%h" rpl)
8879 (replace-match (url-hexify-string (or tag "")) t t rpl))
8880 (t (concat rpl tag)))))
8881 link))
8883 ;;; Storing and inserting links
8885 (defvar org-insert-link-history nil
8886 "Minibuffer history for links inserted with `org-insert-link'.")
8888 (defvar org-stored-links nil
8889 "Contains the links stored with `org-store-link'.")
8891 (defvar org-store-link-plist nil
8892 "Plist with info about the most recently link created with `org-store-link'.")
8894 (defvar org-link-protocols nil
8895 "Link protocols added to Org-mode using `org-add-link-type'.")
8897 (defvar org-store-link-functions nil
8898 "List of functions that are called to create and store a link.
8899 Each function will be called in turn until one returns a non-nil
8900 value. Each function should check if it is responsible for creating
8901 this link (for example by looking at the major mode).
8902 If not, it must exit and return nil.
8903 If yes, it should return a non-nil value after a calling
8904 `org-store-link-props' with a list of properties and values.
8905 Special properties are:
8907 :type The link prefix, like \"http\". This must be given.
8908 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8909 This is obligatory as well.
8910 :description Optional default description for the second pair
8911 of brackets in an Org-mode link. The user can still change
8912 this when inserting this link into an Org-mode buffer.
8914 In addition to these, any additional properties can be specified
8915 and then used in capture templates.")
8917 (defun org-add-link-type (type &optional follow export)
8918 "Add TYPE to the list of `org-link-types'.
8919 Re-compute all regular expressions depending on `org-link-types'
8921 FOLLOW and EXPORT are two functions.
8923 FOLLOW should take the link path as the single argument and do whatever
8924 is necessary to follow the link, for example find a file or display
8925 a mail message.
8927 EXPORT should format the link path for export to one of the export formats.
8928 It should be a function accepting three arguments:
8930 path the path of the link, the text after the prefix (like \"http:\")
8931 desc the description of the link, if any, or a description added by
8932 org-export-normalize-links if there is none
8933 format the export format, a symbol like `html' or `latex' or `ascii'..
8935 The function may use the FORMAT information to return different values
8936 depending on the format. The return value will be put literally into
8937 the exported file. If the return value is nil, this means Org should
8938 do what it normally does with links which do not have EXPORT defined.
8940 Org-mode has a built-in default for exporting links. If you are happy with
8941 this default, there is no need to define an export function for the link
8942 type. For a simple example of an export function, see `org-bbdb.el'."
8943 (add-to-list 'org-link-types type t)
8944 (org-make-link-regexps)
8945 (if (assoc type org-link-protocols)
8946 (setcdr (assoc type org-link-protocols) (list follow export))
8947 (push (list type follow export) org-link-protocols)))
8949 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8950 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8952 ;;;###autoload
8953 (defun org-store-link (arg)
8954 "\\<org-mode-map>Store an org-link to the current location.
8955 This link is added to `org-stored-links' and can later be inserted
8956 into an org-buffer with \\[org-insert-link].
8958 For some link types, a prefix arg is interpreted.
8959 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8960 For file links, arg negates `org-context-in-file-links'.
8962 A double prefix arg force skipping storing functions that are not
8963 part of Org's core."
8964 (interactive "P")
8965 (org-load-modules-maybe)
8966 (setq org-store-link-plist nil) ; reset
8967 (org-with-limited-levels
8968 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
8969 (cond
8970 ((and (not (equal arg '(16)))
8971 (setq sfuns
8972 (delq
8973 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
8974 org-store-link-functions))
8975 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
8976 (or (and (cdr sfuns)
8977 (funcall (intern
8978 (completing-read "Which function for creating the link? "
8979 sfunsn t (car sfunsn)))))
8980 (funcall (caar sfuns)))
8981 (setq link (plist-get org-store-link-plist :link)
8982 desc (or (plist-get org-store-link-plist :description) link))))
8983 ((org-src-edit-buffer-p)
8984 (let (label gc)
8985 (while (or (not label)
8986 (save-excursion
8987 (save-restriction
8988 (widen)
8989 (goto-char (point-min))
8990 (re-search-forward
8991 (regexp-quote (format org-coderef-label-format label))
8992 nil t))))
8993 (when label (message "Label exists already") (sit-for 2))
8994 (setq label (read-string "Code line label: " label)))
8995 (end-of-line 1)
8996 (setq link (format org-coderef-label-format label))
8997 (setq gc (- 79 (length link)))
8998 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8999 (insert link)
9000 (setq link (concat "(" label ")") desc nil)))
9002 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9003 ;; We are in the agenda, link to referenced location
9004 (let ((m (or (get-text-property (point) 'org-hd-marker)
9005 (get-text-property (point) 'org-marker))))
9006 (when m
9007 (org-with-point-at m
9008 (setq agenda-link
9009 (if (org-called-interactively-p 'any)
9010 (call-interactively 'org-store-link)
9011 (org-store-link nil)))))))
9013 ((eq major-mode 'calendar-mode)
9014 (let ((cd (calendar-cursor-to-date)))
9015 (setq link
9016 (format-time-string
9017 (car org-time-stamp-formats)
9018 (apply 'encode-time
9019 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9020 nil nil nil))))
9021 (org-store-link-props :type "calendar" :date cd)))
9023 ((eq major-mode 'help-mode)
9024 (setq link (concat "help:" (save-excursion
9025 (goto-char (point-min))
9026 (looking-at "^[^ ]+")
9027 (match-string 0))))
9028 (org-store-link-props :type "help"))
9030 ((eq major-mode 'w3-mode)
9031 (setq cpltxt (if (and (buffer-name)
9032 (not (string-match "Untitled" (buffer-name))))
9033 (buffer-name)
9034 (url-view-url t))
9035 link (url-view-url t))
9036 (org-store-link-props :type "w3" :url (url-view-url t)))
9038 ((setq search (run-hook-with-args-until-success
9039 'org-create-file-search-functions))
9040 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9041 "::" search))
9042 (setq cpltxt (or description link)))
9044 ((eq major-mode 'image-mode)
9045 (setq cpltxt (concat "file:"
9046 (abbreviate-file-name buffer-file-name))
9047 link cpltxt)
9048 (org-store-link-props :type "image" :file buffer-file-name))
9050 ((eq major-mode 'dired-mode)
9051 ;; link to the file in the current line
9052 (let ((file (dired-get-filename nil t)))
9053 (setq file (if file
9054 (abbreviate-file-name
9055 (expand-file-name (dired-get-filename nil t)))
9056 ;; otherwise, no file so use current directory.
9057 default-directory))
9058 (setq cpltxt (concat "file:" file)
9059 link cpltxt)))
9061 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9062 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9063 (cond
9064 ((org-in-regexp "<<\\(.*?\\)>>")
9065 (setq cpltxt
9066 (concat "file:"
9067 (abbreviate-file-name
9068 (buffer-file-name (buffer-base-buffer)))
9069 "::" (match-string 1))
9070 link cpltxt))
9071 ((and (featurep 'org-id)
9072 (or (eq org-id-link-to-org-use-id t)
9073 (and (org-called-interactively-p 'any)
9074 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9075 (and (eq org-id-link-to-org-use-id
9076 'create-if-interactive-and-no-custom-id)
9077 (not custom-id))))
9078 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9079 ;; We can make a link using the ID.
9080 (setq link (condition-case nil
9081 (prog1 (org-id-store-link)
9082 (setq desc (plist-get org-store-link-plist :description)))
9083 (error
9084 ;; probably before first headline, link to file only
9085 (concat "file:"
9086 (abbreviate-file-name
9087 (buffer-file-name (buffer-base-buffer))))))))
9089 ;; Just link to current headline
9090 (setq cpltxt (concat "file:"
9091 (abbreviate-file-name
9092 (buffer-file-name (buffer-base-buffer)))))
9093 ;; Add a context search string
9094 (when (org-xor org-context-in-file-links arg)
9095 (let* ((ee (org-element-at-point))
9096 (et (org-element-type ee))
9097 (ev (plist-get (cadr ee) :value)))
9098 (setq txt (cond
9099 ((org-at-heading-p) nil)
9100 ((eq et 'keyword) ev)
9101 ((org-region-active-p)
9102 (buffer-substring (region-beginning) (region-end)))))
9103 (when (or (null txt) (string-match "\\S-" txt))
9104 (setq cpltxt
9105 (concat cpltxt "::"
9106 (condition-case nil
9107 (org-make-org-heading-search-string txt)
9108 (error "")))
9109 desc (or (and (eq et 'keyword) ev)
9110 (nth 4 (ignore-errors (org-heading-components)))
9111 "NONE")))))
9112 (if (string-match "::\\'" cpltxt)
9113 (setq cpltxt (substring cpltxt 0 -2)))
9114 (setq link cpltxt))))
9116 ((buffer-file-name (buffer-base-buffer))
9117 ;; Just link to this file here.
9118 (setq cpltxt (concat "file:"
9119 (abbreviate-file-name
9120 (buffer-file-name (buffer-base-buffer)))))
9121 ;; Add a context string
9122 (when (org-xor org-context-in-file-links arg)
9123 (setq txt (if (org-region-active-p)
9124 (buffer-substring (region-beginning) (region-end))
9125 (buffer-substring (point-at-bol) (point-at-eol))))
9126 ;; Only use search option if there is some text.
9127 (when (string-match "\\S-" txt)
9128 (setq cpltxt
9129 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9130 desc "NONE")))
9131 (setq link cpltxt))
9133 ((org-called-interactively-p 'interactive)
9134 (user-error "No method for storing a link from this buffer"))
9136 (t (setq link nil)))
9138 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9139 (setq link (or link cpltxt)
9140 desc (or desc cpltxt))
9141 (cond ((equal desc "NONE") (setq desc nil))
9142 ((string-match org-bracket-link-regexp desc)
9143 (setq desc (replace-regexp-in-string
9144 org-bracket-link-regexp
9145 (concat "\\3" (if (equal (length (match-string 0 desc))
9146 (length desc)) "*" "")) desc))))
9148 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9149 (progn
9150 (setq org-stored-links
9151 (cons (list link desc) org-stored-links))
9152 (message "Stored: %s" (or desc link))
9153 (when custom-id
9154 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9155 "::#" custom-id))
9156 (setq org-stored-links
9157 (cons (list link desc) org-stored-links))))
9158 (or agenda-link (and link (org-make-link-string link desc)))))))
9160 (defun org-store-link-props (&rest plist)
9161 "Store link properties, extract names and addresses."
9162 (let (x adr)
9163 (when (setq x (plist-get plist :from))
9164 (setq adr (mail-extract-address-components x))
9165 (setq plist (plist-put plist :fromname (car adr)))
9166 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9167 (when (setq x (plist-get plist :to))
9168 (setq adr (mail-extract-address-components x))
9169 (setq plist (plist-put plist :toname (car adr)))
9170 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9171 (let ((from (plist-get plist :from))
9172 (to (plist-get plist :to)))
9173 (when (and from to org-from-is-user-regexp)
9174 (setq plist
9175 (plist-put plist :fromto
9176 (if (string-match org-from-is-user-regexp from)
9177 (concat "to %t")
9178 (concat "from %f"))))))
9179 (setq org-store-link-plist plist))
9181 (defun org-add-link-props (&rest plist)
9182 "Add these properties to the link property list."
9183 (let (key value)
9184 (while plist
9185 (setq key (pop plist) value (pop plist))
9186 (setq org-store-link-plist
9187 (plist-put org-store-link-plist key value)))))
9189 (defun org-email-link-description (&optional fmt)
9190 "Return the description part of an email link.
9191 This takes information from `org-store-link-plist' and formats it
9192 according to FMT (default from `org-email-link-description-format')."
9193 (setq fmt (or fmt org-email-link-description-format))
9194 (let* ((p org-store-link-plist)
9195 (to (plist-get p :toaddress))
9196 (from (plist-get p :fromaddress))
9197 (table
9198 (list
9199 (cons "%c" (plist-get p :fromto))
9200 (cons "%F" (plist-get p :from))
9201 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9202 (cons "%T" (plist-get p :to))
9203 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9204 (cons "%s" (plist-get p :subject))
9205 (cons "%d" (plist-get p :date))
9206 (cons "%m" (plist-get p :message-id)))))
9207 (when (string-match "%c" fmt)
9208 ;; Check if the user wrote this message
9209 (if (and org-from-is-user-regexp from to
9210 (save-match-data (string-match org-from-is-user-regexp from)))
9211 (setq fmt (replace-match "to %t" t t fmt))
9212 (setq fmt (replace-match "from %f" t t fmt))))
9213 (org-replace-escapes fmt table)))
9215 (defun org-make-org-heading-search-string (&optional string)
9216 "Make search string for the current headline or STRING."
9217 (let ((s (or string
9218 (and (derived-mode-p 'org-mode)
9219 (save-excursion
9220 (org-back-to-heading t)
9221 (plist-get (cadr (org-element-at-point))
9222 :raw-value)))))
9223 (lines org-context-in-file-links))
9224 (or string (setq s (concat "*" s))) ; Add * for headlines
9225 (when (and string (integerp lines) (> lines 0))
9226 (let ((slines (org-split-string s "\n")))
9227 (when (< lines (length slines))
9228 (setq s (mapconcat
9229 'identity
9230 (reverse (nthcdr (- (length slines) lines)
9231 (reverse slines))) "\n")))))
9232 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9234 (defun org-make-link-string (link &optional description)
9235 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9236 (unless (string-match "\\S-" link)
9237 (error "Empty link"))
9238 (when (and description
9239 (stringp description)
9240 (not (string-match "\\S-" description)))
9241 (setq description nil))
9242 (when (stringp description)
9243 ;; Remove brackets from the description, they are fatal.
9244 (while (string-match "\\[" description)
9245 (setq description (replace-match "{" t t description)))
9246 (while (string-match "\\]" description)
9247 (setq description (replace-match "}" t t description))))
9248 (when (equal link description)
9249 ;; No description needed, it is identical
9250 (setq description nil))
9251 (when (and (not description)
9252 (not (string-match (org-image-file-name-regexp) link))
9253 (not (equal link (org-link-escape link))))
9254 (setq description (org-extract-attributes link)))
9255 (setq link
9256 (cond ((string-match (org-image-file-name-regexp) link) link)
9257 ((string-match org-link-types-re link)
9258 (concat (match-string 1 link)
9259 (org-link-escape (substring link (match-end 1)))))
9260 (t (org-link-escape link))))
9261 (concat "[[" link "]"
9262 (if description (concat "[" description "]") "")
9263 "]"))
9265 (defconst org-link-escape-chars
9266 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9267 "List of characters that should be escaped in link.
9268 This is the list that is used for internal purposes.")
9270 (defconst org-link-escape-chars-browser
9271 '(?\ )
9272 "List of escapes for characters that are problematic in links.
9273 This is the list that is used before handing over to the browser.")
9275 (defun org-link-escape (text &optional table merge)
9276 "Return percent escaped representation of TEXT.
9277 TEXT is a string with the text to escape.
9278 Optional argument TABLE is a list with characters that should be
9279 escaped. When nil, `org-link-escape-chars' is used.
9280 If optional argument MERGE is set, merge TABLE into
9281 `org-link-escape-chars'."
9282 (cond
9283 ((and table merge)
9284 (mapc (lambda (defchr)
9285 (unless (member defchr table)
9286 (setq table (cons defchr table)))) org-link-escape-chars))
9287 ((null table)
9288 (setq table org-link-escape-chars)))
9289 (mapconcat
9290 (lambda (char)
9291 (if (or (member char table)
9292 (and (or (< char 32) (= char 37) (> char 126))
9293 org-url-hexify-p))
9294 (mapconcat (lambda (sequence-element)
9295 (format "%%%.2X" sequence-element))
9296 (or (encode-coding-char char 'utf-8)
9297 (error "Unable to percent escape character: %s"
9298 (char-to-string char))) "")
9299 (char-to-string char))) text ""))
9301 (defun org-link-unescape (str)
9302 "Unhex hexified Unicode strings as returned from the JavaScript function
9303 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9304 (unless (and (null str) (string= "" str))
9305 (let ((pos 0) (case-fold-search t) unhexed)
9306 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9307 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9308 (setq str (replace-match unhexed t t str))
9309 (setq pos (+ pos (length unhexed))))))
9310 str)
9312 (defun org-link-unescape-compound (hex)
9313 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9314 Note: this function also decodes single byte encodings like
9315 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9316 (save-match-data
9317 (let* ((bytes (cdr (split-string hex "%")))
9318 (ret "")
9319 (eat 0)
9320 (sum 0))
9321 (while bytes
9322 (let* ((val (string-to-number (pop bytes) 16))
9323 (shift-xor
9324 (if (= 0 eat)
9325 (cond
9326 ((>= val 252) (cons 6 252))
9327 ((>= val 248) (cons 5 248))
9328 ((>= val 240) (cons 4 240))
9329 ((>= val 224) (cons 3 224))
9330 ((>= val 192) (cons 2 192))
9331 (t (cons 0 0)))
9332 (cons 6 128))))
9333 (if (>= val 192) (setq eat (car shift-xor)))
9334 (setq val (logxor val (cdr shift-xor)))
9335 (setq sum (+ (lsh sum (car shift-xor)) val))
9336 (if (> eat 0) (setq eat (- eat 1)))
9337 (cond
9338 ((= 0 eat) ;multi byte
9339 (setq ret (concat ret (org-char-to-string sum)))
9340 (setq sum 0))
9341 ((not bytes) ; single byte(s)
9342 (setq ret (org-link-unescape-single-byte-sequence hex))))
9343 )) ;; end (while bytes
9344 ret )))
9346 (defun org-link-unescape-single-byte-sequence (hex)
9347 "Unhexify hex-encoded single byte character sequences."
9348 (mapconcat (lambda (byte)
9349 (char-to-string (string-to-number byte 16)))
9350 (cdr (split-string hex "%")) ""))
9352 (defun org-xor (a b)
9353 "Exclusive or."
9354 (if a (not b) b))
9356 (defun org-fixup-message-id-for-http (s)
9357 "Replace special characters in a message id, so it can be used in an http query."
9358 (when (string-match "%" s)
9359 (setq s (mapconcat (lambda (c)
9360 (if (eq c ?%)
9361 "%25"
9362 (char-to-string c)))
9363 s "")))
9364 (while (string-match "<" s)
9365 (setq s (replace-match "%3C" t t s)))
9366 (while (string-match ">" s)
9367 (setq s (replace-match "%3E" t t s)))
9368 (while (string-match "@" s)
9369 (setq s (replace-match "%40" t t s)))
9372 (defun org-link-prettify (link)
9373 "Return a human-readable representation of LINK.
9374 The car of LINK must be a raw link the cdr of LINK must be either
9375 a link description or nil."
9376 (let ((desc (or (cadr link) "<no description>")))
9377 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9378 "<" (car link) ">")))
9380 ;;;###autoload
9381 (defun org-insert-link-global ()
9382 "Insert a link like Org-mode does.
9383 This command can be called in any mode to insert a link in Org-mode syntax."
9384 (interactive)
9385 (org-load-modules-maybe)
9386 (org-run-like-in-org-mode 'org-insert-link))
9388 (defun org-insert-all-links (&optional keep)
9389 "Insert all links in `org-stored-links'."
9390 (interactive "P")
9391 (let ((links (copy-sequence org-stored-links)) l)
9392 (while (setq l (if keep (pop links) (pop org-stored-links)))
9393 (insert "- ")
9394 (org-insert-link nil (car l) (cadr l))
9395 (insert "\n"))))
9397 (defun org-link-fontify-links-to-this-file ()
9398 "Fontify links to the current file in `org-stored-links'."
9399 (let ((f (buffer-file-name)) a b)
9400 (setq a (mapcar (lambda(l)
9401 (let ((ll (car l)))
9402 (when (and (string-match "^file:\\(.+\\)::" ll)
9403 (equal f (expand-file-name (match-string 1 ll))))
9404 ll)))
9405 org-stored-links))
9406 (when (featurep 'org-id)
9407 (setq b (mapcar (lambda(l)
9408 (let ((ll (car l)))
9409 (when (and (string-match "^id:\\(.+\\)$" ll)
9410 (equal f (expand-file-name
9411 (or (org-id-find-id-file
9412 (match-string 1 ll)) ""))))
9413 ll)))
9414 org-stored-links)))
9415 (mapcar (lambda(l)
9416 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9417 (delq nil (append a b)))))
9419 (defvar org-link-links-in-this-file nil)
9420 (defun org-insert-link (&optional complete-file link-location default-description)
9421 "Insert a link. At the prompt, enter the link.
9423 Completion can be used to insert any of the link protocol prefixes like
9424 http or ftp in use.
9426 The history can be used to select a link previously stored with
9427 `org-store-link'. When the empty string is entered (i.e. if you just
9428 press RET at the prompt), the link defaults to the most recently
9429 stored link. As SPC triggers completion in the minibuffer, you need to
9430 use M-SPC or C-q SPC to force the insertion of a space character.
9432 You will also be prompted for a description, and if one is given, it will
9433 be displayed in the buffer instead of the link.
9435 If there is already a link at point, this command will allow you to edit link
9436 and description parts.
9438 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9439 be selected using completion. The path to the file will be relative to the
9440 current directory if the file is in the current directory or a subdirectory.
9441 Otherwise, the link will be the absolute path as completed in the minibuffer
9442 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9443 option `org-link-file-path-type'.
9445 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9446 the current directory or below.
9448 With three \\[universal-argument] prefixes, negate the meaning of
9449 `org-keep-stored-link-after-insertion'.
9451 If `org-make-link-description-function' is non-nil, this function will be
9452 called with the link target, and the result will be the default
9453 link description.
9455 If the LINK-LOCATION parameter is non-nil, this value will be
9456 used as the link location instead of reading one interactively.
9458 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9459 be used as the default description."
9460 (interactive "P")
9461 (let* ((wcf (current-window-configuration))
9462 (origbuf (current-buffer))
9463 (region (if (org-region-active-p)
9464 (buffer-substring (region-beginning) (region-end))))
9465 (remove (and region (list (region-beginning) (region-end))))
9466 (desc region)
9467 tmphist ; byte-compile incorrectly complains about this
9468 (link link-location)
9469 (abbrevs org-link-abbrev-alist-local)
9470 entry file all-prefixes auto-desc)
9471 (cond
9472 (link-location) ; specified by arg, just use it.
9473 ((org-in-regexp org-bracket-link-regexp 1)
9474 ;; We do have a link at point, and we are going to edit it.
9475 (setq remove (list (match-beginning 0) (match-end 0)))
9476 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9477 (setq link (read-string "Link: "
9478 (org-link-unescape
9479 (org-match-string-no-properties 1)))))
9480 ((or (org-in-regexp org-angle-link-re)
9481 (org-in-regexp org-plain-link-re))
9482 ;; Convert to bracket link
9483 (setq remove (list (match-beginning 0) (match-end 0))
9484 link (read-string "Link: "
9485 (org-remove-angle-brackets (match-string 0)))))
9486 ((member complete-file '((4) (16)))
9487 ;; Completing read for file names.
9488 (setq link (org-file-complete-link complete-file)))
9490 ;; Read link, with completion for stored links.
9491 (org-link-fontify-links-to-this-file)
9492 (org-switch-to-buffer-other-window "*Org Links*")
9493 (with-current-buffer "*Org Links*"
9494 (erase-buffer)
9495 (insert "Insert a link.
9496 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9497 (when org-stored-links
9498 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9499 (insert (mapconcat 'org-link-prettify
9500 (reverse org-stored-links) "\n")))
9501 (goto-char (point-min)))
9502 (let ((cw (selected-window)))
9503 (select-window (get-buffer-window "*Org Links*" 'visible))
9504 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9505 (unless (pos-visible-in-window-p (point-max))
9506 (org-fit-window-to-buffer))
9507 (and (window-live-p cw) (select-window cw)))
9508 ;; Fake a link history, containing the stored links.
9509 (setq tmphist (append (mapcar 'car org-stored-links)
9510 org-insert-link-history))
9511 (setq all-prefixes (append (mapcar 'car abbrevs)
9512 (mapcar 'car org-link-abbrev-alist)
9513 org-link-types))
9514 (unwind-protect
9515 (progn
9516 (setq link
9517 (org-completing-read
9518 "Link: "
9519 (append
9520 (mapcar (lambda (x) (concat x ":"))
9521 all-prefixes)
9522 (mapcar 'car org-stored-links))
9523 nil nil nil
9524 'tmphist
9525 (caar org-stored-links)))
9526 (if (not (string-match "\\S-" link))
9527 (error "No link selected"))
9528 (mapc (lambda(l)
9529 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9530 org-stored-links)
9531 (if (or (member link all-prefixes)
9532 (and (equal ":" (substring link -1))
9533 (member (substring link 0 -1) all-prefixes)
9534 (setq link (substring link 0 -1))))
9535 (setq link (with-current-buffer origbuf
9536 (org-link-try-special-completion link)))))
9537 (set-window-configuration wcf)
9538 (kill-buffer "*Org Links*"))
9539 (setq entry (assoc link org-stored-links))
9540 (or entry (push link org-insert-link-history))
9541 (setq desc (or desc (nth 1 entry)))))
9543 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9544 (not org-keep-stored-link-after-insertion))
9545 (setq org-stored-links (delq (assoc link org-stored-links)
9546 org-stored-links)))
9548 (if (string-match org-plain-link-re link)
9549 ;; URL-like link, normalize the use of angular brackets.
9550 (setq link (org-remove-angle-brackets link)))
9552 ;; Check if we are linking to the current file with a search
9553 ;; option If yes, simplify the link by using only the search
9554 ;; option.
9555 (when (and buffer-file-name
9556 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9557 (let* ((path (match-string 1 link))
9558 (case-fold-search nil)
9559 (search (match-string 2 link)))
9560 (save-match-data
9561 (if (equal (file-truename buffer-file-name) (file-truename path))
9562 ;; We are linking to this same file, with a search option
9563 (setq link search)))))
9565 ;; Check if we can/should use a relative path. If yes, simplify the link
9566 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9567 (let* ((type (match-string 1 link))
9568 (path (match-string 2 link))
9569 (origpath path)
9570 (case-fold-search nil))
9571 (cond
9572 ((or (eq org-link-file-path-type 'absolute)
9573 (equal complete-file '(16)))
9574 (setq path (abbreviate-file-name (expand-file-name path))))
9575 ((eq org-link-file-path-type 'noabbrev)
9576 (setq path (expand-file-name path)))
9577 ((eq org-link-file-path-type 'relative)
9578 (setq path (file-relative-name path)))
9580 (save-match-data
9581 (if (string-match (concat "^" (regexp-quote
9582 (expand-file-name
9583 (file-name-as-directory
9584 default-directory))))
9585 (expand-file-name path))
9586 ;; We are linking a file with relative path name.
9587 (setq path (substring (expand-file-name path)
9588 (match-end 0)))
9589 (setq path (abbreviate-file-name (expand-file-name path)))))))
9590 (setq link (concat type path))
9591 (if (equal desc origpath)
9592 (setq desc path))))
9594 (if org-make-link-description-function
9595 (setq desc
9596 (or (condition-case nil
9597 (funcall org-make-link-description-function link desc)
9598 (error (progn (message "Can't get link description from `%s'"
9599 (symbol-name org-make-link-description-function))
9600 (sit-for 2) nil)))
9601 (read-string "Description: " default-description)))
9602 (if default-description (setq desc default-description)
9603 (setq desc (or (and auto-desc desc)
9604 (read-string "Description: " desc)))))
9606 (unless (string-match "\\S-" desc) (setq desc nil))
9607 (if remove (apply 'delete-region remove))
9608 (insert (org-make-link-string link desc))))
9610 (defun org-link-try-special-completion (type)
9611 "If there is completion support for link type TYPE, offer it."
9612 (let ((fun (intern (concat "org-" type "-complete-link"))))
9613 (if (functionp fun)
9614 (funcall fun)
9615 (read-string "Link (no completion support): " (concat type ":")))))
9617 (defun org-file-complete-link (&optional arg)
9618 "Create a file link using completion."
9619 (let (file link)
9620 (setq file (org-iread-file-name "File: "))
9621 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9622 (pwd1 (file-name-as-directory (abbreviate-file-name
9623 (expand-file-name ".")))))
9624 (cond
9625 ((equal arg '(16))
9626 (setq link (concat
9627 "file:"
9628 (abbreviate-file-name (expand-file-name file)))))
9629 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9630 (setq link (concat "file:" (match-string 1 file))))
9631 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9632 (expand-file-name file))
9633 (setq link (concat
9634 "file:" (match-string 1 (expand-file-name file)))))
9635 (t (setq link (concat "file:" file)))))
9636 link))
9638 (defun org-iread-file-name (&rest args)
9639 "Read-file-name using `ido-mode' speedup if available.
9640 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9641 See `read-file-name' for a description of parameters."
9642 (org-without-partial-completion
9643 (if (and org-completion-use-ido
9644 (fboundp 'ido-read-file-name)
9645 (boundp 'ido-mode) ido-mode
9646 (listp (second args)))
9647 (let ((ido-enter-matching-directory nil))
9648 (apply 'ido-read-file-name args))
9649 (apply 'read-file-name args))))
9651 (defun org-completing-read (&rest args)
9652 "Completing-read with SPACE being a normal character."
9653 (let ((enable-recursive-minibuffers t)
9654 (minibuffer-local-completion-map
9655 (copy-keymap minibuffer-local-completion-map)))
9656 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9657 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9658 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9659 (apply 'org-icompleting-read args)))
9661 (defun org-completing-read-no-i (&rest args)
9662 (let (org-completion-use-ido org-completion-use-iswitchb)
9663 (apply 'org-completing-read args)))
9665 (defun org-iswitchb-completing-read (prompt choices &rest args)
9666 "Use iswitch as a completing-read replacement to choose from choices.
9667 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9668 from."
9669 (let* ((iswitchb-use-virtual-buffers nil)
9670 (iswitchb-make-buflist-hook
9671 (lambda ()
9672 (setq iswitchb-temp-buflist choices))))
9673 (iswitchb-read-buffer prompt)))
9675 (defun org-icompleting-read (&rest args)
9676 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9677 (org-without-partial-completion
9678 (if (and org-completion-use-ido
9679 (fboundp 'ido-completing-read)
9680 (boundp 'ido-mode) ido-mode
9681 (listp (second args)))
9682 (let ((ido-enter-matching-directory nil))
9683 (apply 'ido-completing-read (concat (car args))
9684 (if (consp (car (nth 1 args)))
9685 (mapcar 'car (nth 1 args))
9686 (nth 1 args))
9687 (cddr args)))
9688 (if (and org-completion-use-iswitchb
9689 (boundp 'iswitchb-mode) iswitchb-mode
9690 (listp (second args)))
9691 (apply 'org-iswitchb-completing-read (concat (car args))
9692 (if (consp (car (nth 1 args)))
9693 (mapcar 'car (nth 1 args))
9694 (nth 1 args))
9695 (cddr args))
9696 (apply 'completing-read args)))))
9698 (defun org-extract-attributes (s)
9699 "Extract the attributes cookie from a string and set as text property."
9700 (let (a attr (start 0) key value)
9701 (save-match-data
9702 (when (string-match "{{\\([^}]+\\)}}$" s)
9703 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9704 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9705 (setq key (match-string 1 a) value (match-string 2 a)
9706 start (match-end 0)
9707 attr (plist-put attr (intern key) value))))
9708 (org-add-props s nil 'org-attr attr))
9711 (defun org-extract-attributes-from-string (tag)
9712 (let (key value attr)
9713 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9714 (setq key (match-string 1 tag) value (match-string 2 tag)
9715 tag (replace-match "" t t tag)
9716 attr (plist-put attr (intern key) value)))
9717 (cons tag attr)))
9719 (defun org-attributes-to-string (plist)
9720 "Format a property list into an HTML attribute list."
9721 (let ((s "") key value)
9722 (while plist
9723 (setq key (pop plist) value (pop plist))
9724 (and value
9725 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9728 ;;; Opening/following a link
9730 (defvar org-link-search-failed nil)
9732 (defvar org-open-link-functions nil
9733 "Hook for functions finding a plain text link.
9734 These functions must take a single argument, the link content.
9735 They will be called for links that look like [[link text][description]]
9736 when LINK TEXT does not have a protocol like \"http:\" and does not look
9737 like a filename (e.g. \"./blue.png\").
9739 These functions will be called *before* Org attempts to resolve the
9740 link by doing text searches in the current buffer - so if you want a
9741 link \"[[target]]\" to still find \"<<target>>\", your function should
9742 handle this as a special case.
9744 When the function does handle the link, it must return a non-nil value.
9745 If it decides that it is not responsible for this link, it must return
9746 nil to indicate that that Org-mode can continue with other options
9747 like exact and fuzzy text search.")
9749 (defun org-next-link ()
9750 "Move forward to the next link.
9751 If the link is in hidden text, expose it."
9752 (interactive)
9753 (when (and org-link-search-failed (eq this-command last-command))
9754 (goto-char (point-min))
9755 (message "Link search wrapped back to beginning of buffer"))
9756 (setq org-link-search-failed nil)
9757 (let* ((pos (point))
9758 (ct (org-context))
9759 (a (assoc :link ct)))
9760 (if a (goto-char (nth 2 a)))
9761 (if (re-search-forward org-any-link-re nil t)
9762 (progn
9763 (goto-char (match-beginning 0))
9764 (if (outline-invisible-p) (org-show-context)))
9765 (goto-char pos)
9766 (setq org-link-search-failed t)
9767 (error "No further link found"))))
9769 (defun org-previous-link ()
9770 "Move backward to the previous link.
9771 If the link is in hidden text, expose it."
9772 (interactive)
9773 (when (and org-link-search-failed (eq this-command last-command))
9774 (goto-char (point-max))
9775 (message "Link search wrapped back to end of buffer"))
9776 (setq org-link-search-failed nil)
9777 (let* ((pos (point))
9778 (ct (org-context))
9779 (a (assoc :link ct)))
9780 (if a (goto-char (nth 1 a)))
9781 (if (re-search-backward org-any-link-re nil t)
9782 (progn
9783 (goto-char (match-beginning 0))
9784 (if (outline-invisible-p) (org-show-context)))
9785 (goto-char pos)
9786 (setq org-link-search-failed t)
9787 (error "No further link found"))))
9789 (defun org-translate-link (s)
9790 "Translate a link string if a translation function has been defined."
9791 (if (and org-link-translation-function
9792 (fboundp org-link-translation-function)
9793 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9794 (progn
9795 (setq s (funcall org-link-translation-function
9796 (match-string 1 s) (match-string 2 s)))
9797 (concat (car s) ":" (cdr s)))
9800 (defun org-translate-link-from-planner (type path)
9801 "Translate a link from Emacs Planner syntax so that Org can follow it.
9802 This is still an experimental function, your mileage may vary."
9803 (cond
9804 ((member type '("http" "https" "news" "ftp"))
9805 ;; standard Internet links are the same.
9806 nil)
9807 ((and (equal type "irc") (string-match "^//" path))
9808 ;; Planner has two / at the beginning of an irc link, we have 1.
9809 ;; We should have zero, actually....
9810 (setq path (substring path 1)))
9811 ((and (equal type "lisp") (string-match "^/" path))
9812 ;; Planner has a slash, we do not.
9813 (setq type "elisp" path (substring path 1)))
9814 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9815 ;; A typical message link. Planner has the id after the final slash,
9816 ;; we separate it with a hash mark
9817 (setq path (concat (match-string 1 path) "#"
9818 (org-remove-angle-brackets (match-string 2 path)))))
9820 (cons type path))
9822 (defun org-find-file-at-mouse (ev)
9823 "Open file link or URL at mouse."
9824 (interactive "e")
9825 (mouse-set-point ev)
9826 (org-open-at-point 'in-emacs))
9828 (defun org-open-at-mouse (ev)
9829 "Open file link or URL at mouse.
9830 See the docstring of `org-open-file' for details."
9831 (interactive "e")
9832 (mouse-set-point ev)
9833 (if (eq major-mode 'org-agenda-mode)
9834 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9835 (org-open-at-point))
9837 (defvar org-window-config-before-follow-link nil
9838 "The window configuration before following a link.
9839 This is saved in case the need arises to restore it.")
9841 (defvar org-open-link-marker (make-marker)
9842 "Marker pointing to the location where `org-open-at-point; was called.")
9844 ;;;###autoload
9845 (defun org-open-at-point-global ()
9846 "Follow a link like Org-mode does.
9847 This command can be called in any mode to follow a link that has
9848 Org-mode syntax."
9849 (interactive)
9850 (org-run-like-in-org-mode 'org-open-at-point))
9852 ;;;###autoload
9853 (defun org-open-link-from-string (s &optional arg reference-buffer)
9854 "Open a link in the string S, as if it was in Org-mode."
9855 (interactive "sLink: \nP")
9856 (let ((reference-buffer (or reference-buffer (current-buffer))))
9857 (with-temp-buffer
9858 (let ((org-inhibit-startup (not reference-buffer)))
9859 (org-mode)
9860 (insert s)
9861 (goto-char (point-min))
9862 (when reference-buffer
9863 (setq org-link-abbrev-alist-local
9864 (with-current-buffer reference-buffer
9865 org-link-abbrev-alist-local)))
9866 (org-open-at-point arg reference-buffer)))))
9868 (defvar org-open-at-point-functions nil
9869 "Hook that is run when following a link at point.
9871 Functions in this hook must return t if they identify and follow
9872 a link at point. If they don't find anything interesting at point,
9873 they must return nil.")
9875 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9876 (defun org-open-at-point (&optional arg reference-buffer)
9877 "Open link at or after point.
9878 If there is no link at point, this function will search forward up to
9879 the end of the current line.
9880 Normally, files will be opened by an appropriate application. If the
9881 optional prefix argument ARG is non-nil, Emacs will visit the file.
9882 With a double prefix argument, try to open outside of Emacs, in the
9883 application the system uses for this file type."
9884 (interactive "P")
9885 ;; if in a code block, then open the block's results
9886 (unless (call-interactively #'org-babel-open-src-block-result)
9887 (org-load-modules-maybe)
9888 (move-marker org-open-link-marker (point))
9889 (setq org-window-config-before-follow-link (current-window-configuration))
9890 (org-remove-occur-highlights nil nil t)
9891 (cond
9892 ((and (org-at-heading-p)
9893 (not (org-at-timestamp-p t))
9894 (not (org-in-regexp
9895 (concat org-plain-link-re "\\|"
9896 org-bracket-link-regexp "\\|"
9897 org-angle-link-re "\\|"
9898 "[ \t]:[^ \t\n]+:[ \t]*$")))
9899 (not (get-text-property (point) 'org-linked-text)))
9900 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9901 (lk0 (car lkall))
9902 (lk (if (stringp lk0) (list lk0) lk0))
9903 (lkend (cdr lkall)))
9904 (mapcar (lambda(l)
9905 (search-forward l nil lkend)
9906 (goto-char (match-beginning 0))
9907 (org-open-at-point))
9908 lk))
9909 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9910 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9911 ((and (org-at-timestamp-p t)
9912 (not (org-in-regexp org-bracket-link-regexp)))
9913 (org-follow-timestamp-link))
9914 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9915 (not (org-in-regexp org-any-link-re)))
9916 (org-footnote-action))
9918 (let (type path link line search (pos (point)))
9919 (catch 'match
9920 (save-excursion
9921 (skip-chars-forward "^]\n\r")
9922 (when (org-in-regexp org-bracket-link-regexp 1)
9923 (setq link (org-extract-attributes
9924 (org-link-unescape (org-match-string-no-properties 1))))
9925 (while (string-match " *\n *" link)
9926 (setq link (replace-match " " t t link)))
9927 (setq link (org-link-expand-abbrev link))
9928 (cond
9929 ((or (file-name-absolute-p link)
9930 (string-match "^\\.\\.?/" link))
9931 (setq type "file" path link))
9932 ((string-match org-link-re-with-space3 link)
9933 (setq type (match-string 1 link) path (match-string 2 link)))
9934 ((string-match "^help:+\\(.+\\)" link)
9935 (setq type "help" path (match-string 1 link)))
9936 (t (setq type "thisfile" path link)))
9937 (throw 'match t)))
9939 (when (get-text-property (point) 'org-linked-text)
9940 (setq type "thisfile"
9941 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9942 (1+ (point)) (point))
9943 path (buffer-substring
9944 (or (previous-single-property-change pos 'org-linked-text)
9945 (point-min))
9946 (or (next-single-property-change pos 'org-linked-text)
9947 (point-max))))
9948 (throw 'match t))
9950 (save-excursion
9951 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9952 (when (or (org-in-regexp org-angle-link-re)
9953 (and plinkpos (goto-char (car plinkpos))
9954 (save-match-data (not (looking-back "\\[\\[")))))
9955 (setq type (match-string 1)
9956 path (org-link-unescape (match-string 2)))
9957 (throw 'match t))))
9958 (save-excursion
9959 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9960 (setq type "tags"
9961 path (match-string 1))
9962 (while (string-match ":" path)
9963 (setq path (replace-match "+" t t path)))
9964 (throw 'match t)))
9965 (when (org-in-regexp "<\\([^><\n]+\\)>")
9966 (setq type "tree-match"
9967 path (match-string 1))
9968 (throw 'match t)))
9969 (unless path
9970 (user-error "No link found"))
9972 ;; switch back to reference buffer
9973 ;; needed when if called in a temporary buffer through
9974 ;; org-open-link-from-string
9975 (with-current-buffer (or reference-buffer (current-buffer))
9977 ;; Remove any trailing spaces in path
9978 (if (string-match " +\\'" path)
9979 (setq path (replace-match "" t t path)))
9980 (if (and org-link-translation-function
9981 (fboundp org-link-translation-function))
9982 ;; Check if we need to translate the link
9983 (let ((tmp (funcall org-link-translation-function type path)))
9984 (setq type (car tmp) path (cdr tmp))))
9986 (cond
9988 ((assoc type org-link-protocols)
9989 (funcall (nth 1 (assoc type org-link-protocols)) path))
9991 ((equal type "help")
9992 (let ((f-or-v (intern path)))
9993 (cond ((fboundp f-or-v)
9994 (describe-function f-or-v))
9995 ((boundp f-or-v)
9996 (describe-variable f-or-v))
9997 (t (error "Not a known function or variable")))))
9999 ((equal type "mailto")
10000 (let ((cmd (car org-link-mailto-program))
10001 (args (cdr org-link-mailto-program)) args1
10002 (address path) (subject "") a)
10003 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10004 (setq address (match-string 1 path)
10005 subject (org-link-escape (match-string 2 path))))
10006 (while args
10007 (cond
10008 ((not (stringp (car args))) (push (pop args) args1))
10009 (t (setq a (pop args))
10010 (if (string-match "%a" a)
10011 (setq a (replace-match address t t a)))
10012 (if (string-match "%s" a)
10013 (setq a (replace-match subject t t a)))
10014 (push a args1))))
10015 (apply cmd (nreverse args1))))
10017 ((member type '("http" "https" "ftp" "news"))
10018 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10019 (org-link-escape
10020 path org-link-escape-chars-browser)
10021 path))))
10023 ((string= type "doi")
10024 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10025 (org-link-escape
10026 path org-link-escape-chars-browser)
10027 path))))
10029 ((member type '("message"))
10030 (browse-url (concat type ":" path)))
10032 ((string= type "tags")
10033 (org-tags-view arg path))
10035 ((string= type "tree-match")
10036 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10038 ((string= type "file")
10039 (if (string-match "::\\([0-9]+\\)\\'" path)
10040 (setq line (string-to-number (match-string 1 path))
10041 path (substring path 0 (match-beginning 0)))
10042 (if (string-match "::\\(.+\\)\\'" path)
10043 (setq search (match-string 1 path)
10044 path (substring path 0 (match-beginning 0)))))
10045 (if (string-match "[*?{]" (file-name-nondirectory path))
10046 (dired path)
10047 (org-open-file path arg line search)))
10049 ((string= type "shell")
10050 (let ((buf (generate-new-buffer "*Org Shell Output"))
10051 (cmd path))
10052 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10053 (string-match org-confirm-shell-link-not-regexp cmd))
10054 (not org-confirm-shell-link-function)
10055 (funcall org-confirm-shell-link-function
10056 (format "Execute \"%s\" in shell? "
10057 (org-add-props cmd nil
10058 'face 'org-warning))))
10059 (progn
10060 (message "Executing %s" cmd)
10061 (shell-command cmd buf)
10062 (if (featurep 'midnight)
10063 (setq clean-buffer-list-kill-buffer-names
10064 (cons buf clean-buffer-list-kill-buffer-names))))
10065 (error "Abort"))))
10067 ((string= type "elisp")
10068 (let ((cmd path))
10069 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10070 (string-match org-confirm-elisp-link-not-regexp cmd))
10071 (not org-confirm-elisp-link-function)
10072 (funcall org-confirm-elisp-link-function
10073 (format "Execute \"%s\" as elisp? "
10074 (org-add-props cmd nil
10075 'face 'org-warning))))
10076 (message "%s => %s" cmd
10077 (if (equal (string-to-char cmd) ?\()
10078 (eval (read cmd))
10079 (call-interactively (read cmd))))
10080 (error "Abort"))))
10082 ((and (string= type "thisfile")
10083 (run-hook-with-args-until-success
10084 'org-open-link-functions path)))
10086 ((string= type "thisfile")
10087 (if arg
10088 (switch-to-buffer-other-window
10089 (org-get-buffer-for-internal-link (current-buffer)))
10090 (org-mark-ring-push))
10091 (let ((cmd `(org-link-search
10092 ,path
10093 ,(cond ((equal arg '(4)) ''occur)
10094 ((equal arg '(16)) ''org-occur))
10095 ,pos)))
10096 (condition-case nil (let ((org-link-search-inhibit-query t))
10097 (eval cmd))
10098 (error (progn (widen) (eval cmd))))))
10100 (t (browse-url-at-point)))))))
10101 (move-marker org-open-link-marker nil)
10102 (run-hook-with-args 'org-follow-link-hook)))
10104 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10105 "Offer links in the current entry and return the selected link.
10106 If there is only one link, return it.
10107 If NTH is an integer, return the NTH link found.
10108 If ZERO is a string, check also this string for a link, and if
10109 there is one, return it."
10110 (with-current-buffer buffer
10111 (save-excursion
10112 (save-restriction
10113 (widen)
10114 (goto-char marker)
10115 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10116 "\\(" org-angle-link-re "\\)\\|"
10117 "\\(" org-plain-link-re "\\)"))
10118 (cnt ?0)
10119 (in-emacs (if (integerp nth) nil nth))
10120 have-zero end links link c)
10121 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10122 (push (match-string 0 zero) links)
10123 (setq cnt (1- cnt) have-zero t))
10124 (save-excursion
10125 (org-back-to-heading t)
10126 (setq end (save-excursion (outline-next-heading) (point)))
10127 (while (re-search-forward re end t)
10128 (push (match-string 0) links))
10129 (setq links (org-uniquify (reverse links))))
10130 (cond
10131 ((null links)
10132 (message "No links"))
10133 ((equal (length links) 1)
10134 (setq link (car links)))
10135 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10136 (setq link (nth (if have-zero nth (1- nth)) links)))
10137 (t ; we have to select a link
10138 (save-excursion
10139 (save-window-excursion
10140 (delete-other-windows)
10141 (with-output-to-temp-buffer "*Select Link*"
10142 (mapc (lambda (l)
10143 (if (not (string-match org-bracket-link-regexp l))
10144 (princ (format "[%c] %s\n" (incf cnt)
10145 (org-remove-angle-brackets l)))
10146 (if (match-end 3)
10147 (princ (format "[%c] %s (%s)\n" (incf cnt)
10148 (match-string 3 l) (match-string 1 l)))
10149 (princ (format "[%c] %s\n" (incf cnt)
10150 (match-string 1 l))))))
10151 links))
10152 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10153 (message "Select link to open, RET to open all:")
10154 (setq c (read-char-exclusive))
10155 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10156 (when (equal c ?q) (error "Abort"))
10157 (if (equal c ?\C-m)
10158 (setq link links)
10159 (setq nth (- c ?0))
10160 (if have-zero (setq nth (1+ nth)))
10161 (unless (and (integerp nth) (>= (length links) nth))
10162 (error "Invalid link selection"))
10163 (setq link (nth (1- nth) links)))))
10164 (cons link end))))))
10166 ;; Add special file links that specify the way of opening
10168 (org-add-link-type "file+sys" 'org-open-file-with-system)
10169 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10170 (defun org-open-file-with-system (path)
10171 "Open file at PATH using the system way of opening it."
10172 (org-open-file path 'system))
10173 (defun org-open-file-with-emacs (path)
10174 "Open file at PATH in Emacs."
10175 (org-open-file path 'emacs))
10176 (defun org-remove-file-link-modifiers ()
10177 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10178 (goto-char (point-min))
10179 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10180 (org-if-unprotected
10181 (replace-match "file:" t t))))
10182 (eval-after-load "org-exp"
10183 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10184 'org-remove-file-link-modifiers))
10186 ;;; File search
10188 (defvar org-create-file-search-functions nil
10189 "List of functions to construct the right search string for a file link.
10190 These functions are called in turn with point at the location to
10191 which the link should point.
10193 A function in the hook should first test if it would like to
10194 handle this file type, for example by checking the `major-mode'
10195 or the file extension. If it decides not to handle this file, it
10196 should just return nil to give other functions a chance. If it
10197 does handle the file, it must return the search string to be used
10198 when following the link. The search string will be part of the
10199 file link, given after a double colon, and `org-open-at-point'
10200 will automatically search for it. If special measures must be
10201 taken to make the search successful, another function should be
10202 added to the companion hook `org-execute-file-search-functions',
10203 which see.
10205 A function in this hook may also use `setq' to set the variable
10206 `description' to provide a suggestion for the descriptive text to
10207 be used for this link when it gets inserted into an Org-mode
10208 buffer with \\[org-insert-link].")
10210 (defvar org-execute-file-search-functions nil
10211 "List of functions to execute a file search triggered by a link.
10213 Functions added to this hook must accept a single argument, the
10214 search string that was part of the file link, the part after the
10215 double colon. The function must first check if it would like to
10216 handle this search, for example by checking the `major-mode' or
10217 the file extension. If it decides not to handle this search, it
10218 should just return nil to give other functions a chance. If it
10219 does handle the search, it must return a non-nil value to keep
10220 other functions from trying.
10222 Each function can access the current prefix argument through the
10223 variable `current-prefix-argument'. Note that a single prefix is
10224 used to force opening a link in Emacs, so it may be good to only
10225 use a numeric or double prefix to guide the search function.
10227 In case this is needed, a function in this hook can also restore
10228 the window configuration before `org-open-at-point' was called using:
10230 (set-window-configuration org-window-config-before-follow-link)")
10232 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10233 (defun org-link-search (s &optional type avoid-pos stealth)
10234 "Search for a link search option.
10235 If S is surrounded by forward slashes, it is interpreted as a
10236 regular expression. In org-mode files, this will create an `org-occur'
10237 sparse tree. In ordinary files, `occur' will be used to list matches.
10238 If the current buffer is in `dired-mode', grep will be used to search
10239 in all files. If AVOID-POS is given, ignore matches near that position.
10241 When optional argument STEALTH is non-nil, do not modify
10242 visibility around point, thus ignoring
10243 `org-show-hierarchy-above', `org-show-following-heading' and
10244 `org-show-siblings' variables."
10245 (let ((case-fold-search t)
10246 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10247 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10248 (append '(("") (" ") ("\t") ("\n"))
10249 org-emphasis-alist)
10250 "\\|") "\\)"))
10251 (pos (point))
10252 (pre nil) (post nil)
10253 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10254 (cond
10255 ;; First check if there are any special search functions
10256 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10257 ;; Now try the builtin stuff
10258 ((and (equal (string-to-char s0) ?#)
10259 (> (length s0) 1)
10260 (save-excursion
10261 (goto-char (point-min))
10262 (and
10263 (re-search-forward
10264 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10265 (setq type 'dedicated
10266 pos (match-beginning 0))))
10267 ;; There is an exact target for this
10268 (goto-char pos)
10269 (org-back-to-heading t)))
10270 ((save-excursion
10271 (goto-char (point-min))
10272 (and
10273 (re-search-forward
10274 (concat "<<" (regexp-quote s0) ">>") nil t)
10275 (setq type 'dedicated
10276 pos (match-beginning 0))))
10277 ;; There is an exact target for this
10278 (goto-char pos))
10279 ((save-excursion
10280 (goto-char (point-min))
10281 (and
10282 (re-search-forward
10283 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10284 (setq type 'dedicated pos (match-beginning 0))))
10285 ;; Found an invisible target.
10286 (goto-char pos))
10287 ((save-excursion
10288 (goto-char (point-min))
10289 (and
10290 (re-search-forward
10291 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10292 (setq type 'dedicated pos (match-beginning 0))))
10293 ;; Found an element with a matching #+name affiliated keyword.
10294 (goto-char pos))
10295 ((and (string-match "^(\\(.*\\))$" s0)
10296 (save-excursion
10297 (goto-char (point-min))
10298 (and
10299 (re-search-forward
10300 (concat "[^[]" (regexp-quote
10301 (format org-coderef-label-format
10302 (match-string 1 s0))))
10303 nil t)
10304 (setq type 'dedicated
10305 pos (1+ (match-beginning 0))))))
10306 ;; There is a coderef target for this
10307 (goto-char pos))
10308 ((string-match "^/\\(.*\\)/$" s)
10309 ;; A regular expression
10310 (cond
10311 ((derived-mode-p 'org-mode)
10312 (org-occur (match-string 1 s)))
10313 ;;((eq major-mode 'dired-mode)
10314 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10315 (t (org-do-occur (match-string 1 s)))))
10316 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10317 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10318 (goto-char (point-min))
10319 (cond
10320 ((let (case-fold-search)
10321 (re-search-forward (format org-complex-heading-regexp-format
10322 (regexp-quote s))
10323 nil t))
10324 ;; OK, found a match
10325 (setq type 'dedicated)
10326 (goto-char (match-beginning 0)))
10327 ((and (not org-link-search-inhibit-query)
10328 (eq org-link-search-must-match-exact-headline 'query-to-create)
10329 (y-or-n-p "No match - create this as a new heading? "))
10330 (goto-char (point-max))
10331 (or (bolp) (newline))
10332 (insert "* " s "\n")
10333 (beginning-of-line 0))
10335 (goto-char pos)
10336 (error "No match"))))
10338 ;; A normal search string
10339 (when (equal (string-to-char s) ?*)
10340 ;; Anchor on headlines, post may include tags.
10341 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10342 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10343 s (substring s 1)))
10344 (remove-text-properties
10345 0 (length s)
10346 '(face nil mouse-face nil keymap nil fontified nil) s)
10347 ;; Make a series of regular expressions to find a match
10348 (setq words (org-split-string s "[ \n\r\t]+")
10350 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10351 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10352 "\\)" markers)
10353 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10354 re2a (concat "[ \t\r\n]" re2a_)
10355 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10356 re4 (concat "[^a-zA-Z_]" re4_)
10358 re1 (concat pre re2 post)
10359 re3 (concat pre (if pre re4_ re4) post)
10360 re5 (concat pre ".*" re4)
10361 re2 (concat pre re2)
10362 re2a (concat pre (if pre re2a_ re2a))
10363 re4 (concat pre (if pre re4_ re4))
10364 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10365 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10366 re5 "\\)"
10368 (cond
10369 ((eq type 'org-occur) (org-occur reall))
10370 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10371 (t (goto-char (point-min))
10372 (setq type 'fuzzy)
10373 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10374 (org-search-not-self 1 re1 nil t)
10375 (org-search-not-self 1 re2 nil t)
10376 (org-search-not-self 1 re2a nil t)
10377 (org-search-not-self 1 re3 nil t)
10378 (org-search-not-self 1 re4 nil t)
10379 (org-search-not-self 1 re5 nil t)
10381 (goto-char (match-beginning 1))
10382 (goto-char pos)
10383 (error "No match"))))))
10384 (and (derived-mode-p 'org-mode)
10385 (not stealth)
10386 (org-show-context 'link-search))
10387 type))
10389 (defun org-search-not-self (group &rest args)
10390 "Execute `re-search-forward', but only accept matches that do not
10391 enclose the position of `org-open-link-marker'."
10392 (let ((m org-open-link-marker))
10393 (catch 'exit
10394 (while (apply 're-search-forward args)
10395 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10396 (goto-char (match-end group))
10397 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10398 (> (match-beginning 0) (marker-position m))
10399 (< (match-end 0) (marker-position m)))
10400 (save-match-data
10401 (or (not (org-in-regexp
10402 org-bracket-link-analytic-regexp 1))
10403 (not (match-end 4)) ; no description
10404 (and (<= (match-beginning 4) (point))
10405 (>= (match-end 4) (point))))))
10406 (throw 'exit (point))))))))
10408 (defun org-get-buffer-for-internal-link (buffer)
10409 "Return a buffer to be used for displaying the link target of internal links."
10410 (cond
10411 ((not org-display-internal-link-with-indirect-buffer)
10412 buffer)
10413 ((string-match "(Clone)$" (buffer-name buffer))
10414 (message "Buffer is already a clone, not making another one")
10415 ;; we also do not modify visibility in this case
10416 buffer)
10417 (t ; make a new indirect buffer for displaying the link
10418 (let* ((bn (buffer-name buffer))
10419 (ibn (concat bn "(Clone)"))
10420 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10421 (with-current-buffer ib (org-overview))
10422 ib))))
10424 (defun org-do-occur (regexp &optional cleanup)
10425 "Call the Emacs command `occur'.
10426 If CLEANUP is non-nil, remove the printout of the regular expression
10427 in the *Occur* buffer. This is useful if the regex is long and not useful
10428 to read."
10429 (occur regexp)
10430 (when cleanup
10431 (let ((cwin (selected-window)) win beg end)
10432 (when (setq win (get-buffer-window "*Occur*"))
10433 (select-window win))
10434 (goto-char (point-min))
10435 (when (re-search-forward "match[a-z]+" nil t)
10436 (setq beg (match-end 0))
10437 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10438 (setq end (1- (match-beginning 0)))))
10439 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10440 (goto-char (point-min))
10441 (select-window cwin))))
10443 ;;; The mark ring for links jumps
10445 (defvar org-mark-ring nil
10446 "Mark ring for positions before jumps in Org-mode.")
10447 (defvar org-mark-ring-last-goto nil
10448 "Last position in the mark ring used to go back.")
10449 ;; Fill and close the ring
10450 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10451 (loop for i from 1 to org-mark-ring-length do
10452 (push (make-marker) org-mark-ring))
10453 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10454 org-mark-ring)
10456 (defun org-mark-ring-push (&optional pos buffer)
10457 "Put the current position or POS into the mark ring and rotate it."
10458 (interactive)
10459 (setq pos (or pos (point)))
10460 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10461 (move-marker (car org-mark-ring)
10462 (or pos (point))
10463 (or buffer (current-buffer)))
10464 (message "%s"
10465 (substitute-command-keys
10466 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10468 (defun org-mark-ring-goto (&optional n)
10469 "Jump to the previous position in the mark ring.
10470 With prefix arg N, jump back that many stored positions. When
10471 called several times in succession, walk through the entire ring.
10472 Org-mode commands jumping to a different position in the current file,
10473 or to another Org-mode file, automatically push the old position
10474 onto the ring."
10475 (interactive "p")
10476 (let (p m)
10477 (if (eq last-command this-command)
10478 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10479 (setq p org-mark-ring))
10480 (setq org-mark-ring-last-goto p)
10481 (setq m (car p))
10482 (org-pop-to-buffer-same-window (marker-buffer m))
10483 (goto-char m)
10484 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10486 (defun org-remove-angle-brackets (s)
10487 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10488 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10490 (defun org-add-angle-brackets (s)
10491 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10492 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10494 (defun org-remove-double-quotes (s)
10495 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10496 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10499 ;;; Following specific links
10501 (defun org-follow-timestamp-link ()
10502 "Open an agenda view for the time-stamp date/range at point."
10503 (cond
10504 ((org-at-date-range-p t)
10505 (let ((org-agenda-start-on-weekday)
10506 (t1 (match-string 1))
10507 (t2 (match-string 2)) tt1 tt2)
10508 (setq tt1 (time-to-days (org-time-string-to-time t1))
10509 tt2 (time-to-days (org-time-string-to-time t2)))
10510 (let ((org-agenda-buffer-tmp-name
10511 (format "*Org Agenda(a:%s)"
10512 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10513 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10514 ((org-at-timestamp-p t)
10515 (let ((org-agenda-buffer-tmp-name
10516 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10517 (org-agenda-list nil (time-to-days (org-time-string-to-time
10518 (substring (match-string 1) 0 10)))
10519 1)))
10520 (t (error "This should not happen"))))
10523 ;;; Following file links
10524 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10525 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10526 (declare-function mailcap-mime-info
10527 "mailcap" (string &optional request no-decode))
10528 (defvar org-wait nil)
10529 (defun org-open-file (path &optional in-emacs line search)
10530 "Open the file at PATH.
10531 First, this expands any special file name abbreviations. Then the
10532 configuration variable `org-file-apps' is checked if it contains an
10533 entry for this file type, and if yes, the corresponding command is launched.
10535 If no application is found, Emacs simply visits the file.
10537 With optional prefix argument IN-EMACS, Emacs will visit the file.
10538 With a double \\[universal-argument] \\[universal-argument] \
10539 prefix arg, Org tries to avoid opening in Emacs
10540 and to use an external application to visit the file.
10542 Optional LINE specifies a line to go to, optional SEARCH a string
10543 to search for. If LINE or SEARCH is given, the file will be
10544 opened in Emacs, unless an entry from org-file-apps that makes
10545 use of groups in a regexp matches.
10547 If you want to change the way frames are used when following a
10548 link, please customize `org-link-frame-setup'.
10550 If the file does not exist, an error is thrown."
10551 (let* ((file (if (equal path "")
10552 buffer-file-name
10553 (substitute-in-file-name (expand-file-name path))))
10554 (file-apps (append org-file-apps (org-default-apps)))
10555 (apps (org-remove-if
10556 'org-file-apps-entry-match-against-dlink-p file-apps))
10557 (apps-dlink (org-remove-if-not
10558 'org-file-apps-entry-match-against-dlink-p file-apps))
10559 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10560 (dirp (if remp nil (file-directory-p file)))
10561 (file (if (and dirp org-open-directory-means-index-dot-org)
10562 (concat (file-name-as-directory file) "index.org")
10563 file))
10564 (a-m-a-p (assq 'auto-mode apps))
10565 (dfile (downcase file))
10566 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10567 (link (cond ((and (eq line nil)
10568 (eq search nil))
10569 file)
10570 (line
10571 (concat file "::" (number-to-string line)))
10572 (search
10573 (concat file "::" search))))
10574 (dlink (downcase link))
10575 (old-buffer (current-buffer))
10576 (old-pos (point))
10577 (old-mode major-mode)
10578 ext cmd link-match-data)
10579 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10580 (setq ext (match-string 1 dfile))
10581 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10582 (setq ext (match-string 1 dfile))))
10583 (cond
10584 ((member in-emacs '((16) system))
10585 (setq cmd (cdr (assoc 'system apps))))
10586 (in-emacs (setq cmd 'emacs))
10588 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10589 (and dirp (cdr (assoc 'directory apps)))
10590 ; first, try matching against apps-dlink
10591 ; if we get a match here, store the match data for later
10592 (let ((match (assoc-default dlink apps-dlink
10593 'string-match)))
10594 (if match
10595 (progn (setq link-match-data (match-data))
10596 match)
10597 (progn (setq in-emacs (or in-emacs line search))
10598 nil))) ; if we have no match in apps-dlink,
10599 ; always open the file in emacs if line or search
10600 ; is given (for backwards compatibility)
10601 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10602 'string-match)
10603 (cdr (assoc ext apps))
10604 (cdr (assoc t apps))))))
10605 (when (eq cmd 'system)
10606 (setq cmd (cdr (assoc 'system apps))))
10607 (when (eq cmd 'default)
10608 (setq cmd (cdr (assoc t apps))))
10609 (when (eq cmd 'mailcap)
10610 (require 'mailcap)
10611 (mailcap-parse-mailcaps)
10612 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10613 (command (mailcap-mime-info mime-type)))
10614 (if (stringp command)
10615 (setq cmd command)
10616 (setq cmd 'emacs))))
10617 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10618 (not (file-exists-p file))
10619 (not org-open-non-existing-files))
10620 (error "No such file: %s" file))
10621 (cond
10622 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10623 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10624 (while (string-match "['\"]%s['\"]" cmd)
10625 (setq cmd (replace-match "%s" t t cmd)))
10626 (while (string-match "%s" cmd)
10627 (setq cmd (replace-match
10628 (save-match-data
10629 (shell-quote-argument
10630 (convert-standard-filename file)))
10631 t t cmd)))
10633 ;; Replace "%1", "%2" etc. in command with group matches from regex
10634 (save-match-data
10635 (let ((match-index 1)
10636 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10637 (set-match-data link-match-data)
10638 (while (<= match-index number-of-groups)
10639 (let ((regex (concat "%" (number-to-string match-index)))
10640 (replace-with (match-string match-index dlink)))
10641 (while (string-match regex cmd)
10642 (setq cmd (replace-match replace-with t t cmd))))
10643 (setq match-index (+ match-index 1)))))
10645 (save-window-excursion
10646 (message "Running %s...done" cmd)
10647 (start-process-shell-command cmd nil cmd)
10648 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10649 ((or (stringp cmd)
10650 (eq cmd 'emacs))
10651 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10652 (widen)
10653 (if line (org-goto-line line)
10654 (if search (org-link-search search))))
10655 ((consp cmd)
10656 (let ((file (convert-standard-filename file)))
10657 (save-match-data
10658 (set-match-data link-match-data)
10659 (eval cmd))))
10660 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10661 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10662 (or (not (equal old-buffer (current-buffer)))
10663 (not (equal old-pos (point))))
10664 (org-mark-ring-push old-pos old-buffer))))
10666 (defun org-file-apps-entry-match-against-dlink-p (entry)
10667 "This function returns non-nil if `entry' uses a regular
10668 expression which should be matched against the whole link by
10669 org-open-file.
10671 It assumes that is the case when the entry uses a regular
10672 expression which has at least one grouping construct and the
10673 action is either a lisp form or a command string containing
10674 '%1', i.e. using at least one subexpression match as a
10675 parameter."
10676 (let ((selector (car entry))
10677 (action (cdr entry)))
10678 (if (stringp selector)
10679 (and (> (regexp-opt-depth selector) 0)
10680 (or (and (stringp action)
10681 (string-match "%[0-9]" action))
10682 (consp action)))
10683 nil)))
10685 (defun org-default-apps ()
10686 "Return the default applications for this operating system."
10687 (cond
10688 ((eq system-type 'darwin)
10689 org-file-apps-defaults-macosx)
10690 ((eq system-type 'windows-nt)
10691 org-file-apps-defaults-windowsnt)
10692 (t org-file-apps-defaults-gnu)))
10694 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10695 "Convert extensions to regular expressions in the cars of LIST.
10696 Also, weed out any non-string entries, because the return value is used
10697 only for regexp matching.
10698 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10699 point to the symbol `emacs', indicating that the file should
10700 be opened in Emacs."
10701 (append
10702 (delq nil
10703 (mapcar (lambda (x)
10704 (if (not (stringp (car x)))
10706 (if (string-match "\\W" (car x))
10708 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10709 list))
10710 (if add-auto-mode
10711 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10713 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10714 (defun org-file-remote-p (file)
10715 "Test whether FILE specifies a location on a remote system.
10716 Return non-nil if the location is indeed remote.
10718 For example, the filename \"/user@host:/foo\" specifies a location
10719 on the system \"/user@host:\"."
10720 (cond ((fboundp 'file-remote-p)
10721 (file-remote-p file))
10722 ((fboundp 'tramp-handle-file-remote-p)
10723 (tramp-handle-file-remote-p file))
10724 ((and (boundp 'ange-ftp-name-format)
10725 (string-match (car ange-ftp-name-format) file))
10726 t)))
10729 ;;;; Refiling
10731 (defun org-get-org-file ()
10732 "Read a filename, with default directory `org-directory'."
10733 (let ((default (or org-default-notes-file remember-data-file)))
10734 (read-file-name (format "File name [%s]: " default)
10735 (file-name-as-directory org-directory)
10736 default)))
10738 (defun org-notes-order-reversed-p ()
10739 "Check if the current file should receive notes in reversed order."
10740 (cond
10741 ((not org-reverse-note-order) nil)
10742 ((eq t org-reverse-note-order) t)
10743 ((not (listp org-reverse-note-order)) nil)
10744 (t (catch 'exit
10745 (let ((all org-reverse-note-order)
10746 entry)
10747 (while (setq entry (pop all))
10748 (if (string-match (car entry) buffer-file-name)
10749 (throw 'exit (cdr entry))))
10750 nil)))))
10752 (defvar org-refile-target-table nil
10753 "The list of refile targets, created by `org-refile'.")
10755 (defvar org-agenda-new-buffers nil
10756 "Buffers created to visit agenda files.")
10758 (defvar org-refile-cache nil
10759 "Cache for refile targets.")
10761 (defvar org-refile-markers nil
10762 "All the markers used for caching refile locations.")
10764 (defun org-refile-marker (pos)
10765 "Get a new refile marker, but only if caching is in use."
10766 (if (not org-refile-use-cache)
10768 (let ((m (make-marker)))
10769 (move-marker m pos)
10770 (push m org-refile-markers)
10771 m)))
10773 (defun org-refile-cache-clear ()
10774 "Clear the refile cache and disable all the markers."
10775 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10776 (setq org-refile-markers nil)
10777 (setq org-refile-cache nil)
10778 (message "Refile cache has been cleared"))
10780 (defun org-refile-cache-check-set (set)
10781 "Check if all the markers in the cache still have live buffers."
10782 (let (marker)
10783 (catch 'exit
10784 (while (and set (setq marker (nth 3 (pop set))))
10785 ;; if org-refile-use-outline-path is 'file, marker may be nil
10786 (when (and marker (null (marker-buffer marker)))
10787 (message "not found") (sit-for 3)
10788 (throw 'exit nil)))
10789 t)))
10791 (defun org-refile-cache-put (set &rest identifiers)
10792 "Push the refile targets SET into the cache, under IDENTIFIERS."
10793 (let* ((key (sha1 (prin1-to-string identifiers)))
10794 (entry (assoc key org-refile-cache)))
10795 (if entry
10796 (setcdr entry set)
10797 (push (cons key set) org-refile-cache))))
10799 (defun org-refile-cache-get (&rest identifiers)
10800 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10801 (cond
10802 ((not org-refile-cache) nil)
10803 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10805 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10806 org-refile-cache))))
10807 (and set (org-refile-cache-check-set set) set)))))
10809 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10810 "Produce a table with refile targets."
10811 (let ((case-fold-search nil)
10812 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10813 (entries (or org-refile-targets '((nil . (:level . 1)))))
10814 targets tgs txt re files f desc descre fast-path-p level pos0)
10815 (message "Getting targets...")
10816 (with-current-buffer (or default-buffer (current-buffer))
10817 (while (setq entry (pop entries))
10818 (setq files (car entry) desc (cdr entry))
10819 (setq fast-path-p nil)
10820 (cond
10821 ((null files) (setq files (list (current-buffer))))
10822 ((eq files 'org-agenda-files)
10823 (setq files (org-agenda-files 'unrestricted)))
10824 ((and (symbolp files) (fboundp files))
10825 (setq files (funcall files)))
10826 ((and (symbolp files) (boundp files))
10827 (setq files (symbol-value files))))
10828 (if (stringp files) (setq files (list files)))
10829 (cond
10830 ((eq (car desc) :tag)
10831 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10832 ((eq (car desc) :todo)
10833 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10834 ((eq (car desc) :regexp)
10835 (setq descre (cdr desc)))
10836 ((eq (car desc) :level)
10837 (setq descre (concat "^\\*\\{" (number-to-string
10838 (if org-odd-levels-only
10839 (1- (* 2 (cdr desc)))
10840 (cdr desc)))
10841 "\\}[ \t]")))
10842 ((eq (car desc) :maxlevel)
10843 (setq fast-path-p t)
10844 (setq descre (concat "^\\*\\{1," (number-to-string
10845 (if org-odd-levels-only
10846 (1- (* 2 (cdr desc)))
10847 (cdr desc)))
10848 "\\}[ \t]")))
10849 (t (error "Bad refiling target description %s" desc)))
10850 (while (setq f (pop files))
10851 (with-current-buffer
10852 (if (bufferp f) f (org-get-agenda-file-buffer f))
10854 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10855 (progn
10856 (if (bufferp f) (setq f (buffer-file-name
10857 (buffer-base-buffer f))))
10858 (setq f (and f (expand-file-name f)))
10859 (if (eq org-refile-use-outline-path 'file)
10860 (push (list (file-name-nondirectory f) f nil nil) tgs))
10861 (save-excursion
10862 (save-restriction
10863 (widen)
10864 (goto-char (point-min))
10865 (while (re-search-forward descre nil t)
10866 (goto-char (setq pos0 (point-at-bol)))
10867 (catch 'next
10868 (when org-refile-target-verify-function
10869 (save-match-data
10870 (or (funcall org-refile-target-verify-function)
10871 (throw 'next t))))
10872 (when (and (looking-at org-complex-heading-regexp)
10873 (not (member (match-string 4) excluded-entries))
10874 (match-string 4))
10875 (setq level (org-reduced-level
10876 (- (match-end 1) (match-beginning 1)))
10877 txt (org-link-display-format (match-string 4))
10878 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10879 re (format org-complex-heading-regexp-format
10880 (regexp-quote (match-string 4))))
10881 (when org-refile-use-outline-path
10882 (setq txt (mapconcat
10883 'org-protect-slash
10884 (append
10885 (if (eq org-refile-use-outline-path
10886 'file)
10887 (list (file-name-nondirectory
10888 (buffer-file-name
10889 (buffer-base-buffer))))
10890 (if (eq org-refile-use-outline-path
10891 'full-file-path)
10892 (list (buffer-file-name
10893 (buffer-base-buffer)))))
10894 (org-get-outline-path fast-path-p
10895 level txt)
10896 (list txt))
10897 "/")))
10898 (push (list txt f re (org-refile-marker (point)))
10899 tgs)))
10900 (when (= (point) pos0)
10901 ;; verification function has not moved point
10902 (goto-char (point-at-eol))))))))
10903 (when org-refile-use-cache
10904 (org-refile-cache-put tgs (buffer-file-name) descre))
10905 (setq targets (append tgs targets))
10906 ))))
10907 (message "Getting targets...done")
10908 (nreverse targets)))
10910 (defun org-protect-slash (s)
10911 (while (string-match "/" s)
10912 (setq s (replace-match "\\" t t s)))
10915 (defvar org-olpa (make-vector 20 nil))
10917 (defun org-get-outline-path (&optional fastp level heading)
10918 "Return the outline path to the current entry, as a list.
10920 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10921 routine which makes outline path derivations for an entire file,
10922 avoiding backtracing. Refile target collection makes use of that."
10923 (if fastp
10924 (progn
10925 (if (> level 19)
10926 (error "Outline path failure, more than 19 levels"))
10927 (loop for i from level upto 19 do
10928 (aset org-olpa i nil))
10929 (prog1
10930 (delq nil (append org-olpa nil))
10931 (aset org-olpa level heading)))
10932 (let (rtn case-fold-search)
10933 (save-excursion
10934 (save-restriction
10935 (widen)
10936 (while (org-up-heading-safe)
10937 (when (looking-at org-complex-heading-regexp)
10938 (push (org-match-string-no-properties 4) rtn)))
10939 rtn)))))
10941 (defun org-format-outline-path (path &optional width prefix separator)
10942 "Format the outline path PATH for display.
10943 WIDTH is the maximum number of characters that is available.
10944 PREFIX is a prefix to be included in the returned string,
10945 such as the file name.
10946 SEPARATOR is inserted between the different parts of the path,
10947 the default is \"/\"."
10948 (setq width (or width 79))
10949 (if prefix (setq width (- width (length prefix))))
10950 (if (not path)
10951 (or prefix "")
10952 (let* ((nsteps (length path))
10953 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10954 (maxwidth (if (<= total-width width)
10955 10000 ;; everything fits
10956 ;; we need to shorten the level headings
10957 (/ (- width nsteps) nsteps)))
10958 (org-odd-levels-only nil)
10959 (n 0)
10960 (total (1+ (length prefix))))
10961 (setq maxwidth (max maxwidth 10))
10962 (concat prefix
10963 (if prefix (or separator "/"))
10964 (mapconcat
10965 (lambda (h)
10966 (setq n (1+ n))
10967 (if (and (= n nsteps) (< maxwidth 10000))
10968 (setq maxwidth (- total-width total)))
10969 (if (< (length h) maxwidth)
10970 (progn (setq total (+ total (length h) 1)) h)
10971 (setq h (substring h 0 (- maxwidth 2))
10972 total (+ total maxwidth 1))
10973 (if (string-match "[ \t]+\\'" h)
10974 (setq h (substring h 0 (match-beginning 0))))
10975 (setq h (concat h "..")))
10976 (org-add-props h nil 'face
10977 (nth (% (1- n) org-n-level-faces)
10978 org-level-faces))
10980 path (or separator "/"))))))
10982 (defun org-display-outline-path (&optional file current separator just-return-string)
10983 "Display the current outline path in the echo area.
10985 If FILE is non-nil, prepend the output with the file name.
10986 If CURRENT is non-nil, append the current heading to the output.
10987 SEPARATOR is passed through to `org-format-outline-path'. It separates
10988 the different parts of the path and defaults to \"/\".
10989 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10990 (interactive "P")
10991 (let* (case-fold-search
10992 message-log-max ; Don't populate the *Messages* buffer
10993 (bfn (buffer-file-name (buffer-base-buffer)))
10994 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10995 res)
10996 (if current (setq path (append path
10997 (save-excursion
10998 (org-back-to-heading t)
10999 (if (looking-at org-complex-heading-regexp)
11000 (list (match-string 4)))))))
11001 (setq res
11002 (org-format-outline-path
11003 path
11004 (1- (frame-width))
11005 (and file bfn (concat (file-name-nondirectory bfn) separator))
11006 separator))
11007 (if just-return-string
11008 (org-no-properties res)
11009 (message "%s" res))))
11011 (defvar org-refile-history nil
11012 "History for refiling operations.")
11014 (defvar org-after-refile-insert-hook nil
11015 "Hook run after `org-refile' has inserted its stuff at the new location.
11016 Note that this is still *before* the stuff will be removed from
11017 the *old* location.")
11019 (defvar org-capture-last-stored-marker)
11020 (defvar org-refile-keep nil
11021 "Non-nil means `org-refile' will copy instead of refile.")
11023 (defun org-copy ()
11024 "Like `org-refile', but copy."
11025 (interactive)
11026 (let ((org-refile-keep t))
11027 (funcall 'org-refile nil nil nil "Copy")))
11029 (defun org-refile (&optional goto default-buffer rfloc msg)
11030 "Move the entry or entries at point to another heading.
11031 The list of target headings is compiled using the information in
11032 `org-refile-targets', which see.
11034 At the target location, the entry is filed as a subitem of the target
11035 heading. Depending on `org-reverse-note-order', the new subitem will
11036 either be the first or the last subitem.
11038 If there is an active region, all entries in that region will be moved.
11039 However, the region must fulfill the requirement that the first heading
11040 is the first one sets the top-level of the moved text - at most siblings
11041 below it are allowed.
11043 With prefix arg GOTO, the command will only visit the target location
11044 and not actually move anything.
11046 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11047 go to the location where the last refiling operation has put the subtree.
11048 With a prefix argument of `2', refile to the running clock.
11050 RFLOC can be a refile location obtained in a different way.
11052 MSG is a string to replace \"Refile\" in the default prompt with
11053 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11055 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11057 If you are using target caching (see `org-refile-use-cache'),
11058 you have to clear the target cache in order to find new targets.
11059 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11060 prefix argument (`C-u C-u C-u C-c C-w')."
11062 (interactive "P")
11063 (if (member goto '(0 (64)))
11064 (org-refile-cache-clear)
11065 (let* ((actionmsg (or msg "Refile"))
11066 (cbuf (current-buffer))
11067 (regionp (org-region-active-p))
11068 (region-start (and regionp (region-beginning)))
11069 (region-end (and regionp (region-end)))
11070 (region-length (and regionp (- region-end region-start)))
11071 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11072 pos it nbuf file re level reversed)
11073 (setq last-command nil)
11074 (when regionp
11075 (goto-char region-start)
11076 (or (bolp) (goto-char (point-at-bol)))
11077 (setq region-start (point))
11078 (unless (or (org-kill-is-subtree-p
11079 (buffer-substring region-start region-end))
11080 (prog1 org-refile-active-region-within-subtree
11081 (org-toggle-heading)))
11082 (error "The region is not a (sequence of) subtree(s)")))
11083 (if (equal goto '(16))
11084 (org-refile-goto-last-stored)
11085 (when (or
11086 (and (equal goto 2)
11087 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11088 (prog1
11089 (setq it (list (or org-clock-heading "running clock")
11090 (buffer-file-name
11091 (marker-buffer org-clock-hd-marker))
11093 (marker-position org-clock-hd-marker)))
11094 (setq goto nil)))
11095 (setq it (or rfloc
11096 (let (heading-text)
11097 (save-excursion
11098 (unless goto
11099 (org-back-to-heading t)
11100 (setq heading-text
11101 (nth 4 (org-heading-components))))
11103 (org-refile-get-location
11104 (cond (goto "Goto")
11105 (regionp (concat actionmsg " region to"))
11106 (t (concat actionmsg " subtree \""
11107 heading-text "\" to")))
11108 default-buffer
11109 (and (not (equal '(4) goto))
11110 org-refile-allow-creating-parent-nodes)
11111 goto))))))
11112 (setq file (nth 1 it)
11113 re (nth 2 it)
11114 pos (nth 3 it))
11115 (if (and (not goto)
11117 (equal (buffer-file-name) file)
11118 (if regionp
11119 (and (>= pos region-start)
11120 (<= pos region-end))
11121 (and (>= pos (point))
11122 (< pos (save-excursion
11123 (org-end-of-subtree t t))))))
11124 (error "Cannot refile to position inside the tree or region"))
11126 (setq nbuf (or (find-buffer-visiting file)
11127 (find-file-noselect file)))
11128 (if goto
11129 (progn
11130 (org-pop-to-buffer-same-window nbuf)
11131 (goto-char pos)
11132 (org-show-context 'org-goto))
11133 (if regionp
11134 (progn
11135 (org-kill-new (buffer-substring region-start region-end))
11136 (org-save-markers-in-region region-start region-end))
11137 (org-copy-subtree 1 nil t))
11138 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11139 (find-file-noselect file)))
11140 (setq reversed (org-notes-order-reversed-p))
11141 (save-excursion
11142 (save-restriction
11143 (widen)
11144 (if pos
11145 (progn
11146 (goto-char pos)
11147 (looking-at org-outline-regexp)
11148 (setq level (org-get-valid-level (funcall outline-level) 1))
11149 (goto-char
11150 (if reversed
11151 (or (outline-next-heading) (point-max))
11152 (or (save-excursion (org-get-next-sibling))
11153 (org-end-of-subtree t t)
11154 (point-max)))))
11155 (setq level 1)
11156 (if (not reversed)
11157 (goto-char (point-max))
11158 (goto-char (point-min))
11159 (or (outline-next-heading) (goto-char (point-max)))))
11160 (if (not (bolp)) (newline))
11161 (org-paste-subtree level)
11162 (when org-log-refile
11163 (org-add-log-setup 'refile nil nil 'findpos
11164 org-log-refile)
11165 (unless (eq org-log-refile 'note)
11166 (save-excursion (org-add-log-note))))
11167 (and org-auto-align-tags
11168 (let ((org-loop-over-headlines-in-active-region nil))
11169 (org-set-tags nil t)))
11170 (with-demoted-errors
11171 (bookmark-set "org-refile-last-stored"))
11172 ;; If we are refiling for capture, make sure that the
11173 ;; last-capture pointers point here
11174 (when (org-bound-and-true-p org-refile-for-capture)
11175 (with-demoted-errors
11176 (bookmark-set "org-capture-last-stored-marker"))
11177 (move-marker org-capture-last-stored-marker (point)))
11178 (if (fboundp 'deactivate-mark) (deactivate-mark))
11179 (run-hooks 'org-after-refile-insert-hook))))
11180 (unless org-refile-keep
11181 (if regionp
11182 (delete-region (point) (+ (point) region-length))
11183 (org-cut-subtree)))
11184 (when (featurep 'org-inlinetask)
11185 (org-inlinetask-remove-END-maybe))
11186 (setq org-markers-to-move nil)
11187 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11189 (defun org-refile-goto-last-stored ()
11190 "Go to the location where the last refile was stored."
11191 (interactive)
11192 (bookmark-jump "org-refile-last-stored")
11193 (message "This is the location of the last refile"))
11195 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11196 no-exclude)
11197 "Prompt the user for a refile location, using PROMPT.
11198 PROMPT should not be suffixed with a colon and a space, because
11199 this function appends the default value from
11200 `org-refile-history' automatically, if that is not empty.
11201 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11202 this is used for the GOTO interface."
11203 (let ((org-refile-targets org-refile-targets)
11204 (org-refile-use-outline-path org-refile-use-outline-path)
11205 excluded-entries)
11206 (when (and (derived-mode-p 'org-mode)
11207 (not org-refile-use-cache)
11208 (not no-exclude))
11209 (org-map-tree
11210 (lambda()
11211 (setq excluded-entries
11212 (append excluded-entries (list (org-get-heading t t)))))))
11213 (setq org-refile-target-table
11214 (org-refile-get-targets default-buffer excluded-entries)))
11215 (unless org-refile-target-table
11216 (error "No refile targets"))
11217 (let* ((cbuf (current-buffer))
11218 (partial-completion-mode nil)
11219 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11220 (cfunc (if (and org-refile-use-outline-path
11221 org-outline-path-complete-in-steps)
11222 'org-olpath-completing-read
11223 'org-icompleting-read))
11224 (extra (if org-refile-use-outline-path "/" ""))
11225 (cbnex (concat (buffer-name) extra))
11226 (filename (and cfn (expand-file-name cfn)))
11227 (tbl (mapcar
11228 (lambda (x)
11229 (if (and (not (member org-refile-use-outline-path
11230 '(file full-file-path)))
11231 (not (equal filename (nth 1 x))))
11232 (cons (concat (car x) extra " ("
11233 (file-name-nondirectory (nth 1 x)) ")")
11234 (cdr x))
11235 (cons (concat (car x) extra) (cdr x))))
11236 org-refile-target-table))
11237 (completion-ignore-case t)
11238 cdef
11239 (prompt (concat prompt
11240 (or (and (car org-refile-history)
11241 (concat " (default " (car org-refile-history) ")"))
11242 (and (assoc cbnex tbl) (setq cdef cbnex)
11243 (concat " (default " cbnex ")"))) ": "))
11244 pa answ parent-target child parent old-hist)
11245 (setq old-hist org-refile-history)
11246 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11247 nil 'org-refile-history (or cdef (car org-refile-history))))
11248 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11249 (org-refile-check-position pa)
11250 (if pa
11251 (progn
11252 (when (or (not org-refile-history)
11253 (not (eq old-hist org-refile-history))
11254 (not (equal (car pa) (car org-refile-history))))
11255 (setq org-refile-history
11256 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11257 org-refile-history
11258 (cdr org-refile-history))))
11259 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11260 (pop org-refile-history)))
11262 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11263 (progn
11264 (setq parent (match-string 1 answ)
11265 child (match-string 2 answ))
11266 (setq parent-target (or (assoc parent tbl)
11267 (assoc (concat parent "/") tbl)))
11268 (when (and parent-target
11269 (or (eq new-nodes t)
11270 (and (eq new-nodes 'confirm)
11271 (y-or-n-p (format "Create new node \"%s\"? "
11272 child)))))
11273 (org-refile-new-child parent-target child)))
11274 (error "Invalid target location")))))
11276 (declare-function org-string-nw-p "org-macs" (s))
11277 (defun org-refile-check-position (refile-pointer)
11278 "Check if the refile pointer matches the headline to which it points."
11279 (let* ((file (nth 1 refile-pointer))
11280 (re (nth 2 refile-pointer))
11281 (pos (nth 3 refile-pointer))
11282 buffer)
11283 (if (and (not (markerp pos)) (not file))
11284 (error "Please save the buffer to a file before refiling")
11285 (when (org-string-nw-p re)
11286 (setq buffer (if (markerp pos)
11287 (marker-buffer pos)
11288 (or (find-buffer-visiting file)
11289 (find-file-noselect file))))
11290 (with-current-buffer buffer
11291 (save-excursion
11292 (save-restriction
11293 (widen)
11294 (goto-char pos)
11295 (beginning-of-line 1)
11296 (unless (org-looking-at-p re)
11297 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11299 (defun org-refile-new-child (parent-target child)
11300 "Use refile target PARENT-TARGET to add new CHILD below it."
11301 (unless parent-target
11302 (error "Cannot find parent for new node"))
11303 (let ((file (nth 1 parent-target))
11304 (pos (nth 3 parent-target))
11305 level)
11306 (with-current-buffer (or (find-buffer-visiting file)
11307 (find-file-noselect file))
11308 (save-excursion
11309 (save-restriction
11310 (widen)
11311 (if pos
11312 (goto-char pos)
11313 (goto-char (point-max))
11314 (if (not (bolp)) (newline)))
11315 (when (looking-at org-outline-regexp)
11316 (setq level (funcall outline-level))
11317 (org-end-of-subtree t t))
11318 (org-back-over-empty-lines)
11319 (insert "\n" (make-string
11320 (if pos (org-get-valid-level level 1) 1) ?*)
11321 " " child "\n")
11322 (beginning-of-line 0)
11323 (list (concat (car parent-target) "/" child) file "" (point)))))))
11325 (defun org-olpath-completing-read (prompt collection &rest args)
11326 "Read an outline path like a file name."
11327 (let ((thetable collection)
11328 (org-completion-use-ido nil) ; does not work with ido.
11329 (org-completion-use-iswitchb nil)) ; or iswitchb
11330 (apply
11331 'org-icompleting-read prompt
11332 (lambda (string predicate &optional flag)
11333 (let (rtn r f (l (length string)))
11334 (cond
11335 ((eq flag nil)
11336 ;; try completion
11337 (try-completion string thetable))
11338 ((eq flag t)
11339 ;; all-completions
11340 (setq rtn (all-completions string thetable predicate))
11341 (mapcar
11342 (lambda (x)
11343 (setq r (substring x l))
11344 (if (string-match " ([^)]*)$" x)
11345 (setq f (match-string 0 x))
11346 (setq f ""))
11347 (if (string-match "/" r)
11348 (concat string (substring r 0 (match-end 0)) f)
11350 rtn))
11351 ((eq flag 'lambda)
11352 ;; exact match?
11353 (assoc string thetable)))))
11354 args)))
11356 ;;;; Dynamic blocks
11358 (defun org-find-dblock (name)
11359 "Find the first dynamic block with name NAME in the buffer.
11360 If not found, stay at current position and return nil."
11361 (let ((case-fold-search t) pos)
11362 (save-excursion
11363 (goto-char (point-min))
11364 (setq pos (and (re-search-forward
11365 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11366 (match-beginning 0))))
11367 (if pos (goto-char pos))
11368 pos))
11370 (defconst org-dblock-start-re
11371 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11372 "Matches the start line of a dynamic block, with parameters.")
11374 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11375 "Matches the end of a dynamic block.")
11377 (defun org-create-dblock (plist)
11378 "Create a dynamic block section, with parameters taken from PLIST.
11379 PLIST must contain a :name entry which is used as name of the block."
11380 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11381 (end-of-line 1)
11382 (newline))
11383 (let ((col (current-column))
11384 (name (plist-get plist :name)))
11385 (insert "#+BEGIN: " name)
11386 (while plist
11387 (if (eq (car plist) :name)
11388 (setq plist (cddr plist))
11389 (insert " " (prin1-to-string (pop plist)))))
11390 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11391 (beginning-of-line -2)))
11393 (defun org-prepare-dblock ()
11394 "Prepare dynamic block for refresh.
11395 This empties the block, puts the cursor at the insert position and returns
11396 the property list including an extra property :name with the block name."
11397 (unless (looking-at org-dblock-start-re)
11398 (error "Not at a dynamic block"))
11399 (let* ((begdel (1+ (match-end 0)))
11400 (name (org-no-properties (match-string 1)))
11401 (params (append (list :name name)
11402 (read (concat "(" (match-string 3) ")")))))
11403 (save-excursion
11404 (beginning-of-line 1)
11405 (skip-chars-forward " \t")
11406 (setq params (plist-put params :indentation-column (current-column))))
11407 (unless (re-search-forward org-dblock-end-re nil t)
11408 (error "Dynamic block not terminated"))
11409 (setq params
11410 (append params
11411 (list :content (buffer-substring
11412 begdel (match-beginning 0)))))
11413 (delete-region begdel (match-beginning 0))
11414 (goto-char begdel)
11415 (open-line 1)
11416 params))
11418 (defun org-map-dblocks (&optional command)
11419 "Apply COMMAND to all dynamic blocks in the current buffer.
11420 If COMMAND is not given, use `org-update-dblock'."
11421 (let ((cmd (or command 'org-update-dblock)))
11422 (save-excursion
11423 (goto-char (point-min))
11424 (while (re-search-forward org-dblock-start-re nil t)
11425 (goto-char (match-beginning 0))
11426 (save-excursion
11427 (condition-case nil
11428 (funcall cmd)
11429 (error (message "Error during update of dynamic block"))))
11430 (unless (re-search-forward org-dblock-end-re nil t)
11431 (error "Dynamic block not terminated"))))))
11433 (defun org-dblock-update (&optional arg)
11434 "User command for updating dynamic blocks.
11435 Update the dynamic block at point. With prefix ARG, update all dynamic
11436 blocks in the buffer."
11437 (interactive "P")
11438 (if arg
11439 (org-update-all-dblocks)
11440 (or (looking-at org-dblock-start-re)
11441 (org-beginning-of-dblock))
11442 (org-update-dblock)))
11444 (defun org-update-dblock ()
11445 "Update the dynamic block at point.
11446 This means to empty the block, parse for parameters and then call
11447 the correct writing function."
11448 (interactive)
11449 (save-window-excursion
11450 (let* ((pos (point))
11451 (line (org-current-line))
11452 (params (org-prepare-dblock))
11453 (name (plist-get params :name))
11454 (indent (plist-get params :indentation-column))
11455 (cmd (intern (concat "org-dblock-write:" name))))
11456 (message "Updating dynamic block `%s' at line %d..." name line)
11457 (funcall cmd params)
11458 (message "Updating dynamic block `%s' at line %d...done" name line)
11459 (goto-char pos)
11460 (when (and indent (> indent 0))
11461 (setq indent (make-string indent ?\ ))
11462 (save-excursion
11463 (org-beginning-of-dblock)
11464 (forward-line 1)
11465 (while (not (looking-at org-dblock-end-re))
11466 (insert indent)
11467 (beginning-of-line 2))
11468 (when (looking-at org-dblock-end-re)
11469 (and (looking-at "[ \t]+")
11470 (replace-match ""))
11471 (insert indent)))))))
11473 (defun org-beginning-of-dblock ()
11474 "Find the beginning of the dynamic block at point.
11475 Error if there is no such block at point."
11476 (let ((pos (point))
11477 beg)
11478 (end-of-line 1)
11479 (if (and (re-search-backward org-dblock-start-re nil t)
11480 (setq beg (match-beginning 0))
11481 (re-search-forward org-dblock-end-re nil t)
11482 (> (match-end 0) pos))
11483 (goto-char beg)
11484 (goto-char pos)
11485 (error "Not in a dynamic block"))))
11487 (defun org-update-all-dblocks ()
11488 "Update all dynamic blocks in the buffer.
11489 This function can be used in a hook."
11490 (interactive)
11491 (when (derived-mode-p 'org-mode)
11492 (org-map-dblocks 'org-update-dblock)))
11495 ;;;; Completion
11497 (defconst org-additional-option-like-keywords
11498 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11499 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11500 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11501 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11502 "BEGIN:" "END:"
11503 "ORGTBL" "TBLFM:" "TBLNAME:"
11504 "BEGIN_EXAMPLE" "END_EXAMPLE"
11505 "BEGIN_VERBATIM" "END_VERBATIM"
11506 "BEGIN_QUOTE" "END_QUOTE"
11507 "BEGIN_VERSE" "END_VERSE"
11508 "BEGIN_CENTER" "END_CENTER"
11509 "BEGIN_SRC" "END_SRC"
11510 "BEGIN_RESULT" "END_RESULT"
11511 "BEGIN_lstlisting" "END_lstlisting"
11512 "NAME:" "RESULTS:"
11513 "HEADER:" "HEADERS:"
11514 "COLUMNS:" "PROPERTY:"
11515 "CAPTION:" "LABEL:"
11516 "SETUPFILE:"
11517 "INCLUDE:" "INDEX:"
11518 "BIND:"
11519 "MACRO:"))
11521 (defconst org-options-keywords
11522 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11523 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11524 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11525 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11526 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11527 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11528 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11530 (defconst org-additional-option-like-keywords-for-flyspell
11531 (delete-dups
11532 (split-string
11533 (mapconcat (lambda(k)
11534 (replace-regexp-in-string
11535 "_\\|:" " "
11536 (concat k " " (downcase k) " " (upcase k))))
11537 (append org-options-keywords org-additional-option-like-keywords)
11538 " ")
11539 " +" t)))
11541 (defcustom org-structure-template-alist
11542 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11543 "<src lang=\"?\">\n\n</src>")
11544 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11545 "<example>\n?\n</example>")
11546 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11547 "<quote>\n?\n</quote>")
11548 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11549 "<verse>\n?\n</verse>")
11550 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11551 "<verbatim>\n?\n</verbatim>")
11552 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11553 "<center>\n?\n</center>")
11554 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11555 "<literal style=\"latex\">\n?\n</literal>")
11556 ("L" "#+LaTeX: "
11557 "<literal style=\"latex\">?</literal>")
11558 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11559 "<literal style=\"html\">\n?\n</literal>")
11560 ("H" "#+HTML: "
11561 "<literal style=\"html\">?</literal>")
11562 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11563 ("A" "#+ASCII: ")
11564 ("i" "#+INDEX: ?"
11565 "#+INDEX: ?")
11566 ("I" "#+INCLUDE: %file ?"
11567 "<include file=%file markup=\"?\">"))
11568 "Structure completion elements.
11569 This is a list of abbreviation keys and values. The value gets inserted
11570 if you type `<' followed by the key and then press the completion key,
11571 usually `M-TAB'. %file will be replaced by a file name after prompting
11572 for the file using completion. The cursor will be placed at the position
11573 of the `?` in the template.
11574 There are two templates for each key, the first uses the original Org syntax,
11575 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11576 the default when the /org-mtags.el/ module has been loaded. See also the
11577 variable `org-mtags-prefer-muse-templates'."
11578 :group 'org-completion
11579 :type '(repeat
11580 (string :tag "Key")
11581 (string :tag "Template")
11582 (string :tag "Muse Template")))
11584 (defun org-try-structure-completion ()
11585 "Try to complete a structure template before point.
11586 This looks for strings like \"<e\" on an otherwise empty line and
11587 expands them."
11588 (let ((l (buffer-substring (point-at-bol) (point)))
11590 (when (and (looking-at "[ \t]*$")
11591 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11592 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11593 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11594 (match-beginning 1)) a)
11595 t)))
11597 (defun org-complete-expand-structure-template (start cell)
11598 "Expand a structure template."
11599 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11600 (rpl (nth (if musep 2 1) cell))
11601 (ind ""))
11602 (delete-region start (point))
11603 (when (string-match "\\`#\\+" rpl)
11604 (cond
11605 ((bolp))
11606 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11607 (setq ind (buffer-substring (point-at-bol) (point))))
11608 (t (newline))))
11609 (setq start (point))
11610 (if (string-match "%file" rpl)
11611 (setq rpl (replace-match
11612 (concat
11613 "\""
11614 (save-match-data
11615 (abbreviate-file-name (read-file-name "Include file: ")))
11616 "\"")
11617 t t rpl)))
11618 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11619 (concat "\n" ind)))
11620 (insert rpl)
11621 (if (re-search-backward "\\?" start t) (delete-char 1))))
11623 ;;;; TODO, DEADLINE, Comments
11625 (defun org-toggle-comment ()
11626 "Change the COMMENT state of an entry."
11627 (interactive)
11628 (save-excursion
11629 (org-back-to-heading)
11630 (let (case-fold-search)
11631 (cond
11632 ((looking-at (format org-heading-keyword-regexp-format
11633 org-comment-string))
11634 (goto-char (match-end 1))
11635 (looking-at (concat " +" org-comment-string))
11636 (replace-match "" t t)
11637 (when (eolp) (insert " ")))
11638 ((looking-at org-outline-regexp)
11639 (goto-char (match-end 0))
11640 (insert org-comment-string " "))))))
11642 (defvar org-last-todo-state-is-todo nil
11643 "This is non-nil when the last TODO state change led to a TODO state.
11644 If the last change removed the TODO tag or switched to DONE, then
11645 this is nil.")
11647 (defvar org-setting-tags nil) ; dynamically skipped
11649 (defvar org-todo-setup-filter-hook nil
11650 "Hook for functions that pre-filter todo specs.
11651 Each function takes a todo spec and returns either nil or the spec
11652 transformed into canonical form." )
11654 (defvar org-todo-get-default-hook nil
11655 "Hook for functions that get a default item for todo.
11656 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11657 nil or a string to be used for the todo mark." )
11659 (defvar org-agenda-headline-snapshot-before-repeat)
11661 (defun org-current-effective-time ()
11662 "Return current time adjusted for `org-extend-today-until' variable."
11663 (let* ((ct (org-current-time))
11664 (dct (decode-time ct))
11665 (ct1
11666 (cond
11667 (org-use-last-clock-out-time-as-effective-time
11668 (or (org-clock-get-last-clock-out-time) ct))
11669 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11670 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11671 (t ct))))
11672 ct1))
11674 (defun org-todo-yesterday (&optional arg)
11675 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11676 (interactive "P")
11677 (if (eq major-mode 'org-agenda-mode)
11678 (apply 'org-agenda-todo-yesterday arg)
11679 (let* ((hour (third (decode-time
11680 (org-current-time))))
11681 (org-extend-today-until (1+ hour)))
11682 (org-todo arg))))
11684 (defvar org-block-entry-blocking ""
11685 "First entry preventing the TODO state change.")
11687 (defun org-todo (&optional arg)
11688 "Change the TODO state of an item.
11689 The state of an item is given by a keyword at the start of the heading,
11690 like
11691 *** TODO Write paper
11692 *** DONE Call mom
11694 The different keywords are specified in the variable `org-todo-keywords'.
11695 By default the available states are \"TODO\" and \"DONE\".
11696 So for this example: when the item starts with TODO, it is changed to DONE.
11697 When it starts with DONE, the DONE is removed. And when neither TODO nor
11698 DONE are present, add TODO at the beginning of the heading.
11700 With \\[universal-argument] prefix arg, use completion to determine the new \
11701 state.
11702 With numeric prefix arg, switch to that state.
11703 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11704 keywords (nextset).
11705 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11706 With a numeric prefix arg of 0, inhibit note taking for the change.
11708 For calling through lisp, arg is also interpreted in the following way:
11709 'none -> empty state
11710 \"\"(empty string) -> switch to empty state
11711 'done -> switch to DONE
11712 'nextset -> switch to the next set of keywords
11713 'previousset -> switch to the previous set of keywords
11714 \"WAITING\" -> switch to the specified keyword, but only if it
11715 really is a member of `org-todo-keywords'."
11716 (interactive "P")
11717 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11718 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11719 'region-start-level 'region))
11720 org-loop-over-headlines-in-active-region)
11721 (org-map-entries
11722 `(org-todo ,arg)
11723 org-loop-over-headlines-in-active-region
11724 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11725 (if (equal arg '(16)) (setq arg 'nextset))
11726 (let ((org-blocker-hook org-blocker-hook)
11727 commentp
11728 case-fold-search)
11729 (when (equal arg '(64))
11730 (setq arg nil org-blocker-hook nil))
11731 (when (and org-blocker-hook
11732 (or org-inhibit-blocking
11733 (org-entry-get nil "NOBLOCKING")))
11734 (setq org-blocker-hook nil))
11735 (save-excursion
11736 (catch 'exit
11737 (org-back-to-heading t)
11738 (when (looking-at (concat "^\\*+ " org-comment-string))
11739 (org-toggle-comment)
11740 (setq commentp t))
11741 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11742 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11743 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11744 (let* ((match-data (match-data))
11745 (startpos (point-at-bol))
11746 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11747 (org-log-done org-log-done)
11748 (org-log-repeat org-log-repeat)
11749 (org-todo-log-states org-todo-log-states)
11750 (org-inhibit-logging
11751 (if (equal arg 0)
11752 (progn (setq arg nil) 'note) org-inhibit-logging))
11753 (this (match-string 1))
11754 (hl-pos (match-beginning 0))
11755 (head (org-get-todo-sequence-head this))
11756 (ass (assoc head org-todo-kwd-alist))
11757 (interpret (nth 1 ass))
11758 (done-word (nth 3 ass))
11759 (final-done-word (nth 4 ass))
11760 (org-last-state (or this ""))
11761 (completion-ignore-case t)
11762 (member (member this org-todo-keywords-1))
11763 (tail (cdr member))
11764 (org-state (cond
11765 ((and org-todo-key-trigger
11766 (or (and (equal arg '(4))
11767 (eq org-use-fast-todo-selection 'prefix))
11768 (and (not arg) org-use-fast-todo-selection
11769 (not (eq org-use-fast-todo-selection
11770 'prefix)))))
11771 ;; Use fast selection
11772 (org-fast-todo-selection))
11773 ((and (equal arg '(4))
11774 (or (not org-use-fast-todo-selection)
11775 (not org-todo-key-trigger)))
11776 ;; Read a state with completion
11777 (org-icompleting-read
11778 "State: " (mapcar (lambda(x) (list x))
11779 org-todo-keywords-1)
11780 nil t))
11781 ((eq arg 'right)
11782 (if this
11783 (if tail (car tail) nil)
11784 (car org-todo-keywords-1)))
11785 ((eq arg 'left)
11786 (if (equal member org-todo-keywords-1)
11788 (if this
11789 (nth (- (length org-todo-keywords-1)
11790 (length tail) 2)
11791 org-todo-keywords-1)
11792 (org-last org-todo-keywords-1))))
11793 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11794 (setq arg nil))) ; hack to fall back to cycling
11795 (arg
11796 ;; user or caller requests a specific state
11797 (cond
11798 ((equal arg "") nil)
11799 ((eq arg 'none) nil)
11800 ((eq arg 'done) (or done-word (car org-done-keywords)))
11801 ((eq arg 'nextset)
11802 (or (car (cdr (member head org-todo-heads)))
11803 (car org-todo-heads)))
11804 ((eq arg 'previousset)
11805 (let ((org-todo-heads (reverse org-todo-heads)))
11806 (or (car (cdr (member head org-todo-heads)))
11807 (car org-todo-heads))))
11808 ((car (member arg org-todo-keywords-1)))
11809 ((stringp arg)
11810 (error "State `%s' not valid in this file" arg))
11811 ((nth (1- (prefix-numeric-value arg))
11812 org-todo-keywords-1))))
11813 ((null member) (or head (car org-todo-keywords-1)))
11814 ((equal this final-done-word) nil) ;; -> make empty
11815 ((null tail) nil) ;; -> first entry
11816 ((memq interpret '(type priority))
11817 (if (eq this-command last-command)
11818 (car tail)
11819 (if (> (length tail) 0)
11820 (or done-word (car org-done-keywords))
11821 nil)))
11823 (car tail))))
11824 (org-state (or
11825 (run-hook-with-args-until-success
11826 'org-todo-get-default-hook org-state org-last-state)
11827 org-state))
11828 (next (if org-state (concat " " org-state " ") " "))
11829 (change-plist (list :type 'todo-state-change :from this :to org-state
11830 :position startpos))
11831 dolog now-done-p)
11832 (when org-blocker-hook
11833 (setq org-last-todo-state-is-todo
11834 (not (member this org-done-keywords)))
11835 (unless (save-excursion
11836 (save-match-data
11837 (org-with-wide-buffer
11838 (run-hook-with-args-until-failure
11839 'org-blocker-hook change-plist))))
11840 (if (org-called-interactively-p 'interactive)
11841 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11842 this org-state org-block-entry-blocking)
11843 ;; fail silently
11844 (message "TODO state change from %s to %s blocked (by \"%s\")"
11845 this org-state org-block-entry-blocking)
11846 (throw 'exit nil))))
11847 (store-match-data match-data)
11848 (replace-match next t t)
11849 (unless (pos-visible-in-window-p hl-pos)
11850 (message "TODO state changed to %s" (org-trim next)))
11851 (unless head
11852 (setq head (org-get-todo-sequence-head org-state)
11853 ass (assoc head org-todo-kwd-alist)
11854 interpret (nth 1 ass)
11855 done-word (nth 3 ass)
11856 final-done-word (nth 4 ass)))
11857 (when (memq arg '(nextset previousset))
11858 (message "Keyword-Set %d/%d: %s"
11859 (- (length org-todo-sets) -1
11860 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11861 (length org-todo-sets)
11862 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11863 (setq org-last-todo-state-is-todo
11864 (not (member org-state org-done-keywords)))
11865 (setq now-done-p (and (member org-state org-done-keywords)
11866 (not (member this org-done-keywords))))
11867 (and logging (org-local-logging logging))
11868 (when (and (or org-todo-log-states org-log-done)
11869 (not (eq org-inhibit-logging t))
11870 (not (memq arg '(nextset previousset))))
11871 ;; we need to look at recording a time and note
11872 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11873 (nth 2 (assoc this org-todo-log-states))))
11874 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11875 (setq dolog 'time))
11876 (when (and org-state
11877 (member org-state org-not-done-keywords)
11878 (not (member this org-not-done-keywords)))
11879 ;; This is now a todo state and was not one before
11880 ;; If there was a CLOSED time stamp, get rid of it.
11881 (org-add-planning-info nil nil 'closed))
11882 (when (and now-done-p org-log-done)
11883 ;; It is now done, and it was not done before
11884 (org-add-planning-info 'closed (org-current-effective-time))
11885 (if (and (not dolog) (eq 'note org-log-done))
11886 (org-add-log-setup 'done org-state this 'findpos 'note)))
11887 (when (and org-state dolog)
11888 ;; This is a non-nil state, and we need to log it
11889 (org-add-log-setup 'state org-state this 'findpos dolog)))
11890 ;; Fixup tag positioning
11891 (org-todo-trigger-tag-changes org-state)
11892 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11893 (when org-provide-todo-statistics
11894 (org-update-parent-todo-statistics))
11895 (run-hooks 'org-after-todo-state-change-hook)
11896 (if (and arg (not (member org-state org-done-keywords)))
11897 (setq head (org-get-todo-sequence-head org-state)))
11898 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11899 ;; Do we need to trigger a repeat?
11900 (when now-done-p
11901 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11902 ;; This is for the agenda, take a snapshot of the headline.
11903 (save-match-data
11904 (setq org-agenda-headline-snapshot-before-repeat
11905 (org-get-heading))))
11906 (org-auto-repeat-maybe org-state))
11907 ;; Fixup cursor location if close to the keyword
11908 (if (and (outline-on-heading-p)
11909 (not (bolp))
11910 (save-excursion (beginning-of-line 1)
11911 (looking-at org-todo-line-regexp))
11912 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11913 (progn
11914 (goto-char (or (match-end 2) (match-end 1)))
11915 (and (looking-at " ") (just-one-space))))
11916 (when org-trigger-hook
11917 (save-excursion
11918 (run-hook-with-args 'org-trigger-hook change-plist)))
11919 (when commentp (org-toggle-comment))))))))
11921 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11922 "Block turning an entry into a TODO, using the hierarchy.
11923 This checks whether the current task should be blocked from state
11924 changes. Such blocking occurs when:
11926 1. The task has children which are not all in a completed state.
11928 2. A task has a parent with the property :ORDERED:, and there
11929 are siblings prior to the current task with incomplete
11930 status.
11932 3. The parent of the task is blocked because it has siblings that should
11933 be done first, or is child of a block grandparent TODO entry."
11935 (if (not org-enforce-todo-dependencies)
11936 t ; if locally turned off don't block
11937 (catch 'dont-block
11938 ;; If this is not a todo state change, or if this entry is already DONE,
11939 ;; do not block
11940 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11941 (member (plist-get change-plist :from)
11942 (cons 'done org-done-keywords))
11943 (member (plist-get change-plist :to)
11944 (cons 'todo org-not-done-keywords))
11945 (not (plist-get change-plist :to)))
11946 (throw 'dont-block t))
11947 ;; If this task has children, and any are undone, it's blocked
11948 (save-excursion
11949 (org-back-to-heading t)
11950 (let ((this-level (funcall outline-level)))
11951 (outline-next-heading)
11952 (let ((child-level (funcall outline-level)))
11953 (while (and (not (eobp))
11954 (> child-level this-level))
11955 ;; this todo has children, check whether they are all
11956 ;; completed
11957 (if (and (not (org-entry-is-done-p))
11958 (org-entry-is-todo-p))
11959 (progn (setq org-block-entry-blocking (org-get-heading))
11960 (throw 'dont-block nil)))
11961 (outline-next-heading)
11962 (setq child-level (funcall outline-level))))))
11963 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11964 ;; any previous siblings are undone, it's blocked
11965 (save-excursion
11966 (org-back-to-heading t)
11967 (let* ((pos (point))
11968 (parent-pos (and (org-up-heading-safe) (point))))
11969 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11970 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11971 (forward-line 1)
11972 (re-search-forward org-not-done-heading-regexp pos t))
11973 (setq org-block-entry-blocking (match-string 0))
11974 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11975 ;; Search further up the hierarchy, to see if an ancestor is blocked
11976 (while t
11977 (goto-char parent-pos)
11978 (if (not (looking-at org-not-done-heading-regexp))
11979 (throw 'dont-block t)) ; do not block, parent is not a TODO
11980 (setq pos (point))
11981 (setq parent-pos (and (org-up-heading-safe) (point)))
11982 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11983 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11984 (forward-line 1)
11985 (re-search-forward org-not-done-heading-regexp pos t)
11986 (setq org-block-entry-blocking (org-get-heading)))
11987 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11989 (defcustom org-track-ordered-property-with-tag nil
11990 "Should the ORDERED property also be shown as a tag?
11991 The ORDERED property decides if an entry should require subtasks to be
11992 completed in sequence. Since a property is not very visible, setting
11993 this option means that toggling the ORDERED property with the command
11994 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11995 not relevant for the behavior, but it makes things more visible.
11997 Note that toggling the tag with tags commands will not change the property
11998 and therefore not influence behavior!
12000 This can be t, meaning the tag ORDERED should be used, It can also be a
12001 string to select a different tag for this task."
12002 :group 'org-todo
12003 :type '(choice
12004 (const :tag "No tracking" nil)
12005 (const :tag "Track with ORDERED tag" t)
12006 (string :tag "Use other tag")))
12008 (defun org-toggle-ordered-property ()
12009 "Toggle the ORDERED property of the current entry.
12010 For better visibility, you can track the value of this property with a tag.
12011 See variable `org-track-ordered-property-with-tag'."
12012 (interactive)
12013 (let* ((t1 org-track-ordered-property-with-tag)
12014 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12015 (save-excursion
12016 (org-back-to-heading)
12017 (if (org-entry-get nil "ORDERED")
12018 (progn
12019 (org-delete-property "ORDERED")
12020 (and tag (org-toggle-tag tag 'off))
12021 (message "Subtasks can be completed in arbitrary order"))
12022 (org-entry-put nil "ORDERED" "t")
12023 (and tag (org-toggle-tag tag 'on))
12024 (message "Subtasks must be completed in sequence")))))
12026 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12027 (defun org-block-todo-from-checkboxes (change-plist)
12028 "Block turning an entry into a TODO, using checkboxes.
12029 This checks whether the current task should be blocked from state
12030 changes because there are unchecked boxes in this entry."
12031 (if (not org-enforce-todo-checkbox-dependencies)
12032 t ; if locally turned off don't block
12033 (catch 'dont-block
12034 ;; If this is not a todo state change, or if this entry is already DONE,
12035 ;; do not block
12036 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12037 (member (plist-get change-plist :from)
12038 (cons 'done org-done-keywords))
12039 (member (plist-get change-plist :to)
12040 (cons 'todo org-not-done-keywords))
12041 (not (plist-get change-plist :to)))
12042 (throw 'dont-block t))
12043 ;; If this task has checkboxes that are not checked, it's blocked
12044 (save-excursion
12045 (org-back-to-heading t)
12046 (let ((beg (point)) end)
12047 (outline-next-heading)
12048 (setq end (point))
12049 (goto-char beg)
12050 (if (org-list-search-forward
12051 (concat (org-item-beginning-re)
12052 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12053 "\\[[- ]\\]")
12054 end t)
12055 (progn
12056 (if (boundp 'org-blocked-by-checkboxes)
12057 (setq org-blocked-by-checkboxes t))
12058 (throw 'dont-block nil)))))
12059 t))) ; do not block
12061 (defun org-entry-blocked-p ()
12062 "Is the current entry blocked?"
12063 (org-with-buffer-modified-unmodified
12064 (if (org-entry-get nil "NOBLOCKING")
12065 nil ;; Never block this entry
12066 (not
12067 (run-hook-with-args-until-failure
12068 'org-blocker-hook
12069 (list :type 'todo-state-change
12070 :position (point)
12071 :from 'todo
12072 :to 'done))))))
12074 (defun org-update-statistics-cookies (all)
12075 "Update the statistics cookie, either from TODO or from checkboxes.
12076 This should be called with the cursor in a line with a statistics cookie."
12077 (interactive "P")
12078 (if all
12079 (progn
12080 (org-update-checkbox-count 'all)
12081 (org-map-entries 'org-update-parent-todo-statistics))
12082 (if (not (org-at-heading-p))
12083 (org-update-checkbox-count)
12084 (let ((pos (point-marker))
12085 end l1 l2)
12086 (ignore-errors (org-back-to-heading t))
12087 (if (not (org-at-heading-p))
12088 (org-update-checkbox-count)
12089 (setq l1 (org-outline-level))
12090 (setq end (save-excursion
12091 (outline-next-heading)
12092 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12093 (point)))
12094 (if (and (save-excursion
12095 (re-search-forward
12096 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12097 (not (save-excursion (re-search-forward
12098 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12099 (org-update-checkbox-count)
12100 (if (and l2 (> l2 l1))
12101 (progn
12102 (goto-char end)
12103 (org-update-parent-todo-statistics))
12104 (goto-char pos)
12105 (beginning-of-line 1)
12106 (while (re-search-forward
12107 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12108 (point-at-eol) t)
12109 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12110 (goto-char pos)
12111 (move-marker pos nil)))))
12113 (defvar org-entry-property-inherited-from) ;; defined below
12114 (defun org-update-parent-todo-statistics ()
12115 "Update any statistics cookie in the parent of the current headline.
12116 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12117 the entire subtree and this will travel up the hierarchy and update
12118 statistics everywhere."
12119 (let* ((prop (save-excursion (org-up-heading-safe)
12120 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12121 (recursive (or (not org-hierarchical-todo-statistics)
12122 (and prop (string-match "\\<recursive\\>" prop))))
12123 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12125 (first t)
12126 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12127 level ltoggle l1 new ndel
12128 (cnt-all 0) (cnt-done 0) is-percent kwd
12129 checkbox-beg ov ovs ove cookie-present)
12130 (catch 'exit
12131 (save-excursion
12132 (beginning-of-line 1)
12133 (setq ltoggle (funcall outline-level))
12134 ;; Three situations are to consider:
12136 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12137 ;; to the top-level ancestor on the headline;
12139 ;; 2. If parent has "recursive" property, repeat up to the
12140 ;; headline setting that property, taking inheritance into
12141 ;; account;
12143 ;; 3. Else, move up to direct parent and proceed only once.
12144 (while (and (setq level (org-up-heading-safe))
12145 (or recursive first)
12146 (>= (point) lim))
12147 (setq first nil cookie-present nil)
12148 (unless (and level
12149 (not (string-match
12150 "\\<checkbox\\>"
12151 (downcase (or (org-entry-get nil "COOKIE_DATA")
12152 "")))))
12153 (throw 'exit nil))
12154 (while (re-search-forward box-re (point-at-eol) t)
12155 (setq cnt-all 0 cnt-done 0 cookie-present t)
12156 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12157 (save-match-data
12158 (unless (outline-next-heading) (throw 'exit nil))
12159 (while (and (looking-at org-complex-heading-regexp)
12160 (> (setq l1 (length (match-string 1))) level))
12161 (setq kwd (and (or recursive (= l1 ltoggle))
12162 (match-string 2)))
12163 (if (or (eq org-provide-todo-statistics 'all-headlines)
12164 (and (listp org-provide-todo-statistics)
12165 (or (member kwd org-provide-todo-statistics)
12166 (member kwd org-done-keywords))))
12167 (setq cnt-all (1+ cnt-all))
12168 (if (eq org-provide-todo-statistics t)
12169 (and kwd (setq cnt-all (1+ cnt-all)))))
12170 (and (member kwd org-done-keywords)
12171 (setq cnt-done (1+ cnt-done)))
12172 (outline-next-heading)))
12173 (setq new
12174 (if is-percent
12175 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12176 (format "[%d/%d]" cnt-done cnt-all))
12177 ndel (- (match-end 0) checkbox-beg))
12178 ;; handle overlays when updating cookie from column view
12179 (when (setq ov (car (overlays-at checkbox-beg)))
12180 (setq ovs (overlay-start ov) ove (overlay-end ov))
12181 (delete-overlay ov))
12182 (goto-char checkbox-beg)
12183 (insert new)
12184 (delete-region (point) (+ (point) ndel))
12185 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12186 (when ov (move-overlay ov ovs ove)))
12187 (when cookie-present
12188 (run-hook-with-args 'org-after-todo-statistics-hook
12189 cnt-done (- cnt-all cnt-done))))))
12190 (run-hooks 'org-todo-statistics-hook)))
12192 (defvar org-after-todo-statistics-hook nil
12193 "Hook that is called after a TODO statistics cookie has been updated.
12194 Each function is called with two arguments: the number of not-done entries
12195 and the number of done entries.
12197 For example, the following function, when added to this hook, will switch
12198 an entry to DONE when all children are done, and back to TODO when new
12199 entries are set to a TODO status. Note that this hook is only called
12200 when there is a statistics cookie in the headline!
12202 (defun org-summary-todo (n-done n-not-done)
12203 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12204 (let (org-log-done org-log-states) ; turn off logging
12205 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12208 (defvar org-todo-statistics-hook nil
12209 "Hook that is run whenever Org thinks TODO statistics should be updated.
12210 This hook runs even if there is no statistics cookie present, in which case
12211 `org-after-todo-statistics-hook' would not run.")
12213 (defun org-todo-trigger-tag-changes (state)
12214 "Apply the changes defined in `org-todo-state-tags-triggers'."
12215 (let ((l org-todo-state-tags-triggers)
12216 changes)
12217 (when (or (not state) (equal state ""))
12218 (setq changes (append changes (cdr (assoc "" l)))))
12219 (when (and (stringp state) (> (length state) 0))
12220 (setq changes (append changes (cdr (assoc state l)))))
12221 (when (member state org-not-done-keywords)
12222 (setq changes (append changes (cdr (assoc 'todo l)))))
12223 (when (member state org-done-keywords)
12224 (setq changes (append changes (cdr (assoc 'done l)))))
12225 (dolist (c changes)
12226 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12228 (defun org-local-logging (value)
12229 "Get logging settings from a property VALUE."
12230 (let* (words w a)
12231 ;; directly set the variables, they are already local.
12232 (setq org-log-done nil
12233 org-log-repeat nil
12234 org-todo-log-states nil)
12235 (setq words (org-split-string value))
12236 (while (setq w (pop words))
12237 (cond
12238 ((setq a (assoc w org-startup-options))
12239 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12240 (set (nth 1 a) (nth 2 a))))
12241 ((setq a (org-extract-log-state-settings w))
12242 (and (member (car a) org-todo-keywords-1)
12243 (push a org-todo-log-states)))))))
12245 (defun org-get-todo-sequence-head (kwd)
12246 "Return the head of the TODO sequence to which KWD belongs.
12247 If KWD is not set, check if there is a text property remembering the
12248 right sequence."
12249 (let (p)
12250 (cond
12251 ((not kwd)
12252 (or (get-text-property (point-at-bol) 'org-todo-head)
12253 (progn
12254 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12255 nil (point-at-eol)))
12256 (get-text-property p 'org-todo-head))))
12257 ((not (member kwd org-todo-keywords-1))
12258 (car org-todo-keywords-1))
12259 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12261 (defun org-fast-todo-selection ()
12262 "Fast TODO keyword selection with single keys.
12263 Returns the new TODO keyword, or nil if no state change should occur."
12264 (let* ((fulltable org-todo-key-alist)
12265 (done-keywords org-done-keywords) ;; needed for the faces.
12266 (maxlen (apply 'max (mapcar
12267 (lambda (x)
12268 (if (stringp (car x)) (string-width (car x)) 0))
12269 fulltable)))
12270 (expert nil)
12271 (fwidth (+ maxlen 3 1 3))
12272 (ncol (/ (- (window-width) 4) fwidth))
12273 tg cnt e c tbl
12274 groups ingroup)
12275 (save-excursion
12276 (save-window-excursion
12277 (if expert
12278 (set-buffer (get-buffer-create " *Org todo*"))
12279 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12280 (erase-buffer)
12281 (org-set-local 'org-done-keywords done-keywords)
12282 (setq tbl fulltable cnt 0)
12283 (while (setq e (pop tbl))
12284 (cond
12285 ((equal e '(:startgroup))
12286 (push '() groups) (setq ingroup t)
12287 (when (not (= cnt 0))
12288 (setq cnt 0)
12289 (insert "\n"))
12290 (insert "{ "))
12291 ((equal e '(:endgroup))
12292 (setq ingroup nil cnt 0)
12293 (insert "}\n"))
12294 ((equal e '(:newline))
12295 (when (not (= cnt 0))
12296 (setq cnt 0)
12297 (insert "\n")
12298 (setq e (car tbl))
12299 (while (equal (car tbl) '(:newline))
12300 (insert "\n")
12301 (setq tbl (cdr tbl)))))
12303 (setq tg (car e) c (cdr e))
12304 (if ingroup (push tg (car groups)))
12305 (setq tg (org-add-props tg nil 'face
12306 (org-get-todo-face tg)))
12307 (if (and (= cnt 0) (not ingroup)) (insert " "))
12308 (insert "[" c "] " tg (make-string
12309 (- fwidth 4 (length tg)) ?\ ))
12310 (when (= (setq cnt (1+ cnt)) ncol)
12311 (insert "\n")
12312 (if ingroup (insert " "))
12313 (setq cnt 0)))))
12314 (insert "\n")
12315 (goto-char (point-min))
12316 (if (not expert) (org-fit-window-to-buffer))
12317 (message "[a-z..]:Set [SPC]:clear")
12318 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12319 (cond
12320 ((or (= c ?\C-g)
12321 (and (= c ?q) (not (rassoc c fulltable))))
12322 (setq quit-flag t))
12323 ((= c ?\ ) nil)
12324 ((setq e (rassoc c fulltable) tg (car e))
12326 (t (setq quit-flag t)))))))
12328 (defun org-entry-is-todo-p ()
12329 (member (org-get-todo-state) org-not-done-keywords))
12331 (defun org-entry-is-done-p ()
12332 (member (org-get-todo-state) org-done-keywords))
12334 (defun org-get-todo-state ()
12335 (save-excursion
12336 (org-back-to-heading t)
12337 (and (looking-at org-todo-line-regexp)
12338 (match-end 2)
12339 (match-string 2))))
12341 (defun org-at-date-range-p (&optional inactive-ok)
12342 "Is the cursor inside a date range?"
12343 (interactive)
12344 (save-excursion
12345 (catch 'exit
12346 (let ((pos (point)))
12347 (skip-chars-backward "^[<\r\n")
12348 (skip-chars-backward "<[")
12349 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12350 (>= (match-end 0) pos)
12351 (throw 'exit t))
12352 (skip-chars-backward "^<[\r\n")
12353 (skip-chars-backward "<[")
12354 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12355 (>= (match-end 0) pos)
12356 (throw 'exit t)))
12357 nil)))
12359 (defun org-get-repeat (&optional tagline)
12360 "Check if there is a deadline/schedule with repeater in this entry."
12361 (save-match-data
12362 (save-excursion
12363 (org-back-to-heading t)
12364 (and (re-search-forward (if tagline
12365 (concat tagline "\\s-*" org-repeat-re)
12366 org-repeat-re)
12367 (org-entry-end-position) t)
12368 (match-string-no-properties 1)))))
12370 (defvar org-last-changed-timestamp)
12371 (defvar org-last-inserted-timestamp)
12372 (defvar org-log-post-message)
12373 (defvar org-log-note-purpose)
12374 (defvar org-log-note-how)
12375 (defvar org-log-note-extra)
12376 (defun org-auto-repeat-maybe (done-word)
12377 "Check if the current headline contains a repeated deadline/schedule.
12378 If yes, set TODO state back to what it was and change the base date
12379 of repeating deadline/scheduled time stamps to new date.
12380 This function is run automatically after each state change to a DONE state."
12381 ;; last-state is dynamically scoped into this function
12382 (let* ((repeat (org-get-repeat))
12383 (aa (assoc org-last-state org-todo-kwd-alist))
12384 (interpret (nth 1 aa))
12385 (head (nth 2 aa))
12386 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12387 (msg "Entry repeats: ")
12388 (org-log-done nil)
12389 (org-todo-log-states nil)
12390 re type n what ts time to-state)
12391 (when repeat
12392 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12393 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12394 org-todo-repeat-to-state))
12395 (unless (and to-state (member to-state org-todo-keywords-1))
12396 (setq to-state (if (eq interpret 'type) org-last-state head)))
12397 (org-todo to-state)
12398 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12399 (org-entry-put nil "LAST_REPEAT" (format-time-string
12400 (org-time-stamp-format t t))))
12401 (when org-log-repeat
12402 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12403 (memq 'org-add-log-note post-command-hook))
12404 ;; OK, we are already setup for some record
12405 (if (eq org-log-repeat 'note)
12406 ;; make sure we take a note, not only a time stamp
12407 (setq org-log-note-how 'note))
12408 ;; Set up for taking a record
12409 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12410 org-last-state
12411 'findpos org-log-repeat)))
12412 (org-back-to-heading t)
12413 (org-add-planning-info nil nil 'closed)
12414 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12415 org-deadline-time-regexp "\\)\\|\\("
12416 org-ts-regexp "\\)"))
12417 (while (re-search-forward
12418 re (save-excursion (outline-next-heading) (point)) t)
12419 (setq type (if (match-end 1) org-scheduled-string
12420 (if (match-end 3) org-deadline-string "Plain:"))
12421 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12422 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12423 (setq n (string-to-number (match-string 2 ts))
12424 what (match-string 3 ts))
12425 (if (equal what "w") (setq n (* n 7) what "d"))
12426 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12427 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12428 ;; Preparation, see if we need to modify the start date for the change
12429 (when (match-end 1)
12430 (setq time (save-match-data (org-time-string-to-time ts)))
12431 (cond
12432 ((equal (match-string 1 ts) ".")
12433 ;; Shift starting date to today
12434 (org-timestamp-change
12435 (- (org-today) (time-to-days time))
12436 'day))
12437 ((equal (match-string 1 ts) "+")
12438 (let ((nshiftmax 10) (nshift 0))
12439 (while (or (= nshift 0)
12440 (<= (time-to-days time)
12441 (time-to-days (current-time))))
12442 (when (= (incf nshift) nshiftmax)
12443 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12444 (error "Abort")))
12445 (org-timestamp-change n (cdr (assoc what whata)))
12446 (org-at-timestamp-p t)
12447 (setq ts (match-string 1))
12448 (setq time (save-match-data (org-time-string-to-time ts)))))
12449 (org-timestamp-change (- n) (cdr (assoc what whata)))
12450 ;; rematch, so that we have everything in place for the real shift
12451 (org-at-timestamp-p t)
12452 (setq ts (match-string 1))
12453 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12454 (org-timestamp-change n (cdr (assoc what whata)))
12455 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12456 (setq org-log-post-message msg)
12457 (message "%s" msg))))
12459 (defun org-show-todo-tree (arg)
12460 "Make a compact tree which shows all headlines marked with TODO.
12461 The tree will show the lines where the regexp matches, and all higher
12462 headlines above the match.
12463 With a \\[universal-argument] prefix, prompt for a regexp to match.
12464 With a numeric prefix N, construct a sparse tree for the Nth element
12465 of `org-todo-keywords-1'."
12466 (interactive "P")
12467 (let ((case-fold-search nil)
12468 (kwd-re
12469 (cond ((null arg) org-not-done-regexp)
12470 ((equal arg '(4))
12471 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12472 (mapcar 'list org-todo-keywords-1))))
12473 (concat "\\("
12474 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12475 "\\)\\>")))
12476 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12477 (regexp-quote (nth (1- (prefix-numeric-value arg))
12478 org-todo-keywords-1)))
12479 (t (error "Invalid prefix argument: %s" arg)))))
12480 (message "%d TODO entries found"
12481 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12483 (defun org-deadline (&optional remove time)
12484 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12485 With argument REMOVE, remove any deadline from the item.
12486 With argument TIME, set the deadline at the corresponding date. TIME
12487 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12488 (interactive "P")
12489 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12490 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12491 'region-start-level 'region))
12492 org-loop-over-headlines-in-active-region)
12493 (org-map-entries
12494 `(org-deadline ',remove ,time)
12495 org-loop-over-headlines-in-active-region
12496 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12497 (let* ((old-date (org-entry-get nil "DEADLINE"))
12498 (repeater (and old-date
12499 (string-match
12500 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12501 old-date)
12502 (match-string 1 old-date))))
12503 (if remove
12504 (progn
12505 (when (and old-date org-log-redeadline)
12506 (org-add-log-setup 'deldeadline nil old-date 'findpos
12507 org-log-redeadline))
12508 (org-remove-timestamp-with-keyword org-deadline-string)
12509 (message "Item no longer has a deadline."))
12510 (org-add-planning-info 'deadline time 'closed)
12511 (when (and old-date org-log-redeadline
12512 (not (equal old-date
12513 (substring org-last-inserted-timestamp 1 -1))))
12514 (org-add-log-setup 'redeadline nil old-date 'findpos
12515 org-log-redeadline))
12516 (when repeater
12517 (save-excursion
12518 (org-back-to-heading t)
12519 (when (re-search-forward (concat org-deadline-string " "
12520 org-last-inserted-timestamp)
12521 (save-excursion
12522 (outline-next-heading) (point)) t)
12523 (goto-char (1- (match-end 0)))
12524 (insert " " repeater)
12525 (setq org-last-inserted-timestamp
12526 (concat (substring org-last-inserted-timestamp 0 -1)
12527 " " repeater
12528 (substring org-last-inserted-timestamp -1))))))
12529 (message "Deadline on %s" org-last-inserted-timestamp)))))
12531 (defun org-schedule (&optional remove time)
12532 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12533 With argument REMOVE, remove any scheduling date from the item.
12534 With argument TIME, scheduled at the corresponding date. TIME can
12535 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12536 (interactive "P")
12537 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12538 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12539 'region-start-level 'region))
12540 org-loop-over-headlines-in-active-region)
12541 (org-map-entries
12542 `(org-schedule ',remove ,time)
12543 org-loop-over-headlines-in-active-region
12544 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12545 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12546 (repeater (and old-date
12547 (string-match
12548 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12549 old-date)
12550 (match-string 1 old-date))))
12551 (if remove
12552 (progn
12553 (when (and old-date org-log-reschedule)
12554 (org-add-log-setup 'delschedule nil old-date 'findpos
12555 org-log-reschedule))
12556 (org-remove-timestamp-with-keyword org-scheduled-string)
12557 (message "Item is no longer scheduled."))
12558 (org-add-planning-info 'scheduled time 'closed)
12559 (when (and old-date org-log-reschedule
12560 (not (equal old-date
12561 (substring org-last-inserted-timestamp 1 -1))))
12562 (org-add-log-setup 'reschedule nil old-date 'findpos
12563 org-log-reschedule))
12564 (when repeater
12565 (save-excursion
12566 (org-back-to-heading t)
12567 (when (re-search-forward (concat org-scheduled-string " "
12568 org-last-inserted-timestamp)
12569 (save-excursion
12570 (outline-next-heading) (point)) t)
12571 (goto-char (1- (match-end 0)))
12572 (insert " " repeater)
12573 (setq org-last-inserted-timestamp
12574 (concat (substring org-last-inserted-timestamp 0 -1)
12575 " " repeater
12576 (substring org-last-inserted-timestamp -1))))))
12577 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12579 (defun org-get-scheduled-time (pom &optional inherit)
12580 "Get the scheduled time as a time tuple, of a format suitable
12581 for calling org-schedule with, or if there is no scheduling,
12582 returns nil."
12583 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12584 (when time
12585 (apply 'encode-time (org-parse-time-string time)))))
12587 (defun org-get-deadline-time (pom &optional inherit)
12588 "Get the deadline as a time tuple, of a format suitable for
12589 calling org-deadline with, or if there is no scheduling, returns
12590 nil."
12591 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12592 (when time
12593 (apply 'encode-time (org-parse-time-string time)))))
12595 (defun org-remove-timestamp-with-keyword (keyword)
12596 "Remove all time stamps with KEYWORD in the current entry."
12597 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12598 beg)
12599 (save-excursion
12600 (org-back-to-heading t)
12601 (setq beg (point))
12602 (outline-next-heading)
12603 (while (re-search-backward re beg t)
12604 (replace-match "")
12605 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12606 (equal (char-before) ?\ ))
12607 (backward-delete-char 1)
12608 (if (string-match "^[ \t]*$" (buffer-substring
12609 (point-at-bol) (point-at-eol)))
12610 (delete-region (point-at-bol)
12611 (min (point-max) (1+ (point-at-eol))))))))))
12613 (defun org-add-planning-info (what &optional time &rest remove)
12614 "Insert new timestamp with keyword in the line directly after the headline.
12615 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12616 If non is given, the user is prompted for a date.
12617 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12618 be removed."
12619 (interactive)
12620 (let (org-time-was-given org-end-time-was-given ts
12621 end default-time default-input)
12623 (catch 'exit
12624 (when (and (memq what '(scheduled deadline))
12625 (or (not time)
12626 (and (stringp time)
12627 (string-match "^[-+]+[0-9]" time))))
12628 ;; Try to get a default date/time from existing timestamp
12629 (save-excursion
12630 (org-back-to-heading t)
12631 (setq end (save-excursion (outline-next-heading) (point)))
12632 (when (re-search-forward (if (eq what 'scheduled)
12633 org-scheduled-time-regexp
12634 org-deadline-time-regexp)
12635 end t)
12636 (setq ts (match-string 1)
12637 default-time
12638 (apply 'encode-time (org-parse-time-string ts))
12639 default-input (and ts (org-get-compact-tod ts))))))
12640 (when what
12641 (setq time
12642 (if (stringp time)
12643 ;; This is a string (relative or absolute), set proper date
12644 (apply 'encode-time
12645 (org-read-date-analyze
12646 time default-time (decode-time default-time)))
12647 ;; If necessary, get the time from the user
12648 (or time (org-read-date nil 'to-time nil nil
12649 default-time default-input)))))
12651 (when (and org-insert-labeled-timestamps-at-point
12652 (member what '(scheduled deadline)))
12653 (insert
12654 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12655 (org-insert-time-stamp time org-time-was-given
12656 nil nil nil (list org-end-time-was-given))
12657 (setq what nil))
12658 (save-excursion
12659 (save-restriction
12660 (let (col list elt ts buffer-invisibility-spec)
12661 (org-back-to-heading t)
12662 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12663 (goto-char (match-end 1))
12664 (setq col (current-column))
12665 (goto-char (match-end 0))
12666 (if (eobp) (insert "\n") (forward-char 1))
12667 (when (and (not what)
12668 (not (looking-at
12669 (concat "[ \t]*"
12670 org-keyword-time-not-clock-regexp))))
12671 ;; Nothing to add, nothing to remove...... :-)
12672 (throw 'exit nil))
12673 (if (and (not (looking-at org-outline-regexp))
12674 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12675 "[^\r\n]*"))
12676 (not (equal (match-string 1) org-clock-string)))
12677 (narrow-to-region (match-beginning 0) (match-end 0))
12678 (insert-before-markers "\n")
12679 (backward-char 1)
12680 (narrow-to-region (point) (point))
12681 (and org-adapt-indentation (org-indent-to-column col)))
12682 ;; Check if we have to remove something.
12683 (setq list (cons what remove))
12684 (while list
12685 (setq elt (pop list))
12686 (when (or (and (eq elt 'scheduled)
12687 (re-search-forward org-scheduled-time-regexp nil t))
12688 (and (eq elt 'deadline)
12689 (re-search-forward org-deadline-time-regexp nil t))
12690 (and (eq elt 'closed)
12691 (re-search-forward org-closed-time-regexp nil t)))
12692 (replace-match "")
12693 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12694 (and (looking-at "[ \t]+") (replace-match ""))
12695 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12696 (when what
12697 (insert
12698 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12699 (cond ((eq what 'scheduled) org-scheduled-string)
12700 ((eq what 'deadline) org-deadline-string)
12701 ((eq what 'closed) org-closed-string))
12702 " ")
12703 (setq ts (org-insert-time-stamp
12704 time
12705 (or org-time-was-given
12706 (and (eq what 'closed) org-log-done-with-time))
12707 (eq what 'closed)
12708 nil nil (list org-end-time-was-given)))
12709 (insert
12710 (if (not (or (bolp) (eq (char-before) ?\ )
12711 (memq (char-after) '(32 10))
12712 (eobp))) " " ""))
12713 (end-of-line 1))
12714 (goto-char (point-min))
12715 (widen)
12716 (if (and (looking-at "[ \t]*\n")
12717 (equal (char-before) ?\n))
12718 (delete-region (1- (point)) (point-at-eol)))
12719 ts))))))
12721 (defvar org-log-note-marker (make-marker))
12722 (defvar org-log-note-purpose nil)
12723 (defvar org-log-note-state nil)
12724 (defvar org-log-note-previous-state nil)
12725 (defvar org-log-note-how nil)
12726 (defvar org-log-note-extra nil)
12727 (defvar org-log-note-window-configuration nil)
12728 (defvar org-log-note-return-to (make-marker))
12729 (defvar org-log-note-effective-time nil
12730 "Remembered current time so that dynamically scoped
12731 `org-extend-today-until' affects tha timestamps in state change
12732 log")
12734 (defvar org-log-post-message nil
12735 "Message to be displayed after a log note has been stored.
12736 The auto-repeater uses this.")
12738 (defun org-add-note ()
12739 "Add a note to the current entry.
12740 This is done in the same way as adding a state change note."
12741 (interactive)
12742 (org-add-log-setup 'note nil nil 'findpos nil))
12744 (defvar org-property-end-re)
12745 (defun org-add-log-setup (&optional purpose state prev-state
12746 findpos how extra)
12747 "Set up the post command hook to take a note.
12748 If this is about to TODO state change, the new state is expected in STATE.
12749 When FINDPOS is non-nil, find the correct position for the note in
12750 the current entry. If not, assume that it can be inserted at point.
12751 HOW is an indicator what kind of note should be created.
12752 EXTRA is additional text that will be inserted into the notes buffer."
12753 (let* ((org-log-into-drawer (org-log-into-drawer))
12754 (drawer (cond ((stringp org-log-into-drawer)
12755 org-log-into-drawer)
12756 (org-log-into-drawer "LOGBOOK"))))
12757 (save-restriction
12758 (save-excursion
12759 (when findpos
12760 (org-back-to-heading t)
12761 (narrow-to-region (point) (save-excursion
12762 (outline-next-heading) (point)))
12763 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12764 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12765 "[^\r\n]*\\)?"))
12766 (goto-char (match-end 0))
12767 (cond
12768 (drawer
12769 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12770 nil t)
12771 (progn
12772 (goto-char (match-end 0))
12773 (or org-log-states-order-reversed
12774 (and (re-search-forward org-property-end-re nil t)
12775 (goto-char (1- (match-beginning 0))))))
12776 (insert "\n:" drawer ":\n:END:")
12777 (beginning-of-line 0)
12778 (org-indent-line)
12779 (beginning-of-line 2)
12780 (org-indent-line)
12781 (end-of-line 0)))
12782 ((and org-log-state-notes-insert-after-drawers
12783 (save-excursion
12784 (forward-line) (looking-at org-drawer-regexp)))
12785 (forward-line)
12786 (while (looking-at org-drawer-regexp)
12787 (goto-char (match-end 0))
12788 (re-search-forward org-property-end-re (point-max) t)
12789 (forward-line))
12790 (forward-line -1)))
12791 (unless org-log-states-order-reversed
12792 (and (= (char-after) ?\n) (forward-char 1))
12793 (org-skip-over-state-notes)
12794 (skip-chars-backward " \t\n\r")))
12795 (move-marker org-log-note-marker (point))
12796 (setq org-log-note-purpose purpose
12797 org-log-note-state state
12798 org-log-note-previous-state prev-state
12799 org-log-note-how how
12800 org-log-note-extra extra
12801 org-log-note-effective-time (org-current-effective-time))
12802 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12804 (defun org-skip-over-state-notes ()
12805 "Skip past the list of State notes in an entry."
12806 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12807 (when (ignore-errors (goto-char (org-in-item-p)))
12808 (let* ((struct (org-list-struct))
12809 (prevs (org-list-prevs-alist struct)))
12810 (while (looking-at "[ \t]*- State")
12811 (goto-char (or (org-list-get-next-item (point) struct prevs)
12812 (org-list-get-item-end (point) struct)))))))
12814 (defun org-add-log-note (&optional purpose)
12815 "Pop up a window for taking a note, and add this note later at point."
12816 (remove-hook 'post-command-hook 'org-add-log-note)
12817 (setq org-log-note-window-configuration (current-window-configuration))
12818 (delete-other-windows)
12819 (move-marker org-log-note-return-to (point))
12820 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12821 (goto-char org-log-note-marker)
12822 (org-switch-to-buffer-other-window "*Org Note*")
12823 (erase-buffer)
12824 (if (memq org-log-note-how '(time state))
12825 (let (current-prefix-arg) (org-store-log-note))
12826 (let ((org-inhibit-startup t)) (org-mode))
12827 (insert (format "# Insert note for %s.
12828 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12829 (cond
12830 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12831 ((eq org-log-note-purpose 'done) "closed todo item")
12832 ((eq org-log-note-purpose 'state)
12833 (format "state change from \"%s\" to \"%s\""
12834 (or org-log-note-previous-state "")
12835 (or org-log-note-state "")))
12836 ((eq org-log-note-purpose 'reschedule)
12837 "rescheduling")
12838 ((eq org-log-note-purpose 'delschedule)
12839 "no longer scheduled")
12840 ((eq org-log-note-purpose 'redeadline)
12841 "changing deadline")
12842 ((eq org-log-note-purpose 'deldeadline)
12843 "removing deadline")
12844 ((eq org-log-note-purpose 'refile)
12845 "refiling")
12846 ((eq org-log-note-purpose 'note)
12847 "this entry")
12848 (t (error "This should not happen")))))
12849 (if org-log-note-extra (insert org-log-note-extra))
12850 (org-set-local 'org-finish-function 'org-store-log-note)
12851 (run-hooks 'org-log-buffer-setup-hook)))
12853 (defvar org-note-abort nil) ; dynamically scoped
12854 (defun org-store-log-note ()
12855 "Finish taking a log note, and insert it to where it belongs."
12856 (let ((txt (buffer-string)))
12857 (kill-buffer (current-buffer))
12858 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12859 lines ind bul)
12860 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12861 (setq txt (replace-match "" t t txt)))
12862 (if (string-match "\\s-+\\'" txt)
12863 (setq txt (replace-match "" t t txt)))
12864 (setq lines (org-split-string txt "\n"))
12865 (when (and note (string-match "\\S-" note))
12866 (setq note
12867 (org-replace-escapes
12868 note
12869 (list (cons "%u" (user-login-name))
12870 (cons "%U" user-full-name)
12871 (cons "%t" (format-time-string
12872 (org-time-stamp-format 'long 'inactive)
12873 org-log-note-effective-time))
12874 (cons "%T" (format-time-string
12875 (org-time-stamp-format 'long nil)
12876 org-log-note-effective-time))
12877 (cons "%d" (format-time-string
12878 (org-time-stamp-format nil 'inactive)
12879 org-log-note-effective-time))
12880 (cons "%D" (format-time-string
12881 (org-time-stamp-format nil nil)
12882 org-log-note-effective-time))
12883 (cons "%s" (if org-log-note-state
12884 (concat "\"" org-log-note-state "\"")
12885 ""))
12886 (cons "%S" (if org-log-note-previous-state
12887 (concat "\"" org-log-note-previous-state "\"")
12888 "\"\"")))))
12889 (if lines (setq note (concat note " \\\\")))
12890 (push note lines))
12891 (when (or current-prefix-arg org-note-abort)
12892 (when org-log-into-drawer
12893 (org-remove-empty-drawer-at
12894 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12895 org-log-note-marker))
12896 (setq lines nil))
12897 (when lines
12898 (with-current-buffer (marker-buffer org-log-note-marker)
12899 (save-excursion
12900 (goto-char org-log-note-marker)
12901 (move-marker org-log-note-marker nil)
12902 (end-of-line 1)
12903 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12904 (setq ind (save-excursion
12905 (if (ignore-errors (goto-char (org-in-item-p)))
12906 (let ((struct (org-list-struct)))
12907 (org-list-get-ind
12908 (org-list-get-top-point struct) struct))
12909 (skip-chars-backward " \r\t\n")
12910 (cond
12911 ((and (org-at-heading-p)
12912 org-adapt-indentation)
12913 (1+ (org-current-level)))
12914 ((org-at-heading-p) 0)
12915 (t (org-get-indentation))))))
12916 (setq bul (org-list-bullet-string "-"))
12917 (org-indent-line-to ind)
12918 (insert bul (pop lines))
12919 (let ((ind-body (+ (length bul) ind)))
12920 (while lines
12921 (insert "\n")
12922 (org-indent-line-to ind-body)
12923 (insert (pop lines))))
12924 (message "Note stored")
12925 (org-back-to-heading t)
12926 (org-cycle-hide-drawers 'children))))))
12927 (set-window-configuration org-log-note-window-configuration)
12928 (with-current-buffer (marker-buffer org-log-note-return-to)
12929 (goto-char org-log-note-return-to))
12930 (move-marker org-log-note-return-to nil)
12931 (and org-log-post-message (message "%s" org-log-post-message)))
12933 (defun org-remove-empty-drawer-at (drawer pos)
12934 "Remove an empty drawer DRAWER at position POS.
12935 POS may also be a marker."
12936 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12937 (save-excursion
12938 (save-restriction
12939 (widen)
12940 (goto-char pos)
12941 (if (org-in-regexp
12942 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12943 (replace-match ""))))))
12945 (defvar org-ts-type nil)
12946 (defun org-sparse-tree (&optional arg type)
12947 "Create a sparse tree, prompt for the details.
12948 This command can create sparse trees. You first need to select the type
12949 of match used to create the tree:
12951 t Show all TODO entries.
12952 T Show entries with a specific TODO keyword.
12953 m Show entries selected by a tags/property match.
12954 p Enter a property name and its value (both with completion on existing
12955 names/values) and show entries with that property.
12956 r Show entries matching a regular expression (`/' can be used as well).
12957 b Show deadlines and scheduled items before a date.
12958 a Show deadlines and scheduled items after a date.
12959 d Show deadlines due within `org-deadline-warning-days'.
12960 D Show deadlines and scheduled items between a date range."
12961 (interactive "P")
12962 (let (ans kwd value ts-type)
12963 (setq type (or type org-sparse-tree-default-date-type))
12964 (setq org-ts-type type)
12965 (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"
12966 (cond ((eq type 'all) "all timestamps")
12967 ((eq type 'scheduled) "only scheduled")
12968 ((eq type 'deadline) "only deadline")
12969 ((eq type 'active) "only active timestamps")
12970 ((eq type 'inactive) "only inactive timestamps")
12971 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12972 (t "scheduled/deadline")))
12973 (setq ans (read-char-exclusive))
12974 (cond
12975 ((equal ans ?c)
12976 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12977 ((equal ans ?d)
12978 (call-interactively 'org-check-deadlines))
12979 ((equal ans ?b)
12980 (call-interactively 'org-check-before-date))
12981 ((equal ans ?a)
12982 (call-interactively 'org-check-after-date))
12983 ((equal ans ?D)
12984 (call-interactively 'org-check-dates-range))
12985 ((equal ans ?t)
12986 (call-interactively 'org-show-todo-tree))
12987 ((equal ans ?T)
12988 (org-show-todo-tree '(4)))
12989 ((member ans '(?T ?m))
12990 (call-interactively 'org-match-sparse-tree))
12991 ((member ans '(?p ?P))
12992 (setq kwd (org-icompleting-read "Property: "
12993 (mapcar 'list (org-buffer-property-keys))))
12994 (setq value (org-icompleting-read "Value: "
12995 (mapcar 'list (org-property-values kwd))))
12996 (unless (string-match "\\`{.*}\\'" value)
12997 (setq value (concat "\"" value "\"")))
12998 (org-match-sparse-tree arg (concat kwd "=" value)))
12999 ((member ans '(?r ?R ?/))
13000 (call-interactively 'org-occur))
13001 (t (error "No such sparse tree command \"%c\"" ans)))))
13003 (defvar org-occur-highlights nil
13004 "List of overlays used for occur matches.")
13005 (make-variable-buffer-local 'org-occur-highlights)
13006 (defvar org-occur-parameters nil
13007 "Parameters of the active org-occur calls.
13008 This is a list, each call to org-occur pushes as cons cell,
13009 containing the regular expression and the callback, onto the list.
13010 The list can contain several entries if `org-occur' has been called
13011 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13012 will only contain one set of parameters. When the highlights are
13013 removed (for example with `C-c C-c', or with the next edit (depending
13014 on `org-remove-highlights-with-change'), this variable is emptied
13015 as well.")
13016 (make-variable-buffer-local 'org-occur-parameters)
13018 (defun org-occur (regexp &optional keep-previous callback)
13019 "Make a compact tree which shows all matches of REGEXP.
13020 The tree will show the lines where the regexp matches, and all higher
13021 headlines above the match. It will also show the heading after the match,
13022 to make sure editing the matching entry is easy.
13023 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13024 call to `org-occur' will be kept, to allow stacking of calls to this
13025 command.
13026 If CALLBACK is non-nil, it is a function which is called to confirm
13027 that the match should indeed be shown."
13028 (interactive "sRegexp: \nP")
13029 (when (equal regexp "")
13030 (error "Regexp cannot be empty"))
13031 (unless keep-previous
13032 (org-remove-occur-highlights nil nil t))
13033 (push (cons regexp callback) org-occur-parameters)
13034 (let ((cnt 0))
13035 (save-excursion
13036 (goto-char (point-min))
13037 (if (or (not keep-previous) ; do not want to keep
13038 (not org-occur-highlights)) ; no previous matches
13039 ;; hide everything
13040 (org-overview))
13041 (while (re-search-forward regexp nil t)
13042 (when (or (not callback)
13043 (save-match-data (funcall callback)))
13044 (setq cnt (1+ cnt))
13045 (when org-highlight-sparse-tree-matches
13046 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13047 (org-show-context 'occur-tree))))
13048 (when org-remove-highlights-with-change
13049 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13050 nil 'local))
13051 (unless org-sparse-tree-open-archived-trees
13052 (org-hide-archived-subtrees (point-min) (point-max)))
13053 (run-hooks 'org-occur-hook)
13054 (if (org-called-interactively-p 'interactive)
13055 (message "%d match(es) for regexp %s" cnt regexp))
13056 cnt))
13058 (defun org-occur-next-match (&optional n reset)
13059 "Function for `next-error-function' to find sparse tree matches.
13060 N is the number of matches to move, when negative move backwards.
13061 RESET is entirely ignored - this function always goes back to the
13062 starting point when no match is found."
13063 (let* ((limit (if (< n 0) (point-min) (point-max)))
13064 (search-func (if (< n 0)
13065 'previous-single-char-property-change
13066 'next-single-char-property-change))
13067 (n (abs n))
13068 (pos (point))
13070 (catch 'exit
13071 (while (setq p1 (funcall search-func (point) 'org-type))
13072 (when (equal p1 limit)
13073 (goto-char pos)
13074 (error "No more matches"))
13075 (when (equal (get-char-property p1 'org-type) 'org-occur)
13076 (setq n (1- n))
13077 (when (= n 0)
13078 (goto-char p1)
13079 (throw 'exit (point))))
13080 (goto-char p1))
13081 (goto-char p1)
13082 (error "No more matches"))))
13084 (defun org-show-context (&optional key)
13085 "Make sure point and context are visible.
13086 How much context is shown depends upon the variables
13087 `org-show-hierarchy-above', `org-show-following-heading',
13088 `org-show-entry-below' and `org-show-siblings'."
13089 (let ((heading-p (org-at-heading-p t))
13090 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13091 (following-p (org-get-alist-option org-show-following-heading key))
13092 (entry-p (org-get-alist-option org-show-entry-below key))
13093 (siblings-p (org-get-alist-option org-show-siblings key)))
13094 (catch 'exit
13095 ;; Show heading or entry text
13096 (if (and heading-p (not entry-p))
13097 (org-flag-heading nil) ; only show the heading
13098 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13099 (org-show-hidden-entry))) ; show entire entry
13100 (when following-p
13101 ;; Show next sibling, or heading below text
13102 (save-excursion
13103 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13104 (org-flag-heading nil))))
13105 (when siblings-p (org-show-siblings))
13106 (when hierarchy-p
13107 ;; show all higher headings, possibly with siblings
13108 (save-excursion
13109 (while (and (condition-case nil
13110 (progn (org-up-heading-all 1) t)
13111 (error nil))
13112 (not (bobp)))
13113 (org-flag-heading nil)
13114 (when siblings-p (org-show-siblings))))))))
13116 (defvar org-reveal-start-hook nil
13117 "Hook run before revealing a location.")
13119 (defun org-reveal (&optional siblings)
13120 "Show current entry, hierarchy above it, and the following headline.
13121 This can be used to show a consistent set of context around locations
13122 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13123 not t for the search context.
13125 With optional argument SIBLINGS, on each level of the hierarchy all
13126 siblings are shown. This repairs the tree structure to what it would
13127 look like when opened with hierarchical calls to `org-cycle'.
13128 With double optional argument \\[universal-argument] \\[universal-argument], \
13129 go to the parent and show the
13130 entire tree."
13131 (interactive "P")
13132 (run-hooks 'org-reveal-start-hook)
13133 (let ((org-show-hierarchy-above t)
13134 (org-show-following-heading t)
13135 (org-show-siblings (if siblings t org-show-siblings)))
13136 (org-show-context nil))
13137 (when (equal siblings '(16))
13138 (save-excursion
13139 (when (org-up-heading-safe)
13140 (org-show-subtree)
13141 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13143 (defun org-highlight-new-match (beg end)
13144 "Highlight from BEG to END and mark the highlight is an occur headline."
13145 (let ((ov (make-overlay beg end)))
13146 (overlay-put ov 'face 'secondary-selection)
13147 (overlay-put ov 'org-type 'org-occur)
13148 (push ov org-occur-highlights)))
13150 (defun org-remove-occur-highlights (&optional beg end noremove)
13151 "Remove the occur highlights from the buffer.
13152 BEG and END are ignored. If NOREMOVE is nil, remove this function
13153 from the `before-change-functions' in the current buffer."
13154 (interactive)
13155 (unless org-inhibit-highlight-removal
13156 (mapc 'delete-overlay org-occur-highlights)
13157 (setq org-occur-highlights nil)
13158 (setq org-occur-parameters nil)
13159 (unless noremove
13160 (remove-hook 'before-change-functions
13161 'org-remove-occur-highlights 'local))))
13163 ;;;; Priorities
13165 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13166 "Regular expression matching the priority indicator.")
13168 (defvar org-remove-priority-next-time nil)
13170 (defun org-priority-up ()
13171 "Increase the priority of the current item."
13172 (interactive)
13173 (org-priority 'up))
13175 (defun org-priority-down ()
13176 "Decrease the priority of the current item."
13177 (interactive)
13178 (org-priority 'down))
13180 (defun org-priority (&optional action show)
13181 "Change the priority of an item.
13182 ACTION can be `set', `up', `down', or a character."
13183 (interactive "P")
13184 (if (equal action '(4))
13185 (org-show-priority)
13186 (unless org-enable-priority-commands
13187 (error "Priority commands are disabled"))
13188 (setq action (or action 'set))
13189 (let (current new news have remove)
13190 (save-excursion
13191 (org-back-to-heading t)
13192 (if (looking-at org-priority-regexp)
13193 (setq current (string-to-char (match-string 2))
13194 have t))
13195 (cond
13196 ((eq action 'remove)
13197 (setq remove t new ?\ ))
13198 ((or (eq action 'set)
13199 (if (featurep 'xemacs) (characterp action) (integerp action)))
13200 (if (not (eq action 'set))
13201 (setq new action)
13202 (message "Priority %c-%c, SPC to remove: "
13203 org-highest-priority org-lowest-priority)
13204 (save-match-data
13205 (setq new (read-char-exclusive))))
13206 (if (and (= (upcase org-highest-priority) org-highest-priority)
13207 (= (upcase org-lowest-priority) org-lowest-priority))
13208 (setq new (upcase new)))
13209 (cond ((equal new ?\ ) (setq remove t))
13210 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13211 (error "Priority must be between `%c' and `%c'"
13212 org-highest-priority org-lowest-priority))))
13213 ((eq action 'up)
13214 (setq new (if have
13215 (1- current) ; normal cycling
13216 ;; last priority was empty
13217 (if (eq last-command this-command)
13218 org-lowest-priority ; wrap around empty to lowest
13219 ;; default
13220 (if org-priority-start-cycle-with-default
13221 org-default-priority
13222 (1- org-default-priority))))))
13223 ((eq action 'down)
13224 (setq new (if have
13225 (1+ current) ; normal cycling
13226 ;; last priority was empty
13227 (if (eq last-command this-command)
13228 org-highest-priority ; wrap around empty to highest
13229 ;; default
13230 (if org-priority-start-cycle-with-default
13231 org-default-priority
13232 (1+ org-default-priority))))))
13233 (t (error "Invalid action")))
13234 (if (or (< (upcase new) org-highest-priority)
13235 (> (upcase new) org-lowest-priority))
13236 (if (and (memq action '(up down))
13237 (not have) (not (eq last-command this-command)))
13238 ;; `new' is from default priority
13239 (error
13240 "The default can not be set, see `org-default-priority' why")
13241 ;; normal cycling: `new' is beyond highest/lowest priority
13242 ;; and is wrapped around to the empty priority
13243 (setq remove t)))
13244 (setq news (format "%c" new))
13245 (if have
13246 (if remove
13247 (replace-match "" t t nil 1)
13248 (replace-match news t t nil 2))
13249 (if remove
13250 (error "No priority cookie found in line")
13251 (let ((case-fold-search nil))
13252 (looking-at org-todo-line-regexp))
13253 (if (match-end 2)
13254 (progn
13255 (goto-char (match-end 2))
13256 (insert " [#" news "]"))
13257 (goto-char (match-beginning 3))
13258 (insert "[#" news "] "))))
13259 (org-preserve-lc (org-set-tags nil 'align)))
13260 (if remove
13261 (message "Priority removed")
13262 (message "Priority of current item set to %s" news)))))
13264 (defun org-show-priority ()
13265 "Show the priority of the current item.
13266 This priority is composed of the main priority given with the [#A] cookies,
13267 and by additional input from the age of a schedules or deadline entry."
13268 (interactive)
13269 (let ((pri (if (eq major-mode 'org-agenda-mode)
13270 (org-get-at-bol 'priority)
13271 (save-excursion
13272 (save-match-data
13273 (beginning-of-line)
13274 (and (looking-at org-heading-regexp)
13275 (org-get-priority (match-string 0))))))))
13276 (message "Priority is %d" (if pri pri -1000))))
13278 (defun org-get-priority (s)
13279 "Find priority cookie and return priority."
13280 (save-match-data
13281 (if (functionp org-get-priority-function)
13282 (funcall org-get-priority-function)
13283 (if (not (string-match org-priority-regexp s))
13284 (* 1000 (- org-lowest-priority org-default-priority))
13285 (* 1000 (- org-lowest-priority
13286 (string-to-char (match-string 2 s))))))))
13288 ;;;; Tags
13290 (defvar org-agenda-archives-mode)
13291 (defvar org-map-continue-from nil
13292 "Position from where mapping should continue.
13293 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13295 (defvar org-scanner-tags nil
13296 "The current tag list while the tags scanner is running.")
13297 (defvar org-trust-scanner-tags nil
13298 "Should `org-get-tags-at' use the tags for the scanner.
13299 This is for internal dynamical scoping only.
13300 When this is non-nil, the function `org-get-tags-at' will return the value
13301 of `org-scanner-tags' instead of building the list by itself. This
13302 can lead to large speed-ups when the tags scanner is used in a file with
13303 many entries, and when the list of tags is retrieved, for example to
13304 obtain a list of properties. Building the tags list for each entry in such
13305 a file becomes an N^2 operation - but with this variable set, it scales
13306 as N.")
13308 (defun org-scan-tags (action matcher todo-only &optional start-level)
13309 "Scan headline tags with inheritance and produce output ACTION.
13311 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13312 or `agenda' to produce an entry list for an agenda view. It can also be
13313 a Lisp form or a function that should be called at each matched headline, in
13314 this case the return value is a list of all return values from these calls.
13316 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13317 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13318 only lines with a not-done TODO keyword are included in the output.
13319 This should be the same variable that was scoped into
13320 and set by `org-make-tags-matcher' when it constructed MATCHER.
13322 START-LEVEL can be a string with asterisks, reducing the scope to
13323 headlines matching this string."
13324 (require 'org-agenda)
13325 (let* ((re (concat "^"
13326 (if start-level
13327 ;; Get the correct level to match
13328 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13329 org-outline-regexp)
13330 " *\\(\\<\\("
13331 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13332 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13333 (props (list 'face 'default
13334 'done-face 'org-agenda-done
13335 'undone-face 'default
13336 'mouse-face 'highlight
13337 'org-not-done-regexp org-not-done-regexp
13338 'org-todo-regexp org-todo-regexp
13339 'org-complex-heading-regexp org-complex-heading-regexp
13340 'help-echo
13341 (format "mouse-2 or RET jump to org file %s"
13342 (abbreviate-file-name
13343 (or (buffer-file-name (buffer-base-buffer))
13344 (buffer-name (buffer-base-buffer)))))))
13345 (case-fold-search nil)
13346 (org-map-continue-from nil)
13347 lspos tags tags-list
13348 (tags-alist (list (cons 0 org-file-tags)))
13349 (llast 0) rtn rtn1 level category i txt
13350 todo marker entry priority)
13351 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13352 (setq action (list 'lambda nil action)))
13353 (save-excursion
13354 (goto-char (point-min))
13355 (when (eq action 'sparse-tree)
13356 (org-overview)
13357 (org-remove-occur-highlights))
13358 (while (re-search-forward re nil t)
13359 (setq org-map-continue-from nil)
13360 (catch :skip
13361 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13362 tags (if (match-end 4) (org-match-string-no-properties 4)))
13363 (goto-char (setq lspos (match-beginning 0)))
13364 (setq level (org-reduced-level (org-outline-level))
13365 category (org-get-category))
13366 (setq i llast llast level)
13367 ;; remove tag lists from same and sublevels
13368 (while (>= i level)
13369 (when (setq entry (assoc i tags-alist))
13370 (setq tags-alist (delete entry tags-alist)))
13371 (setq i (1- i)))
13372 ;; add the next tags
13373 (when tags
13374 (setq tags (org-split-string tags ":")
13375 tags-alist
13376 (cons (cons level tags) tags-alist)))
13377 ;; compile tags for current headline
13378 (setq tags-list
13379 (if org-use-tag-inheritance
13380 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13381 tags)
13382 org-scanner-tags tags-list)
13383 (when org-use-tag-inheritance
13384 (setcdr (car tags-alist)
13385 (mapcar (lambda (x)
13386 (setq x (copy-sequence x))
13387 (org-add-prop-inherited x))
13388 (cdar tags-alist))))
13389 (when (and tags org-use-tag-inheritance
13390 (or (not (eq t org-use-tag-inheritance))
13391 org-tags-exclude-from-inheritance))
13392 ;; selective inheritance, remove uninherited ones
13393 (setcdr (car tags-alist)
13394 (org-remove-uninherited-tags (cdar tags-alist))))
13395 (when (and
13397 ;; eval matcher only when the todo condition is OK
13398 (and (or (not todo-only) (member todo org-not-done-keywords))
13399 (let ((case-fold-search t) (org-trust-scanner-tags t))
13400 (eval matcher)))
13402 ;; Call the skipper, but return t if it does not skip,
13403 ;; so that the `and' form continues evaluating
13404 (progn
13405 (unless (eq action 'sparse-tree) (org-agenda-skip))
13408 ;; Check if timestamps are deselecting this entry
13409 (or (not todo-only)
13410 (and (member todo org-not-done-keywords)
13411 (or (not org-agenda-tags-todo-honor-ignore-options)
13412 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13414 ;; select this headline
13415 (cond
13416 ((eq action 'sparse-tree)
13417 (and org-highlight-sparse-tree-matches
13418 (org-get-heading) (match-end 0)
13419 (org-highlight-new-match
13420 (match-beginning 1) (match-end 1)))
13421 (org-show-context 'tags-tree))
13422 ((eq action 'agenda)
13423 (setq txt (org-agenda-format-item
13425 (concat
13426 (if (eq org-tags-match-list-sublevels 'indented)
13427 (make-string (1- level) ?.) "")
13428 (org-get-heading))
13429 level category
13430 tags-list)
13431 priority (org-get-priority txt))
13432 (goto-char lspos)
13433 (setq marker (org-agenda-new-marker))
13434 (org-add-props txt props
13435 'org-marker marker 'org-hd-marker marker 'org-category category
13436 'todo-state todo
13437 'priority priority 'type "tagsmatch")
13438 (push txt rtn))
13439 ((functionp action)
13440 (setq org-map-continue-from nil)
13441 (save-excursion
13442 (setq rtn1 (funcall action))
13443 (push rtn1 rtn)))
13444 (t (error "Invalid action")))
13446 ;; if we are to skip sublevels, jump to end of subtree
13447 (unless org-tags-match-list-sublevels
13448 (org-end-of-subtree t)
13449 (backward-char 1))))
13450 ;; Get the correct position from where to continue
13451 (if org-map-continue-from
13452 (goto-char org-map-continue-from)
13453 (and (= (point) lspos) (end-of-line 1)))))
13454 (when (and (eq action 'sparse-tree)
13455 (not org-sparse-tree-open-archived-trees))
13456 (org-hide-archived-subtrees (point-min) (point-max)))
13457 (nreverse rtn)))
13459 (defun org-remove-uninherited-tags (tags)
13460 "Remove all tags that are not inherited from the list TAGS."
13461 (cond
13462 ((eq org-use-tag-inheritance t)
13463 (if org-tags-exclude-from-inheritance
13464 (org-delete-all org-tags-exclude-from-inheritance tags)
13465 tags))
13466 ((not org-use-tag-inheritance) nil)
13467 ((stringp org-use-tag-inheritance)
13468 (delq nil (mapcar
13469 (lambda (x)
13470 (if (and (string-match org-use-tag-inheritance x)
13471 (not (member x org-tags-exclude-from-inheritance)))
13472 x nil))
13473 tags)))
13474 ((listp org-use-tag-inheritance)
13475 (delq nil (mapcar
13476 (lambda (x)
13477 (if (member x org-use-tag-inheritance) x nil))
13478 tags)))))
13480 (defun org-match-sparse-tree (&optional todo-only match)
13481 "Create a sparse tree according to tags string MATCH.
13482 MATCH can contain positive and negative selection of tags, like
13483 \"+WORK+URGENT-WITHBOSS\".
13484 If optional argument TODO-ONLY is non-nil, only select lines that are
13485 also TODO lines."
13486 (interactive "P")
13487 (org-agenda-prepare-buffers (list (current-buffer)))
13488 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13490 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13492 (defvar org-cached-props nil)
13493 (defun org-cached-entry-get (pom property)
13494 (if (or (eq t org-use-property-inheritance)
13495 (and (stringp org-use-property-inheritance)
13496 (string-match org-use-property-inheritance property))
13497 (and (listp org-use-property-inheritance)
13498 (member property org-use-property-inheritance)))
13499 ;; Caching is not possible, check it directly
13500 (org-entry-get pom property 'inherit)
13501 ;; Get all properties, so that we can do complicated checks easily
13502 (cdr (assoc property (or org-cached-props
13503 (setq org-cached-props
13504 (org-entry-properties pom)))))))
13506 (defun org-global-tags-completion-table (&optional files)
13507 "Return the list of all tags in all agenda buffer/files.
13508 Optional FILES argument is a list of files which can be used
13509 instead of the agenda files."
13510 (save-excursion
13511 (org-uniquify
13512 (delq nil
13513 (apply 'append
13514 (mapcar
13515 (lambda (file)
13516 (set-buffer (find-file-noselect file))
13517 (append (org-get-buffer-tags)
13518 (mapcar (lambda (x) (if (stringp (car-safe x))
13519 (list (car-safe x)) nil))
13520 org-tag-alist)))
13521 (if (and files (car files))
13522 files
13523 (org-agenda-files))))))))
13525 (defun org-make-tags-matcher (match)
13526 "Create the TAGS/TODO matcher form for the selection string MATCH.
13528 The variable `todo-only' is scoped dynamically into this function.
13529 It will be set to t if the matcher restricts matching to TODO entries,
13530 otherwise will not be touched.
13532 Returns a cons of the selection string MATCH and the constructed
13533 lisp form implementing the matcher. The matcher is to be evaluated
13534 at an Org entry, with point on the headline, and returns t if the
13535 entry matches the selection string MATCH. The returned lisp form
13536 references two variables with information about the entry, which
13537 must be bound around the form's evaluation: todo, the TODO keyword
13538 at the entry (or nil of none); and tags-list, the list of all tags
13539 at the entry including inherited ones. Additionally, the category
13540 of the entry (if any) must be specified as the text property
13541 'org-category on the headline.
13543 See also `org-scan-tags'.
13545 (declare (special todo-only))
13546 (unless (boundp 'todo-only)
13547 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13548 (unless match
13549 ;; Get a new match request, with completion
13550 (let ((org-last-tags-completion-table
13551 (org-global-tags-completion-table)))
13552 (setq match (org-completing-read-no-i
13553 "Match: " 'org-tags-completion-function nil nil nil
13554 'org-tags-history))))
13556 ;; Parse the string and create a lisp form
13557 (let ((match0 match)
13558 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13559 minus tag mm
13560 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13561 orterms term orlist re-p str-p level-p level-op time-p
13562 prop-p pn pv po gv rest)
13563 (if (string-match "/+" match)
13564 ;; match contains also a todo-matching request
13565 (progn
13566 (setq tagsmatch (substring match 0 (match-beginning 0))
13567 todomatch (substring match (match-end 0)))
13568 (if (string-match "^!" todomatch)
13569 (setq todo-only t todomatch (substring todomatch 1)))
13570 (if (string-match "^\\s-*$" todomatch)
13571 (setq todomatch nil)))
13572 ;; only matching tags
13573 (setq tagsmatch match todomatch nil))
13575 ;; Make the tags matcher
13576 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13577 (setq tagsmatcher t)
13578 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13579 (while (setq term (pop orterms))
13580 (while (and (equal (substring term -1) "\\") orterms)
13581 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13582 (while (string-match re term)
13583 (setq rest (substring term (match-end 0))
13584 minus (and (match-end 1)
13585 (equal (match-string 1 term) "-"))
13586 tag (save-match-data (replace-regexp-in-string
13587 "\\\\-" "-"
13588 (match-string 2 term)))
13589 re-p (equal (string-to-char tag) ?{)
13590 level-p (match-end 4)
13591 prop-p (match-end 5)
13592 mm (cond
13593 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13594 (level-p
13595 (setq level-op (org-op-to-function (match-string 3 term)))
13596 `(,level-op level ,(string-to-number
13597 (match-string 4 term))))
13598 (prop-p
13599 (setq pn (match-string 5 term)
13600 po (match-string 6 term)
13601 pv (match-string 7 term)
13602 re-p (equal (string-to-char pv) ?{)
13603 str-p (equal (string-to-char pv) ?\")
13604 time-p (save-match-data
13605 (string-match "^\"[[<].*[]>]\"$" pv))
13606 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13607 (if time-p (setq pv (org-matcher-time pv)))
13608 (setq po (org-op-to-function po (if time-p 'time str-p)))
13609 (cond
13610 ((equal pn "CATEGORY")
13611 (setq gv '(get-text-property (point) 'org-category)))
13612 ((equal pn "TODO")
13613 (setq gv 'todo))
13615 (setq gv `(org-cached-entry-get nil ,pn))))
13616 (if re-p
13617 (if (eq po 'org<>)
13618 `(not (string-match ,pv (or ,gv "")))
13619 `(string-match ,pv (or ,gv "")))
13620 (if str-p
13621 `(,po (or ,gv "") ,pv)
13622 `(,po (string-to-number (or ,gv ""))
13623 ,(string-to-number pv) ))))
13624 (t `(member ,tag tags-list)))
13625 mm (if minus (list 'not mm) mm)
13626 term rest)
13627 (push mm tagsmatcher))
13628 (push (if (> (length tagsmatcher) 1)
13629 (cons 'and tagsmatcher)
13630 (car tagsmatcher))
13631 orlist)
13632 (setq tagsmatcher nil))
13633 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13634 (setq tagsmatcher
13635 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13636 ;; Make the todo matcher
13637 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13638 (setq todomatcher t)
13639 (setq orterms (org-split-string todomatch "|") orlist nil)
13640 (while (setq term (pop orterms))
13641 (while (string-match re term)
13642 (setq minus (and (match-end 1)
13643 (equal (match-string 1 term) "-"))
13644 kwd (match-string 2 term)
13645 re-p (equal (string-to-char kwd) ?{)
13646 term (substring term (match-end 0))
13647 mm (if re-p
13648 `(string-match ,(substring kwd 1 -1) todo)
13649 (list 'equal 'todo kwd))
13650 mm (if minus (list 'not mm) mm))
13651 (push mm todomatcher))
13652 (push (if (> (length todomatcher) 1)
13653 (cons 'and todomatcher)
13654 (car todomatcher))
13655 orlist)
13656 (setq todomatcher nil))
13657 (setq todomatcher (if (> (length orlist) 1)
13658 (cons 'or orlist) (car orlist))))
13660 ;; Return the string and lisp forms of the matcher
13661 (setq matcher (if todomatcher
13662 (list 'and tagsmatcher todomatcher)
13663 tagsmatcher))
13664 (when todo-only
13665 (setq matcher (list 'and '(member todo org-not-done-keywords)
13666 matcher)))
13667 (cons match0 matcher)))
13669 (defun org-op-to-function (op &optional stringp)
13670 "Turn an operator into the appropriate function."
13671 (setq op
13672 (cond
13673 ((equal op "<" ) '(< string< org-time<))
13674 ((equal op ">" ) '(> org-string> org-time>))
13675 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13676 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13677 ((member op '("=" "==")) '(= string= org-time=))
13678 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13679 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13681 (defun org<> (a b) (not (= a b)))
13682 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13683 (defun org-string>= (a b) (not (string< a b)))
13684 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13685 (defun org-string<> (a b) (not (string= a b)))
13686 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13687 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< 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) (org<> a b)))
13692 (defun org-2ft (s)
13693 "Convert S to a floating point time.
13694 If S is already a number, just return it. If it is a string, parse
13695 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13696 (cond
13697 ((numberp s) s)
13698 ((stringp s)
13699 (condition-case nil
13700 (float-time (apply 'encode-time (org-parse-time-string s)))
13701 (error 0.)))
13702 (t 0.)))
13704 (defun org-time-today ()
13705 "Time in seconds today at 0:00.
13706 Returns the float number of seconds since the beginning of the
13707 epoch to the beginning of today (00:00)."
13708 (float-time (apply 'encode-time
13709 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13711 (defun org-matcher-time (s)
13712 "Interpret a time comparison value."
13713 (save-match-data
13714 (cond
13715 ((string= s "<now>") (float-time))
13716 ((string= s "<today>") (org-time-today))
13717 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13718 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13719 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13720 (+ (org-time-today)
13721 (* (string-to-number (match-string 1 s))
13722 (cdr (assoc (match-string 2 s)
13723 '(("d" . 86400.0) ("w" . 604800.0)
13724 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13725 (t (org-2ft s)))))
13727 (defun org-match-any-p (re list)
13728 "Does re match any element of list?"
13729 (setq list (mapcar (lambda (x) (string-match re x)) list))
13730 (delq nil list))
13732 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13733 (defvar org-tags-overlay (make-overlay 1 1))
13734 (org-detach-overlay org-tags-overlay)
13736 (defun org-get-local-tags-at (&optional pos)
13737 "Get a list of tags defined in the current headline."
13738 (org-get-tags-at pos 'local))
13740 (defun org-get-local-tags ()
13741 "Get a list of tags defined in the current headline."
13742 (org-get-tags-at nil 'local))
13744 (defun org-get-tags-at (&optional pos local)
13745 "Get a list of all headline tags applicable at POS.
13746 POS defaults to point. If tags are inherited, the list contains
13747 the targets in the same sequence as the headlines appear, i.e.
13748 the tags of the current headline come last.
13749 When LOCAL is non-nil, only return tags from the current headline,
13750 ignore inherited ones."
13751 (interactive)
13752 (if (and org-trust-scanner-tags
13753 (or (not pos) (equal pos (point)))
13754 (not local))
13755 org-scanner-tags
13756 (let (tags ltags lastpos parent)
13757 (save-excursion
13758 (save-restriction
13759 (widen)
13760 (goto-char (or pos (point)))
13761 (save-match-data
13762 (catch 'done
13763 (condition-case nil
13764 (progn
13765 (org-back-to-heading t)
13766 (while (not (equal lastpos (point)))
13767 (setq lastpos (point))
13768 (when (looking-at
13769 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13770 (setq ltags (org-split-string
13771 (org-match-string-no-properties 1) ":"))
13772 (when parent
13773 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13774 (setq tags (append
13775 (if parent
13776 (org-remove-uninherited-tags ltags)
13777 ltags)
13778 tags)))
13779 (or org-use-tag-inheritance (throw 'done t))
13780 (if local (throw 'done t))
13781 (or (org-up-heading-safe) (error nil))
13782 (setq parent t)))
13783 (error nil)))))
13784 (if local
13785 tags
13786 (reverse (delete-dups
13787 (reverse (append
13788 (org-remove-uninherited-tags
13789 org-file-tags) tags)))))))))
13791 (defun org-add-prop-inherited (s)
13792 (add-text-properties 0 (length s) '(inherited t) s)
13795 (defun org-toggle-tag (tag &optional onoff)
13796 "Toggle the tag TAG for the current line.
13797 If ONOFF is `on' or `off', don't toggle but set to this state."
13798 (let (res current)
13799 (save-excursion
13800 (org-back-to-heading t)
13801 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13802 (point-at-eol) t)
13803 (progn
13804 (setq current (match-string 1))
13805 (replace-match ""))
13806 (setq current ""))
13807 (setq current (nreverse (org-split-string current ":")))
13808 (cond
13809 ((eq onoff 'on)
13810 (setq res t)
13811 (or (member tag current) (push tag current)))
13812 ((eq onoff 'off)
13813 (or (not (member tag current)) (setq current (delete tag current))))
13814 (t (if (member tag current)
13815 (setq current (delete tag current))
13816 (setq res t)
13817 (push tag current))))
13818 (end-of-line 1)
13819 (if current
13820 (progn
13821 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13822 (org-set-tags nil t))
13823 (delete-horizontal-space))
13824 (run-hooks 'org-after-tags-change-hook))
13825 res))
13827 (defun org-align-tags-here (to-col)
13828 ;; Assumes that this is a headline
13829 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13830 (beginning-of-line 1)
13831 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13832 (< pos (match-beginning 2)))
13833 (progn
13834 (setq tags-l (- (match-end 2) (match-beginning 2)))
13835 (goto-char (match-beginning 1))
13836 (insert " ")
13837 (delete-region (point) (1+ (match-beginning 2)))
13838 (setq ncol (max (current-column)
13839 (1+ col)
13840 (if (> to-col 0)
13841 to-col
13842 (- (abs to-col) tags-l))))
13843 (setq p (point))
13844 (insert (make-string (- ncol (current-column)) ?\ ))
13845 (setq ncol (current-column))
13846 (when indent-tabs-mode (tabify p (point-at-eol)))
13847 (org-move-to-column (min ncol col) t))
13848 (goto-char pos))))
13850 (defun org-set-tags-command (&optional arg just-align)
13851 "Call the set-tags command for the current entry."
13852 (interactive "P")
13853 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13854 (org-set-tags arg just-align)
13855 (save-excursion
13856 (org-back-to-heading t)
13857 (org-set-tags arg just-align))))
13859 (defun org-set-tags-to (data)
13860 "Set the tags of the current entry to DATA, replacing the current tags.
13861 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13862 If DATA is nil or the empty string, any tags will be removed."
13863 (interactive "sTags: ")
13864 (setq data
13865 (cond
13866 ((eq data nil) "")
13867 ((equal data "") "")
13868 ((stringp data)
13869 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13870 ":"))
13871 ((listp data)
13872 (concat ":" (mapconcat 'identity data ":") ":"))))
13873 (when data
13874 (save-excursion
13875 (org-back-to-heading t)
13876 (when (looking-at org-complex-heading-regexp)
13877 (if (match-end 5)
13878 (progn
13879 (goto-char (match-beginning 5))
13880 (insert data)
13881 (delete-region (point) (point-at-eol))
13882 (org-set-tags nil 'align))
13883 (goto-char (point-at-eol))
13884 (insert " " data)
13885 (org-set-tags nil 'align)))
13886 (beginning-of-line 1)
13887 (if (looking-at ".*?\\([ \t]+\\)$")
13888 (delete-region (match-beginning 1) (match-end 1))))))
13890 (defun org-align-all-tags ()
13891 "Align the tags i all headings."
13892 (interactive)
13893 (save-excursion
13894 (or (ignore-errors (org-back-to-heading t))
13895 (outline-next-heading))
13896 (if (org-at-heading-p)
13897 (org-set-tags t)
13898 (message "No headings"))))
13900 (defvar org-indent-indentation-per-level)
13901 (defun org-set-tags (&optional arg just-align)
13902 "Set the tags for the current headline.
13903 With prefix ARG, realign all tags in headings in the current buffer."
13904 (interactive "P")
13905 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13906 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13907 'region-start-level 'region))
13908 org-loop-over-headlines-in-active-region)
13909 (org-map-entries
13910 ;; We don't use ARG and JUST-ALIGN here these args are not
13911 ;; useful when looping over headlines
13912 `(org-set-tags)
13913 org-loop-over-headlines-in-active-region
13914 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13915 (let* ((re org-outline-regexp-bol)
13916 (current (unless arg (org-get-tags-string)))
13917 (col (current-column))
13918 (org-setting-tags t)
13919 table current-tags inherited-tags ; computed below when needed
13920 tags p0 c0 c1 rpl di tc level)
13921 (if arg
13922 (save-excursion
13923 (goto-char (point-min))
13924 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13925 (while (re-search-forward re nil t)
13926 (org-set-tags nil t)
13927 (end-of-line 1)))
13928 (message "All tags realigned to column %d" org-tags-column))
13929 (if just-align
13930 (setq tags current)
13931 ;; Get a new set of tags from the user
13932 (save-excursion
13933 (setq table (append org-tag-persistent-alist
13934 (or org-tag-alist (org-get-buffer-tags))
13935 (and
13936 org-complete-tags-always-offer-all-agenda-tags
13937 (org-global-tags-completion-table
13938 (org-agenda-files))))
13939 org-last-tags-completion-table table
13940 current-tags (org-split-string current ":")
13941 inherited-tags (nreverse
13942 (nthcdr (length current-tags)
13943 (nreverse (org-get-tags-at))))
13944 tags
13945 (if (or (eq t org-use-fast-tag-selection)
13946 (and org-use-fast-tag-selection
13947 (delq nil (mapcar 'cdr table))))
13948 (org-fast-tag-selection
13949 current-tags inherited-tags table
13950 (if org-fast-tag-selection-include-todo
13951 org-todo-key-alist))
13952 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13953 (org-trim
13954 (org-icompleting-read "Tags: "
13955 'org-tags-completion-function
13956 nil nil current 'org-tags-history))))))
13957 (while (string-match "[-+&]+" tags)
13958 ;; No boolean logic, just a list
13959 (setq tags (replace-match ":" t t tags))))
13961 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13963 (if org-tags-sort-function
13964 (setq tags (mapconcat 'identity
13965 (sort (org-split-string
13966 tags (org-re "[^[:alnum:]_@#%]+"))
13967 org-tags-sort-function) ":")))
13969 (if (string-match "\\`[\t ]*\\'" tags)
13970 (setq tags "")
13971 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13972 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13974 ;; Insert new tags at the correct column
13975 (beginning-of-line 1)
13976 (setq level (or (and (looking-at org-outline-regexp)
13977 (- (match-end 0) (point) 1))
13979 (cond
13980 ((and (equal current "") (equal tags "")))
13981 ((re-search-forward
13982 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13983 (point-at-eol) t)
13984 (if (equal tags "")
13985 (setq rpl "")
13986 (goto-char (match-beginning 0))
13987 (setq c0 (current-column)
13988 ;; compute offset for the case of org-indent-mode active
13989 di (if org-indent-mode
13990 (* (1- org-indent-indentation-per-level) (1- level))
13992 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13993 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13994 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13995 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13996 (replace-match rpl t t)
13997 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13998 tags)
13999 (t (error "Tags alignment failed")))
14000 (org-move-to-column col)
14001 (unless just-align
14002 (run-hooks 'org-after-tags-change-hook))))))
14004 (defun org-change-tag-in-region (beg end tag off)
14005 "Add or remove TAG for each entry in the region.
14006 This works in the agenda, and also in an org-mode buffer."
14007 (interactive
14008 (list (region-beginning) (region-end)
14009 (let ((org-last-tags-completion-table
14010 (if (derived-mode-p 'org-mode)
14011 (org-get-buffer-tags)
14012 (org-global-tags-completion-table))))
14013 (org-icompleting-read
14014 "Tag: " 'org-tags-completion-function nil nil nil
14015 'org-tags-history))
14016 (progn
14017 (message "[s]et or [r]emove? ")
14018 (equal (read-char-exclusive) ?r))))
14019 (if (fboundp 'deactivate-mark) (deactivate-mark))
14020 (let ((agendap (equal major-mode 'org-agenda-mode))
14021 l1 l2 m buf pos newhead (cnt 0))
14022 (goto-char end)
14023 (setq l2 (1- (org-current-line)))
14024 (goto-char beg)
14025 (setq l1 (org-current-line))
14026 (loop for l from l1 to l2 do
14027 (org-goto-line l)
14028 (setq m (get-text-property (point) 'org-hd-marker))
14029 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14030 (and agendap m))
14031 (setq buf (if agendap (marker-buffer m) (current-buffer))
14032 pos (if agendap m (point)))
14033 (with-current-buffer buf
14034 (save-excursion
14035 (save-restriction
14036 (goto-char pos)
14037 (setq cnt (1+ cnt))
14038 (org-toggle-tag tag (if off 'off 'on))
14039 (setq newhead (org-get-heading)))))
14040 (and agendap (org-agenda-change-all-lines newhead m))))
14041 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14043 (defun org-tags-completion-function (string predicate &optional flag)
14044 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14045 (confirm (lambda (x) (stringp (car x)))))
14046 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14047 (setq s1 (match-string 1 string)
14048 s2 (match-string 2 string))
14049 (setq s1 "" s2 string))
14050 (cond
14051 ((eq flag nil)
14052 ;; try completion
14053 (setq rtn (try-completion s2 ctable confirm))
14054 (if (stringp rtn)
14055 (setq rtn
14056 (concat s1 s2 (substring rtn (length s2))
14057 (if (and org-add-colon-after-tag-completion
14058 (assoc rtn ctable))
14059 ":" ""))))
14060 rtn)
14061 ((eq flag t)
14062 ;; all-completions
14063 (all-completions s2 ctable confirm)
14065 ((eq flag 'lambda)
14066 ;; exact match?
14067 (assoc s2 ctable)))
14070 (defun org-fast-tag-insert (kwd tags face &optional end)
14071 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14072 (insert (format "%-12s" (concat kwd ":"))
14073 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14074 (or end "")))
14076 (defun org-fast-tag-show-exit (flag)
14077 (save-excursion
14078 (org-goto-line 3)
14079 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14080 (replace-match ""))
14081 (when flag
14082 (end-of-line 1)
14083 (org-move-to-column (- (window-width) 19) t)
14084 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14086 (defun org-set-current-tags-overlay (current prefix)
14087 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14088 (if (featurep 'xemacs)
14089 (org-overlay-display org-tags-overlay (concat prefix s)
14090 'secondary-selection)
14091 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14092 (org-overlay-display org-tags-overlay (concat prefix s)))))
14094 (defvar org-last-tag-selection-key nil)
14095 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14096 "Fast tag selection with single keys.
14097 CURRENT is the current list of tags in the headline, INHERITED is the
14098 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14099 possibly with grouping information. TODO-TABLE is a similar table with
14100 TODO keywords, should these have keys assigned to them.
14101 If the keys are nil, a-z are automatically assigned.
14102 Returns the new tags string, or nil to not change the current settings."
14103 (let* ((fulltable (append table todo-table))
14104 (maxlen (apply 'max (mapcar
14105 (lambda (x)
14106 (if (stringp (car x)) (string-width (car x)) 0))
14107 fulltable)))
14108 (buf (current-buffer))
14109 (expert (eq org-fast-tag-selection-single-key 'expert))
14110 (buffer-tags nil)
14111 (fwidth (+ maxlen 3 1 3))
14112 (ncol (/ (- (window-width) 4) fwidth))
14113 (i-face 'org-done)
14114 (c-face 'org-todo)
14115 tg cnt e c char c1 c2 ntable tbl rtn
14116 ov-start ov-end ov-prefix
14117 (exit-after-next org-fast-tag-selection-single-key)
14118 (done-keywords org-done-keywords)
14119 groups ingroup)
14120 (save-excursion
14121 (beginning-of-line 1)
14122 (if (looking-at
14123 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14124 (setq ov-start (match-beginning 1)
14125 ov-end (match-end 1)
14126 ov-prefix "")
14127 (setq ov-start (1- (point-at-eol))
14128 ov-end (1+ ov-start))
14129 (skip-chars-forward "^\n\r")
14130 (setq ov-prefix
14131 (concat
14132 (buffer-substring (1- (point)) (point))
14133 (if (> (current-column) org-tags-column)
14135 (make-string (- org-tags-column (current-column)) ?\ ))))))
14136 (move-overlay org-tags-overlay ov-start ov-end)
14137 (save-window-excursion
14138 (if expert
14139 (set-buffer (get-buffer-create " *Org tags*"))
14140 (delete-other-windows)
14141 (split-window-vertically)
14142 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14143 (erase-buffer)
14144 (org-set-local 'org-done-keywords done-keywords)
14145 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14146 (org-fast-tag-insert "Current" current c-face "\n\n")
14147 (org-fast-tag-show-exit exit-after-next)
14148 (org-set-current-tags-overlay current ov-prefix)
14149 (setq tbl fulltable char ?a cnt 0)
14150 (while (setq e (pop tbl))
14151 (cond
14152 ((equal (car e) :startgroup)
14153 (push '() groups) (setq ingroup t)
14154 (when (not (= cnt 0))
14155 (setq cnt 0)
14156 (insert "\n"))
14157 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14158 ((equal (car e) :endgroup)
14159 (setq ingroup nil cnt 0)
14160 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14161 ((equal e '(:newline))
14162 (when (not (= cnt 0))
14163 (setq cnt 0)
14164 (insert "\n")
14165 (setq e (car tbl))
14166 (while (equal (car tbl) '(:newline))
14167 (insert "\n")
14168 (setq tbl (cdr tbl)))))
14170 (setq tg (copy-sequence (car e)) c2 nil)
14171 (if (cdr e)
14172 (setq c (cdr e))
14173 ;; automatically assign a character.
14174 (setq c1 (string-to-char
14175 (downcase (substring
14176 tg (if (= (string-to-char tg) ?@) 1 0)))))
14177 (if (or (rassoc c1 ntable) (rassoc c1 table))
14178 (while (or (rassoc char ntable) (rassoc char table))
14179 (setq char (1+ char)))
14180 (setq c2 c1))
14181 (setq c (or c2 char)))
14182 (if ingroup (push tg (car groups)))
14183 (setq tg (org-add-props tg nil 'face
14184 (cond
14185 ((not (assoc tg table))
14186 (org-get-todo-face tg))
14187 ((member tg current) c-face)
14188 ((member tg inherited) i-face))))
14189 (if (and (= cnt 0) (not ingroup)) (insert " "))
14190 (insert "[" c "] " tg (make-string
14191 (- fwidth 4 (length tg)) ?\ ))
14192 (push (cons tg c) ntable)
14193 (when (= (setq cnt (1+ cnt)) ncol)
14194 (insert "\n")
14195 (if ingroup (insert " "))
14196 (setq cnt 0)))))
14197 (setq ntable (nreverse ntable))
14198 (insert "\n")
14199 (goto-char (point-min))
14200 (if (not expert) (org-fit-window-to-buffer))
14201 (setq rtn
14202 (catch 'exit
14203 (while t
14204 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14205 (if (not groups) "no " "")
14206 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14207 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14208 (setq org-last-tag-selection-key c)
14209 (cond
14210 ((= c ?\r) (throw 'exit t))
14211 ((= c ?!)
14212 (setq groups (not groups))
14213 (goto-char (point-min))
14214 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14215 ((= c ?\C-c)
14216 (if (not expert)
14217 (org-fast-tag-show-exit
14218 (setq exit-after-next (not exit-after-next)))
14219 (setq expert nil)
14220 (delete-other-windows)
14221 (set-window-buffer (split-window-vertically) " *Org tags*")
14222 (org-switch-to-buffer-other-window " *Org tags*")
14223 (org-fit-window-to-buffer)))
14224 ((or (= c ?\C-g)
14225 (and (= c ?q) (not (rassoc c ntable))))
14226 (org-detach-overlay org-tags-overlay)
14227 (setq quit-flag t))
14228 ((= c ?\ )
14229 (setq current nil)
14230 (if exit-after-next (setq exit-after-next 'now)))
14231 ((= c ?\t)
14232 (condition-case nil
14233 (setq tg (org-icompleting-read
14234 "Tag: "
14235 (or buffer-tags
14236 (with-current-buffer buf
14237 (org-get-buffer-tags)))))
14238 (quit (setq tg "")))
14239 (when (string-match "\\S-" tg)
14240 (add-to-list 'buffer-tags (list tg))
14241 (if (member tg current)
14242 (setq current (delete tg current))
14243 (push tg current)))
14244 (if exit-after-next (setq exit-after-next 'now)))
14245 ((setq e (rassoc c todo-table) tg (car e))
14246 (with-current-buffer buf
14247 (save-excursion (org-todo tg)))
14248 (if exit-after-next (setq exit-after-next 'now)))
14249 ((setq e (rassoc c ntable) tg (car e))
14250 (if (member tg current)
14251 (setq current (delete tg current))
14252 (loop for g in groups do
14253 (if (member tg g)
14254 (mapc (lambda (x)
14255 (setq current (delete x current)))
14256 g)))
14257 (push tg current))
14258 (if exit-after-next (setq exit-after-next 'now))))
14260 ;; Create a sorted list
14261 (setq current
14262 (sort current
14263 (lambda (a b)
14264 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14265 (if (eq exit-after-next 'now) (throw 'exit t))
14266 (goto-char (point-min))
14267 (beginning-of-line 2)
14268 (delete-region (point) (point-at-eol))
14269 (org-fast-tag-insert "Current" current c-face)
14270 (org-set-current-tags-overlay current ov-prefix)
14271 (while (re-search-forward
14272 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14273 (setq tg (match-string 1))
14274 (add-text-properties
14275 (match-beginning 1) (match-end 1)
14276 (list 'face
14277 (cond
14278 ((member tg current) c-face)
14279 ((member tg inherited) i-face)
14280 (t (get-text-property (match-beginning 1) 'face))))))
14281 (goto-char (point-min)))))
14282 (org-detach-overlay org-tags-overlay)
14283 (if rtn
14284 (mapconcat 'identity current ":")
14285 nil))))
14287 (defun org-get-tags-string ()
14288 "Get the TAGS string in the current headline."
14289 (unless (org-at-heading-p t)
14290 (error "Not on a heading"))
14291 (save-excursion
14292 (beginning-of-line 1)
14293 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14294 (org-match-string-no-properties 1)
14295 "")))
14297 (defun org-get-tags ()
14298 "Get the list of tags specified in the current headline."
14299 (org-split-string (org-get-tags-string) ":"))
14301 (defun org-get-buffer-tags ()
14302 "Get a table of all tags used in the buffer, for completion."
14303 (let (tags)
14304 (save-excursion
14305 (goto-char (point-min))
14306 (while (re-search-forward
14307 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14308 (when (equal (char-after (point-at-bol 0)) ?*)
14309 (mapc (lambda (x) (add-to-list 'tags x))
14310 (org-split-string (org-match-string-no-properties 1) ":")))))
14311 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14312 (mapcar 'list tags)))
14314 ;;;; The mapping API
14316 (defun org-map-entries (func &optional match scope &rest skip)
14317 "Call FUNC at each headline selected by MATCH in SCOPE.
14319 FUNC is a function or a lisp form. The function will be called without
14320 arguments, with the cursor positioned at the beginning of the headline.
14321 The return values of all calls to the function will be collected and
14322 returned as a list.
14324 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14325 does not need to preserve point. After evaluation, the cursor will be
14326 moved to the end of the line (presumably of the headline of the
14327 processed entry) and search continues from there. Under some
14328 circumstances, this may not produce the wanted results. For example,
14329 if you have removed (e.g. archived) the current (sub)tree it could
14330 mean that the next entry will be skipped entirely. In such cases, you
14331 can specify the position from where search should continue by making
14332 FUNC set the variable `org-map-continue-from' to the desired buffer
14333 position.
14335 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14336 Only headlines that are matched by this query will be considered during
14337 the iteration. When MATCH is nil or t, all headlines will be
14338 visited by the iteration.
14340 SCOPE determines the scope of this command. It can be any of:
14342 nil The current buffer, respecting the restriction if any
14343 tree The subtree started with the entry at point
14344 region The entries within the active region, if any
14345 region-start-level
14346 The entries within the active region, but only those at
14347 the same level than the first one.
14348 file The current buffer, without restriction
14349 file-with-archives
14350 The current buffer, and any archives associated with it
14351 agenda All agenda files
14352 agenda-with-archives
14353 All agenda files with any archive files associated with them
14354 \(file1 file2 ...)
14355 If this is a list, all files in the list will be scanned
14357 The remaining args are treated as settings for the skipping facilities of
14358 the scanner. The following items can be given here:
14360 archive skip trees with the archive tag.
14361 comment skip trees with the COMMENT keyword
14362 function or Emacs Lisp form:
14363 will be used as value for `org-agenda-skip-function', so whenever
14364 the function returns t, FUNC will not be called for that
14365 entry and search will continue from the point where the
14366 function leaves it.
14368 If your function needs to retrieve the tags including inherited tags
14369 at the *current* entry, you can use the value of the variable
14370 `org-scanner-tags' which will be much faster than getting the value
14371 with `org-get-tags-at'. If your function gets properties with
14372 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14373 to t around the call to `org-entry-properties' to get the same speedup.
14374 Note that if your function moves around to retrieve tags and properties at
14375 a *different* entry, you cannot use these techniques."
14376 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14377 (not (org-region-active-p)))
14378 (let* ((org-agenda-archives-mode nil) ; just to make sure
14379 (org-agenda-skip-archived-trees (memq 'archive skip))
14380 (org-agenda-skip-comment-trees (memq 'comment skip))
14381 (org-agenda-skip-function
14382 (car (org-delete-all '(comment archive) skip)))
14383 (org-tags-match-list-sublevels t)
14384 (start-level (eq scope 'region-start-level))
14385 matcher file res
14386 org-todo-keywords-for-agenda
14387 org-done-keywords-for-agenda
14388 org-todo-keyword-alist-for-agenda
14389 org-drawers-for-agenda
14390 org-tag-alist-for-agenda
14391 todo-only)
14393 (cond
14394 ((eq match t) (setq matcher t))
14395 ((eq match nil) (setq matcher t))
14396 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14398 (save-excursion
14399 (save-restriction
14400 (cond ((eq scope 'tree)
14401 (org-back-to-heading t)
14402 (org-narrow-to-subtree)
14403 (setq scope nil))
14404 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14405 (org-region-active-p))
14406 ;; If needed, set start-level to a string like "2"
14407 (when start-level
14408 (save-excursion
14409 (goto-char (region-beginning))
14410 (unless (org-at-heading-p) (outline-next-heading))
14411 (setq start-level (org-current-level))))
14412 (narrow-to-region (region-beginning)
14413 (save-excursion
14414 (goto-char (region-end))
14415 (unless (and (bolp) (org-at-heading-p))
14416 (outline-next-heading))
14417 (point)))
14418 (setq scope nil)))
14420 (if (not scope)
14421 (progn
14422 (org-agenda-prepare-buffers
14423 (list (buffer-file-name (current-buffer))))
14424 (setq res (org-scan-tags func matcher todo-only start-level)))
14425 ;; Get the right scope
14426 (cond
14427 ((and scope (listp scope) (symbolp (car scope)))
14428 (setq scope (eval scope)))
14429 ((eq scope 'agenda)
14430 (setq scope (org-agenda-files t)))
14431 ((eq scope 'agenda-with-archives)
14432 (setq scope (org-agenda-files t))
14433 (setq scope (org-add-archive-files scope)))
14434 ((eq scope 'file)
14435 (setq scope (list (buffer-file-name))))
14436 ((eq scope 'file-with-archives)
14437 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14438 (org-agenda-prepare-buffers scope)
14439 (while (setq file (pop scope))
14440 (with-current-buffer (org-find-base-buffer-visiting file)
14441 (save-excursion
14442 (save-restriction
14443 (widen)
14444 (goto-char (point-min))
14445 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14446 res)))
14448 ;;;; Properties
14450 ;;; Setting and retrieving properties
14452 (defconst org-special-properties
14453 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14454 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14455 "The special properties valid in Org-mode.
14457 These are properties that are not defined in the property drawer,
14458 but in some other way.")
14460 (defconst org-default-properties
14461 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14462 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14463 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14464 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14465 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14466 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14467 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14468 "Some properties that are used by Org-mode for various purposes.
14469 Being in this list makes sure that they are offered for completion.")
14471 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14472 "Regular expression matching the first line of a property drawer.")
14474 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14475 "Regular expression matching the last line of a property drawer.")
14477 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14478 "Regular expression matching the first line of a property drawer.")
14480 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14481 "Regular expression matching the first line of a property drawer.")
14483 (defconst org-property-drawer-re
14484 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14485 org-property-end-re "\\)\n?")
14486 "Matches an entire property drawer.")
14488 (defconst org-clock-drawer-re
14489 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14490 org-property-end-re "\\)\n?")
14491 "Matches an entire clock drawer.")
14493 (defsubst org-re-property (property)
14494 "Return a regexp matching a PROPERTY line.
14495 Match group 1 will be set to the value."
14496 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14498 (defsubst org-re-property-keyword (property)
14499 "Return a regexp matching a PROPERTY line, possibly with no
14500 value for the property."
14501 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14503 (defun org-property-action ()
14504 "Do an action on properties."
14505 (interactive)
14506 (let (c)
14507 (org-at-property-p)
14508 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14509 (setq c (read-char-exclusive))
14510 (cond
14511 ((equal c ?s)
14512 (call-interactively 'org-set-property))
14513 ((equal c ?d)
14514 (call-interactively 'org-delete-property))
14515 ((equal c ?D)
14516 (call-interactively 'org-delete-property-globally))
14517 ((equal c ?c)
14518 (call-interactively 'org-compute-property-at-point))
14519 (t (error "No such property action %c" c)))))
14521 (defun org-inc-effort ()
14522 "Increment the value of the effort property in the current entry."
14523 (interactive)
14524 (org-set-effort nil t))
14526 (defun org-set-effort (&optional value increment)
14527 "Set the effort property of the current entry.
14528 With numerical prefix arg, use the nth allowed value, 0 stands for the
14529 10th allowed value.
14531 When INCREMENT is non-nil, set the property to the next allowed value."
14532 (interactive "P")
14533 (if (equal value 0) (setq value 10))
14534 (let* ((completion-ignore-case t)
14535 (prop org-effort-property)
14536 (cur (org-entry-get nil prop))
14537 (allowed (org-property-get-allowed-values nil prop 'table))
14538 (existing (mapcar 'list (org-property-values prop)))
14540 (val (cond
14541 ((stringp value) value)
14542 ((and allowed (integerp value))
14543 (or (car (nth (1- value) allowed))
14544 (car (org-last allowed))))
14545 ((and allowed increment)
14546 (or (caadr (member (list cur) allowed))
14547 (error "Allowed effort values are not set")))
14548 (allowed
14549 (message "Select 1-9,0, [RET%s]: %s"
14550 (if cur (concat "=" cur) "")
14551 (mapconcat 'car allowed " "))
14552 (setq rpl (read-char-exclusive))
14553 (if (equal rpl ?\r)
14555 (setq rpl (- rpl ?0))
14556 (if (equal rpl 0) (setq rpl 10))
14557 (if (and (> rpl 0) (<= rpl (length allowed)))
14558 (car (nth (1- rpl) allowed))
14559 (org-completing-read "Effort: " allowed nil))))
14561 (let (org-completion-use-ido org-completion-use-iswitchb)
14562 (org-completing-read
14563 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14564 (concat "[" cur "]") "")
14565 ": ")
14566 existing nil nil "" nil cur))))))
14567 (unless (equal (org-entry-get nil prop) val)
14568 (org-entry-put nil prop val))
14569 (save-excursion
14570 (org-back-to-heading t)
14571 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14572 (message "%s is now %s" prop val)))
14574 (defun org-at-property-p ()
14575 "Is cursor inside a property drawer?"
14576 (save-excursion
14577 (beginning-of-line 1)
14578 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14579 (save-match-data ;; Used by calling procedures
14580 (let ((p (point))
14581 (range (unless (org-before-first-heading-p)
14582 (org-get-property-block))))
14583 (and range (<= (car range) p) (< p (cdr range))))))))
14585 (defun org-get-property-block (&optional beg end force)
14586 "Return the (beg . end) range of the body of the property drawer.
14587 BEG and END are the beginning and end of the current subtree, or of
14588 the part before the first headline. If they are not given, they will
14589 be found. If the drawer does not exist and FORCE is non-nil, create
14590 the drawer."
14591 (catch 'exit
14592 (save-excursion
14593 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14594 (progn (org-back-to-heading t) (point))))
14595 (end (or end (and (not (outline-next-heading)) (point-max))
14596 (point))))
14597 (goto-char beg)
14598 (if (re-search-forward org-property-start-re end t)
14599 (setq beg (1+ (match-end 0)))
14600 (if force
14601 (save-excursion
14602 (org-insert-property-drawer)
14603 (setq end (progn (outline-next-heading) (point))))
14604 (throw 'exit nil))
14605 (goto-char beg)
14606 (if (re-search-forward org-property-start-re end t)
14607 (setq beg (1+ (match-end 0)))))
14608 (if (re-search-forward org-property-end-re end t)
14609 (setq end (match-beginning 0))
14610 (or force (throw 'exit nil))
14611 (goto-char beg)
14612 (setq end beg)
14613 (org-indent-line)
14614 (insert ":END:\n"))
14615 (cons beg end)))))
14617 (defun org-entry-properties (&optional pom which specific)
14618 "Get all properties of the entry at point-or-marker POM.
14619 This includes the TODO keyword, the tags, time strings for deadline,
14620 scheduled, and clocking, and any additional properties defined in the
14621 entry. The return value is an alist, keys may occur multiple times
14622 if the property key was used several times.
14623 POM may also be nil, in which case the current entry is used.
14624 If WHICH is nil or `all', get all properties. If WHICH is
14625 `special' or `standard', only get that subclass. If WHICH
14626 is a string only get exactly this property. SPECIFIC can be a string, the
14627 specific property we are interested in. Specifying it can speed
14628 things up because then unnecessary parsing is avoided."
14629 (setq which (or which 'all))
14630 (org-with-point-at pom
14631 (let ((clockstr (substring org-clock-string 0 -1))
14632 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14633 (case-fold-search nil)
14634 beg end range props sum-props key key1 value string clocksum clocksumt)
14635 (save-excursion
14636 (when (condition-case nil
14637 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14638 (error nil))
14639 (setq beg (point))
14640 (setq sum-props (get-text-property (point) 'org-summaries))
14641 (setq clocksum (get-text-property (point) :org-clock-minutes)
14642 clocksumt (get-text-property (point) :org-clock-minutes-today))
14643 (outline-next-heading)
14644 (setq end (point))
14645 (when (memq which '(all special))
14646 ;; Get the special properties, like TODO and tags
14647 (goto-char beg)
14648 (when (and (or (not specific) (string= specific "TODO"))
14649 (looking-at org-todo-line-regexp) (match-end 2))
14650 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14651 (when (and (or (not specific) (string= specific "PRIORITY"))
14652 (looking-at org-priority-regexp))
14653 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14654 (when (or (not specific) (string= specific "FILE"))
14655 (push (cons "FILE" buffer-file-name) props))
14656 (when (and (or (not specific) (string= specific "TAGS"))
14657 (setq value (org-get-tags-string))
14658 (string-match "\\S-" value))
14659 (push (cons "TAGS" value) props))
14660 (when (and (or (not specific) (string= specific "ALLTAGS"))
14661 (setq value (org-get-tags-at)))
14662 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14663 ":"))
14664 props))
14665 (when (or (not specific) (string= specific "BLOCKED"))
14666 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14667 (when (or (not specific)
14668 (member specific
14669 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14670 "TIMESTAMP" "TIMESTAMP_IA")))
14671 (catch 'match
14672 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14673 (setq key (if (match-end 1)
14674 (substring (org-match-string-no-properties 1)
14675 0 -1))
14676 string (if (equal key clockstr)
14677 (org-trim
14678 (buffer-substring-no-properties
14679 (match-beginning 3) (goto-char
14680 (point-at-eol))))
14681 (substring (org-match-string-no-properties 3)
14682 1 -1)))
14683 ;; Get the correct property name from the key. This is
14684 ;; necessary if the user has configured time keywords.
14685 (setq key1 (concat key ":"))
14686 (cond
14687 ((not key)
14688 (setq key
14689 (if (= (char-after (match-beginning 3)) ?\[)
14690 "TIMESTAMP_IA" "TIMESTAMP")))
14691 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14692 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14693 ((equal key1 org-closed-string) (setq key "CLOSED"))
14694 ((equal key1 org-clock-string) (setq key "CLOCK")))
14695 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14696 (progn
14697 (push (cons key string) props)
14698 ;; no need to search further if match is found
14699 (throw 'match t))
14700 (when (or (equal key "CLOCK") (not (assoc key props)))
14701 (push (cons key string) props)))))))
14703 (when (memq which '(all standard))
14704 ;; Get the standard properties, like :PROP: ...
14705 (setq range (org-get-property-block beg end))
14706 (when range
14707 (goto-char (car range))
14708 (while (re-search-forward
14709 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14710 (cdr range) t)
14711 (setq key (org-match-string-no-properties 1)
14712 value (org-trim (or (org-match-string-no-properties 2) "")))
14713 (unless (member key excluded)
14714 (push (cons key (or value "")) props)))))
14715 (if clocksum
14716 (push (cons "CLOCKSUM"
14717 (org-columns-number-to-string (/ (float clocksum) 60.)
14718 'add_times))
14719 props))
14720 (if clocksumt
14721 (push (cons "CLOCKSUM_T"
14722 (org-columns-number-to-string (/ (float clocksumt) 60.)
14723 'add_times))
14724 props))
14725 (unless (assoc "CATEGORY" props)
14726 (push (cons "CATEGORY" (org-get-category)) props))
14727 (append sum-props (nreverse props)))))))
14729 (defun org-entry-get (pom property &optional inherit literal-nil)
14730 "Get value of PROPERTY for entry or content at point-or-marker POM.
14731 If INHERIT is non-nil and the entry does not have the property,
14732 then also check higher levels of the hierarchy.
14733 If INHERIT is the symbol `selective', use inheritance only if the setting
14734 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14735 If the property is present but empty, the return value is the empty string.
14736 If the property is not present at all, nil is returned.
14738 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14739 do not interpret it as the list atom nil. This is used for inheritance
14740 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14741 (org-with-point-at pom
14742 (if (and inherit (if (eq inherit 'selective)
14743 (org-property-inherit-p property)
14745 (org-entry-get-with-inheritance property literal-nil)
14746 (if (member property org-special-properties)
14747 ;; We need a special property. Use `org-entry-properties' to
14748 ;; retrieve it, but specify the wanted property
14749 (cdr (assoc property (org-entry-properties nil 'special property)))
14750 (let ((range (org-get-property-block)))
14751 (when (and range (not (eq (car range) (cdr range))))
14752 (let* ((props (list (or (assoc property org-file-properties)
14753 (assoc property org-global-properties)
14754 (assoc property org-global-properties-fixed))))
14755 (ap (lambda (key)
14756 (when (re-search-forward
14757 (org-re-property key) (cdr range) t)
14758 (setq props
14759 (org-update-property-plist
14761 (if (match-end 1)
14762 (org-match-string-no-properties 1) "")
14763 props)))))
14764 val)
14765 (goto-char (car range))
14766 (funcall ap property)
14767 (goto-char (car range))
14768 (while (funcall ap (concat property "+")))
14769 (setq val (cdr (assoc property props)))
14770 (when val (if literal-nil val (org-not-nil val))))))))))
14772 (defun org-property-or-variable-value (var &optional inherit)
14773 "Check if there is a property fixing the value of VAR.
14774 If yes, return this value. If not, return the current value of the variable."
14775 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14776 (if (and prop (stringp prop) (string-match "\\S-" prop))
14777 (read prop)
14778 (symbol-value var))))
14780 (defun org-entry-delete (pom property)
14781 "Delete the property PROPERTY from entry at point-or-marker POM."
14782 (org-with-point-at pom
14783 (if (member property org-special-properties)
14784 nil ; cannot delete these properties.
14785 (let ((range (org-get-property-block)))
14786 (if (and range
14787 (goto-char (car range))
14788 (re-search-forward
14789 (org-re-property property)
14790 (cdr range) t))
14791 (progn
14792 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14794 nil)))))
14796 ;; Multi-values properties are properties that contain multiple values
14797 ;; These values are assumed to be single words, separated by whitespace.
14798 (defun org-entry-add-to-multivalued-property (pom property value)
14799 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14800 (let* ((old (org-entry-get pom property))
14801 (values (and old (org-split-string old "[ \t]"))))
14802 (setq value (org-entry-protect-space value))
14803 (unless (member value values)
14804 (setq values (cons value values))
14805 (org-entry-put pom property
14806 (mapconcat 'identity values " ")))))
14808 (defun org-entry-remove-from-multivalued-property (pom property value)
14809 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14810 (let* ((old (org-entry-get pom property))
14811 (values (and old (org-split-string old "[ \t]"))))
14812 (setq value (org-entry-protect-space value))
14813 (when (member value values)
14814 (setq values (delete value values))
14815 (org-entry-put pom property
14816 (mapconcat 'identity values " ")))))
14818 (defun org-entry-member-in-multivalued-property (pom property value)
14819 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14820 (let* ((old (org-entry-get pom property))
14821 (values (and old (org-split-string old "[ \t]"))))
14822 (setq value (org-entry-protect-space value))
14823 (member value values)))
14825 (defun org-entry-get-multivalued-property (pom property)
14826 "Return a list of values in a multivalued property."
14827 (let* ((value (org-entry-get pom property))
14828 (values (and value (org-split-string value "[ \t]"))))
14829 (mapcar 'org-entry-restore-space values)))
14831 (defun org-entry-put-multivalued-property (pom property &rest values)
14832 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14833 VALUES should be a list of strings. Spaces will be protected."
14834 (org-entry-put pom property
14835 (mapconcat 'org-entry-protect-space values " "))
14836 (let* ((value (org-entry-get pom property))
14837 (values (and value (org-split-string value "[ \t]"))))
14838 (mapcar 'org-entry-restore-space values)))
14840 (defun org-entry-protect-space (s)
14841 "Protect spaces and newline in string S."
14842 (while (string-match " " s)
14843 (setq s (replace-match "%20" t t s)))
14844 (while (string-match "\n" s)
14845 (setq s (replace-match "%0A" t t s)))
14848 (defun org-entry-restore-space (s)
14849 "Restore spaces and newline in string S."
14850 (while (string-match "%20" s)
14851 (setq s (replace-match " " t t s)))
14852 (while (string-match "%0A" s)
14853 (setq s (replace-match "\n" t t s)))
14856 (defvar org-entry-property-inherited-from (make-marker)
14857 "Marker pointing to the entry from where a property was inherited.
14858 Each call to `org-entry-get-with-inheritance' will set this marker to the
14859 location of the entry where the inheritance search matched. If there was
14860 no match, the marker will point nowhere.
14861 Note that also `org-entry-get' calls this function, if the INHERIT flag
14862 is set.")
14864 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14865 "Get PROPERTY of entry or content at point, search higher levels if needed.
14866 The search will stop at the first ancestor which has the property defined.
14867 If the value found is \"nil\", return nil to show that the property
14868 should be considered as undefined (this is the meaning of nil here).
14869 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14870 (move-marker org-entry-property-inherited-from nil)
14871 (let (tmp)
14872 (save-excursion
14873 (save-restriction
14874 (widen)
14875 (catch 'ex
14876 (while t
14877 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14878 (or (ignore-errors (org-back-to-heading t))
14879 (goto-char (point-min)))
14880 (move-marker org-entry-property-inherited-from (point))
14881 (throw 'ex tmp))
14882 (or (ignore-errors (org-up-heading-safe))
14883 (throw 'ex nil))))))
14884 (setq tmp (or tmp
14885 (cdr (assoc property org-file-properties))
14886 (cdr (assoc property org-global-properties))
14887 (cdr (assoc property org-global-properties-fixed))))
14888 (if literal-nil tmp (org-not-nil tmp))))
14890 (defvar org-property-changed-functions nil
14891 "Hook called when the value of a property has changed.
14892 Each hook function should accept two arguments, the name of the property
14893 and the new value.")
14895 (defun org-entry-put (pom property value)
14896 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14897 (org-with-point-at pom
14898 (org-back-to-heading t)
14899 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14900 range)
14901 (cond
14902 ((equal property "TODO")
14903 (when (and (stringp value) (string-match "\\S-" value)
14904 (not (member value org-todo-keywords-1)))
14905 (error "\"%s\" is not a valid TODO state" value))
14906 (if (or (not value)
14907 (not (string-match "\\S-" value)))
14908 (setq value 'none))
14909 (org-todo value)
14910 (org-set-tags nil 'align))
14911 ((equal property "PRIORITY")
14912 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14913 (string-to-char value) ?\ ))
14914 (org-set-tags nil 'align))
14915 ((equal property "CLOCKSUM")
14916 (if (not (re-search-forward
14917 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14918 (error "Cannot find a clock log")
14919 (goto-char (- (match-end 1) 2))
14920 (cond
14921 ((eq value 'earlier) (org-timestamp-down))
14922 ((eq value 'later) (org-timestamp-up)))
14923 (org-clock-sum-current-item)))
14924 ((equal property "SCHEDULED")
14925 (if (re-search-forward org-scheduled-time-regexp end t)
14926 (cond
14927 ((eq value 'earlier) (org-timestamp-change -1 'day))
14928 ((eq value 'later) (org-timestamp-change 1 'day))
14929 (t (call-interactively 'org-schedule)))
14930 (call-interactively 'org-schedule)))
14931 ((equal property "DEADLINE")
14932 (if (re-search-forward org-deadline-time-regexp end t)
14933 (cond
14934 ((eq value 'earlier) (org-timestamp-change -1 'day))
14935 ((eq value 'later) (org-timestamp-change 1 'day))
14936 (t (call-interactively 'org-deadline)))
14937 (call-interactively 'org-deadline)))
14938 ((member property org-special-properties)
14939 (error "The %s property can not yet be set with `org-entry-put'"
14940 property))
14941 (t ; a non-special property
14942 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14943 (setq range (org-get-property-block beg end 'force))
14944 (goto-char (car range))
14945 (if (re-search-forward
14946 (org-re-property-keyword property) (cdr range) t)
14947 (progn
14948 (delete-region (match-beginning 0) (match-end 0))
14949 (goto-char (match-beginning 0)))
14950 (goto-char (cdr range))
14951 (insert "\n")
14952 (backward-char 1)
14953 (org-indent-line))
14954 (insert ":" property ":")
14955 (and value (insert " " value))
14956 (org-indent-line)))))
14957 (run-hook-with-args 'org-property-changed-functions property value)))
14959 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14960 "Get all property keys in the current buffer.
14961 With INCLUDE-SPECIALS, also list the special properties that reflect things
14962 like tags and TODO state.
14963 With INCLUDE-DEFAULTS, also include properties that has special meaning
14964 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14965 and others.
14966 With INCLUDE-COLUMNS, also include property names given in COLUMN
14967 formats in the current buffer."
14968 (let (rtn range cfmt s p)
14969 (save-excursion
14970 (save-restriction
14971 (widen)
14972 (goto-char (point-min))
14973 (while (re-search-forward org-property-start-re nil t)
14974 (setq range (org-get-property-block))
14975 (goto-char (car range))
14976 (while (re-search-forward
14977 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14978 (cdr range) t)
14979 (add-to-list 'rtn (org-match-string-no-properties 1)))
14980 (outline-next-heading))))
14982 (when include-specials
14983 (setq rtn (append org-special-properties rtn)))
14985 (when include-defaults
14986 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14987 (add-to-list 'rtn org-effort-property))
14989 (when include-columns
14990 (save-excursion
14991 (save-restriction
14992 (widen)
14993 (goto-char (point-min))
14994 (while (re-search-forward
14995 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14996 nil t)
14997 (setq cfmt (match-string 2) s 0)
14998 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14999 cfmt s)
15000 (setq s (match-end 0)
15001 p (match-string 1 cfmt))
15002 (unless (or (equal p "ITEM")
15003 (member p org-special-properties))
15004 (add-to-list 'rtn (match-string 1 cfmt))))))))
15006 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15008 (defun org-property-values (key)
15009 "Return a list of all values of property KEY in the current buffer."
15010 (save-excursion
15011 (save-restriction
15012 (widen)
15013 (goto-char (point-min))
15014 (let ((re (org-re-property key))
15015 values)
15016 (while (re-search-forward re nil t)
15017 (add-to-list 'values (org-trim (match-string 1))))
15018 (delete "" values)))))
15020 (defun org-insert-property-drawer ()
15021 "Insert a property drawer into the current entry."
15022 (org-back-to-heading t)
15023 (looking-at org-outline-regexp)
15024 (let ((indent (if org-adapt-indentation
15025 (- (match-end 0) (match-beginning 0))
15027 (beg (point))
15028 (re (concat "^[ \t]*" org-keyword-time-regexp))
15029 end hiddenp)
15030 (outline-next-heading)
15031 (setq end (point))
15032 (goto-char beg)
15033 (while (re-search-forward re end t))
15034 (setq hiddenp (outline-invisible-p))
15035 (end-of-line 1)
15036 (and (equal (char-after) ?\n) (forward-char 1))
15037 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15038 (if (member (match-string 1) '("CLOCK:" ":END:"))
15039 ;; just skip this line
15040 (beginning-of-line 2)
15041 ;; Drawer start, find the end
15042 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15043 (beginning-of-line 1)))
15044 (org-skip-over-state-notes)
15045 (skip-chars-backward " \t\n\r")
15046 (if (eq (char-before) ?*) (forward-char 1))
15047 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15048 (beginning-of-line 0)
15049 (org-indent-to-column indent)
15050 (beginning-of-line 2)
15051 (org-indent-to-column indent)
15052 (beginning-of-line 0)
15053 (if hiddenp
15054 (save-excursion
15055 (org-back-to-heading t)
15056 (hide-entry))
15057 (org-flag-drawer t))))
15059 (defun org-insert-drawer (&optional arg drawer)
15060 "Insert a drawer at point.
15062 Optional argument DRAWER, when non-nil, is a string representing
15063 drawer's name. Otherwise, the user is prompted for a name.
15065 If a region is active, insert the drawer around that region
15066 instead.
15068 Point is left between drawer's boundaries."
15069 (interactive "P")
15070 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15071 "LOGBOOK"))
15072 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15073 ;; internally by Org. They are meant to be inserted
15074 ;; automatically.
15075 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15076 ;; Remove system drawers from list. Note: For some reason,
15077 ;; `org-completing-read' ignores the predicate while
15078 ;; `completing-read' handles it fine.
15079 (drawer (if arg "PROPERTIES"
15080 (or drawer
15081 (completing-read
15082 "Drawer: " org-drawers
15083 (lambda (d) (not (member d system-drawers))))))))
15084 (cond
15085 ;; With C-u, fall back on `org-insert-property-drawer'
15086 (arg (org-insert-property-drawer))
15087 ;; With an active region, insert a drawer at point.
15088 ((not (org-region-active-p))
15089 (progn
15090 (unless (bolp) (insert "\n"))
15091 (insert (format ":%s:\n\n:END:\n" drawer))
15092 (forward-line -2)))
15093 ;; Otherwise, insert the drawer at point
15095 (let ((rbeg (region-beginning))
15096 (rend (copy-marker (region-end))))
15097 (unwind-protect
15098 (progn
15099 (goto-char rbeg)
15100 (beginning-of-line)
15101 (when (save-excursion
15102 (re-search-forward org-outline-regexp-bol rend t))
15103 (error "Drawers cannot contain headlines"))
15104 ;; Position point at the beginning of the first
15105 ;; non-blank line in region. Insert drawer's opening
15106 ;; there, then indent it.
15107 (org-skip-whitespace)
15108 (beginning-of-line)
15109 (insert ":" drawer ":\n")
15110 (forward-line -1)
15111 (indent-for-tab-command)
15112 ;; Move point to the beginning of the first blank line
15113 ;; after the last non-blank line in region. Insert
15114 ;; drawer's closing, then indent it.
15115 (goto-char rend)
15116 (skip-chars-backward " \r\t\n")
15117 (insert "\n:END:")
15118 (deactivate-mark t)
15119 (indent-for-tab-command)
15120 (unless (eolp) (insert "\n")))
15121 ;; Clear marker, whatever the outcome of insertion is.
15122 (set-marker rend nil)))))))
15124 (defvar org-property-set-functions-alist nil
15125 "Property set function alist.
15126 Each entry should have the following format:
15128 (PROPERTY . READ-FUNCTION)
15130 The read function will be called with the same argument as
15131 `org-completing-read'.")
15133 (defun org-set-property-function (property)
15134 "Get the function that should be used to set PROPERTY.
15135 This is computed according to `org-property-set-functions-alist'."
15136 (or (cdr (assoc property org-property-set-functions-alist))
15137 'org-completing-read))
15139 (defun org-read-property-value (property)
15140 "Read PROPERTY value from user."
15141 (let* ((completion-ignore-case t)
15142 (allowed (org-property-get-allowed-values nil property 'table))
15143 (cur (org-entry-get nil property))
15144 (prompt (concat property " value"
15145 (if (and cur (string-match "\\S-" cur))
15146 (concat " [" cur "]") "") ": "))
15147 (set-function (org-set-property-function property))
15148 (val (if allowed
15149 (funcall set-function prompt allowed nil
15150 (not (get-text-property 0 'org-unrestricted
15151 (caar allowed))))
15152 (let (org-completion-use-ido org-completion-use-iswitchb)
15153 (funcall set-function prompt
15154 (mapcar 'list (org-property-values property))
15155 nil nil "" nil cur)))))
15156 (if (equal val "")
15158 val)))
15160 (defvar org-last-set-property nil)
15161 (defvar org-last-set-property-value nil)
15162 (defun org-read-property-name ()
15163 "Read a property name."
15164 (let* ((completion-ignore-case t)
15165 (keys (org-buffer-property-keys nil t t))
15166 (default-prop (or (save-excursion
15167 (save-match-data
15168 (beginning-of-line)
15169 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15170 (null (string= (match-string 1) "END"))
15171 (match-string 1))))
15172 org-last-set-property))
15173 (property (org-icompleting-read
15174 (concat "Property"
15175 (if default-prop (concat " [" default-prop "]") "")
15176 ": ")
15177 (mapcar 'list keys)
15178 nil nil nil nil
15179 default-prop)))
15180 (if (member property keys)
15181 property
15182 (or (cdr (assoc (downcase property)
15183 (mapcar (lambda (x) (cons (downcase x) x))
15184 keys)))
15185 property))))
15187 (defun org-set-property-and-value (use-last)
15188 "Allow to set [PROPERTY]: [value] direction from prompt.
15189 When use-default, don't even ask, just use the last
15190 \"[PROPERTY]: [value]\" string from the history."
15191 (interactive "P")
15192 (let* ((completion-ignore-case t)
15193 (pv (or (and use-last org-last-set-property-value)
15194 (org-completing-read
15195 "Enter a \"[Property]: [value]\" pair: "
15196 nil nil nil nil nil
15197 org-last-set-property-value)))
15198 prop val)
15199 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15200 (setq prop (match-string 1 pv)
15201 val (match-string 2 pv))
15202 (org-set-property prop val))))
15204 (defun org-set-property (property value)
15205 "In the current entry, set PROPERTY to VALUE.
15206 When called interactively, this will prompt for a property name, offering
15207 completion on existing and default properties. And then it will prompt
15208 for a value, offering completion either on allowed values (via an inherited
15209 xxx_ALL property) or on existing values in other instances of this property
15210 in the current file."
15211 (interactive (list nil nil))
15212 (let* ((property (or property (org-read-property-name)))
15213 (value (or value (org-read-property-value property)))
15214 (fn (cdr (assoc property org-properties-postprocess-alist))))
15215 (setq org-last-set-property property)
15216 (setq org-last-set-property-value (concat property ": " value))
15217 ;; Possibly postprocess the inserted value:
15218 (when fn (setq value (funcall fn value)))
15219 (unless (equal (org-entry-get nil property) value)
15220 (org-entry-put nil property value))))
15222 (defun org-delete-property (property)
15223 "In the current entry, delete PROPERTY."
15224 (interactive
15225 (let* ((completion-ignore-case t)
15226 (prop (org-icompleting-read "Property: "
15227 (org-entry-properties nil 'standard))))
15228 (list prop)))
15229 (message "Property %s %s" property
15230 (if (org-entry-delete nil property)
15231 "deleted"
15232 "was not present in the entry")))
15234 (defun org-delete-property-globally (property)
15235 "Remove PROPERTY globally, from all entries."
15236 (interactive
15237 (let* ((completion-ignore-case t)
15238 (prop (org-icompleting-read
15239 "Globally remove property: "
15240 (mapcar 'list (org-buffer-property-keys)))))
15241 (list prop)))
15242 (save-excursion
15243 (save-restriction
15244 (widen)
15245 (goto-char (point-min))
15246 (let ((cnt 0))
15247 (while (re-search-forward
15248 (org-re-property property)
15249 nil t)
15250 (setq cnt (1+ cnt))
15251 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15252 (message "Property \"%s\" removed from %d entries" property cnt)))))
15254 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15256 (defun org-compute-property-at-point ()
15257 "Compute the property at point.
15258 This looks for an enclosing column format, extracts the operator and
15259 then applies it to the property in the column format's scope."
15260 (interactive)
15261 (unless (org-at-property-p)
15262 (error "Not at a property"))
15263 (let ((prop (org-match-string-no-properties 2)))
15264 (org-columns-get-format-and-top-level)
15265 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15266 (error "No operator defined for property %s" prop))
15267 (org-columns-compute prop)))
15269 (defvar org-property-allowed-value-functions nil
15270 "Hook for functions supplying allowed values for a specific property.
15271 The functions must take a single argument, the name of the property, and
15272 return a flat list of allowed values. If \":ETC\" is one of
15273 the values, this means that these values are intended as defaults for
15274 completion, but that other values should be allowed too.
15275 The functions must return nil if they are not responsible for this
15276 property.")
15278 (defun org-property-get-allowed-values (pom property &optional table)
15279 "Get allowed values for the property PROPERTY.
15280 When TABLE is non-nil, return an alist that can directly be used for
15281 completion."
15282 (let (vals)
15283 (cond
15284 ((equal property "TODO")
15285 (setq vals (org-with-point-at pom
15286 (append org-todo-keywords-1 '("")))))
15287 ((equal property "PRIORITY")
15288 (let ((n org-lowest-priority))
15289 (while (>= n org-highest-priority)
15290 (push (char-to-string n) vals)
15291 (setq n (1- n)))))
15292 ((member property org-special-properties))
15293 ((setq vals (run-hook-with-args-until-success
15294 'org-property-allowed-value-functions property)))
15296 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15297 (when (and vals (string-match "\\S-" vals))
15298 (setq vals (car (read-from-string (concat "(" vals ")"))))
15299 (setq vals (mapcar (lambda (x)
15300 (cond ((stringp x) x)
15301 ((numberp x) (number-to-string x))
15302 ((symbolp x) (symbol-name x))
15303 (t "???")))
15304 vals)))))
15305 (when (member ":ETC" vals)
15306 (setq vals (remove ":ETC" vals))
15307 (org-add-props (car vals) '(org-unrestricted t)))
15308 (if table (mapcar 'list vals) vals)))
15310 (defun org-property-previous-allowed-value (&optional previous)
15311 "Switch to the next allowed value for this property."
15312 (interactive)
15313 (org-property-next-allowed-value t))
15315 (defun org-property-next-allowed-value (&optional previous)
15316 "Switch to the next allowed value for this property."
15317 (interactive)
15318 (unless (org-at-property-p)
15319 (error "Not at a property"))
15320 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15321 (key (match-string 2))
15322 (value (match-string 3))
15323 (allowed (or (org-property-get-allowed-values (point) key)
15324 (and (member value '("[ ]" "[-]" "[X]"))
15325 '("[ ]" "[X]"))))
15326 nval)
15327 (unless allowed
15328 (error "Allowed values for this property have not been defined"))
15329 (if previous (setq allowed (reverse allowed)))
15330 (if (member value allowed)
15331 (setq nval (car (cdr (member value allowed)))))
15332 (setq nval (or nval (car allowed)))
15333 (if (equal nval value)
15334 (error "Only one allowed value for this property"))
15335 (org-at-property-p)
15336 (replace-match (concat " :" key ": " nval) t t)
15337 (org-indent-line)
15338 (beginning-of-line 1)
15339 (skip-chars-forward " \t")
15340 (when (equal prop org-effort-property)
15341 (save-excursion
15342 (org-back-to-heading t)
15343 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15344 (run-hook-with-args 'org-property-changed-functions key nval)))
15346 (defun org-find-olp (path &optional this-buffer)
15347 "Return a marker pointing to the entry at outline path OLP.
15348 If anything goes wrong, throw an error.
15349 You can wrap this call to catch the error like this:
15351 (condition-case msg
15352 (org-mobile-locate-entry (match-string 4))
15353 (error (nth 1 msg)))
15355 The return value will then be either a string with the error message,
15356 or a marker if everything is OK.
15358 If THIS-BUFFER is set, the outline path does not contain a file,
15359 only headings."
15360 (let* ((file (if this-buffer buffer-file-name (pop path)))
15361 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15362 (level 1)
15363 (lmin 1)
15364 (lmax 1)
15365 limit re end found pos heading cnt flevel)
15366 (unless buffer (error "File not found :%s" file))
15367 (with-current-buffer buffer
15368 (save-excursion
15369 (save-restriction
15370 (widen)
15371 (setq limit (point-max))
15372 (goto-char (point-min))
15373 (while (setq heading (pop path))
15374 (setq re (format org-complex-heading-regexp-format
15375 (regexp-quote heading)))
15376 (setq cnt 0 pos (point))
15377 (while (re-search-forward re end t)
15378 (setq level (- (match-end 1) (match-beginning 1)))
15379 (if (and (>= level lmin) (<= level lmax))
15380 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15381 (when (= cnt 0) (error "Heading not found on level %d: %s"
15382 lmax heading))
15383 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15384 lmax heading))
15385 (goto-char found)
15386 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15387 (setq end (save-excursion (org-end-of-subtree t t))))
15388 (when (org-at-heading-p)
15389 (point-marker)))))))
15391 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15392 "Find node HEADING in BUFFER.
15393 Return a marker to the heading if it was found, or nil if not.
15394 If POS-ONLY is set, return just the position instead of a marker.
15396 The heading text must match exact, but it may have a TODO keyword,
15397 a priority cookie and tags in the standard locations."
15398 (with-current-buffer (or buffer (current-buffer))
15399 (save-excursion
15400 (save-restriction
15401 (widen)
15402 (goto-char (point-min))
15403 (let (case-fold-search)
15404 (if (re-search-forward
15405 (format org-complex-heading-regexp-format
15406 (regexp-quote heading)) nil t)
15407 (if pos-only
15408 (match-beginning 0)
15409 (move-marker (make-marker) (match-beginning 0)))))))))
15411 (defun org-find-exact-heading-in-directory (heading &optional dir)
15412 "Find Org node headline HEADING in all .org files in directory DIR.
15413 When the target headline is found, return a marker to this location."
15414 (let ((files (directory-files (or dir default-directory)
15415 nil "\\`[^.#].*\\.org\\'"))
15416 file visiting m buffer)
15417 (catch 'found
15418 (while (setq file (pop files))
15419 (message "trying %s" file)
15420 (setq visiting (org-find-base-buffer-visiting file))
15421 (setq buffer (or visiting (find-file-noselect file)))
15422 (setq m (org-find-exact-headline-in-buffer
15423 heading buffer))
15424 (when (and (not m) (not visiting)) (kill-buffer buffer))
15425 (and m (throw 'found m))))))
15427 (defun org-find-entry-with-id (ident)
15428 "Locate the entry that contains the ID property with exact value IDENT.
15429 IDENT can be a string, a symbol or a number, this function will search for
15430 the string representation of it.
15431 Return the position where this entry starts, or nil if there is no such entry."
15432 (interactive "sID: ")
15433 (let ((id (cond
15434 ((stringp ident) ident)
15435 ((symbol-name ident) (symbol-name ident))
15436 ((numberp ident) (number-to-string ident))
15437 (t (error "IDENT %s must be a string, symbol or number" ident))))
15438 (case-fold-search nil))
15439 (save-excursion
15440 (save-restriction
15441 (widen)
15442 (goto-char (point-min))
15443 (when (re-search-forward
15444 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15445 nil t)
15446 (org-back-to-heading t)
15447 (point))))))
15449 ;;;; Timestamps
15451 (defvar org-last-changed-timestamp nil)
15452 (defvar org-last-inserted-timestamp nil
15453 "The last time stamp inserted with `org-insert-time-stamp'.")
15454 (defvar org-time-was-given) ; dynamically scoped parameter
15455 (defvar org-end-time-was-given) ; dynamically scoped parameter
15456 (defvar org-ts-what) ; dynamically scoped parameter
15458 (defun org-time-stamp (arg &optional inactive)
15459 "Prompt for a date/time and insert a time stamp.
15460 If the user specifies a time like HH:MM or if this command is
15461 called with at least one prefix argument, the time stamp contains
15462 the date and the time. Otherwise, only the date is be included.
15464 All parts of a date not specified by the user is filled in from
15465 the current date/time. So if you just press return without
15466 typing anything, the time stamp will represent the current
15467 date/time.
15469 If there is already a timestamp at the cursor, it will be
15470 modified.
15472 With two universal prefix arguments, insert an active timestamp
15473 with the current time without prompting the user."
15474 (interactive "P")
15475 (let* ((ts nil)
15476 (default-time
15477 ;; Default time is either today, or, when entering a range,
15478 ;; the range start.
15479 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15480 (save-excursion
15481 (re-search-backward
15482 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15483 (- (point) 20) t)))
15484 (apply 'encode-time (org-parse-time-string (match-string 1)))
15485 (current-time)))
15486 (default-input (and ts (org-get-compact-tod ts)))
15487 (repeater (save-excursion
15488 (save-match-data
15489 (beginning-of-line)
15490 (when (re-search-forward
15491 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15492 (save-excursion (progn (end-of-line) (point))) t)
15493 (match-string 0)))))
15494 org-time-was-given org-end-time-was-given time)
15495 (cond
15496 ((and (org-at-timestamp-p t)
15497 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15498 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15499 (insert "--")
15500 (setq time (let ((this-command this-command))
15501 (org-read-date arg 'totime nil nil
15502 default-time default-input inactive)))
15503 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15504 ((org-at-timestamp-p t)
15505 (setq time (let ((this-command this-command))
15506 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15507 (when (org-at-timestamp-p t) ; just to get the match data
15508 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15509 (replace-match "")
15510 (setq org-last-changed-timestamp
15511 (org-insert-time-stamp
15512 time (or org-time-was-given arg)
15513 inactive nil nil (list org-end-time-was-given)))
15514 (when repeater (goto-char (1- (point))) (insert " " repeater)
15515 (setq org-last-changed-timestamp
15516 (concat (substring org-last-inserted-timestamp 0 -1)
15517 " " repeater ">"))))
15518 (message "Timestamp updated"))
15519 ((equal arg '(16))
15520 (org-insert-time-stamp (current-time) t))
15522 (setq time (let ((this-command this-command))
15523 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15524 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15525 nil nil (list org-end-time-was-given))))))
15527 ;; FIXME: can we use this for something else, like computing time differences?
15528 (defun org-get-compact-tod (s)
15529 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15530 (let* ((t1 (match-string 1 s))
15531 (h1 (string-to-number (match-string 2 s)))
15532 (m1 (string-to-number (match-string 3 s)))
15533 (t2 (and (match-end 4) (match-string 5 s)))
15534 (h2 (and t2 (string-to-number (match-string 6 s))))
15535 (m2 (and t2 (string-to-number (match-string 7 s))))
15536 dh dm)
15537 (if (not t2)
15539 (setq dh (- h2 h1) dm (- m2 m1))
15540 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15541 (concat t1 "+" (number-to-string dh)
15542 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15544 (defun org-time-stamp-inactive (&optional arg)
15545 "Insert an inactive time stamp.
15546 An inactive time stamp is enclosed in square brackets instead of angle
15547 brackets. It is inactive in the sense that it does not trigger agenda entries,
15548 does not link to the calendar and cannot be changed with the S-cursor keys.
15549 So these are more for recording a certain time/date."
15550 (interactive "P")
15551 (org-time-stamp arg 'inactive))
15553 (defvar org-date-ovl (make-overlay 1 1))
15554 (overlay-put org-date-ovl 'face 'org-date-selected)
15555 (org-detach-overlay org-date-ovl)
15557 (defvar org-ans1) ; dynamically scoped parameter
15558 (defvar org-ans2) ; dynamically scoped parameter
15560 (defvar org-plain-time-of-day-regexp) ; defined below
15562 (defvar org-overriding-default-time nil) ; dynamically scoped
15563 (defvar org-read-date-overlay nil)
15564 (defvar org-dcst nil) ; dynamically scoped
15565 (defvar org-read-date-history nil)
15566 (defvar org-read-date-final-answer nil)
15567 (defvar org-read-date-analyze-futurep nil)
15568 (defvar org-read-date-analyze-forced-year nil)
15569 (defvar org-read-date-inactive)
15571 (defun org-read-date (&optional org-with-time to-time from-string prompt
15572 default-time default-input inactive)
15573 "Read a date, possibly a time, and make things smooth for the user.
15574 The prompt will suggest to enter an ISO date, but you can also enter anything
15575 which will at least partially be understood by `parse-time-string'.
15576 Unrecognized parts of the date will default to the current day, month, year,
15577 hour and minute. If this command is called to replace a timestamp at point,
15578 or to enter the second timestamp of a range, the default time is taken
15579 from the existing stamp. Furthermore, the command prefers the future,
15580 so if you are giving a date where the year is not given, and the day-month
15581 combination is already past in the current year, it will assume you
15582 mean next year. For details, see the manual. A few examples:
15584 3-2-5 --> 2003-02-05
15585 feb 15 --> currentyear-02-15
15586 2/15 --> currentyear-02-15
15587 sep 12 9 --> 2009-09-12
15588 12:45 --> today 12:45
15589 22 sept 0:34 --> currentyear-09-22 0:34
15590 12 --> currentyear-currentmonth-12
15591 Fri --> nearest Friday (today or later)
15592 etc.
15594 Furthermore you can specify a relative date by giving, as the *first* thing
15595 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15596 change in days weeks, months, years.
15597 With a single plus or minus, the date is relative to today. With a double
15598 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15599 +4d --> four days from today
15600 +4 --> same as above
15601 +2w --> two weeks from today
15602 ++5 --> five days from default date
15604 The function understands only English month and weekday abbreviations.
15606 While prompting, a calendar is popped up - you can also select the
15607 date with the mouse (button 1). The calendar shows a period of three
15608 months. To scroll it to other months, use the keys `>' and `<'.
15609 If you don't like the calendar, turn it off with
15610 \(setq org-read-date-popup-calendar nil)
15612 With optional argument TO-TIME, the date will immediately be converted
15613 to an internal time.
15614 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15615 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15616 still enter a time, and this function will inform the calling routine
15617 about this change. The calling routine may then choose to change the
15618 format used to insert the time stamp into the buffer to include the time.
15619 With optional argument FROM-STRING, read from this string instead from
15620 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15621 the time/date that is used for everything that is not specified by the
15622 user."
15623 (require 'parse-time)
15624 (let* ((org-time-stamp-rounding-minutes
15625 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15626 (org-dcst org-display-custom-times)
15627 (ct (org-current-time))
15628 (org-def (or org-overriding-default-time default-time ct))
15629 (org-defdecode (decode-time org-def))
15630 (dummy (progn
15631 (when (< (nth 2 org-defdecode) org-extend-today-until)
15632 (setcar (nthcdr 2 org-defdecode) -1)
15633 (setcar (nthcdr 1 org-defdecode) 59)
15634 (setq org-def (apply 'encode-time org-defdecode)
15635 org-defdecode (decode-time org-def)))))
15636 (mouse-autoselect-window nil) ; Don't let the mouse jump
15637 (calendar-frame-setup nil)
15638 (calendar-setup nil)
15639 (calendar-move-hook nil)
15640 (calendar-view-diary-initially-flag nil)
15641 (calendar-view-holidays-initially-flag nil)
15642 (timestr (format-time-string
15643 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15644 (prompt (concat (if prompt (concat prompt " ") "")
15645 (format "Date+time [%s]: " timestr)))
15646 ans (org-ans0 "") org-ans1 org-ans2 final)
15648 (cond
15649 (from-string (setq ans from-string))
15650 (org-read-date-popup-calendar
15651 (save-excursion
15652 (save-window-excursion
15653 (calendar)
15654 (org-eval-in-calendar '(setq cursor-type nil) t)
15655 (unwind-protect
15656 (progn
15657 (calendar-forward-day (- (time-to-days org-def)
15658 (calendar-absolute-from-gregorian
15659 (calendar-current-date))))
15660 (org-eval-in-calendar nil t)
15661 (let* ((old-map (current-local-map))
15662 (map (copy-keymap calendar-mode-map))
15663 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15664 (org-defkey map (kbd "RET") 'org-calendar-select)
15665 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15666 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15667 (org-defkey minibuffer-local-map [(meta shift left)]
15668 (lambda () (interactive)
15669 (org-eval-in-calendar '(calendar-backward-month 1))))
15670 (org-defkey minibuffer-local-map [(meta shift right)]
15671 (lambda () (interactive)
15672 (org-eval-in-calendar '(calendar-forward-month 1))))
15673 (org-defkey minibuffer-local-map [(meta shift up)]
15674 (lambda () (interactive)
15675 (org-eval-in-calendar '(calendar-backward-year 1))))
15676 (org-defkey minibuffer-local-map [(meta shift down)]
15677 (lambda () (interactive)
15678 (org-eval-in-calendar '(calendar-forward-year 1))))
15679 (org-defkey minibuffer-local-map [?\e (shift left)]
15680 (lambda () (interactive)
15681 (org-eval-in-calendar '(calendar-backward-month 1))))
15682 (org-defkey minibuffer-local-map [?\e (shift right)]
15683 (lambda () (interactive)
15684 (org-eval-in-calendar '(calendar-forward-month 1))))
15685 (org-defkey minibuffer-local-map [?\e (shift up)]
15686 (lambda () (interactive)
15687 (org-eval-in-calendar '(calendar-backward-year 1))))
15688 (org-defkey minibuffer-local-map [?\e (shift down)]
15689 (lambda () (interactive)
15690 (org-eval-in-calendar '(calendar-forward-year 1))))
15691 (org-defkey minibuffer-local-map [(shift up)]
15692 (lambda () (interactive)
15693 (org-eval-in-calendar '(calendar-backward-week 1))))
15694 (org-defkey minibuffer-local-map [(shift down)]
15695 (lambda () (interactive)
15696 (org-eval-in-calendar '(calendar-forward-week 1))))
15697 (org-defkey minibuffer-local-map [(shift left)]
15698 (lambda () (interactive)
15699 (org-eval-in-calendar '(calendar-backward-day 1))))
15700 (org-defkey minibuffer-local-map [(shift right)]
15701 (lambda () (interactive)
15702 (org-eval-in-calendar '(calendar-forward-day 1))))
15703 (org-defkey minibuffer-local-map ">"
15704 (lambda () (interactive)
15705 (org-eval-in-calendar '(scroll-calendar-left 1))))
15706 (org-defkey minibuffer-local-map "<"
15707 (lambda () (interactive)
15708 (org-eval-in-calendar '(scroll-calendar-right 1))))
15709 (org-defkey minibuffer-local-map "\C-v"
15710 (lambda () (interactive)
15711 (org-eval-in-calendar
15712 '(calendar-scroll-left-three-months 1))))
15713 (org-defkey minibuffer-local-map "\M-v"
15714 (lambda () (interactive)
15715 (org-eval-in-calendar
15716 '(calendar-scroll-right-three-months 1))))
15717 (run-hooks 'org-read-date-minibuffer-setup-hook)
15718 (unwind-protect
15719 (progn
15720 (use-local-map map)
15721 (setq org-read-date-inactive inactive)
15722 (add-hook 'post-command-hook 'org-read-date-display)
15723 (setq org-ans0 (read-string prompt default-input
15724 'org-read-date-history nil))
15725 ;; org-ans0: from prompt
15726 ;; org-ans1: from mouse click
15727 ;; org-ans2: from calendar motion
15728 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15729 (remove-hook 'post-command-hook 'org-read-date-display)
15730 (use-local-map old-map)
15731 (when org-read-date-overlay
15732 (delete-overlay org-read-date-overlay)
15733 (setq org-read-date-overlay nil)))))
15734 (bury-buffer "*Calendar*")))))
15736 (t ; Naked prompt only
15737 (unwind-protect
15738 (setq ans (read-string prompt default-input
15739 'org-read-date-history timestr))
15740 (when org-read-date-overlay
15741 (delete-overlay org-read-date-overlay)
15742 (setq org-read-date-overlay nil)))))
15744 (setq final (org-read-date-analyze ans org-def org-defdecode))
15746 (when org-read-date-analyze-forced-year
15747 (message "Year was forced into %s"
15748 (if org-read-date-force-compatible-dates
15749 "compatible range (1970-2037)"
15750 "range representable on this machine"))
15751 (ding))
15753 ;; One round trip to get rid of 34th of August and stuff like that....
15754 (setq final (decode-time (apply 'encode-time final)))
15756 (setq org-read-date-final-answer ans)
15758 (if to-time
15759 (apply 'encode-time final)
15760 (if (and (boundp 'org-time-was-given) org-time-was-given)
15761 (format "%04d-%02d-%02d %02d:%02d"
15762 (nth 5 final) (nth 4 final) (nth 3 final)
15763 (nth 2 final) (nth 1 final))
15764 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15766 (defvar org-def)
15767 (defvar org-defdecode)
15768 (defvar org-with-time)
15769 (defun org-read-date-display ()
15770 "Display the current date prompt interpretation in the minibuffer."
15771 (when org-read-date-display-live
15772 (when org-read-date-overlay
15773 (delete-overlay org-read-date-overlay))
15774 (when (minibufferp (current-buffer))
15775 (save-excursion
15776 (end-of-line 1)
15777 (while (not (equal (buffer-substring
15778 (max (point-min) (- (point) 4)) (point))
15779 " "))
15780 (insert " ")))
15781 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15782 " " (or org-ans1 org-ans2)))
15783 (org-end-time-was-given nil)
15784 (f (org-read-date-analyze ans org-def org-defdecode))
15785 (fmts (if org-dcst
15786 org-time-stamp-custom-formats
15787 org-time-stamp-formats))
15788 (fmt (if (or org-with-time
15789 (and (boundp 'org-time-was-given) org-time-was-given))
15790 (cdr fmts)
15791 (car fmts)))
15792 (txt (format-time-string fmt (apply 'encode-time f)))
15793 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15794 (txt (concat "=> " txt)))
15795 (when (and org-end-time-was-given
15796 (string-match org-plain-time-of-day-regexp txt))
15797 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15798 org-end-time-was-given
15799 (substring txt (match-end 0)))))
15800 (when org-read-date-analyze-futurep
15801 (setq txt (concat txt " (=>F)")))
15802 (setq org-read-date-overlay
15803 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15804 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15806 (defun org-read-date-analyze (ans org-def org-defdecode)
15807 "Analyze the combined answer of the date prompt."
15808 ;; FIXME: cleanup and comment
15809 (let ((nowdecode (decode-time (current-time)))
15810 delta deltan deltaw deltadef year month day
15811 hour minute second wday pm h2 m2 tl wday1
15812 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15813 (setq org-read-date-analyze-futurep nil
15814 org-read-date-analyze-forced-year nil)
15815 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15816 (setq ans "+0"))
15818 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15819 (setq ans (replace-match "" t t ans)
15820 deltan (car delta)
15821 deltaw (nth 1 delta)
15822 deltadef (nth 2 delta)))
15824 ;; Check if there is an iso week date in there. If yes, store the
15825 ;; info and postpone interpreting it until the rest of the parsing
15826 ;; is done.
15827 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15828 (setq iso-year (if (match-end 1)
15829 (org-small-year-to-year
15830 (string-to-number (match-string 1 ans))))
15831 iso-weekday (if (match-end 3)
15832 (string-to-number (match-string 3 ans)))
15833 iso-week (string-to-number (match-string 2 ans)))
15834 (setq ans (replace-match "" t t ans)))
15836 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15837 (when (string-match
15838 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15839 (setq year (if (match-end 2)
15840 (string-to-number (match-string 2 ans))
15841 (progn (setq kill-year t)
15842 (string-to-number (format-time-string "%Y"))))
15843 month (string-to-number (match-string 3 ans))
15844 day (string-to-number (match-string 4 ans)))
15845 (if (< year 100) (setq year (+ 2000 year)))
15846 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15847 t nil ans)))
15849 ;; Help matching dotted european dates
15850 (when (string-match
15851 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15852 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15853 (setq kill-year t)
15854 (string-to-number (format-time-string "%Y")))
15855 day (string-to-number (match-string 1 ans))
15856 month (string-to-number (match-string 2 ans))
15857 ans (replace-match (format "%04d-%02d-%02d" year month day)
15858 t nil ans)))
15860 ;; Help matching american dates, like 5/30 or 5/30/7
15861 (when (string-match
15862 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15863 (setq year (if (match-end 4)
15864 (string-to-number (match-string 4 ans))
15865 (progn (setq kill-year t)
15866 (string-to-number (format-time-string "%Y"))))
15867 month (string-to-number (match-string 1 ans))
15868 day (string-to-number (match-string 2 ans)))
15869 (if (< year 100) (setq year (+ 2000 year)))
15870 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15871 t nil ans)))
15872 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15873 ;; If there is a time with am/pm, and *no* time without it, we convert
15874 ;; so that matching will be successful.
15875 (loop for i from 1 to 2 do ; twice, for end time as well
15876 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15877 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15878 (setq hour (string-to-number (match-string 1 ans))
15879 minute (if (match-end 3)
15880 (string-to-number (match-string 3 ans))
15882 pm (equal ?p
15883 (string-to-char (downcase (match-string 4 ans)))))
15884 (if (and (= hour 12) (not pm))
15885 (setq hour 0)
15886 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15887 (setq ans (replace-match (format "%02d:%02d" hour minute)
15888 t t ans))))
15890 ;; Check if a time range is given as a duration
15891 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15892 (setq hour (string-to-number (match-string 1 ans))
15893 h2 (+ hour (string-to-number (match-string 3 ans)))
15894 minute (string-to-number (match-string 2 ans))
15895 m2 (+ minute (if (match-end 5) (string-to-number
15896 (match-string 5 ans))0)))
15897 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15898 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15899 t t ans)))
15901 ;; Check if there is a time range
15902 (when (boundp 'org-end-time-was-given)
15903 (setq org-time-was-given nil)
15904 (when (and (string-match org-plain-time-of-day-regexp ans)
15905 (match-end 8))
15906 (setq org-end-time-was-given (match-string 8 ans))
15907 (setq ans (concat (substring ans 0 (match-beginning 7))
15908 (substring ans (match-end 7))))))
15910 (setq tl (parse-time-string ans)
15911 day (or (nth 3 tl) (nth 3 org-defdecode))
15912 month (or (nth 4 tl)
15913 (if (and org-read-date-prefer-future
15914 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15915 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15916 (nth 4 org-defdecode)))
15917 year (or (and (not kill-year) (nth 5 tl))
15918 (if (and org-read-date-prefer-future
15919 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15920 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15921 (nth 5 org-defdecode)))
15922 hour (or (nth 2 tl) (nth 2 org-defdecode))
15923 minute (or (nth 1 tl) (nth 1 org-defdecode))
15924 second (or (nth 0 tl) 0)
15925 wday (nth 6 tl))
15927 (when (and (eq org-read-date-prefer-future 'time)
15928 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15929 (equal day (nth 3 nowdecode))
15930 (equal month (nth 4 nowdecode))
15931 (equal year (nth 5 nowdecode))
15932 (nth 2 tl)
15933 (or (< (nth 2 tl) (nth 2 nowdecode))
15934 (and (= (nth 2 tl) (nth 2 nowdecode))
15935 (nth 1 tl)
15936 (< (nth 1 tl) (nth 1 nowdecode)))))
15937 (setq day (1+ day)
15938 futurep t))
15940 ;; Special date definitions below
15941 (cond
15942 (iso-week
15943 ;; There was an iso week
15944 (require 'cal-iso)
15945 (setq futurep nil)
15946 (setq year (or iso-year year)
15947 day (or iso-weekday wday 1)
15948 wday nil ; to make sure that the trigger below does not match
15949 iso-date (calendar-gregorian-from-absolute
15950 (calendar-absolute-from-iso
15951 (list iso-week day year))))
15952 ; FIXME: Should we also push ISO weeks into the future?
15953 ; (when (and org-read-date-prefer-future
15954 ; (not iso-year)
15955 ; (< (calendar-absolute-from-gregorian iso-date)
15956 ; (time-to-days (current-time))))
15957 ; (setq year (1+ year)
15958 ; iso-date (calendar-gregorian-from-absolute
15959 ; (calendar-absolute-from-iso
15960 ; (list iso-week day year)))))
15961 (setq month (car iso-date)
15962 year (nth 2 iso-date)
15963 day (nth 1 iso-date)))
15964 (deltan
15965 (setq futurep nil)
15966 (unless deltadef
15967 (let ((now (decode-time (current-time))))
15968 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15969 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15970 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15971 ((equal deltaw "m") (setq month (+ month deltan)))
15972 ((equal deltaw "y") (setq year (+ year deltan)))))
15973 ((and wday (not (nth 3 tl)))
15974 ;; Weekday was given, but no day, so pick that day in the week
15975 ;; on or after the derived date.
15976 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15977 (unless (equal wday wday1)
15978 (setq day (+ day (% (- wday wday1 -7) 7))))))
15979 (if (and (boundp 'org-time-was-given)
15980 (nth 2 tl))
15981 (setq org-time-was-given t))
15982 (if (< year 100) (setq year (+ 2000 year)))
15983 ;; Check of the date is representable
15984 (if org-read-date-force-compatible-dates
15985 (progn
15986 (if (< year 1970)
15987 (setq year 1970 org-read-date-analyze-forced-year t))
15988 (if (> year 2037)
15989 (setq year 2037 org-read-date-analyze-forced-year t)))
15990 (condition-case nil
15991 (ignore (encode-time second minute hour day month year))
15992 (error
15993 (setq year (nth 5 org-defdecode))
15994 (setq org-read-date-analyze-forced-year t))))
15995 (setq org-read-date-analyze-futurep futurep)
15996 (list second minute hour day month year)))
15998 (defvar parse-time-weekdays)
15999 (defun org-read-date-get-relative (s today default)
16000 "Check string S for special relative date string.
16001 TODAY and DEFAULT are internal times, for today and for a default.
16002 Return shift list (N what def-flag)
16003 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16004 N is the number of WHATs to shift.
16005 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16006 the DEFAULT date rather than TODAY."
16007 (require 'parse-time)
16008 (when (and
16009 (string-match
16010 (concat
16011 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16012 "\\([0-9]+\\)?"
16013 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16014 "\\([ \t]\\|$\\)") s)
16015 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16016 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16017 (string-to-char (substring (match-string 1 s) -1))
16018 ?+))
16019 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16020 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16021 (what (if (match-end 3) (match-string 3 s) "d"))
16022 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16023 (date (if rel default today))
16024 (wday (nth 6 (decode-time date)))
16025 delta)
16026 (if wday1
16027 (progn
16028 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16029 (if (= dir ?-) (setq delta (- delta 7)))
16030 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16031 (list delta "d" rel))
16032 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16034 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16035 "Turn a user-specified date into the internal representation.
16036 The internal representation needed by the calendar is (month day year).
16037 This is a wrapper to handle the brain-dead convention in calendar that
16038 user function argument order change dependent on argument order."
16039 (if (boundp 'calendar-date-style)
16040 (cond
16041 ((eq calendar-date-style 'american)
16042 (list arg1 arg2 arg3))
16043 ((eq calendar-date-style 'european)
16044 (list arg2 arg1 arg3))
16045 ((eq calendar-date-style 'iso)
16046 (list arg2 arg3 arg1)))
16047 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16048 (if (org-bound-and-true-p european-calendar-style)
16049 (list arg2 arg1 arg3)
16050 (list arg1 arg2 arg3)))))
16052 (defun org-eval-in-calendar (form &optional keepdate)
16053 "Eval FORM in the calendar window and return to current window.
16054 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16055 otherwise stick to the current value of `org-ans2'."
16056 (let ((sf (selected-frame))
16057 (sw (selected-window)))
16058 (select-window (get-buffer-window "*Calendar*" t))
16059 (eval form)
16060 (when (and (not keepdate) (calendar-cursor-to-date))
16061 (let* ((date (calendar-cursor-to-date))
16062 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16063 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16064 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16065 (select-window sw)
16066 (org-select-frame-set-input-focus sf)))
16068 (defun org-calendar-select ()
16069 "Return to `org-read-date' with the date currently selected.
16070 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16071 (interactive)
16072 (when (calendar-cursor-to-date)
16073 (let* ((date (calendar-cursor-to-date))
16074 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16075 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16076 (if (active-minibuffer-window) (exit-minibuffer))))
16078 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16079 "Insert a date stamp for the date given by the internal TIME.
16080 WITH-HM means use the stamp format that includes the time of the day.
16081 INACTIVE means use square brackets instead of angular ones, so that the
16082 stamp will not contribute to the agenda.
16083 PRE and POST are optional strings to be inserted before and after the
16084 stamp.
16085 The command returns the inserted time stamp."
16086 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16087 stamp)
16088 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16089 (insert-before-markers (or pre ""))
16090 (when (listp extra)
16091 (setq extra (car extra))
16092 (if (and (stringp extra)
16093 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16094 (setq extra (format "-%02d:%02d"
16095 (string-to-number (match-string 1 extra))
16096 (string-to-number (match-string 2 extra))))
16097 (setq extra nil)))
16098 (when extra
16099 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16100 (insert-before-markers (setq stamp (format-time-string fmt time)))
16101 (insert-before-markers (or post ""))
16102 (setq org-last-inserted-timestamp stamp)))
16104 (defun org-toggle-time-stamp-overlays ()
16105 "Toggle the use of custom time stamp formats."
16106 (interactive)
16107 (setq org-display-custom-times (not org-display-custom-times))
16108 (unless org-display-custom-times
16109 (let ((p (point-min)) (bmp (buffer-modified-p)))
16110 (while (setq p (next-single-property-change p 'display))
16111 (if (and (get-text-property p 'display)
16112 (eq (get-text-property p 'face) 'org-date))
16113 (remove-text-properties
16114 p (setq p (next-single-property-change p 'display))
16115 '(display t))))
16116 (set-buffer-modified-p bmp)))
16117 (if (featurep 'xemacs)
16118 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16119 (org-restart-font-lock)
16120 (setq org-table-may-need-update t)
16121 (if org-display-custom-times
16122 (message "Time stamps are overlaid with custom format")
16123 (message "Time stamp overlays removed")))
16125 (defun org-display-custom-time (beg end)
16126 "Overlay modified time stamp format over timestamp between BEG and END."
16127 (let* ((ts (buffer-substring beg end))
16128 t1 w1 with-hm tf time str w2 (off 0))
16129 (save-match-data
16130 (setq t1 (org-parse-time-string ts t))
16131 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16132 (setq off (- (match-end 0) (match-beginning 0)))))
16133 (setq end (- end off))
16134 (setq w1 (- end beg)
16135 with-hm (and (nth 1 t1) (nth 2 t1))
16136 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16137 time (org-fix-decoded-time t1)
16138 str (org-add-props
16139 (format-time-string
16140 (substring tf 1 -1) (apply 'encode-time time))
16141 nil 'mouse-face 'highlight)
16142 w2 (length str))
16143 (if (not (= w2 w1))
16144 (add-text-properties (1+ beg) (+ 2 beg)
16145 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16146 (if (featurep 'xemacs)
16147 (progn
16148 (put-text-property beg end 'invisible t)
16149 (put-text-property beg end 'end-glyph (make-glyph str)))
16150 (put-text-property beg end 'display str))))
16152 (defun org-translate-time (string)
16153 "Translate all timestamps in STRING to custom format.
16154 But do this only if the variable `org-display-custom-times' is set."
16155 (when org-display-custom-times
16156 (save-match-data
16157 (let* ((start 0)
16158 (re org-ts-regexp-both)
16159 t1 with-hm inactive tf time str beg end)
16160 (while (setq start (string-match re string start))
16161 (setq beg (match-beginning 0)
16162 end (match-end 0)
16163 t1 (save-match-data
16164 (org-parse-time-string (substring string beg end) t))
16165 with-hm (and (nth 1 t1) (nth 2 t1))
16166 inactive (equal (substring string beg (1+ beg)) "[")
16167 tf (funcall (if with-hm 'cdr 'car)
16168 org-time-stamp-custom-formats)
16169 time (org-fix-decoded-time t1)
16170 str (format-time-string
16171 (concat
16172 (if inactive "[" "<") (substring tf 1 -1)
16173 (if inactive "]" ">"))
16174 (apply 'encode-time time))
16175 string (replace-match str t t string)
16176 start (+ start (length str)))))))
16177 string)
16179 (defun org-fix-decoded-time (time)
16180 "Set 0 instead of nil for the first 6 elements of time.
16181 Don't touch the rest."
16182 (let ((n 0))
16183 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16185 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16187 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16188 "Difference between TIMESTAMP-STRING and now in days.
16189 If SECONDS is non-nil, return the difference in seconds."
16190 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16191 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16192 (funcall fdiff (current-time)))))
16194 (defun org-deadline-close (timestamp-string &optional ndays)
16195 "Is the time in TIMESTAMP-STRING close to the current date?"
16196 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16197 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16198 (not (org-entry-is-done-p))))
16200 (defun org-get-wdays (ts)
16201 "Get the deadline lead time appropriate for timestring TS."
16202 (cond
16203 ((<= org-deadline-warning-days 0)
16204 ;; 0 or negative, enforce this value no matter what
16205 (- org-deadline-warning-days))
16206 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16207 ;; lead time is specified.
16208 (floor (* (string-to-number (match-string 1 ts))
16209 (cdr (assoc (match-string 2 ts)
16210 '(("d" . 1) ("w" . 7)
16211 ("m" . 30.4) ("y" . 365.25)))))))
16212 ;; go for the default.
16213 (t org-deadline-warning-days)))
16215 (defun org-calendar-select-mouse (ev)
16216 "Return to `org-read-date' with the date currently selected.
16217 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16218 (interactive "e")
16219 (mouse-set-point ev)
16220 (when (calendar-cursor-to-date)
16221 (let* ((date (calendar-cursor-to-date))
16222 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16223 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16224 (if (active-minibuffer-window) (exit-minibuffer))))
16226 (defun org-check-deadlines (ndays)
16227 "Check if there are any deadlines due or past due.
16228 A deadline is considered due if it happens within `org-deadline-warning-days'
16229 days from today's date. If the deadline appears in an entry marked DONE,
16230 it is not shown. The prefix arg NDAYS can be used to test that many
16231 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16232 (interactive "P")
16233 (let* ((org-warn-days
16234 (cond
16235 ((equal ndays '(4)) 100000)
16236 (ndays (prefix-numeric-value ndays))
16237 (t (abs org-deadline-warning-days))))
16238 (case-fold-search nil)
16239 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16240 (callback
16241 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16243 (message "%d deadlines past-due or due within %d days"
16244 (org-occur regexp nil callback)
16245 org-warn-days)))
16247 (defsubst org-re-timestamp (type)
16248 "Return a regexp for timestamp TYPE.
16249 Allowed values for TYPE are:
16251 all: all timestamps
16252 active: only active timestamps (<...>)
16253 inactive: only inactive timestamps ([...])
16254 scheduled: only scheduled timestamps
16255 deadline: only deadline timestamps
16257 When TYPE is nil, fall back on returning a regexp that matches
16258 both scheduled and deadline timestamps."
16259 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16260 ((eq type 'active) org-ts-regexp)
16261 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16262 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16263 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16264 ((eq type 'scheduled-or-deadline)
16265 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16267 (defun org-check-before-date (date)
16268 "Check if there are deadlines or scheduled entries before DATE."
16269 (interactive (list (org-read-date)))
16270 (let ((case-fold-search nil)
16271 (regexp (org-re-timestamp org-ts-type))
16272 (callback
16273 (lambda () (time-less-p
16274 (org-time-string-to-time (match-string 1))
16275 (org-time-string-to-time date)))))
16276 (message "%d entries before %s"
16277 (org-occur regexp nil callback) date)))
16279 (defun org-check-after-date (date)
16280 "Check if there are deadlines or scheduled entries after DATE."
16281 (interactive (list (org-read-date)))
16282 (let ((case-fold-search nil)
16283 (regexp (org-re-timestamp org-ts-type))
16284 (callback
16285 (lambda () (not
16286 (time-less-p
16287 (org-time-string-to-time (match-string 1))
16288 (org-time-string-to-time date))))))
16289 (message "%d entries after %s"
16290 (org-occur regexp nil callback) date)))
16292 (defun org-check-dates-range (start-date end-date)
16293 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16294 (interactive (list (org-read-date nil nil nil "Range starts")
16295 (org-read-date nil nil nil "Range end")))
16296 (let ((case-fold-search nil)
16297 (regexp (org-re-timestamp org-ts-type))
16298 (callback
16299 (lambda ()
16300 (let ((match (match-string 1)))
16301 (and
16302 (not (time-less-p
16303 (org-time-string-to-time match)
16304 (org-time-string-to-time start-date)))
16305 (time-less-p
16306 (org-time-string-to-time match)
16307 (org-time-string-to-time end-date)))))))
16308 (message "%d entries between %s and %s"
16309 (org-occur regexp nil callback) start-date end-date)))
16311 (defun org-evaluate-time-range (&optional to-buffer)
16312 "Evaluate a time range by computing the difference between start and end.
16313 Normally the result is just printed in the echo area, but with prefix arg
16314 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16315 If the time range is actually in a table, the result is inserted into the
16316 next column.
16317 For time difference computation, a year is assumed to be exactly 365
16318 days in order to avoid rounding problems."
16319 (interactive "P")
16321 (org-clock-update-time-maybe)
16322 (save-excursion
16323 (unless (org-at-date-range-p t)
16324 (goto-char (point-at-bol))
16325 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16326 (if (not (org-at-date-range-p t))
16327 (error "Not at a time-stamp range, and none found in current line")))
16328 (let* ((ts1 (match-string 1))
16329 (ts2 (match-string 2))
16330 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16331 (match-end (match-end 0))
16332 (time1 (org-time-string-to-time ts1))
16333 (time2 (org-time-string-to-time ts2))
16334 (t1 (org-float-time time1))
16335 (t2 (org-float-time time2))
16336 (diff (abs (- t2 t1)))
16337 (negative (< (- t2 t1) 0))
16338 ;; (ys (floor (* 365 24 60 60)))
16339 (ds (* 24 60 60))
16340 (hs (* 60 60))
16341 (fy "%dy %dd %02d:%02d")
16342 (fy1 "%dy %dd")
16343 (fd "%dd %02d:%02d")
16344 (fd1 "%dd")
16345 (fh "%02d:%02d")
16346 y d h m align)
16347 (if havetime
16348 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16350 d (floor (/ diff ds)) diff (mod diff ds)
16351 h (floor (/ diff hs)) diff (mod diff hs)
16352 m (floor (/ diff 60)))
16353 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16355 d (floor (+ (/ diff ds) 0.5))
16356 h 0 m 0))
16357 (if (not to-buffer)
16358 (message "%s" (org-make-tdiff-string y d h m))
16359 (if (org-at-table-p)
16360 (progn
16361 (goto-char match-end)
16362 (setq align t)
16363 (and (looking-at " *|") (goto-char (match-end 0))))
16364 (goto-char match-end))
16365 (if (looking-at
16366 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16367 (replace-match ""))
16368 (if negative (insert " -"))
16369 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16370 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16371 (insert " " (format fh h m))))
16372 (if align (org-table-align))
16373 (message "Time difference inserted")))))
16375 (defun org-make-tdiff-string (y d h m)
16376 (let ((fmt "")
16377 (l nil))
16378 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16379 l (push y l)))
16380 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16381 l (push d l)))
16382 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16383 l (push h l)))
16384 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16385 l (push m l)))
16386 (apply 'format fmt (nreverse l))))
16388 (defun org-time-string-to-time (s &optional buffer pos)
16389 "Convert a timestamp string into internal time."
16390 (condition-case errdata
16391 (apply 'encode-time (org-parse-time-string s))
16392 (error (error "Bad timestamp `%s'%s\nError was: %s"
16393 s (if (not (and buffer pos))
16395 (format " at %d in buffer `%s'" pos buffer))
16396 (cdr errdata)))))
16398 (defun org-time-string-to-seconds (s)
16399 "Convert a timestamp string to a number of seconds."
16400 (org-float-time (org-time-string-to-time s)))
16402 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16403 "Convert a time stamp to an absolute day number.
16404 If there is a specifier for a cyclic time stamp, get the closest date to
16405 DAYNR.
16406 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16407 The variable date is bound by the calendar when this is called."
16408 (cond
16409 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16410 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16411 daynr
16412 (+ daynr 1000)))
16413 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16414 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16415 (time-to-days (current-time))) (match-string 0 s)
16416 prefer show-all))
16417 (t (time-to-days
16418 (condition-case errdata
16419 (apply 'encode-time (org-parse-time-string s))
16420 (error (error "Bad timestamp `%s'%s\nError was: %s"
16421 s (if (not (and buffer pos))
16423 (format " at %d in buffer `%s'" pos buffer))
16424 (cdr errdata))))))))
16426 (defun org-days-to-iso-week (days)
16427 "Return the iso week number."
16428 (require 'cal-iso)
16429 (car (calendar-iso-from-absolute days)))
16431 (defun org-small-year-to-year (year)
16432 "Convert 2-digit years into 4-digit years.
16433 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16434 The year 2000 cannot be abbreviated. Any year larger than 99
16435 is returned unchanged."
16436 (if (< year 38)
16437 (setq year (+ 2000 year))
16438 (if (< year 100)
16439 (setq year (+ 1900 year))))
16440 year)
16442 (defun org-time-from-absolute (d)
16443 "Return the time corresponding to date D.
16444 D may be an absolute day number, or a calendar-type list (month day year)."
16445 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16446 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16448 (defun org-calendar-holiday ()
16449 "List of holidays, for Diary display in Org-mode."
16450 (require 'holidays)
16451 (let ((hl (funcall
16452 (if (fboundp 'calendar-check-holidays)
16453 'calendar-check-holidays 'check-calendar-holidays) date)))
16454 (if hl (mapconcat 'identity hl "; "))))
16456 (defun org-diary-sexp-entry (sexp entry date)
16457 "Process a SEXP diary ENTRY for DATE."
16458 (require 'diary-lib)
16459 (let ((result (if calendar-debug-sexp
16460 (let ((stack-trace-on-error t))
16461 (eval (car (read-from-string sexp))))
16462 (condition-case nil
16463 (eval (car (read-from-string sexp)))
16464 (error
16465 (beep)
16466 (message "Bad sexp at line %d in %s: %s"
16467 (org-current-line)
16468 (buffer-file-name) sexp)
16469 (sleep-for 2))))))
16470 (cond ((stringp result) (split-string result "; "))
16471 ((and (consp result)
16472 (not (consp (cdr result)))
16473 (stringp (cdr result))) (cdr result))
16474 ((and (consp result)
16475 (stringp (car result))) result)
16476 (result entry))))
16478 (defun org-diary-to-ical-string (frombuf)
16479 "Get iCalendar entries from diary entries in buffer FROMBUF.
16480 This uses the icalendar.el library."
16481 (let* ((tmpdir (if (featurep 'xemacs)
16482 (temp-directory)
16483 temporary-file-directory))
16484 (tmpfile (make-temp-name
16485 (expand-file-name "orgics" tmpdir)))
16486 buf rtn b e)
16487 (with-current-buffer frombuf
16488 (icalendar-export-region (point-min) (point-max) tmpfile)
16489 (setq buf (find-buffer-visiting tmpfile))
16490 (set-buffer buf)
16491 (goto-char (point-min))
16492 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16493 (setq b (match-beginning 0)))
16494 (goto-char (point-max))
16495 (if (re-search-backward "^END:VEVENT" nil t)
16496 (setq e (match-end 0)))
16497 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16498 (kill-buffer buf)
16499 (delete-file tmpfile)
16500 rtn))
16502 (defun org-closest-date (start current change prefer show-all)
16503 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16504 When PREFER is `past', return a date that is either CURRENT or past.
16505 When PREFER is `future', return a date that is either CURRENT or future.
16506 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16507 ;; Make the proper lists from the dates
16508 (catch 'exit
16509 (let ((a1 '(("h" . hour)
16510 ("d" . day)
16511 ("w" . week)
16512 ("m" . month)
16513 ("y" . year)))
16514 (shour (nth 2 (org-parse-time-string start)))
16515 dn dw sday cday n1 n2 n0
16516 d m y y1 y2 date1 date2 nmonths nm ny m2)
16518 (setq start (org-date-to-gregorian start)
16519 current (org-date-to-gregorian
16520 (if show-all
16521 current
16522 (time-to-days (current-time))))
16523 sday (calendar-absolute-from-gregorian start)
16524 cday (calendar-absolute-from-gregorian current))
16526 (if (<= cday sday) (throw 'exit sday))
16528 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16529 (setq dn (string-to-number (match-string 1 change))
16530 dw (cdr (assoc (match-string 2 change) a1)))
16531 (error "Invalid change specifier: %s" change))
16532 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16533 (cond
16534 ((eq dw 'hour)
16535 (let ((missing-hours
16536 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16537 dn)))
16538 (setq n1 (if (zerop missing-hours) cday
16539 (- cday (1+ (floor (/ missing-hours 24)))))
16540 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16541 ((eq dw 'day)
16542 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16543 n2 (+ n1 dn)))
16544 ((eq dw 'year)
16545 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16546 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16547 (setq date1 (list m d y1)
16548 n1 (calendar-absolute-from-gregorian date1)
16549 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16550 n2 (calendar-absolute-from-gregorian date2)))
16551 ((eq dw 'month)
16552 ;; approx number of month between the two dates
16553 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16554 ;; How often does dn fit in there?
16555 (setq d (nth 1 start) m (car start) y (nth 2 start)
16556 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16557 m (+ m nm)
16558 ny (floor (/ m 12))
16559 y (+ y ny)
16560 m (- m (* ny 12)))
16561 (while (> m 12) (setq m (- m 12) y (1+ y)))
16562 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16563 (setq m2 (+ m dn) y2 y)
16564 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16565 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16566 (while (<= n2 cday)
16567 (setq n1 n2 m m2 y y2)
16568 (setq m2 (+ m dn) y2 y)
16569 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16570 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16571 ;; Make sure n1 is the earlier date
16572 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16573 (if show-all
16574 (cond
16575 ((eq prefer 'past) (if (= cday n2) n2 n1))
16576 ((eq prefer 'future) (if (= cday n1) n1 n2))
16577 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16578 (cond
16579 ((eq prefer 'past) (if (= cday n2) n2 n1))
16580 ((eq prefer 'future) (if (= cday n1) n1 n2))
16581 (t (if (= cday n1) n1 n2)))))))
16583 (defun org-date-to-gregorian (date)
16584 "Turn any specification of DATE into a Gregorian date for the calendar."
16585 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16586 ((and (listp date) (= (length date) 3)) date)
16587 ((stringp date)
16588 (setq date (org-parse-time-string date))
16589 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16590 ((listp date)
16591 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16593 (defun org-parse-time-string (s &optional nodefault)
16594 "Parse the standard Org-mode time string.
16595 This should be a lot faster than the normal `parse-time-string'.
16596 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16597 hour and minute fields will be nil if not given."
16598 (cond ((string-match org-ts-regexp0 s)
16599 (list 0
16600 (if (or (match-beginning 8) (not nodefault))
16601 (string-to-number (or (match-string 8 s) "0")))
16602 (if (or (match-beginning 7) (not nodefault))
16603 (string-to-number (or (match-string 7 s) "0")))
16604 (string-to-number (match-string 4 s))
16605 (string-to-number (match-string 3 s))
16606 (string-to-number (match-string 2 s))
16607 nil nil nil))
16608 ((string-match "^<[^>]+>$" s)
16609 (decode-time (seconds-to-time (org-matcher-time s))))
16610 (t (error "Not a standard Org-mode time string: %s" s))))
16612 (defun org-timestamp-up (&optional arg)
16613 "Increase the date item at the cursor by one.
16614 If the cursor is on the year, change the year. If it is on the month,
16615 the day or the time, change that.
16616 With prefix ARG, change by that many units."
16617 (interactive "p")
16618 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16620 (defun org-timestamp-down (&optional arg)
16621 "Decrease the date item at the cursor by one.
16622 If the cursor is on the year, change the year. If it is on the month,
16623 the day or the time, change that.
16624 With prefix ARG, change by that many units."
16625 (interactive "p")
16626 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16628 (defun org-timestamp-up-day (&optional arg)
16629 "Increase the date in the time stamp by one day.
16630 With prefix ARG, change that many days."
16631 (interactive "p")
16632 (if (and (not (org-at-timestamp-p t))
16633 (org-at-heading-p))
16634 (org-todo 'up)
16635 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16637 (defun org-timestamp-down-day (&optional arg)
16638 "Decrease the date in the time stamp by one day.
16639 With prefix ARG, change that many days."
16640 (interactive "p")
16641 (if (and (not (org-at-timestamp-p t))
16642 (org-at-heading-p))
16643 (org-todo 'down)
16644 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16646 (defun org-at-timestamp-p (&optional inactive-ok)
16647 "Determine if the cursor is in or at a timestamp."
16648 (interactive)
16649 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16650 (pos (point))
16651 (ans (or (looking-at tsr)
16652 (save-excursion
16653 (skip-chars-backward "^[<\n\r\t")
16654 (if (> (point) (point-min)) (backward-char 1))
16655 (and (looking-at tsr)
16656 (> (- (match-end 0) pos) -1))))))
16657 (and ans
16658 (boundp 'org-ts-what)
16659 (setq org-ts-what
16660 (cond
16661 ((= pos (match-beginning 0)) 'bracket)
16662 ;; Point is considered to be "on the bracket" whether
16663 ;; it's really on it or right after it.
16664 ((= pos (1- (match-end 0))) 'bracket)
16665 ((= pos (match-end 0)) 'after)
16666 ((org-pos-in-match-range pos 2) 'year)
16667 ((org-pos-in-match-range pos 3) 'month)
16668 ((org-pos-in-match-range pos 7) 'hour)
16669 ((org-pos-in-match-range pos 8) 'minute)
16670 ((or (org-pos-in-match-range pos 4)
16671 (org-pos-in-match-range pos 5)) 'day)
16672 ((and (> pos (or (match-end 8) (match-end 5)))
16673 (< pos (match-end 0)))
16674 (- pos (or (match-end 8) (match-end 5))))
16675 (t 'day))))
16676 ans))
16678 (defun org-toggle-timestamp-type ()
16679 "Toggle the type (<active> or [inactive]) of a time stamp."
16680 (interactive)
16681 (when (org-at-timestamp-p t)
16682 (let ((beg (match-beginning 0)) (end (match-end 0))
16683 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16684 (save-excursion
16685 (goto-char beg)
16686 (while (re-search-forward "[][<>]" end t)
16687 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16688 t t)))
16689 (message "Timestamp is now %sactive"
16690 (if (equal (char-after beg) ?<) "" "in")))))
16692 (defvar org-clock-history) ; defined in org-clock.el
16693 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16694 (defun org-timestamp-change (n &optional what updown)
16695 "Change the date in the time stamp at point.
16696 The date will be changed by N times WHAT. WHAT can be `day', `month',
16697 `year', `minute', `second'. If WHAT is not given, the cursor position
16698 in the timestamp determines what will be changed."
16699 (let ((origin (point)) origin-cat
16700 with-hm inactive
16701 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16702 org-ts-what
16703 extra rem
16704 ts time time0 fixnext clrgx)
16705 (if (not (org-at-timestamp-p t))
16706 (error "Not at a timestamp"))
16707 (if (and (not what) (eq org-ts-what 'bracket))
16708 (org-toggle-timestamp-type)
16709 ;; Point isn't on brackets. Remember the part of the time-stamp
16710 ;; the point was in. Indeed, size of time-stamps may change,
16711 ;; but point must be kept in the same category nonetheless.
16712 (setq origin-cat org-ts-what)
16713 (if (and (not what) (not (eq org-ts-what 'day))
16714 org-display-custom-times
16715 (get-text-property (point) 'display)
16716 (not (get-text-property (1- (point)) 'display)))
16717 (setq org-ts-what 'day))
16718 (setq org-ts-what (or what org-ts-what)
16719 inactive (= (char-after (match-beginning 0)) ?\[)
16720 ts (match-string 0))
16721 (replace-match "")
16722 (if (string-match
16723 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16725 (setq extra (match-string 1 ts)))
16726 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16727 (setq with-hm t))
16728 (setq time0 (org-parse-time-string ts))
16729 (when (and updown
16730 (eq org-ts-what 'minute)
16731 (not current-prefix-arg))
16732 ;; This looks like s-up and s-down. Change by one rounding step.
16733 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16734 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16735 (setcar (cdr time0) (+ (nth 1 time0)
16736 (if (> n 0) (- rem) (- dm rem))))))
16737 (setq time
16738 (encode-time (or (car time0) 0)
16739 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16740 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16741 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16742 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16743 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16744 (nthcdr 6 time0)))
16745 (when (and (member org-ts-what '(hour minute))
16746 extra
16747 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16748 (setq extra (org-modify-ts-extra
16749 extra
16750 (if (eq org-ts-what 'hour) 2 5)
16751 n dm)))
16752 (when (integerp org-ts-what)
16753 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16754 (if (eq what 'calendar)
16755 (let ((cal-date (org-get-date-from-calendar)))
16756 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16757 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16758 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16759 (setcar time0 (or (car time0) 0))
16760 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16761 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16762 (setq time (apply 'encode-time time0))))
16763 ;; Insert the new time-stamp, and ensure point stays in the same
16764 ;; category as before (i.e. not after the last position in that
16765 ;; category).
16766 (let ((pos (point)))
16767 ;; Stay before inserted string. `save-excursion' is of no use.
16768 (setq org-last-changed-timestamp
16769 (org-insert-time-stamp time with-hm inactive nil nil extra))
16770 (goto-char pos))
16771 (save-match-data
16772 (looking-at org-ts-regexp3)
16773 (goto-char (cond
16774 ;; `day' category ends before `hour' if any, or at
16775 ;; the end of the day name.
16776 ((eq origin-cat 'day)
16777 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16778 ((eq origin-cat 'hour) (min (match-end 7) origin))
16779 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16780 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16781 ;; `year' and `month' have both fixed size: point
16782 ;; couldn't have moved into another part.
16783 (t origin))))
16784 ;; Update clock if on a CLOCK line.
16785 (org-clock-update-time-maybe)
16786 ;; Maybe adjust the closest clock in `org-clock-history'
16787 (when org-clock-adjust-closest
16788 (if (not (and (org-at-clock-log-p)
16789 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16790 org-clock-history))))))
16791 (message "No clock to adjust")
16792 (cond ((save-excursion ; fix previous clock?
16793 (re-search-backward org-ts-regexp0 nil t)
16794 (org-looking-back (concat org-clock-string " \\[")))
16795 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16796 ((save-excursion ; fix next clock?
16797 (re-search-backward org-ts-regexp0 nil t)
16798 (looking-at (concat org-ts-regexp0 "\\] =>")))
16799 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16800 (save-window-excursion
16801 ;; Find closest clock to point, adjust the previous/next one in history
16802 (let* ((p (save-excursion (org-back-to-heading t)))
16803 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16804 (clfixnth
16805 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16806 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16807 (if (not clfixpos)
16808 (message "No clock to adjust")
16809 (save-excursion
16810 (org-goto-marker-or-bmk clfixpos)
16811 (org-show-subtree)
16812 (when (re-search-forward clrgx nil t)
16813 (goto-char (match-beginning 1))
16814 (let (org-clock-adjust-closest)
16815 (org-timestamp-change n org-ts-what updown))
16816 (message "Clock adjusted in %s for heading: %s"
16817 (file-name-nondirectory (buffer-file-name))
16818 (org-get-heading t t)))))))))
16819 ;; Try to recenter the calendar window, if any.
16820 (if (and org-calendar-follow-timestamp-change
16821 (get-buffer-window "*Calendar*" t)
16822 (memq org-ts-what '(day month year)))
16823 (org-recenter-calendar (time-to-days time))))))
16825 (defun org-modify-ts-extra (s pos n dm)
16826 "Change the different parts of the lead-time and repeat fields in timestamp."
16827 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16828 ng h m new rem)
16829 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16830 (cond
16831 ((or (org-pos-in-match-range pos 2)
16832 (org-pos-in-match-range pos 3))
16833 (setq m (string-to-number (match-string 3 s))
16834 h (string-to-number (match-string 2 s)))
16835 (if (org-pos-in-match-range pos 2)
16836 (setq h (+ h n))
16837 (setq n (* dm (org-no-warnings (signum n))))
16838 (when (not (= 0 (setq rem (% m dm))))
16839 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16840 (setq m (+ m n)))
16841 (if (< m 0) (setq m (+ m 60) h (1- h)))
16842 (if (> m 59) (setq m (- m 60) h (1+ h)))
16843 (setq h (min 24 (max 0 h)))
16844 (setq ng 1 new (format "-%02d:%02d" h m)))
16845 ((org-pos-in-match-range pos 6)
16846 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16847 ((org-pos-in-match-range pos 5)
16848 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16850 ((org-pos-in-match-range pos 9)
16851 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16852 ((org-pos-in-match-range pos 8)
16853 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16855 (when ng
16856 (setq s (concat
16857 (substring s 0 (match-beginning ng))
16859 (substring s (match-end ng))))))
16862 (defun org-recenter-calendar (date)
16863 "If the calendar is visible, recenter it to DATE."
16864 (let ((cwin (get-buffer-window "*Calendar*" t)))
16865 (when cwin
16866 (let ((calendar-move-hook nil))
16867 (with-selected-window cwin
16868 (calendar-goto-date (if (listp date) date
16869 (calendar-gregorian-from-absolute date))))))))
16871 (defun org-goto-calendar (&optional arg)
16872 "Go to the Emacs calendar at the current date.
16873 If there is a time stamp in the current line, go to that date.
16874 A prefix ARG can be used to force the current date."
16875 (interactive "P")
16876 (let ((tsr org-ts-regexp) diff
16877 (calendar-move-hook nil)
16878 (calendar-view-holidays-initially-flag nil)
16879 (calendar-view-diary-initially-flag nil))
16880 (if (or (org-at-timestamp-p)
16881 (save-excursion
16882 (beginning-of-line 1)
16883 (looking-at (concat ".*" tsr))))
16884 (let ((d1 (time-to-days (current-time)))
16885 (d2 (time-to-days
16886 (org-time-string-to-time (match-string 1)))))
16887 (setq diff (- d2 d1))))
16888 (calendar)
16889 (calendar-goto-today)
16890 (if (and diff (not arg)) (calendar-forward-day diff))))
16892 (defun org-get-date-from-calendar ()
16893 "Return a list (month day year) of date at point in calendar."
16894 (with-current-buffer "*Calendar*"
16895 (save-match-data
16896 (calendar-cursor-to-date))))
16898 (defun org-date-from-calendar ()
16899 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16900 If there is already a time stamp at the cursor position, update it."
16901 (interactive)
16902 (if (org-at-timestamp-p t)
16903 (org-timestamp-change 0 'calendar)
16904 (let ((cal-date (org-get-date-from-calendar)))
16905 (org-insert-time-stamp
16906 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16908 (defcustom org-effort-durations
16909 `(("h" . 60)
16910 ("d" . ,(* 60 8))
16911 ("w" . ,(* 60 8 5))
16912 ("m" . ,(* 60 8 5 4))
16913 ("y" . ,(* 60 8 5 40)))
16914 "Conversion factor to minutes for an effort modifier.
16916 Each entry has the form (MODIFIER . MINUTES).
16918 In an effort string, a number followed by MODIFIER is multiplied
16919 by the specified number of MINUTES to obtain an effort in
16920 minutes.
16922 For example, if the value of this variable is ((\"hours\" . 60)), then an
16923 effort string \"2hours\" is equivalent to 120 minutes."
16924 :group 'org-agenda
16925 :version "24.1"
16926 :type '(alist :key-type (string :tag "Modifier")
16927 :value-type (number :tag "Minutes")))
16929 (defun org-minutes-to-clocksum-string (m)
16930 "Format number of minutes as a clocksum string.
16931 The format is determined by `org-time-clocksum-format',
16932 `org-time-clocksum-use-fractional' and
16933 `org-time-clocksum-fractional-format' and
16934 `org-time-clocksum-use-effort-durations'."
16935 (let ((clocksum "") h d w mo y fmt n)
16936 (setq h (if org-time-clocksum-use-effort-durations
16937 (cdr (assoc "h" org-effort-durations)) 60)
16938 d (if org-time-clocksum-use-effort-durations
16939 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
16940 w (if org-time-clocksum-use-effort-durations
16941 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
16942 mo (if org-time-clocksum-use-effort-durations
16943 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
16944 y (if org-time-clocksum-use-effort-durations
16945 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
16946 ;; fractional format
16947 (if org-time-clocksum-use-fractional
16948 (cond
16949 ;; single format string
16950 ((stringp org-time-clocksum-fractional-format)
16951 (format org-time-clocksum-fractional-format (/ m (float h))))
16952 ;; choice of fractional formats for different time units
16953 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
16954 (> (/ (truncate m) (* y d h)) 0))
16955 (format fmt (/ m (* y d (float h)))))
16956 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
16957 (> (/ (truncate m) (* mo d h)) 0))
16958 (format fmt (/ m (* mo d (float h)))))
16959 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16960 (> (/ (truncate m) (* w d h)) 0))
16961 (format fmt (/ m (* w d (float h)))))
16962 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
16963 (> (/ (truncate m) (* d h)) 0))
16964 (format fmt (/ m (* d (float h)))))
16965 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16966 (> (/ (truncate m) h) 0))
16967 (format fmt (/ m (float h))))
16968 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
16969 (format fmt m))
16970 ;; fall back to smallest time unit with a format
16971 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16972 (format fmt (/ m (float h))))
16973 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
16974 (format fmt (/ m (* d (float h)))))
16975 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16976 (format fmt (/ m (* w d (float h)))))
16977 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
16978 (format fmt (/ m (* mo d (float h)))))
16979 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
16980 (format fmt (/ m (* y d (float h))))))
16981 ;; standard (non-fractional) format, with single format string
16982 (if (stringp org-time-clocksum-format)
16983 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
16984 ;; separate formats components
16985 (and (setq fmt (plist-get org-time-clocksum-format :years))
16986 (or (> (setq n (/ (truncate m) (* y d h))) 0)
16987 (plist-get org-time-clocksum-format :require-years))
16988 (setq clocksum (concat clocksum (format fmt n))
16989 m (- m (* n y d h))))
16990 (and (setq fmt (plist-get org-time-clocksum-format :months))
16991 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
16992 (plist-get org-time-clocksum-format :require-months))
16993 (setq clocksum (concat clocksum (format fmt n))
16994 m (- m (* n mo d h))))
16995 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
16996 (or (> (setq n (/ (truncate m) (* w d h))) 0)
16997 (plist-get org-time-clocksum-format :require-weeks))
16998 (setq clocksum (concat clocksum (format fmt n))
16999 m (- m (* n w d h))))
17000 (and (setq fmt (plist-get org-time-clocksum-format :days))
17001 (or (> (setq n (/ (truncate m) (* d h))) 0)
17002 (plist-get org-time-clocksum-format :require-days))
17003 (setq clocksum (concat clocksum (format fmt n))
17004 m (- m (* n d h))))
17005 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17006 (or (> (setq n (/ (truncate m) h)) 0)
17007 (plist-get org-time-clocksum-format :require-hours))
17008 (setq clocksum (concat clocksum (format fmt n))
17009 m (- m (* n h))))
17010 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17011 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17012 (setq clocksum (concat clocksum (format fmt m))))
17013 ;; return formatted time duration
17014 clocksum))))
17016 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17017 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17018 "Org mode version 8.0")
17020 (defun org-hours-to-clocksum-string (n)
17021 (org-minutes-to-clocksum-string (* n 60)))
17023 (defun org-hh:mm-string-to-minutes (s)
17024 "Convert a string H:MM to a number of minutes.
17025 If the string is just a number, interpret it as minutes.
17026 In fact, the first hh:mm or number in the string will be taken,
17027 there can be extra stuff in the string.
17028 If no number is found, the return value is 0."
17029 (cond
17030 ((integerp s) s)
17031 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17032 (+ (* (string-to-number (match-string 1 s)) 60)
17033 (string-to-number (match-string 2 s))))
17034 ((string-match "\\([0-9]+\\)" s)
17035 (string-to-number (match-string 1 s)))
17036 (t 0)))
17038 (defcustom org-image-actual-width t
17039 "Should we use the actual width of images when inlining them?
17041 When set to `t', always use the image width.
17043 When set to a number, use imagemagick (when available) to set
17044 the image's width to this value.
17046 When set to a number in a list, try to get the width from the
17047 #+ATTR.* keyword if it matches a width specification like
17048 width=\"[0-9]+\", and fall back on that number if none is found.
17050 When set to nil, try to get the width from an #+ATTR.* keyword
17051 and fall back on the original width if none is found.
17053 This requires Emacs >= 24.1, build with imagemagick support."
17054 :group 'org-appearance
17055 :version "24.3"
17056 :type '(choice
17057 (const :tag "Use the image width" t)
17058 (integer :tag "Use a number of pixels")
17059 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17060 (const :tag "Use #+ATTR* or don't resize" nil)))
17062 (defun org-duration-string-to-minutes (s &optional output-to-string)
17063 "Convert a duration string S to minutes.
17065 A bare number is interpreted as minutes, modifiers can be set by
17066 customizing `org-effort-durations' (which see).
17068 Entries containing a colon are interpreted as H:MM by
17069 `org-hh:mm-string-to-minutes'."
17070 (let ((result 0)
17071 (re (concat "\\([0-9.]+\\) *\\("
17072 (regexp-opt (mapcar 'car org-effort-durations))
17073 "\\)")))
17074 (while (string-match re s)
17075 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17076 (string-to-number (match-string 1 s))))
17077 (setq s (replace-match "" nil t s)))
17078 (setq result (floor result))
17079 (incf result (org-hh:mm-string-to-minutes s))
17080 (if output-to-string (number-to-string result) result)))
17082 ;;;; Files
17084 (defun org-save-all-org-buffers ()
17085 "Save all Org-mode buffers without user confirmation."
17086 (interactive)
17087 (message "Saving all Org-mode buffers...")
17088 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17089 (when (featurep 'org-id) (org-id-locations-save))
17090 (message "Saving all Org-mode buffers... done"))
17092 (defun org-revert-all-org-buffers ()
17093 "Revert all Org-mode buffers.
17094 Prompt for confirmation when there are unsaved changes.
17095 Be sure you know what you are doing before letting this function
17096 overwrite your changes.
17098 This function is useful in a setup where one tracks org files
17099 with a version control system, to revert on one machine after pulling
17100 changes from another. I believe the procedure must be like this:
17102 1. M-x org-save-all-org-buffers
17103 2. Pull changes from the other machine, resolve conflicts
17104 3. M-x org-revert-all-org-buffers"
17105 (interactive)
17106 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17107 (error "Abort"))
17108 (save-excursion
17109 (save-window-excursion
17110 (mapc
17111 (lambda (b)
17112 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17113 (with-current-buffer b buffer-file-name))
17114 (org-pop-to-buffer-same-window b)
17115 (revert-buffer t 'no-confirm)))
17116 (buffer-list))
17117 (when (and (featurep 'org-id) org-id-track-globally)
17118 (org-id-locations-load)))))
17120 ;;;; Agenda files
17122 ;;;###autoload
17123 (defun org-switchb (&optional arg)
17124 "Switch between Org buffers.
17125 With one prefix argument, restrict available buffers to files.
17126 With two prefix arguments, restrict available buffers to agenda files.
17128 Defaults to `iswitchb' for buffer name completion.
17129 Set `org-completion-use-ido' to make it use ido instead."
17130 (interactive "P")
17131 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17132 ((equal arg '(16)) (org-buffer-list 'agenda))
17133 (t (org-buffer-list))))
17134 (org-completion-use-iswitchb org-completion-use-iswitchb)
17135 (org-completion-use-ido org-completion-use-ido))
17136 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17137 (setq org-completion-use-iswitchb t))
17138 (org-pop-to-buffer-same-window
17139 (org-icompleting-read "Org buffer: "
17140 (mapcar 'list (mapcar 'buffer-name blist))
17141 nil t))))
17143 ;;; Define some older names previously used for this functionality
17144 ;;;###autoload
17145 (defalias 'org-ido-switchb 'org-switchb)
17146 ;;;###autoload
17147 (defalias 'org-iswitchb 'org-switchb)
17149 (defun org-buffer-list (&optional predicate exclude-tmp)
17150 "Return a list of Org buffers.
17151 PREDICATE can be `export', `files' or `agenda'.
17153 export restrict the list to Export buffers.
17154 files restrict the list to buffers visiting Org files.
17155 agenda restrict the list to buffers visiting agenda files.
17157 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17158 (let* ((bfn nil)
17159 (agenda-files (and (eq predicate 'agenda)
17160 (mapcar 'file-truename (org-agenda-files t))))
17161 (filter
17162 (cond
17163 ((eq predicate 'files)
17164 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17165 ((eq predicate 'export)
17166 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17167 ((eq predicate 'agenda)
17168 (lambda (b)
17169 (with-current-buffer b
17170 (and (derived-mode-p 'org-mode)
17171 (setq bfn (buffer-file-name b))
17172 (member (file-truename bfn) agenda-files)))))
17173 (t (lambda (b) (with-current-buffer b
17174 (or (derived-mode-p 'org-mode)
17175 (string-match "\*Org .*Export"
17176 (buffer-name b)))))))))
17177 (delq nil
17178 (mapcar
17179 (lambda(b)
17180 (if (and (funcall filter b)
17181 (or (not exclude-tmp)
17182 (not (string-match "tmp" (buffer-name b)))))
17184 nil))
17185 (buffer-list)))))
17187 (defun org-agenda-files (&optional unrestricted archives)
17188 "Get the list of agenda files.
17189 Optional UNRESTRICTED means return the full list even if a restriction
17190 is currently in place.
17191 When ARCHIVES is t, include all archive files that are really being
17192 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17193 `org-agenda-archives-mode' is t."
17194 (let ((files
17195 (cond
17196 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17197 ((stringp org-agenda-files) (org-read-agenda-file-list))
17198 ((listp org-agenda-files) org-agenda-files)
17199 (t (error "Invalid value of `org-agenda-files'")))))
17200 (setq files (apply 'append
17201 (mapcar (lambda (f)
17202 (if (file-directory-p f)
17203 (directory-files
17204 f t org-agenda-file-regexp)
17205 (list f)))
17206 files)))
17207 (when org-agenda-skip-unavailable-files
17208 (setq files (delq nil
17209 (mapcar (function
17210 (lambda (file)
17211 (and (file-readable-p file) file)))
17212 files))))
17213 (when (or (eq archives t)
17214 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17215 (setq files (org-add-archive-files files)))
17216 files))
17218 (defun org-agenda-file-p (&optional file)
17219 "Return non-nil, if FILE is an agenda file.
17220 If FILE is omitted, use the file associated with the current
17221 buffer."
17222 (member (or file (buffer-file-name))
17223 (org-agenda-files t)))
17225 (defun org-edit-agenda-file-list ()
17226 "Edit the list of agenda files.
17227 Depending on setup, this either uses customize to edit the variable
17228 `org-agenda-files', or it visits the file that is holding the list. In the
17229 latter case, the buffer is set up in a way that saving it automatically kills
17230 the buffer and restores the previous window configuration."
17231 (interactive)
17232 (if (stringp org-agenda-files)
17233 (let ((cw (current-window-configuration)))
17234 (find-file org-agenda-files)
17235 (org-set-local 'org-window-configuration cw)
17236 (org-add-hook 'after-save-hook
17237 (lambda ()
17238 (set-window-configuration
17239 (prog1 org-window-configuration
17240 (kill-buffer (current-buffer))))
17241 (org-install-agenda-files-menu)
17242 (message "New agenda file list installed"))
17243 nil 'local)
17244 (message "%s" (substitute-command-keys
17245 "Edit list and finish with \\[save-buffer]")))
17246 (customize-variable 'org-agenda-files)))
17248 (defun org-store-new-agenda-file-list (list)
17249 "Set new value for the agenda file list and save it correctly."
17250 (if (stringp org-agenda-files)
17251 (let ((fe (org-read-agenda-file-list t)) b u)
17252 (while (setq b (find-buffer-visiting org-agenda-files))
17253 (kill-buffer b))
17254 (with-temp-file org-agenda-files
17255 (insert
17256 (mapconcat
17257 (lambda (f) ;; Keep un-expanded entries.
17258 (if (setq u (assoc f fe))
17259 (cdr u)
17261 list "\n")
17262 "\n")))
17263 (let ((org-mode-hook nil) (org-inhibit-startup t)
17264 (org-insert-mode-line-in-empty-file nil))
17265 (setq org-agenda-files list)
17266 (customize-save-variable 'org-agenda-files org-agenda-files))))
17268 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17269 "Read the list of agenda files from a file.
17270 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17271 filenames, used by `org-store-new-agenda-file-list' to write back
17272 un-expanded file names."
17273 (when (file-directory-p org-agenda-files)
17274 (error "`org-agenda-files' cannot be a single directory"))
17275 (when (stringp org-agenda-files)
17276 (with-temp-buffer
17277 (insert-file-contents org-agenda-files)
17278 (mapcar
17279 (lambda (f)
17280 (let ((e (expand-file-name (substitute-in-file-name f)
17281 org-directory)))
17282 (if pair-with-expansion
17283 (cons e f)
17284 e)))
17285 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17287 ;;;###autoload
17288 (defun org-cycle-agenda-files ()
17289 "Cycle through the files in `org-agenda-files'.
17290 If the current buffer visits an agenda file, find the next one in the list.
17291 If the current buffer does not, find the first agenda file."
17292 (interactive)
17293 (let* ((fs (org-agenda-files t))
17294 (files (append fs (list (car fs))))
17295 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17296 file)
17297 (unless files (error "No agenda files"))
17298 (catch 'exit
17299 (while (setq file (pop files))
17300 (if (equal (file-truename file) tcf)
17301 (when (car files)
17302 (find-file (car files))
17303 (throw 'exit t))))
17304 (find-file (car fs)))
17305 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17307 (defun org-agenda-file-to-front (&optional to-end)
17308 "Move/add the current file to the top of the agenda file list.
17309 If the file is not present in the list, it is added to the front. If it is
17310 present, it is moved there. With optional argument TO-END, add/move to the
17311 end of the list."
17312 (interactive "P")
17313 (let ((org-agenda-skip-unavailable-files nil)
17314 (file-alist (mapcar (lambda (x)
17315 (cons (file-truename x) x))
17316 (org-agenda-files t)))
17317 (ctf (file-truename
17318 (or buffer-file-name
17319 (error "Please save the current buffer to a file"))))
17320 x had)
17321 (setq x (assoc ctf file-alist) had x)
17323 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17324 (if to-end
17325 (setq file-alist (append (delq x file-alist) (list x)))
17326 (setq file-alist (cons x (delq x file-alist))))
17327 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17328 (org-install-agenda-files-menu)
17329 (message "File %s to %s of agenda file list"
17330 (if had "moved" "added") (if to-end "end" "front"))))
17332 (defun org-remove-file (&optional file)
17333 "Remove current file from the list of files in variable `org-agenda-files'.
17334 These are the files which are being checked for agenda entries.
17335 Optional argument FILE means use this file instead of the current."
17336 (interactive)
17337 (let* ((org-agenda-skip-unavailable-files nil)
17338 (file (or file buffer-file-name
17339 (error "Current buffer does not visit a file")))
17340 (true-file (file-truename file))
17341 (afile (abbreviate-file-name file))
17342 (files (delq nil (mapcar
17343 (lambda (x)
17344 (if (equal true-file
17345 (file-truename x))
17346 nil x))
17347 (org-agenda-files t)))))
17348 (if (not (= (length files) (length (org-agenda-files t))))
17349 (progn
17350 (org-store-new-agenda-file-list files)
17351 (org-install-agenda-files-menu)
17352 (message "Removed file: %s" afile))
17353 (message "File was not in list: %s (not removed)" afile))))
17355 (defun org-file-menu-entry (file)
17356 (vector file (list 'find-file file) t))
17358 (defun org-check-agenda-file (file)
17359 "Make sure FILE exists. If not, ask user what to do."
17360 (when (not (file-exists-p file))
17361 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17362 (abbreviate-file-name file))
17363 (let ((r (downcase (read-char-exclusive))))
17364 (cond
17365 ((equal r ?r)
17366 (org-remove-file file)
17367 (throw 'nextfile t))
17368 (t (error "Abort"))))))
17370 (defun org-get-agenda-file-buffer (file)
17371 "Get a buffer visiting FILE. If the buffer needs to be created, add
17372 it to the list of buffers which might be released later."
17373 (let ((buf (org-find-base-buffer-visiting file)))
17374 (if buf
17375 buf ; just return it
17376 ;; Make a new buffer and remember it
17377 (setq buf (find-file-noselect file))
17378 (if buf (push buf org-agenda-new-buffers))
17379 buf)))
17381 (defun org-release-buffers (blist)
17382 "Release all buffers in list, asking the user for confirmation when needed.
17383 When a buffer is unmodified, it is just killed. When modified, it is saved
17384 \(if the user agrees) and then killed."
17385 (let (buf file)
17386 (while (setq buf (pop blist))
17387 (setq file (buffer-file-name buf))
17388 (when (and (buffer-modified-p buf)
17389 file
17390 (y-or-n-p (format "Save file %s? " file)))
17391 (with-current-buffer buf (save-buffer)))
17392 (kill-buffer buf))))
17394 (defun org-agenda-prepare-buffers (files)
17395 "Create buffers for all agenda files, protect archived trees and comments."
17396 (interactive)
17397 (let ((pa '(:org-archived t))
17398 (pc '(:org-comment t))
17399 (pall '(:org-archived t :org-comment t))
17400 (inhibit-read-only t)
17401 (rea (concat ":" org-archive-tag ":"))
17402 bmp file re)
17403 (save-excursion
17404 (save-restriction
17405 (while (setq file (pop files))
17406 (catch 'nextfile
17407 (if (bufferp file)
17408 (set-buffer file)
17409 (org-check-agenda-file file)
17410 (set-buffer (org-get-agenda-file-buffer file)))
17411 (widen)
17412 (setq bmp (buffer-modified-p))
17413 (org-refresh-category-properties)
17414 (org-refresh-properties org-effort-property 'org-effort)
17415 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17416 (setq org-todo-keywords-for-agenda
17417 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17418 (setq org-done-keywords-for-agenda
17419 (append org-done-keywords-for-agenda org-done-keywords))
17420 (setq org-todo-keyword-alist-for-agenda
17421 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17422 (setq org-drawers-for-agenda
17423 (append org-drawers-for-agenda org-drawers))
17424 (setq org-tag-alist-for-agenda
17425 (append org-tag-alist-for-agenda org-tag-alist))
17427 (save-excursion
17428 (remove-text-properties (point-min) (point-max) pall)
17429 (when org-agenda-skip-archived-trees
17430 (goto-char (point-min))
17431 (while (re-search-forward rea nil t)
17432 (if (org-at-heading-p t)
17433 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17434 (goto-char (point-min))
17435 (setq re (format org-heading-keyword-regexp-format
17436 org-comment-string))
17437 (while (re-search-forward re nil t)
17438 (add-text-properties
17439 (match-beginning 0) (org-end-of-subtree t) pc)))
17440 (set-buffer-modified-p bmp)))))
17441 (setq org-todo-keywords-for-agenda
17442 (org-uniquify org-todo-keywords-for-agenda))
17443 (setq org-todo-keyword-alist-for-agenda
17444 (org-uniquify org-todo-keyword-alist-for-agenda)
17445 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17447 ;;;; Embedded LaTeX
17449 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17450 "Keymap for the minor `org-cdlatex-mode'.")
17452 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17453 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17454 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17455 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17456 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17458 (defvar org-cdlatex-texmathp-advice-is-done nil
17459 "Flag remembering if we have applied the advice to texmathp already.")
17461 (define-minor-mode org-cdlatex-mode
17462 "Toggle the minor `org-cdlatex-mode'.
17463 This mode supports entering LaTeX environment and math in LaTeX fragments
17464 in Org-mode.
17465 \\{org-cdlatex-mode-map}"
17466 nil " OCDL" nil
17467 (when org-cdlatex-mode
17468 (require 'cdlatex)
17469 (run-hooks 'cdlatex-mode-hook)
17470 (cdlatex-compute-tables))
17471 (unless org-cdlatex-texmathp-advice-is-done
17472 (setq org-cdlatex-texmathp-advice-is-done t)
17473 (defadvice texmathp (around org-math-always-on activate)
17474 "Always return t in org-mode buffers.
17475 This is because we want to insert math symbols without dollars even outside
17476 the LaTeX math segments. If Orgmode thinks that point is actually inside
17477 an embedded LaTeX fragment, let texmathp do its job.
17478 \\[org-cdlatex-mode-map]"
17479 (interactive)
17480 (let (p)
17481 (cond
17482 ((not (derived-mode-p 'org-mode)) ad-do-it)
17483 ((eq this-command 'cdlatex-math-symbol)
17484 (setq ad-return-value t
17485 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17487 (let ((p (org-inside-LaTeX-fragment-p)))
17488 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17489 (setq ad-return-value t
17490 texmathp-why '("Org-mode embedded math" . 0))
17491 (if p ad-do-it)))))))))
17493 (defun turn-on-org-cdlatex ()
17494 "Unconditionally turn on `org-cdlatex-mode'."
17495 (org-cdlatex-mode 1))
17497 (defun org-inside-LaTeX-fragment-p ()
17498 "Test if point is inside a LaTeX fragment.
17499 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17500 sequence appearing also before point.
17501 Even though the matchers for math are configurable, this function assumes
17502 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17503 delimiters are skipped when they have been removed by customization.
17504 The return value is nil, or a cons cell with the delimiter and the
17505 position of this delimiter.
17507 This function does a reasonably good job, but can locally be fooled by
17508 for example currency specifications. For example it will assume being in
17509 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17510 fragments that are properly closed, but during editing, we have to live
17511 with the uncertainty caused by missing closing delimiters. This function
17512 looks only before point, not after."
17513 (catch 'exit
17514 (let ((pos (point))
17515 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17516 (lim (progn
17517 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17518 (point)))
17519 dd-on str (start 0) m re)
17520 (goto-char pos)
17521 (when dodollar
17522 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17523 re (nth 1 (assoc "$" org-latex-regexps)))
17524 (while (string-match re str start)
17525 (cond
17526 ((= (match-end 0) (length str))
17527 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17528 ((= (match-end 0) (- (length str) 5))
17529 (throw 'exit nil))
17530 (t (setq start (match-end 0))))))
17531 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17532 (goto-char pos)
17533 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17534 (and (match-beginning 2) (throw 'exit nil))
17535 ;; count $$
17536 (while (re-search-backward "\\$\\$" lim t)
17537 (setq dd-on (not dd-on)))
17538 (goto-char pos)
17539 (if dd-on (cons "$$" m))))))
17541 (defun org-inside-latex-macro-p ()
17542 "Is point inside a LaTeX macro or its arguments?"
17543 (save-match-data
17544 (org-in-regexp
17545 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17547 (defun org-try-cdlatex-tab ()
17548 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17549 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17550 - inside a LaTeX fragment, or
17551 - after the first word in a line, where an abbreviation expansion could
17552 insert a LaTeX environment."
17553 (when org-cdlatex-mode
17554 (cond
17555 ;; Before any word on the line: No expansion possible.
17556 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17557 ;; Just after first word on the line: Expand it. Make sure it
17558 ;; cannot happen on headlines, though.
17559 ((save-excursion
17560 (skip-chars-backward "a-zA-Z0-9*")
17561 (skip-chars-backward " \t")
17562 (and (bolp) (not (org-at-heading-p))))
17563 (cdlatex-tab) t)
17564 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17566 (defun org-cdlatex-underscore-caret (&optional arg)
17567 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17568 Revert to the normal definition outside of these fragments."
17569 (interactive "P")
17570 (if (org-inside-LaTeX-fragment-p)
17571 (call-interactively 'cdlatex-sub-superscript)
17572 (let (org-cdlatex-mode)
17573 (call-interactively (key-binding (vector last-input-event))))))
17575 (defun org-cdlatex-math-modify (&optional arg)
17576 "Execute `cdlatex-math-modify' in LaTeX fragments.
17577 Revert to the normal definition outside of these fragments."
17578 (interactive "P")
17579 (if (org-inside-LaTeX-fragment-p)
17580 (call-interactively 'cdlatex-math-modify)
17581 (let (org-cdlatex-mode)
17582 (call-interactively (key-binding (vector last-input-event))))))
17584 (defvar org-latex-fragment-image-overlays nil
17585 "List of overlays carrying the images of latex fragments.")
17586 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17588 (defun org-remove-latex-fragment-image-overlays ()
17589 "Remove all overlays with LaTeX fragment images in current buffer."
17590 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17591 (setq org-latex-fragment-image-overlays nil))
17593 (defun org-preview-latex-fragment (&optional subtree)
17594 "Preview the LaTeX fragment at point, or all locally or globally.
17595 If the cursor is in a LaTeX fragment, create the image and overlay
17596 it over the source code. If there is no fragment at point, display
17597 all fragments in the current text, from one headline to the next. With
17598 prefix SUBTREE, display all fragments in the current subtree. With a
17599 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17600 the cursor is before the first headline,
17601 display all fragments in the buffer.
17602 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17603 (interactive "P")
17604 (unless buffer-file-name
17605 (error "Can't preview LaTeX fragment in a non-file buffer"))
17606 (org-remove-latex-fragment-image-overlays)
17607 (save-excursion
17608 (save-restriction
17609 (let (beg end at msg)
17610 (cond
17611 ((or (equal subtree '(16))
17612 (not (save-excursion
17613 (re-search-backward org-outline-regexp-bol nil t))))
17614 (setq beg (point-min) end (point-max)
17615 msg "Creating images for buffer...%s"))
17616 ((equal subtree '(4))
17617 (org-back-to-heading)
17618 (setq beg (point) end (org-end-of-subtree t)
17619 msg "Creating images for subtree...%s"))
17621 (if (setq at (org-inside-LaTeX-fragment-p))
17622 (goto-char (max (point-min) (- (cdr at) 2)))
17623 (org-back-to-heading))
17624 (setq beg (point) end (progn (outline-next-heading) (point))
17625 msg (if at "Creating image...%s"
17626 "Creating images for entry...%s"))))
17627 (message msg "")
17628 (narrow-to-region beg end)
17629 (goto-char beg)
17630 (org-format-latex
17631 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17632 (file-name-nondirectory
17633 buffer-file-name)))
17634 default-directory 'overlays msg at 'forbuffer
17635 org-latex-create-formula-image-program)
17636 (message msg "done. Use `C-c C-c' to remove images.")))))
17638 (defvar org-latex-regexps
17639 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17640 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17641 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17642 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17643 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17644 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17645 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17646 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17647 "Regular expressions for matching embedded LaTeX.")
17649 (defvar org-export-have-math nil) ;; dynamic scoping
17650 (defun org-format-latex (prefix &optional dir overlays msg at
17651 forbuffer processing-type)
17652 "Replace LaTeX fragments with links to an image, and produce images.
17653 Some of the options can be changed using the variable
17654 `org-format-latex-options'."
17655 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17656 (let* ((prefixnodir (file-name-nondirectory prefix))
17657 (absprefix (expand-file-name prefix dir))
17658 (todir (file-name-directory absprefix))
17659 (opt org-format-latex-options)
17660 (optnew org-format-latex-options)
17661 (matchers (plist-get opt :matchers))
17662 (re-list org-latex-regexps)
17663 (org-format-latex-header-extra
17664 (plist-get (org-infile-export-plist) :latex-header-extra))
17665 (cnt 0) txt hash link beg end re e checkdir
17666 string
17667 m n block-type block linkfile movefile ov)
17668 ;; Check the different regular expressions
17669 (while (setq e (pop re-list))
17670 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17671 block (if block-type "\n\n" ""))
17672 (when (member m matchers)
17673 (goto-char (point-min))
17674 (while (re-search-forward re nil t)
17675 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17676 (not (get-text-property (match-beginning n)
17677 'org-protected))
17678 (or (not overlays)
17679 (not (eq (get-char-property (match-beginning n)
17680 'org-overlay-type)
17681 'org-latex-overlay))))
17682 (setq org-export-have-math t)
17683 (cond
17684 ((eq processing-type 'verbatim)
17685 ;; Leave the text verbatim, just protect it
17686 (add-text-properties (match-beginning n) (match-end n)
17687 '(org-protected t)))
17688 ((eq processing-type 'mathjax)
17689 ;; Prepare for MathJax processing
17690 (setq string (match-string n))
17691 (if (member m '("$" "$1"))
17692 (save-excursion
17693 (delete-region (match-beginning n) (match-end n))
17694 (goto-char (match-beginning n))
17695 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17696 "\\)")
17697 '(org-protected t))))
17698 (add-text-properties (match-beginning n) (match-end n)
17699 '(org-protected t))))
17700 ((or (eq processing-type 'dvipng)
17701 (eq processing-type 'imagemagick))
17702 ;; Process to an image
17703 (setq txt (match-string n)
17704 beg (match-beginning n) end (match-end n)
17705 cnt (1+ cnt))
17706 (let ((face (face-at-point))
17707 (fg (plist-get opt :foreground))
17708 (bg (plist-get opt :background))
17709 print-length print-level) ; make sure full list is printed
17710 (when forbuffer
17711 ; Get the colors from the face at point
17712 (goto-char beg)
17713 (when (eq fg 'auto)
17714 (setq fg (face-attribute face :foreground nil 'default)))
17715 (when (eq bg 'auto)
17716 (setq bg (face-attribute face :background nil 'default)))
17717 (setq optnew (copy-sequence opt))
17718 (plist-put optnew :foreground fg)
17719 (plist-put optnew :background bg))
17720 (setq hash (sha1 (prin1-to-string
17721 (list org-format-latex-header
17722 org-format-latex-header-extra
17723 org-export-latex-default-packages-alist
17724 org-export-latex-packages-alist
17725 org-format-latex-options
17726 forbuffer txt fg bg)))
17727 linkfile (format "%s_%s.png" prefix hash)
17728 movefile (format "%s_%s.png" absprefix hash)))
17729 (setq link (concat block "[[file:" linkfile "]]" block))
17730 (if msg (message msg cnt))
17731 (goto-char beg)
17732 (unless checkdir ; make sure the directory exists
17733 (setq checkdir t)
17734 (or (file-directory-p todir) (make-directory todir t)))
17735 (unless (file-exists-p movefile)
17736 (org-create-formula-image
17737 txt movefile optnew forbuffer processing-type))
17738 (if overlays
17739 (progn
17740 (mapc (lambda (o)
17741 (if (eq (overlay-get o 'org-overlay-type)
17742 'org-latex-overlay)
17743 (delete-overlay o)))
17744 (overlays-in beg end))
17745 (setq ov (make-overlay beg end))
17746 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17747 (if (featurep 'xemacs)
17748 (progn
17749 (overlay-put ov 'invisible t)
17750 (overlay-put
17751 ov 'end-glyph
17752 (make-glyph (vector 'png :file movefile))))
17753 (overlay-put
17754 ov 'display
17755 (list 'image :type 'png :file movefile :ascent 'center)))
17756 (push ov org-latex-fragment-image-overlays)
17757 (goto-char end))
17758 (delete-region beg end)
17759 (insert (org-add-props link
17760 (list 'org-latex-src
17761 (replace-regexp-in-string
17762 "\"" "" txt)
17763 'org-latex-src-embed-type
17764 (if block-type 'paragraph 'character))))))
17765 ((eq processing-type 'mathml)
17766 ;; Process to MathML
17767 (unless (save-match-data (org-format-latex-mathml-available-p))
17768 (error "LaTeX to MathML converter not configured"))
17769 (setq txt (match-string n)
17770 beg (match-beginning n) end (match-end n)
17771 cnt (1+ cnt))
17772 (if msg (message msg cnt))
17773 (goto-char beg)
17774 (delete-region beg end)
17775 (insert (org-format-latex-as-mathml
17776 txt block-type prefix dir)))
17778 (error "Unknown conversion type %s for latex fragments"
17779 processing-type)))))))))
17781 (defun org-create-math-formula (latex-frag &optional mathml-file)
17782 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17783 Use `org-latex-to-mathml-convert-command'. If the conversion is
17784 sucessful, return the portion between \"<math...> </math>\"
17785 elements otherwise return nil. When MATHML-FILE is specified,
17786 write the results in to that file. When invoked as an
17787 interactive command, prompt for LATEX-FRAG, with initial value
17788 set to the current active region and echo the results for user
17789 inspection."
17790 (interactive (list (let ((frag (when (org-region-active-p)
17791 (buffer-substring-no-properties
17792 (region-beginning) (region-end)))))
17793 (read-string "LaTeX Fragment: " frag nil frag))))
17794 (unless latex-frag (error "Invalid latex-frag"))
17795 (let* ((tmp-in-file (file-relative-name
17796 (make-temp-name (expand-file-name "ltxmathml-in"))))
17797 (ignore (write-region latex-frag nil tmp-in-file))
17798 (tmp-out-file (file-relative-name
17799 (make-temp-name (expand-file-name "ltxmathml-out"))))
17800 (cmd (format-spec
17801 org-latex-to-mathml-convert-command
17802 `((?j . ,(shell-quote-argument
17803 (expand-file-name org-latex-to-mathml-jar-file)))
17804 (?I . ,(shell-quote-argument tmp-in-file))
17805 (?o . ,(shell-quote-argument tmp-out-file)))))
17806 mathml shell-command-output)
17807 (when (org-called-interactively-p 'any)
17808 (unless (org-format-latex-mathml-available-p)
17809 (error "LaTeX to MathML converter not configured")))
17810 (message "Running %s" cmd)
17811 (setq shell-command-output (shell-command-to-string cmd))
17812 (setq mathml
17813 (when (file-readable-p tmp-out-file)
17814 (with-current-buffer (find-file-noselect tmp-out-file t)
17815 (goto-char (point-min))
17816 (when (re-search-forward
17817 (concat
17818 (regexp-quote
17819 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17820 "\\(.\\|\n\\)*"
17821 (regexp-quote "</math>")) nil t)
17822 (prog1 (match-string 0) (kill-buffer))))))
17823 (cond
17824 (mathml
17825 (setq mathml
17826 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17827 (when mathml-file
17828 (write-region mathml nil mathml-file))
17829 (when (org-called-interactively-p 'any)
17830 (message mathml)))
17831 ((message "LaTeX to MathML conversion failed")
17832 (message shell-command-output)))
17833 (delete-file tmp-in-file)
17834 (when (file-exists-p tmp-out-file)
17835 (delete-file tmp-out-file))
17836 mathml))
17838 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17839 prefix &optional dir)
17840 "Use `org-create-math-formula' but check local cache first."
17841 (let* ((absprefix (expand-file-name prefix dir))
17842 (print-length nil) (print-level nil)
17843 (formula-id (concat
17844 "formula-"
17845 (sha1
17846 (prin1-to-string
17847 (list latex-frag
17848 org-latex-to-mathml-convert-command)))))
17849 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17850 (formula-cache-dir (file-name-directory formula-cache)))
17852 (unless (file-directory-p formula-cache-dir)
17853 (make-directory formula-cache-dir t))
17855 (unless (file-exists-p formula-cache)
17856 (org-create-math-formula latex-frag formula-cache))
17858 (if (file-exists-p formula-cache)
17859 ;; Successful conversion. Return the link to MathML file.
17860 (org-add-props
17861 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17862 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17863 'org-latex-src-embed-type (if latex-frag-type
17864 'paragraph 'character)))
17865 ;; Failed conversion. Return the LaTeX fragment verbatim
17866 (add-text-properties
17867 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17868 latex-frag)))
17870 (defun org-create-formula-image (string tofile options buffer &optional type)
17871 "Create an image from LaTeX source using dvipng or convert.
17872 This function calls either `org-create-formula-image-with-dvipng'
17873 or `org-create-formula-image-with-imagemagick' depending on the
17874 value of `org-latex-create-formula-image-program' or on the value
17875 of the optional TYPE variable.
17877 Note: ultimately these two function should be combined as they
17878 share a good deal of logic."
17879 (org-check-external-command
17880 "latex" "needed to convert LaTeX fragments to images")
17881 (funcall
17882 (case (or type org-latex-create-formula-image-program)
17883 ('dvipng
17884 (org-check-external-command
17885 "dvipng" "needed to convert LaTeX fragments to images")
17886 #'org-create-formula-image-with-dvipng)
17887 ('imagemagick
17888 (org-check-external-command
17889 "convert" "you need to install imagemagick")
17890 #'org-create-formula-image-with-imagemagick)
17891 (t (error
17892 "invalid value of `org-latex-create-formula-image-program'")))
17893 string tofile options buffer))
17895 ;; This function borrows from Ganesh Swami's latex2png.el
17896 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17897 "This calls dvipng."
17898 (require 'org-latex)
17899 (let* ((tmpdir (if (featurep 'xemacs)
17900 (temp-directory)
17901 temporary-file-directory))
17902 (texfilebase (make-temp-name
17903 (expand-file-name "orgtex" tmpdir)))
17904 (texfile (concat texfilebase ".tex"))
17905 (dvifile (concat texfilebase ".dvi"))
17906 (pngfile (concat texfilebase ".png"))
17907 (fnh (if (featurep 'xemacs)
17908 (font-height (face-font 'default))
17909 (face-attribute 'default :height nil)))
17910 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17911 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17912 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17913 "Black"))
17914 (bg (or (plist-get options (if buffer :background :html-background))
17915 "Transparent")))
17916 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17917 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17918 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17919 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17920 (with-temp-file texfile
17921 (insert (org-splice-latex-header
17922 org-format-latex-header
17923 org-export-latex-default-packages-alist
17924 org-export-latex-packages-alist t
17925 org-format-latex-header-extra))
17926 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17927 (require 'org-latex)
17928 (org-export-latex-fix-inputenc))
17929 (let ((dir default-directory))
17930 (condition-case nil
17931 (progn
17932 (cd tmpdir)
17933 (call-process "latex" nil nil nil texfile))
17934 (error nil))
17935 (cd dir))
17936 (if (not (file-exists-p dvifile))
17937 (progn (message "Failed to create dvi file from %s" texfile) nil)
17938 (condition-case nil
17939 (if (featurep 'xemacs)
17940 (call-process "dvipng" nil nil nil
17941 "-fg" fg "-bg" bg
17942 "-T" "tight"
17943 "-o" pngfile
17944 dvifile)
17945 (call-process "dvipng" nil nil nil
17946 "-fg" fg "-bg" bg
17947 "-D" dpi
17948 ;;"-x" scale "-y" scale
17949 "-T" "tight"
17950 "-o" pngfile
17951 dvifile))
17952 (error nil))
17953 (if (not (file-exists-p pngfile))
17954 (if org-format-latex-signal-error
17955 (error "Failed to create png file from %s" texfile)
17956 (message "Failed to create png file from %s" texfile)
17957 nil)
17958 ;; Use the requested file name and clean up
17959 (copy-file pngfile tofile 'replace)
17960 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17961 (if (file-exists-p (concat texfilebase e))
17962 (delete-file (concat texfilebase e))))
17963 pngfile))))
17965 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17966 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17967 "This calls convert, which is included into imagemagick."
17968 (require 'org-latex)
17969 (let* ((tmpdir (if (featurep 'xemacs)
17970 (temp-directory)
17971 temporary-file-directory))
17972 (texfilebase (make-temp-name
17973 (expand-file-name "orgtex" tmpdir)))
17974 (texfile (concat texfilebase ".tex"))
17975 (pdffile (concat texfilebase ".pdf"))
17976 (pngfile (concat texfilebase ".png"))
17977 (fnh (if (featurep 'xemacs)
17978 (font-height (face-font 'default))
17979 (face-attribute 'default :height nil)))
17980 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17981 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17982 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17983 "black"))
17984 (bg (or (plist-get options (if buffer :background :html-background))
17985 "white")))
17986 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17987 (setq fg (org-latex-color-format fg)))
17988 (if (eq bg 'default) (setq bg (org-latex-color :background))
17989 (setq bg (org-latex-color-format
17990 (if (string= bg "Transparent") "white" bg))))
17991 (with-temp-file texfile
17992 (insert (org-splice-latex-header
17993 org-format-latex-header
17994 org-export-latex-default-packages-alist
17995 org-export-latex-packages-alist t
17996 org-format-latex-header-extra))
17997 (insert "\n\\begin{document}\n"
17998 "\\definecolor{fg}{rgb}{" fg "}\n"
17999 "\\definecolor{bg}{rgb}{" bg "}\n"
18000 "\n\\pagecolor{bg}\n"
18001 "\n{\\color{fg}\n"
18002 string
18003 "\n}\n"
18004 "\n\\end{document}\n" )
18005 (require 'org-latex)
18006 (org-export-latex-fix-inputenc))
18007 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18008 (condition-case nil
18009 (progn
18010 (cd tmpdir)
18011 (setq cmds org-latex-to-pdf-process)
18012 (while cmds
18013 (setq latex-frags-cmds (pop cmds))
18014 (if (listp latex-frags-cmds)
18015 (setq cmds nil)
18016 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
18017 (while latex-frags-cmds
18018 (setq cmd (pop latex-frags-cmds))
18019 (while (string-match "%b" cmd)
18020 (setq cmd (replace-match
18021 (save-match-data
18022 (shell-quote-argument texfile))
18023 t t cmd)))
18024 (while (string-match "%f" cmd)
18025 (setq cmd (replace-match
18026 (save-match-data
18027 (shell-quote-argument (file-name-nondirectory texfile)))
18028 t t cmd)))
18029 (while (string-match "%o" cmd)
18030 (setq cmd (replace-match
18031 (save-match-data
18032 (shell-quote-argument (file-name-directory texfile)))
18033 t t cmd)))
18034 (setq cmd (split-string cmd))
18035 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18036 (error nil))
18037 (cd dir))
18038 (if (not (file-exists-p pdffile))
18039 (progn (message "Failed to create pdf file from %s" texfile) nil)
18040 (condition-case nil
18041 (if (featurep 'xemacs)
18042 (call-process "convert" nil nil nil
18043 "-density" "96"
18044 "-trim"
18045 "-antialias"
18046 pdffile
18047 "-quality" "100"
18048 ;; "-sharpen" "0x1.0"
18049 pngfile)
18050 (call-process "convert" nil nil nil
18051 "-density" dpi
18052 "-trim"
18053 "-antialias"
18054 pdffile
18055 "-quality" "100"
18056 ; "-sharpen" "0x1.0"
18057 pngfile))
18058 (error nil))
18059 (if (not (file-exists-p pngfile))
18060 (if org-format-latex-signal-error
18061 (error "Failed to create png file from %s" texfile)
18062 (message "Failed to create png file from %s" texfile)
18063 nil)
18064 ;; Use the requested file name and clean up
18065 (copy-file pngfile tofile 'replace)
18066 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18067 (if (file-exists-p (concat texfilebase e))
18068 (delete-file (concat texfilebase e))))
18069 pngfile))))
18071 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18072 "Fill a LaTeX header template TPL.
18073 In the template, the following place holders will be recognized:
18075 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18076 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18077 [PACKAGES] \\usepackage statements for PKG
18078 [NO-PACKAGES] do not include PKG
18079 [EXTRA] the string EXTRA
18080 [NO-EXTRA] do not include EXTRA
18082 For backward compatibility, if both the positive and the negative place
18083 holder is missing, the positive one (without the \"NO-\") will be
18084 assumed to be present at the end of the template.
18085 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18086 EXTRA is a string.
18087 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18088 (let (rpl (end ""))
18089 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18090 (setq rpl (if (or (match-end 1) (not def-pkg))
18091 "" (org-latex-packages-to-string def-pkg snippets-p t))
18092 tpl (replace-match rpl t t tpl))
18093 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18095 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18096 (setq rpl (if (or (match-end 1) (not pkg))
18097 "" (org-latex-packages-to-string pkg snippets-p t))
18098 tpl (replace-match rpl t t tpl))
18099 (if pkg (setq end
18100 (concat end "\n"
18101 (org-latex-packages-to-string pkg snippets-p)))))
18103 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18104 (setq rpl (if (or (match-end 1) (not extra))
18105 "" (concat extra "\n"))
18106 tpl (replace-match rpl t t tpl))
18107 (if (and extra (string-match "\\S-" extra))
18108 (setq end (concat end "\n" extra))))
18110 (if (string-match "\\S-" end)
18111 (concat tpl "\n" end)
18112 tpl)))
18114 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18115 "Turn an alist of packages into a string with the \\usepackage macros."
18116 (setq pkg (mapconcat (lambda(p)
18117 (cond
18118 ((stringp p) p)
18119 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18120 (format "%% Package %s omitted" (cadr p)))
18121 ((equal "" (car p))
18122 (format "\\usepackage{%s}" (cadr p)))
18124 (format "\\usepackage[%s]{%s}"
18125 (car p) (cadr p)))))
18127 "\n"))
18128 (if newline (concat pkg "\n") pkg))
18130 (defun org-dvipng-color (attr)
18131 "Return a RGB color specification for dvipng."
18132 (apply 'format "rgb %s %s %s"
18133 (mapcar 'org-normalize-color
18134 (if (featurep 'xemacs)
18135 (color-rgb-components
18136 (face-property 'default
18137 (cond ((eq attr :foreground) 'foreground)
18138 ((eq attr :background) 'background))))
18139 (color-values (face-attribute 'default attr nil))))))
18141 (defun org-dvipng-color-format (color-name)
18142 "Convert COLOR-NAME to a RGB color value for dvipng."
18143 (apply 'format "rgb %s %s %s"
18144 (mapcar 'org-normalize-color
18145 (color-values color-name))))
18147 (defun org-latex-color (attr)
18148 "Return a RGB color for the LaTeX color package."
18149 (apply 'format "%s,%s,%s"
18150 (mapcar 'org-normalize-color
18151 (if (featurep 'xemacs)
18152 (color-rgb-components
18153 (face-property 'default
18154 (cond ((eq attr :foreground) 'foreground)
18155 ((eq attr :background) 'background))))
18156 (color-values (face-attribute 'default attr nil))))))
18158 (defun org-latex-color-format (color-name)
18159 "Convert COLOR-NAME to a RGB color value."
18160 (apply 'format "%s,%s,%s"
18161 (mapcar 'org-normalize-color
18162 (color-values color-name))))
18164 (defun org-normalize-color (value)
18165 "Return string to be used as color value for an RGB component."
18166 (format "%g" (/ value 65535.0)))
18168 ;; Image display
18171 (defvar org-inline-image-overlays nil)
18172 (make-variable-buffer-local 'org-inline-image-overlays)
18174 (defun org-toggle-inline-images (&optional include-linked)
18175 "Toggle the display of inline images.
18176 INCLUDE-LINKED is passed to `org-display-inline-images'."
18177 (interactive "P")
18178 (if org-inline-image-overlays
18179 (progn
18180 (org-remove-inline-images)
18181 (message "Inline image display turned off"))
18182 (org-display-inline-images include-linked)
18183 (if (and (org-called-interactively-p)
18184 org-inline-image-overlays)
18185 (message "%d images displayed inline"
18186 (length org-inline-image-overlays))
18187 (message "No images to display inline"))))
18189 (defun org-redisplay-inline-images ()
18190 "Refresh the display of inline images."
18191 (interactive)
18192 (if (not org-inline-image-overlays)
18193 (org-toggle-inline-images)
18194 (org-toggle-inline-images)
18195 (org-toggle-inline-images)))
18197 (defun org-display-inline-images (&optional include-linked refresh beg end)
18198 "Display inline images.
18199 Normally only links without a description part are inlined, because this
18200 is how it will work for export. When INCLUDE-LINKED is set, also links
18201 with a description part will be inlined. This can be nice for a quick
18202 look at those images, but it does not reflect what exported files will look
18203 like.
18204 When REFRESH is set, refresh existing images between BEG and END.
18205 This will create new image displays only if necessary.
18206 BEG and END default to the buffer boundaries."
18207 (interactive "P")
18208 (unless refresh
18209 (org-remove-inline-images)
18210 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18211 (save-excursion
18212 (save-restriction
18213 (widen)
18214 (setq beg (or beg (point-min)) end (or end (point-max)))
18215 (goto-char beg)
18216 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18217 (substring (org-image-file-name-regexp) 0 -2)
18218 "\\)\\]" (if include-linked "" "\\]")))
18219 old file ov img type attrwidth width)
18220 (while (re-search-forward re end t)
18221 (setq old (get-char-property-and-overlay (match-beginning 1)
18222 'org-image-overlay)
18223 file (expand-file-name
18224 (concat (or (match-string 3) "") (match-string 4))))
18225 (when (image-type-available-p 'imagemagick)
18226 (setq attrwidth (if (or (listp org-image-actual-width)
18227 (null org-image-actual-width))
18228 (save-excursion
18229 (save-match-data
18230 (when (re-search-backward
18231 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18232 (save-excursion
18233 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18234 (string-to-number (match-string 1))))))
18235 width (cond ((eq org-image-actual-width t) nil)
18236 ((null org-image-actual-width) attrwidth)
18237 ((numberp org-image-actual-width)
18238 org-image-actual-width)
18239 ((listp org-image-actual-width)
18240 (or attrwidth (car org-image-actual-width))))
18241 type (if width 'imagemagick)))
18242 (when (file-exists-p file)
18243 (if (and (car-safe old) refresh)
18244 (image-refresh (overlay-get (cdr old) 'display))
18245 (setq img (save-match-data (create-image file type nil :width width)))
18246 (when img
18247 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18248 (overlay-put ov 'display img)
18249 (overlay-put ov 'face 'default)
18250 (overlay-put ov 'org-image-overlay t)
18251 (overlay-put ov 'modification-hooks
18252 (list 'org-display-inline-remove-overlay))
18253 (push ov org-inline-image-overlays)))))))))
18255 (define-obsolete-function-alias
18256 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18258 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18259 "Remove inline-display overlay if a corresponding region is modified."
18260 (let ((inhibit-modification-hooks t))
18261 (when (and ov after)
18262 (delete ov org-inline-image-overlays)
18263 (delete-overlay ov))))
18265 (defun org-remove-inline-images ()
18266 "Remove inline display of images."
18267 (interactive)
18268 (mapc 'delete-overlay org-inline-image-overlays)
18269 (setq org-inline-image-overlays nil))
18271 ;;;; Key bindings
18273 ;; Outline functions from `outline-mode-prefix-map'
18274 ;; that can be remapped in Org:
18275 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18276 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18277 (define-key org-mode-map [remap outline-forward-same-level]
18278 'org-forward-heading-same-level)
18279 (define-key org-mode-map [remap outline-backward-same-level]
18280 'org-backward-heading-same-level)
18281 (define-key org-mode-map [remap show-branches]
18282 'org-kill-note-or-show-branches)
18283 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18284 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18285 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18287 ;; Outline functions from `outline-mode-prefix-map' that can not
18288 ;; be remapped in Org:
18290 ;; - the column "key binding" shows whether the Outline function is still
18291 ;; available in Org mode on the same key that it has been bound to in
18292 ;; Outline mode:
18293 ;; - "overridden": key used for a different functionality in Org mode
18294 ;; - else: key still bound to the same Outline function in Org mode
18296 ;; | Outline function | key binding | Org replacement |
18297 ;; |------------------------------------+-------------+-----------------------|
18298 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18299 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18300 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18301 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18302 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18303 ;; | `show-entry' | overridden | no replacement |
18304 ;; | `show-children' | `C-c C-i' | visibility cycling |
18305 ;; | `show-branches' | `C-c C-k' | still same function |
18306 ;; | `show-subtree' | overridden | visibility cycling |
18307 ;; | `show-all' | overridden | no replacement |
18308 ;; | `hide-subtree' | overridden | visibility cycling |
18309 ;; | `hide-body' | overridden | no replacement |
18310 ;; | `hide-entry' | overridden | visibility cycling |
18311 ;; | `hide-leaves' | overridden | no replacement |
18312 ;; | `hide-sublevels' | overridden | no replacement |
18313 ;; | `hide-other' | overridden | no replacement |
18315 ;; Make `C-c C-x' a prefix key
18316 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18318 ;; TAB key with modifiers
18319 (org-defkey org-mode-map "\C-i" 'org-cycle)
18320 (org-defkey org-mode-map [(tab)] 'org-cycle)
18321 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18322 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18323 ;; The following line is necessary under Suse GNU/Linux
18324 (unless (featurep 'xemacs)
18325 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18326 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18327 (define-key org-mode-map [backtab] 'org-shifttab)
18329 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18330 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18331 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18333 ;; Cursor keys with modifiers
18334 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18335 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18336 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18337 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18339 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18340 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18341 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18342 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18344 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18345 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18346 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18347 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18349 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18350 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18351 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18352 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18354 ;; Babel keys
18355 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18356 (mapc (lambda (pair)
18357 (define-key org-babel-map (car pair) (cdr pair)))
18358 org-babel-key-bindings)
18360 ;;; Extra keys for tty access.
18361 ;; We only set them when really needed because otherwise the
18362 ;; menus don't show the simple keys
18364 (when (or org-use-extra-keys
18365 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18366 (not window-system))
18367 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18368 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18369 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18370 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18371 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18372 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18373 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18374 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18375 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18376 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18377 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18378 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18379 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18380 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18381 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18382 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18383 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18384 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18385 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18386 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18387 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18388 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18389 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18390 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18391 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18392 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18393 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18394 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18396 ;; All the other keys
18398 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18399 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18400 (if (boundp 'narrow-map)
18401 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18402 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18403 (if (boundp 'narrow-map)
18404 (org-defkey narrow-map "b" 'org-narrow-to-block)
18405 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18406 (if (boundp 'narrow-map)
18407 (org-defkey narrow-map "e" 'org-narrow-to-element)
18408 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18409 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18410 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18411 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18412 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18413 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18414 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18415 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18416 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18417 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18418 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18419 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18420 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18421 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18422 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18423 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18424 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18425 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18426 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18427 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18428 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18429 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18430 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18431 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18432 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18433 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18434 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18435 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18436 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18437 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18438 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18439 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18440 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18441 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18442 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18443 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18444 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18445 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18446 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18447 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18448 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18449 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18450 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18451 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18452 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18453 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18454 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18455 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18456 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18457 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18458 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18459 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18460 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18461 (org-defkey org-mode-map "\C-c^" 'org-sort)
18462 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18463 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18464 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18465 (org-defkey org-mode-map "\C-m" 'org-return)
18466 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18467 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18468 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18469 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18470 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18471 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18472 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18473 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18474 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18475 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18476 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18477 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18478 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18479 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18480 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18481 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18482 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18483 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18484 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18485 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18486 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18487 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18488 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18490 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18491 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18492 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18494 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18495 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18496 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18497 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18498 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18499 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18500 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18501 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18502 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18503 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18504 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18505 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18506 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18507 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18508 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18509 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18510 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18511 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18512 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18513 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18514 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18515 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18516 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18518 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18519 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18520 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18521 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18522 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18524 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18526 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18528 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18529 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18531 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18534 (when (featurep 'xemacs)
18535 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18538 (defconst org-speed-commands-default
18540 ("Outline Navigation")
18541 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18542 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18543 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18544 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18545 ("u" . (org-speed-move-safe 'outline-up-heading))
18546 ("j" . org-goto)
18547 ("g" . (org-refile t))
18548 ("Outline Visibility")
18549 ("c" . org-cycle)
18550 ("C" . org-shifttab)
18551 (" " . org-display-outline-path)
18552 ("=" . org-columns)
18553 ("Outline Structure Editing")
18554 ("U" . org-shiftmetaup)
18555 ("D" . org-shiftmetadown)
18556 ("r" . org-metaright)
18557 ("l" . org-metaleft)
18558 ("R" . org-shiftmetaright)
18559 ("L" . org-shiftmetaleft)
18560 ("i" . (progn (forward-char 1) (call-interactively
18561 'org-insert-heading-respect-content)))
18562 ("^" . org-sort)
18563 ("w" . org-refile)
18564 ("a" . org-archive-subtree-default-with-confirmation)
18565 ("." . org-mark-subtree)
18566 ("#" . org-toggle-comment)
18567 ("Clock Commands")
18568 ("I" . org-clock-in)
18569 ("O" . org-clock-out)
18570 ("Meta Data Editing")
18571 ("t" . org-todo)
18572 ("," . (org-priority))
18573 ("0" . (org-priority ?\ ))
18574 ("1" . (org-priority ?A))
18575 ("2" . (org-priority ?B))
18576 ("3" . (org-priority ?C))
18577 (":" . org-set-tags-command)
18578 ("e" . org-set-effort)
18579 ("E" . org-inc-effort)
18580 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18581 (org-entry-put (point) "APPT_WARNTIME" m)))
18582 ("Agenda Views etc")
18583 ("v" . org-agenda)
18584 ("/" . org-sparse-tree)
18585 ("Misc")
18586 ("o" . org-open-at-point)
18587 ("?" . org-speed-command-help)
18588 ("<" . (org-agenda-set-restriction-lock 'subtree))
18589 (">" . (org-agenda-remove-restriction-lock))
18591 "The default speed commands.")
18593 (defun org-print-speed-command (e)
18594 (if (> (length (car e)) 1)
18595 (progn
18596 (princ "\n")
18597 (princ (car e))
18598 (princ "\n")
18599 (princ (make-string (length (car e)) ?-))
18600 (princ "\n"))
18601 (princ (car e))
18602 (princ " ")
18603 (if (symbolp (cdr e))
18604 (princ (symbol-name (cdr e)))
18605 (prin1 (cdr e)))
18606 (princ "\n")))
18608 (defun org-speed-command-help ()
18609 "Show the available speed commands."
18610 (interactive)
18611 (if (not org-use-speed-commands)
18612 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18613 (with-output-to-temp-buffer "*Help*"
18614 (princ "User-defined Speed commands\n===========================\n")
18615 (mapc 'org-print-speed-command org-speed-commands-user)
18616 (princ "\n")
18617 (princ "Built-in Speed commands\n=======================\n")
18618 (mapc 'org-print-speed-command org-speed-commands-default))
18619 (with-current-buffer "*Help*"
18620 (setq truncate-lines t))))
18622 (defun org-speed-move-safe (cmd)
18623 "Execute CMD, but make sure that the cursor always ends up in a headline.
18624 If not, return to the original position and throw an error."
18625 (interactive)
18626 (let ((pos (point)))
18627 (call-interactively cmd)
18628 (unless (and (bolp) (org-at-heading-p))
18629 (goto-char pos)
18630 (error "Boundary reached while executing %s" cmd))))
18632 (defvar org-self-insert-command-undo-counter 0)
18634 (defvar org-table-auto-blank-field) ; defined in org-table.el
18635 (defvar org-speed-command nil)
18637 (define-obsolete-function-alias
18638 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18640 (defun org-speed-command-activate (keys)
18641 "Hook for activating single-letter speed commands.
18642 `org-speed-commands-default' specifies a minimal command set.
18643 Use `org-speed-commands-user' for further customization."
18644 (when (or (and (bolp) (looking-at org-outline-regexp))
18645 (and (functionp org-use-speed-commands)
18646 (funcall org-use-speed-commands)))
18647 (cdr (assoc keys (append org-speed-commands-user
18648 org-speed-commands-default)))))
18650 (define-obsolete-function-alias
18651 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18653 (defun org-babel-speed-command-activate (keys)
18654 "Hook for activating single-letter code block commands."
18655 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18656 (cdr (assoc keys org-babel-key-bindings))))
18658 (defcustom org-speed-command-hook
18659 '(org-speed-command-default-hook org-babel-speed-command-hook)
18660 "Hook for activating speed commands at strategic locations.
18661 Hook functions are called in sequence until a valid handler is
18662 found.
18664 Each hook takes a single argument, a user-pressed command key
18665 which is also a `self-insert-command' from the global map.
18667 Within the hook, examine the cursor position and the command key
18668 and return nil or a valid handler as appropriate. Handler could
18669 be one of an interactive command, a function, or a form.
18671 Set `org-use-speed-commands' to non-nil value to enable this
18672 hook. The default setting is `org-speed-command-activate'."
18673 :group 'org-structure
18674 :version "24.1"
18675 :type 'hook)
18677 (defun org-self-insert-command (N)
18678 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18679 If the cursor is in a table looking at whitespace, the whitespace is
18680 overwritten, and the table is not marked as requiring realignment."
18681 (interactive "p")
18682 (org-check-before-invisible-edit 'insert)
18683 (cond
18684 ((and org-use-speed-commands
18685 (setq org-speed-command
18686 (run-hook-with-args-until-success
18687 'org-speed-command-hook (this-command-keys))))
18688 (cond
18689 ((commandp org-speed-command)
18690 (setq this-command org-speed-command)
18691 (call-interactively org-speed-command))
18692 ((functionp org-speed-command)
18693 (funcall org-speed-command))
18694 ((and org-speed-command (listp org-speed-command))
18695 (eval org-speed-command))
18696 (t (let (org-use-speed-commands)
18697 (call-interactively 'org-self-insert-command)))))
18698 ((and
18699 (org-table-p)
18700 (progn
18701 ;; check if we blank the field, and if that triggers align
18702 (and (featurep 'org-table) org-table-auto-blank-field
18703 (member last-command
18704 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18705 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18706 ;; got extra space, this field does not determine column width
18707 (let (org-table-may-need-update) (org-table-blank-field))
18708 ;; no extra space, this field may determine column width
18709 (org-table-blank-field)))
18711 (eq N 1)
18712 (looking-at "[^|\n]* |"))
18713 (let (org-table-may-need-update)
18714 (goto-char (1- (match-end 0)))
18715 (backward-delete-char 1)
18716 (goto-char (match-beginning 0))
18717 (self-insert-command N)))
18719 (setq org-table-may-need-update t)
18720 (self-insert-command N)
18721 (org-fix-tags-on-the-fly)
18722 (if org-self-insert-cluster-for-undo
18723 (if (not (eq last-command 'org-self-insert-command))
18724 (setq org-self-insert-command-undo-counter 1)
18725 (if (>= org-self-insert-command-undo-counter 20)
18726 (setq org-self-insert-command-undo-counter 1)
18727 (and (> org-self-insert-command-undo-counter 0)
18728 buffer-undo-list (listp buffer-undo-list)
18729 (not (cadr buffer-undo-list)) ; remove nil entry
18730 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18731 (setq org-self-insert-command-undo-counter
18732 (1+ org-self-insert-command-undo-counter))))))))
18734 (defun org-check-before-invisible-edit (kind)
18735 "Check is editing if kind KIND would be dangerous with invisible text around.
18736 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18737 ;; First, try to get out of here as quickly as possible, to reduce overhead
18738 (if (and org-catch-invisible-edits
18739 (or (not (boundp 'visible-mode)) (not visible-mode))
18740 (or (get-char-property (point) 'invisible)
18741 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18742 ;; OK, we need to take a closer look
18743 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18744 (invisible-before-point (if (bobp) nil (get-char-property
18745 (1- (point)) 'invisible)))
18746 (border-and-ok-direction
18748 ;; Check if we are acting predictably before invisible text
18749 (and invisible-at-point (not invisible-before-point)
18750 (memq kind '(insert delete-backward)))
18751 ;; Check if we are acting predictably after invisible text
18752 ;; This works not well, and I have turned it off. It seems
18753 ;; better to always show and stop after invisible text.
18754 ;; (and (not invisible-at-point) invisible-before-point
18755 ;; (memq kind '(insert delete)))
18757 (when (or (memq invisible-at-point '(outline org-hide-block t))
18758 (memq invisible-before-point '(outline org-hide-block t)))
18759 (if (eq org-catch-invisible-edits 'error)
18760 (error "Editing in invisible areas is prohibited - make visible first"))
18761 (if (and org-custom-properties-overlays
18762 (y-or-n-p "Display invisible properties in this buffer? "))
18763 (org-toggle-custom-properties-visibility)
18764 ;; Make the area visible
18765 (save-excursion
18766 (if invisible-before-point
18767 (goto-char (previous-single-char-property-change
18768 (point) 'invisible)))
18769 (org-cycle))
18770 (cond
18771 ((eq org-catch-invisible-edits 'show)
18772 ;; That's it, we do the edit after showing
18773 (message
18774 "Unfolding invisible region around point before editing")
18775 (sit-for 1))
18776 ((and (eq org-catch-invisible-edits 'smart)
18777 border-and-ok-direction)
18778 (message "Unfolding invisible region around point before editing"))
18780 ;; Don't do the edit, make the user repeat it in full visibility
18781 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18783 (defun org-fix-tags-on-the-fly ()
18784 (when (and (equal (char-after (point-at-bol)) ?*)
18785 (org-at-heading-p))
18786 (org-align-tags-here org-tags-column)))
18788 (defun org-delete-backward-char (N)
18789 "Like `delete-backward-char', insert whitespace at field end in tables.
18790 When deleting backwards, in tables this function will insert whitespace in
18791 front of the next \"|\" separator, to keep the table aligned. The table will
18792 still be marked for re-alignment if the field did fill the entire column,
18793 because, in this case the deletion might narrow the column."
18794 (interactive "p")
18795 (save-match-data
18796 (org-check-before-invisible-edit 'delete-backward)
18797 (if (and (org-table-p)
18798 (eq N 1)
18799 (string-match "|" (buffer-substring (point-at-bol) (point)))
18800 (looking-at ".*?|"))
18801 (let ((pos (point))
18802 (noalign (looking-at "[^|\n\r]* |"))
18803 (c org-table-may-need-update))
18804 (backward-delete-char N)
18805 (if (not overwrite-mode)
18806 (progn
18807 (skip-chars-forward "^|")
18808 (insert " ")
18809 (goto-char (1- pos))))
18810 ;; noalign: if there were two spaces at the end, this field
18811 ;; does not determine the width of the column.
18812 (if noalign (setq org-table-may-need-update c)))
18813 (backward-delete-char N)
18814 (org-fix-tags-on-the-fly))))
18816 (defun org-delete-char (N)
18817 "Like `delete-char', but insert whitespace at field end in tables.
18818 When deleting characters, in tables this function will insert whitespace in
18819 front of the next \"|\" separator, to keep the table aligned. The table will
18820 still be marked for re-alignment if the field did fill the entire column,
18821 because, in this case the deletion might narrow the column."
18822 (interactive "p")
18823 (save-match-data
18824 (org-check-before-invisible-edit 'delete)
18825 (if (and (org-table-p)
18826 (not (bolp))
18827 (not (= (char-after) ?|))
18828 (eq N 1))
18829 (if (looking-at ".*?|")
18830 (let ((pos (point))
18831 (noalign (looking-at "[^|\n\r]* |"))
18832 (c org-table-may-need-update))
18833 (replace-match (concat
18834 (substring (match-string 0) 1 -1)
18835 " |"))
18836 (goto-char pos)
18837 ;; noalign: if there were two spaces at the end, this field
18838 ;; does not determine the width of the column.
18839 (if noalign (setq org-table-may-need-update c)))
18840 (delete-char N))
18841 (delete-char N)
18842 (org-fix-tags-on-the-fly))))
18844 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18845 (put 'org-self-insert-command 'delete-selection t)
18846 (put 'orgtbl-self-insert-command 'delete-selection t)
18847 (put 'org-delete-char 'delete-selection 'supersede)
18848 (put 'org-delete-backward-char 'delete-selection 'supersede)
18849 (put 'org-yank 'delete-selection 'yank)
18851 ;; Make `flyspell-mode' delay after some commands
18852 (put 'org-self-insert-command 'flyspell-delayed t)
18853 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18854 (put 'org-delete-char 'flyspell-delayed t)
18855 (put 'org-delete-backward-char 'flyspell-delayed t)
18857 ;; Make pabbrev-mode expand after org-mode commands
18858 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18859 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18861 ;; How to do this: Measure non-white length of current string
18862 ;; If equal to column width, we should realign.
18864 (defun org-remap (map &rest commands)
18865 "In MAP, remap the functions given in COMMANDS.
18866 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18867 (let (new old)
18868 (while commands
18869 (setq old (pop commands) new (pop commands))
18870 (if (fboundp 'command-remapping)
18871 (org-defkey map (vector 'remap old) new)
18872 (substitute-key-definition old new map global-map)))))
18874 (when (eq org-enable-table-editor 'optimized)
18875 ;; If the user wants maximum table support, we need to hijack
18876 ;; some standard editing functions
18877 (org-remap org-mode-map
18878 'self-insert-command 'org-self-insert-command
18879 'delete-char 'org-delete-char
18880 'delete-backward-char 'org-delete-backward-char)
18881 (org-defkey org-mode-map "|" 'org-force-self-insert))
18883 (defvar org-ctrl-c-ctrl-c-hook nil
18884 "Hook for functions attaching themselves to `C-c C-c'.
18886 This can be used to add additional functionality to the C-c C-c
18887 key which executes context-dependent commands. This hook is run
18888 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18889 run after the last test.
18891 Each function will be called with no arguments. The function
18892 must check if the context is appropriate for it to act. If yes,
18893 it should do its thing and then return a non-nil value. If the
18894 context is wrong, just do nothing and return nil.")
18896 (defvar org-ctrl-c-ctrl-c-final-hook nil
18897 "Hook for functions attaching themselves to `C-c C-c'.
18899 This can be used to add additional functionality to the C-c C-c
18900 key which executes context-dependent commands. This hook is run
18901 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18902 before the first test.
18904 Each function will be called with no arguments. The function
18905 must check if the context is appropriate for it to act. If yes,
18906 it should do its thing and then return a non-nil value. If the
18907 context is wrong, just do nothing and return nil.")
18909 (defvar org-tab-first-hook nil
18910 "Hook for functions to attach themselves to TAB.
18911 See `org-ctrl-c-ctrl-c-hook' for more information.
18912 This hook runs as the first action when TAB is pressed, even before
18913 `org-cycle' messes around with the `outline-regexp' to cater for
18914 inline tasks and plain list item folding.
18915 If any function in this hook returns t, any other actions that
18916 would have been caused by TAB (such as table field motion or visibility
18917 cycling) will not occur.")
18919 (defvar org-tab-after-check-for-table-hook nil
18920 "Hook for functions to attach themselves to TAB.
18921 See `org-ctrl-c-ctrl-c-hook' for more information.
18922 This hook runs after it has been established that the cursor is not in a
18923 table, but before checking if the cursor is in a headline or if global cycling
18924 should be done.
18925 If any function in this hook returns t, not other actions like visibility
18926 cycling will be done.")
18928 (defvar org-tab-after-check-for-cycling-hook nil
18929 "Hook for functions to attach themselves to TAB.
18930 See `org-ctrl-c-ctrl-c-hook' for more information.
18931 This hook runs after it has been established that not table field motion and
18932 not visibility should be done because of current context. This is probably
18933 the place where a package like yasnippets can hook in.")
18935 (defvar org-tab-before-tab-emulation-hook nil
18936 "Hook for functions to attach themselves to TAB.
18937 See `org-ctrl-c-ctrl-c-hook' for more information.
18938 This hook runs after every other options for TAB have been exhausted, but
18939 before indentation and \t insertion takes place.")
18941 (defvar org-metaleft-hook nil
18942 "Hook for functions attaching themselves to `M-left'.
18943 See `org-ctrl-c-ctrl-c-hook' for more information.")
18944 (defvar org-metaright-hook nil
18945 "Hook for functions attaching themselves to `M-right'.
18946 See `org-ctrl-c-ctrl-c-hook' for more information.")
18947 (defvar org-metaup-hook nil
18948 "Hook for functions attaching themselves to `M-up'.
18949 See `org-ctrl-c-ctrl-c-hook' for more information.")
18950 (defvar org-metadown-hook nil
18951 "Hook for functions attaching themselves to `M-down'.
18952 See `org-ctrl-c-ctrl-c-hook' for more information.")
18953 (defvar org-shiftmetaleft-hook nil
18954 "Hook for functions attaching themselves to `M-S-left'.
18955 See `org-ctrl-c-ctrl-c-hook' for more information.")
18956 (defvar org-shiftmetaright-hook nil
18957 "Hook for functions attaching themselves to `M-S-right'.
18958 See `org-ctrl-c-ctrl-c-hook' for more information.")
18959 (defvar org-shiftmetaup-hook nil
18960 "Hook for functions attaching themselves to `M-S-up'.
18961 See `org-ctrl-c-ctrl-c-hook' for more information.")
18962 (defvar org-shiftmetadown-hook nil
18963 "Hook for functions attaching themselves to `M-S-down'.
18964 See `org-ctrl-c-ctrl-c-hook' for more information.")
18965 (defvar org-metareturn-hook nil
18966 "Hook for functions attaching themselves to `M-RET'.
18967 See `org-ctrl-c-ctrl-c-hook' for more information.")
18968 (defvar org-shiftup-hook nil
18969 "Hook for functions attaching themselves to `S-up'.
18970 See `org-ctrl-c-ctrl-c-hook' for more information.")
18971 (defvar org-shiftup-final-hook nil
18972 "Hook for functions attaching themselves to `S-up'.
18973 This one runs after all other options except shift-select have been excluded.
18974 See `org-ctrl-c-ctrl-c-hook' for more information.")
18975 (defvar org-shiftdown-hook nil
18976 "Hook for functions attaching themselves to `S-down'.
18977 See `org-ctrl-c-ctrl-c-hook' for more information.")
18978 (defvar org-shiftdown-final-hook nil
18979 "Hook for functions attaching themselves to `S-down'.
18980 This one runs after all other options except shift-select have been excluded.
18981 See `org-ctrl-c-ctrl-c-hook' for more information.")
18982 (defvar org-shiftleft-hook nil
18983 "Hook for functions attaching themselves to `S-left'.
18984 See `org-ctrl-c-ctrl-c-hook' for more information.")
18985 (defvar org-shiftleft-final-hook nil
18986 "Hook for functions attaching themselves to `S-left'.
18987 This one runs after all other options except shift-select have been excluded.
18988 See `org-ctrl-c-ctrl-c-hook' for more information.")
18989 (defvar org-shiftright-hook nil
18990 "Hook for functions attaching themselves to `S-right'.
18991 See `org-ctrl-c-ctrl-c-hook' for more information.")
18992 (defvar org-shiftright-final-hook nil
18993 "Hook for functions attaching themselves to `S-right'.
18994 This one runs after all other options except shift-select have been excluded.
18995 See `org-ctrl-c-ctrl-c-hook' for more information.")
18997 (defun org-modifier-cursor-error ()
18998 "Throw an error, a modified cursor command was applied in wrong context."
18999 (error "This command is active in special context like tables, headlines or items"))
19001 (defun org-shiftselect-error ()
19002 "Throw an error because Shift-Cursor command was applied in wrong context."
19003 (if (and (boundp 'shift-select-mode) shift-select-mode)
19004 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19005 (error "This command works only in special context like headlines or timestamps")))
19007 (defun org-call-for-shift-select (cmd)
19008 (let ((this-command-keys-shift-translated t))
19009 (call-interactively cmd)))
19011 (defun org-shifttab (&optional arg)
19012 "Global visibility cycling or move to previous table field.
19013 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19014 on context.
19015 See the individual commands for more information."
19016 (interactive "P")
19017 (cond
19018 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19019 ((integerp arg)
19020 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19021 (message "Content view to level: %d" arg)
19022 (org-content (prefix-numeric-value arg2))
19023 (setq org-cycle-global-status 'overview)))
19024 (t (call-interactively 'org-global-cycle))))
19026 (defun org-shiftmetaleft ()
19027 "Promote subtree or delete table column.
19028 Calls `org-promote-subtree', `org-outdent-item-tree', or
19029 `org-table-delete-column', depending on context. See the
19030 individual commands for more information."
19031 (interactive)
19032 (cond
19033 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19034 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19035 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19036 ((if (not (org-region-active-p)) (org-at-item-p)
19037 (save-excursion (goto-char (region-beginning))
19038 (org-at-item-p)))
19039 (call-interactively 'org-outdent-item-tree))
19040 (t (org-modifier-cursor-error))))
19042 (defun org-shiftmetaright ()
19043 "Demote subtree or insert table column.
19044 Calls `org-demote-subtree', `org-indent-item-tree', or
19045 `org-table-insert-column', depending on context. See the
19046 individual commands for more information."
19047 (interactive)
19048 (cond
19049 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19050 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19051 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19052 ((if (not (org-region-active-p)) (org-at-item-p)
19053 (save-excursion (goto-char (region-beginning))
19054 (org-at-item-p)))
19055 (call-interactively 'org-indent-item-tree))
19056 (t (org-modifier-cursor-error))))
19058 (defun org-shiftmetaup (&optional arg)
19059 "Move subtree up or kill table row.
19060 Calls `org-move-subtree-up' or `org-table-kill-row' or
19061 `org-move-item-up' or `org-timestamp-up', depending on context.
19062 See the individual commands for more information."
19063 (interactive "P")
19064 (cond
19065 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19066 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19067 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19068 ((org-at-item-p) (call-interactively 'org-move-item-up))
19069 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19070 (call-interactively 'org-timestamp-up)))
19071 (t (org-modifier-cursor-error))))
19073 (defun org-shiftmetadown (&optional arg)
19074 "Move subtree down or insert table row.
19075 Calls `org-move-subtree-down' or `org-table-insert-row' or
19076 `org-move-item-down' or `org-timestamp-up', depending on context.
19077 See the individual commands for more information."
19078 (interactive "P")
19079 (cond
19080 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19081 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19082 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19083 ((org-at-item-p) (call-interactively 'org-move-item-down))
19084 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19085 (call-interactively 'org-timestamp-down)))
19086 (t (org-modifier-cursor-error))))
19088 (defsubst org-hidden-tree-error ()
19089 (error
19090 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19092 (defun org-metaleft (&optional arg)
19093 "Promote heading or move table column to left.
19094 Calls `org-do-promote' or `org-table-move-column', depending on context.
19095 With no specific context, calls the Emacs default `backward-word'.
19096 See the individual commands for more information."
19097 (interactive "P")
19098 (cond
19099 ((run-hook-with-args-until-success 'org-metaleft-hook))
19100 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19101 ((org-with-limited-levels
19102 (or (org-at-heading-p)
19103 (and (org-region-active-p)
19104 (save-excursion
19105 (goto-char (region-beginning))
19106 (org-at-heading-p)))))
19107 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19108 (call-interactively 'org-do-promote))
19109 ;; At an inline task.
19110 ((org-at-heading-p)
19111 (call-interactively 'org-inlinetask-promote))
19112 ((or (org-at-item-p)
19113 (and (org-region-active-p)
19114 (save-excursion
19115 (goto-char (region-beginning))
19116 (org-at-item-p))))
19117 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19118 (call-interactively 'org-outdent-item))
19119 (t (call-interactively 'backward-word))))
19121 (defun org-metaright (&optional arg)
19122 "Demote a subtree, a list item or move table column to right.
19123 In front of a drawer or a block keyword, indent it correctly.
19124 With no specific context, calls the Emacs default `forward-word'.
19125 See the individual commands for more information."
19126 (interactive "P")
19127 (cond
19128 ((run-hook-with-args-until-success 'org-metaright-hook))
19129 ((org-at-table-p) (call-interactively 'org-table-move-column))
19130 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19131 ((org-at-block-p) (call-interactively 'org-indent-block))
19132 ((org-with-limited-levels
19133 (or (org-at-heading-p)
19134 (and (org-region-active-p)
19135 (save-excursion
19136 (goto-char (region-beginning))
19137 (org-at-heading-p)))))
19138 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19139 (call-interactively 'org-do-demote))
19140 ;; At an inline task.
19141 ((org-at-heading-p)
19142 (call-interactively 'org-inlinetask-demote))
19143 ((or (org-at-item-p)
19144 (and (org-region-active-p)
19145 (save-excursion
19146 (goto-char (region-beginning))
19147 (org-at-item-p))))
19148 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19149 (call-interactively 'org-indent-item))
19150 (t (call-interactively 'forward-word))))
19152 (defun org-check-for-hidden (what)
19153 "Check if there are hidden headlines/items in the current visual line.
19154 WHAT can be either `headlines' or `items'. If the current line is
19155 an outline or item heading and it has a folded subtree below it,
19156 this function returns t, nil otherwise."
19157 (let ((re (cond
19158 ((eq what 'headlines) org-outline-regexp-bol)
19159 ((eq what 'items) (org-item-beginning-re))
19160 (t (error "This should not happen"))))
19161 beg end)
19162 (save-excursion
19163 (catch 'exit
19164 (unless (org-region-active-p)
19165 (setq beg (point-at-bol))
19166 (beginning-of-line 2)
19167 (while (and (not (eobp)) ;; this is like `next-line'
19168 (get-char-property (1- (point)) 'invisible))
19169 (beginning-of-line 2))
19170 (setq end (point))
19171 (goto-char beg)
19172 (goto-char (point-at-eol))
19173 (setq end (max end (point)))
19174 (while (re-search-forward re end t)
19175 (if (get-char-property (match-beginning 0) 'invisible)
19176 (throw 'exit t))))
19177 nil))))
19179 (defun org-metaup (&optional arg)
19180 "Move subtree up or move table row up.
19181 Calls `org-move-subtree-up' or `org-table-move-row' or
19182 `org-move-item-up', depending on context. See the individual commands
19183 for more information."
19184 (interactive "P")
19185 (cond
19186 ((run-hook-with-args-until-success 'org-metaup-hook))
19187 ((org-region-active-p)
19188 (let* ((a (min (region-beginning) (region-end)))
19189 (b (1- (max (region-beginning) (region-end))))
19190 (c (save-excursion (goto-char a)
19191 (move-beginning-of-line 0)))
19192 (d (save-excursion (goto-char a)
19193 (move-end-of-line 0) (point))))
19194 (transpose-regions a b c d)
19195 (goto-char c)))
19196 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19197 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19198 ((org-at-item-p) (call-interactively 'org-move-item-up))
19199 (t (org-drag-element-backward))))
19201 (defun org-metadown (&optional arg)
19202 "Move subtree down or move table row down.
19203 Calls `org-move-subtree-down' or `org-table-move-row' or
19204 `org-move-item-down', depending on context. See the individual
19205 commands for more information."
19206 (interactive "P")
19207 (cond
19208 ((run-hook-with-args-until-success 'org-metadown-hook))
19209 ((org-region-active-p)
19210 (let* ((a (min (region-beginning) (region-end)))
19211 (b (max (region-beginning) (region-end)))
19212 (c (save-excursion (goto-char b)
19213 (move-beginning-of-line 1)))
19214 (d (save-excursion (goto-char b)
19215 (move-end-of-line 1) (1+ (point)))))
19216 (transpose-regions a b c d)
19217 (goto-char d)))
19218 ((org-at-table-p) (call-interactively 'org-table-move-row))
19219 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19220 ((org-at-item-p) (call-interactively 'org-move-item-down))
19221 (t (org-drag-element-forward))))
19223 (defun org-shiftup (&optional arg)
19224 "Increase item in timestamp or increase priority of current headline.
19225 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19226 depending on context. See the individual commands for more information."
19227 (interactive "P")
19228 (cond
19229 ((run-hook-with-args-until-success 'org-shiftup-hook))
19230 ((and org-support-shift-select (org-region-active-p))
19231 (org-call-for-shift-select 'previous-line))
19232 ((org-at-timestamp-p t)
19233 (call-interactively (if org-edit-timestamp-down-means-later
19234 'org-timestamp-down 'org-timestamp-up)))
19235 ((and (not (eq org-support-shift-select 'always))
19236 org-enable-priority-commands
19237 (org-at-heading-p))
19238 (call-interactively 'org-priority-up))
19239 ((and (not org-support-shift-select) (org-at-item-p))
19240 (call-interactively 'org-previous-item))
19241 ((org-clocktable-try-shift 'up arg))
19242 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19243 (org-support-shift-select
19244 (org-call-for-shift-select 'previous-line))
19245 (t (org-shiftselect-error))))
19247 (defun org-shiftdown (&optional arg)
19248 "Decrease item in timestamp or decrease priority of current headline.
19249 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19250 depending on context. See the individual commands for more information."
19251 (interactive "P")
19252 (cond
19253 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19254 ((and org-support-shift-select (org-region-active-p))
19255 (org-call-for-shift-select 'next-line))
19256 ((org-at-timestamp-p t)
19257 (call-interactively (if org-edit-timestamp-down-means-later
19258 'org-timestamp-up 'org-timestamp-down)))
19259 ((and (not (eq org-support-shift-select 'always))
19260 org-enable-priority-commands
19261 (org-at-heading-p))
19262 (call-interactively 'org-priority-down))
19263 ((and (not org-support-shift-select) (org-at-item-p))
19264 (call-interactively 'org-next-item))
19265 ((org-clocktable-try-shift 'down arg))
19266 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19267 (org-support-shift-select
19268 (org-call-for-shift-select 'next-line))
19269 (t (org-shiftselect-error))))
19271 (defun org-shiftright (&optional arg)
19272 "Cycle the thing at point or in the current line, depending on context.
19273 Depending on context, this does one of the following:
19275 - switch a timestamp at point one day into the future
19276 - on a headline, switch to the next TODO keyword.
19277 - on an item, switch entire list to the next bullet type
19278 - on a property line, switch to the next allowed value
19279 - on a clocktable definition line, move time block into the future"
19280 (interactive "P")
19281 (cond
19282 ((run-hook-with-args-until-success 'org-shiftright-hook))
19283 ((and org-support-shift-select (org-region-active-p))
19284 (org-call-for-shift-select 'forward-char))
19285 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19286 ((and (not (eq org-support-shift-select 'always))
19287 (org-at-heading-p))
19288 (let ((org-inhibit-logging
19289 (not org-treat-S-cursor-todo-selection-as-state-change))
19290 (org-inhibit-blocking
19291 (not org-treat-S-cursor-todo-selection-as-state-change)))
19292 (org-call-with-arg 'org-todo 'right)))
19293 ((or (and org-support-shift-select
19294 (not (eq org-support-shift-select 'always))
19295 (org-at-item-bullet-p))
19296 (and (not org-support-shift-select) (org-at-item-p)))
19297 (org-call-with-arg 'org-cycle-list-bullet nil))
19298 ((and (not (eq org-support-shift-select 'always))
19299 (org-at-property-p))
19300 (call-interactively 'org-property-next-allowed-value))
19301 ((org-clocktable-try-shift 'right arg))
19302 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19303 (org-support-shift-select
19304 (org-call-for-shift-select 'forward-char))
19305 (t (org-shiftselect-error))))
19307 (defun org-shiftleft (&optional arg)
19308 "Cycle the thing at point or in the current line, depending on context.
19309 Depending on context, this does one of the following:
19311 - switch a timestamp at point one day into the past
19312 - on a headline, switch to the previous TODO keyword.
19313 - on an item, switch entire list to the previous bullet type
19314 - on a property line, switch to the previous allowed value
19315 - on a clocktable definition line, move time block into the past"
19316 (interactive "P")
19317 (cond
19318 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19319 ((and org-support-shift-select (org-region-active-p))
19320 (org-call-for-shift-select 'backward-char))
19321 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19322 ((and (not (eq org-support-shift-select 'always))
19323 (org-at-heading-p))
19324 (let ((org-inhibit-logging
19325 (not org-treat-S-cursor-todo-selection-as-state-change))
19326 (org-inhibit-blocking
19327 (not org-treat-S-cursor-todo-selection-as-state-change)))
19328 (org-call-with-arg 'org-todo 'left)))
19329 ((or (and org-support-shift-select
19330 (not (eq org-support-shift-select 'always))
19331 (org-at-item-bullet-p))
19332 (and (not org-support-shift-select) (org-at-item-p)))
19333 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19334 ((and (not (eq org-support-shift-select 'always))
19335 (org-at-property-p))
19336 (call-interactively 'org-property-previous-allowed-value))
19337 ((org-clocktable-try-shift 'left arg))
19338 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19339 (org-support-shift-select
19340 (org-call-for-shift-select 'backward-char))
19341 (t (org-shiftselect-error))))
19343 (defun org-shiftcontrolright ()
19344 "Switch to next TODO set."
19345 (interactive)
19346 (cond
19347 ((and org-support-shift-select (org-region-active-p))
19348 (org-call-for-shift-select 'forward-word))
19349 ((and (not (eq org-support-shift-select 'always))
19350 (org-at-heading-p))
19351 (org-call-with-arg 'org-todo 'nextset))
19352 (org-support-shift-select
19353 (org-call-for-shift-select 'forward-word))
19354 (t (org-shiftselect-error))))
19356 (defun org-shiftcontrolleft ()
19357 "Switch to previous TODO set."
19358 (interactive)
19359 (cond
19360 ((and org-support-shift-select (org-region-active-p))
19361 (org-call-for-shift-select 'backward-word))
19362 ((and (not (eq org-support-shift-select 'always))
19363 (org-at-heading-p))
19364 (org-call-with-arg 'org-todo 'previousset))
19365 (org-support-shift-select
19366 (org-call-for-shift-select 'backward-word))
19367 (t (org-shiftselect-error))))
19369 (defun org-shiftcontrolup (&optional n)
19370 "Change timestamps synchronously up in CLOCK log lines.
19371 Optional argument N tells to change by that many units."
19372 (interactive "P")
19373 (cond ((and (not org-support-shift-select)
19374 (org-at-clock-log-p)
19375 (org-at-timestamp-p t))
19376 (org-clock-timestamps-up n))
19377 (t (org-shiftselect-error))))
19379 (defun org-shiftcontroldown (&optional n)
19380 "Change timestamps synchronously down in CLOCK log lines.
19381 Optional argument N tells to change by that many units."
19382 (interactive "P")
19383 (cond ((and (not org-support-shift-select)
19384 (org-at-clock-log-p)
19385 (org-at-timestamp-p t))
19386 (org-clock-timestamps-down n))
19387 (t (org-shiftselect-error))))
19389 (defun org-ctrl-c-ret ()
19390 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19391 (interactive)
19392 (cond
19393 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19394 (t (call-interactively 'org-insert-heading))))
19396 (defun org-find-visible ()
19397 (let ((s (point)))
19398 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19399 (get-char-property s 'invisible)))
19401 (defun org-find-invisible ()
19402 (let ((s (point)))
19403 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19404 (not (get-char-property s 'invisible))))
19407 (defun org-copy-visible (beg end)
19408 "Copy the visible parts of the region."
19409 (interactive "r")
19410 (let (snippets s)
19411 (save-excursion
19412 (save-restriction
19413 (narrow-to-region beg end)
19414 (setq s (goto-char (point-min)))
19415 (while (not (= (point) (point-max)))
19416 (goto-char (org-find-invisible))
19417 (push (buffer-substring s (point)) snippets)
19418 (setq s (goto-char (org-find-visible))))))
19419 (kill-new (apply 'concat (nreverse snippets)))))
19421 (defun org-copy-special ()
19422 "Copy region in table or copy current subtree.
19423 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19424 See the individual commands for more information."
19425 (interactive)
19426 (call-interactively
19427 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19429 (defun org-cut-special ()
19430 "Cut region in table or cut current subtree.
19431 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19432 See the individual commands for more information."
19433 (interactive)
19434 (call-interactively
19435 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19437 (defun org-paste-special (arg)
19438 "Paste rectangular region into table, or past subtree relative to level.
19439 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19440 See the individual commands for more information."
19441 (interactive "P")
19442 (if (org-at-table-p)
19443 (org-table-paste-rectangle)
19444 (org-paste-subtree arg)))
19446 (defsubst org-in-fixed-width-region-p ()
19447 "Is point in a fixed-width region?"
19448 (save-match-data
19449 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19451 (defun org-edit-special (&optional arg)
19452 "Call a special editor for the element at point.
19453 When at a table, call the formula editor with `org-table-edit-formulas'.
19454 When in a source code block, call `org-edit-src-code'.
19455 When in a fixed-width region, call `org-edit-fixed-width-region'.
19456 When at an #+INCLUDE keyword, visit the included file.
19457 On a link, call `ffap' to visit the link at point.
19458 Otherwise, return a user error."
19459 (interactive)
19460 (let ((element (org-element-at-point)))
19461 (case (org-element-type element)
19462 (src-block
19463 (if (not arg) (org-edit-src-code)
19464 (let* ((info (org-babel-get-src-block-info))
19465 (lang (nth 0 info))
19466 (params (nth 2 info))
19467 (session (cdr (assq :session params))))
19468 (if (not session) (org-edit-src-code)
19469 ;; At a src-block with a session and function called with
19470 ;; an ARG: switch to the buffer related to the inferior
19471 ;; process.
19472 (funcall (intern (concat "org-babel-prep-session:" lang))
19473 session params)))))
19474 (keyword
19475 (if (equal (org-element-property :key element) "INCLUDE")
19476 (find-file
19477 (org-remove-double-quotes
19478 (car (org-split-string (org-element-property :value element)))))
19479 (user-error "No special environment to edit here")))
19480 (table
19481 (if (eq (org-element-property :type element) 'table.el)
19482 (org-edit-src-code)
19483 (call-interactively 'org-table-edit-formulas)))
19484 ;; Only Org tables contain `table-row' type elements.
19485 (table-row (call-interactively 'org-table-edit-formulas))
19486 ((example-block export-block) (org-edit-src-code))
19487 (fixed-width (org-edit-fixed-width-region))
19488 (otherwise
19489 ;; No notable element at point. Though, we may be at a link,
19490 ;; which is an object. Thus, scan deeper.
19491 (if (eq (org-element-type (org-element-context element)) 'link)
19492 (call-interactively 'ffap)
19493 (user-error "No special environment to edit here"))))))
19495 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19496 (defun org-ctrl-c-ctrl-c (&optional arg)
19497 "Set tags in headline, or update according to changed information at point.
19499 This command does many different things, depending on context:
19501 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19502 this is what we do.
19504 - If the cursor is on a statistics cookie, update it.
19506 - If the cursor is in a headline, prompt for tags and insert them
19507 into the current line, aligned to `org-tags-column'. When called
19508 with prefix arg, realign all tags in the current buffer.
19510 - If the cursor is in one of the special #+KEYWORD lines, this
19511 triggers scanning the buffer for these lines and updating the
19512 information.
19514 - If the cursor is inside a table, realign the table. This command
19515 works even if the automatic table editor has been turned off.
19517 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19518 the entire table.
19520 - If the cursor is at a footnote reference or definition, jump to
19521 the corresponding definition or references, respectively.
19523 - If the cursor is a the beginning of a dynamic block, update it.
19525 - If the current buffer is a capture buffer, close note and file it.
19527 - If the cursor is on a <<<target>>>, update radio targets and
19528 corresponding links in this buffer.
19530 - If the cursor is on a numbered item in a plain list, renumber the
19531 ordered list.
19533 - If the cursor is on a checkbox, toggle it.
19535 - If the cursor is on a code block, evaluate it. The variable
19536 `org-confirm-babel-evaluate' can be used to control prompting
19537 before code block evaluation, by default every code block
19538 evaluation requires confirmation. Code block evaluation can be
19539 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19540 (interactive "P")
19541 (let ((org-enable-table-editor t))
19542 (cond
19543 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19544 org-occur-highlights
19545 org-latex-fragment-image-overlays)
19546 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19547 (org-remove-occur-highlights)
19548 (org-remove-latex-fragment-image-overlays)
19549 (message "Temporary highlights/overlays removed from current buffer"))
19550 ((and (local-variable-p 'org-finish-function (current-buffer))
19551 (fboundp org-finish-function))
19552 (funcall org-finish-function))
19553 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19554 ((org-in-regexp org-ts-regexp-both)
19555 (org-timestamp-change 0 'day))
19556 ((or (looking-at org-property-start-re)
19557 (org-at-property-p))
19558 (call-interactively 'org-property-action))
19559 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19560 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19561 (or (org-at-heading-p) (org-at-item-p)))
19562 (call-interactively 'org-update-statistics-cookies))
19563 ((org-at-heading-p) (call-interactively 'org-set-tags))
19564 ((org-at-table.el-p)
19565 (message "Use C-c ' to edit table.el tables"))
19566 ((org-at-table-p)
19567 (org-table-maybe-eval-formula)
19568 (if arg
19569 (call-interactively 'org-table-recalculate)
19570 (org-table-maybe-recalculate-line))
19571 (call-interactively 'org-table-align)
19572 (orgtbl-send-table 'maybe))
19573 ((or (org-footnote-at-reference-p)
19574 (org-footnote-at-definition-p))
19575 (call-interactively 'org-footnote-action))
19576 ((org-at-item-checkbox-p)
19577 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19578 ;; list only if at top item.
19579 (let* ((cbox (match-string 1))
19580 (struct (org-list-struct))
19581 (old-struct (copy-tree struct))
19582 (parents (org-list-parents-alist struct))
19583 (orderedp (org-entry-get nil "ORDERED"))
19584 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19585 block-item)
19586 ;; Use a light version of `org-toggle-checkbox' to avoid
19587 ;; computing list structure twice.
19588 (let ((new-box (cond
19589 ((equal arg '(16)) "[-]")
19590 ((equal arg '(4)) nil)
19591 ((equal "[X]" cbox) "[ ]")
19592 (t "[X]"))))
19593 (if (and firstp arg)
19594 ;; If at first item of sub-list, remove check-box from
19595 ;; every item at the same level.
19596 (mapc
19597 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19598 (org-list-get-all-items
19599 (point-at-bol) struct (org-list-prevs-alist struct)))
19600 (org-list-set-checkbox (point-at-bol) struct new-box)))
19601 ;; Replicate `org-list-write-struct', while grabbing a return
19602 ;; value from `org-list-struct-fix-box'.
19603 (org-list-struct-fix-ind struct parents 2)
19604 (org-list-struct-fix-item-end struct)
19605 (let ((prevs (org-list-prevs-alist struct)))
19606 (org-list-struct-fix-bul struct prevs)
19607 (org-list-struct-fix-ind struct parents)
19608 (setq block-item
19609 (org-list-struct-fix-box struct parents prevs orderedp)))
19610 (if (equal struct old-struct)
19611 (user-error "Cannot toggle this checkbox (unchecked subitems?)")
19612 (org-list-struct-apply-struct struct old-struct)
19613 (org-update-checkbox-count-maybe))
19614 (when block-item
19615 (message
19616 "Checkboxes were removed due to unchecked box at line %d"
19617 (org-current-line block-item)))
19618 (when firstp (org-list-send-list 'maybe))))
19619 ((org-at-item-p)
19620 ;; Cursor at an item: repair list. Do checkbox related actions
19621 ;; only if function was called with an argument. Send list only
19622 ;; if at top item.
19623 (let* ((struct (org-list-struct))
19624 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19625 old-struct)
19626 (when arg
19627 (setq old-struct (copy-tree struct))
19628 (if firstp
19629 ;; If at first item of sub-list, add check-box to every
19630 ;; item at the same level.
19631 (mapc
19632 (lambda (pos)
19633 (unless (org-list-get-checkbox pos struct)
19634 (org-list-set-checkbox pos struct "[ ]")))
19635 (org-list-get-all-items
19636 (point-at-bol) struct (org-list-prevs-alist struct)))
19637 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19638 (org-list-write-struct
19639 struct (org-list-parents-alist struct) old-struct)
19640 (when arg (org-update-checkbox-count-maybe))
19641 (when firstp (org-list-send-list 'maybe))))
19642 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19643 ;; Dynamic block
19644 (beginning-of-line 1)
19645 (save-excursion (org-update-dblock)))
19646 ((save-excursion
19647 (let ((case-fold-search t))
19648 (beginning-of-line 1)
19649 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19650 (cond
19651 ((or (equal (match-string 1) "TBLFM")
19652 (equal (match-string 1) "tblfm"))
19653 ;; Recalculate the table before this line
19654 (save-excursion
19655 (beginning-of-line 1)
19656 (skip-chars-backward " \r\n\t")
19657 (if (org-at-table-p)
19658 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19660 (let ((org-inhibit-startup-visibility-stuff t)
19661 (org-startup-align-all-tables nil))
19662 (when (boundp 'org-table-coordinate-overlays)
19663 (mapc 'delete-overlay org-table-coordinate-overlays)
19664 (setq org-table-coordinate-overlays nil))
19665 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19666 (message "Local setup has been refreshed"))))
19667 ((org-clock-update-time-maybe))
19669 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19670 (error "C-c C-c can do nothing useful at this location"))))))
19672 (defun org-mode-restart ()
19673 "Restart Org-mode, to scan again for special lines.
19674 Also updates the keyword regular expressions."
19675 (interactive)
19676 (org-mode)
19677 (message "Org-mode restarted"))
19679 (defun org-kill-note-or-show-branches ()
19680 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19681 (interactive)
19682 (if (not org-finish-function)
19683 (progn
19684 (hide-subtree)
19685 (call-interactively 'show-branches))
19686 (let ((org-note-abort t))
19687 (funcall org-finish-function))))
19689 (defun org-return (&optional indent)
19690 "Goto next table row or insert a newline.
19691 Calls `org-table-next-row' or `newline', depending on context.
19692 See the individual commands for more information."
19693 (interactive)
19694 (let (org-ts-what)
19695 (cond
19696 ((or (bobp) (org-in-src-block-p))
19697 (if indent (newline-and-indent) (newline)))
19698 ((org-at-table-p)
19699 (org-table-justify-field-maybe)
19700 (call-interactively 'org-table-next-row))
19701 ;; when `newline-and-indent' is called within a list, make sure
19702 ;; text moved stays inside the item.
19703 ((and (org-in-item-p) indent)
19704 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19705 (progn
19706 (save-match-data (newline))
19707 (org-indent-line-to (length (match-string 0))))
19708 (let ((ind (org-get-indentation)))
19709 (newline)
19710 (if (org-looking-back org-list-end-re)
19711 (org-indent-line)
19712 (org-indent-line-to ind)))))
19713 ((and org-return-follows-link
19714 (org-at-timestamp-p t)
19715 (not (eq org-ts-what 'after)))
19716 (org-follow-timestamp-link))
19717 ((and org-return-follows-link
19718 (let ((tprop (get-text-property (point) 'face)))
19719 (or (eq tprop 'org-link)
19720 (and (listp tprop) (memq 'org-link tprop)))))
19721 (call-interactively 'org-open-at-point))
19722 ((and (org-at-heading-p)
19723 (looking-at
19724 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19725 (org-show-entry)
19726 (end-of-line 1)
19727 (newline))
19728 (t (if indent (newline-and-indent) (newline))))))
19730 (defun org-return-indent ()
19731 "Goto next table row or insert a newline and indent.
19732 Calls `org-table-next-row' or `newline-and-indent', depending on
19733 context. See the individual commands for more information."
19734 (interactive)
19735 (org-return t))
19737 (defun org-ctrl-c-star ()
19738 "Compute table, or change heading status of lines.
19739 Calls `org-table-recalculate' or `org-toggle-heading',
19740 depending on context."
19741 (interactive)
19742 (cond
19743 ((org-at-table-p)
19744 (call-interactively 'org-table-recalculate))
19746 ;; Convert all lines in region to list items
19747 (call-interactively 'org-toggle-heading))))
19749 (defun org-ctrl-c-minus ()
19750 "Insert separator line in table or modify bullet status of line.
19751 Also turns a plain line or a region of lines into list items.
19752 Calls `org-table-insert-hline', `org-toggle-item', or
19753 `org-cycle-list-bullet', depending on context."
19754 (interactive)
19755 (cond
19756 ((org-at-table-p)
19757 (call-interactively 'org-table-insert-hline))
19758 ((org-region-active-p)
19759 (call-interactively 'org-toggle-item))
19760 ((org-in-item-p)
19761 (call-interactively 'org-cycle-list-bullet))
19763 (call-interactively 'org-toggle-item))))
19765 (defun org-toggle-item (arg)
19766 "Convert headings or normal lines to items, items to normal lines.
19767 If there is no active region, only the current line is considered.
19769 If the first non blank line in the region is an headline, convert
19770 all headlines to items, shifting text accordingly.
19772 If it is an item, convert all items to normal lines.
19774 If it is normal text, change region into an item. With a prefix
19775 argument ARG, change each line in region into an item."
19776 (interactive "P")
19777 (let ((shift-text
19778 (function
19779 ;; Shift text in current section to IND, from point to END.
19780 ;; The function leaves point to END line.
19781 (lambda (ind end)
19782 (let ((min-i 1000) (end (copy-marker end)))
19783 ;; First determine the minimum indentation (MIN-I) of
19784 ;; the text.
19785 (save-excursion
19786 (catch 'exit
19787 (while (< (point) end)
19788 (let ((i (org-get-indentation)))
19789 (cond
19790 ;; Skip blank lines and inline tasks.
19791 ((looking-at "^[ \t]*$"))
19792 ((looking-at org-outline-regexp-bol))
19793 ;; We can't find less than 0 indentation.
19794 ((zerop i) (throw 'exit (setq min-i 0)))
19795 ((< i min-i) (setq min-i i))))
19796 (forward-line))))
19797 ;; Then indent each line so that a line indented to
19798 ;; MIN-I becomes indented to IND. Ignore blank lines
19799 ;; and inline tasks in the process.
19800 (let ((delta (- ind min-i)))
19801 (while (< (point) end)
19802 (unless (or (looking-at "^[ \t]*$")
19803 (looking-at org-outline-regexp-bol))
19804 (org-indent-line-to (+ (org-get-indentation) delta)))
19805 (forward-line)))))))
19806 (skip-blanks
19807 (function
19808 ;; Return beginning of first non-blank line, starting from
19809 ;; line at POS.
19810 (lambda (pos)
19811 (save-excursion
19812 (goto-char pos)
19813 (skip-chars-forward " \r\t\n")
19814 (point-at-bol)))))
19815 beg end)
19816 ;; Determine boundaries of changes.
19817 (if (org-region-active-p)
19818 (setq beg (funcall skip-blanks (region-beginning))
19819 end (copy-marker (region-end)))
19820 (setq beg (funcall skip-blanks (point-at-bol))
19821 end (copy-marker (point-at-eol))))
19822 ;; Depending on the starting line, choose an action on the text
19823 ;; between BEG and END.
19824 (org-with-limited-levels
19825 (save-excursion
19826 (goto-char beg)
19827 (cond
19828 ;; Case 1. Start at an item: de-itemize. Note that it only
19829 ;; happens when a region is active: `org-ctrl-c-minus'
19830 ;; would call `org-cycle-list-bullet' otherwise.
19831 ((org-at-item-p)
19832 (while (< (point) end)
19833 (when (org-at-item-p)
19834 (skip-chars-forward " \t")
19835 (delete-region (point) (match-end 0)))
19836 (forward-line)))
19837 ;; Case 2. Start at an heading: convert to items.
19838 ((org-at-heading-p)
19839 (let* ((bul (org-list-bullet-string "-"))
19840 (bul-len (length bul))
19841 ;; Indentation of the first heading. It should be
19842 ;; relative to the indentation of its parent, if any.
19843 (start-ind (save-excursion
19844 (cond
19845 ((not org-adapt-indentation) 0)
19846 ((not (outline-previous-heading)) 0)
19847 (t (length (match-string 0))))))
19848 ;; Level of first heading. Further headings will be
19849 ;; compared to it to determine hierarchy in the list.
19850 (ref-level (org-reduced-level (org-outline-level))))
19851 (while (< (point) end)
19852 (let* ((level (org-reduced-level (org-outline-level)))
19853 (delta (max 0 (- level ref-level))))
19854 ;; If current headline is less indented than the first
19855 ;; one, set it as reference, in order to preserve
19856 ;; subtrees.
19857 (when (< level ref-level) (setq ref-level level))
19858 (replace-match bul t t)
19859 (org-indent-line-to (+ start-ind (* delta bul-len)))
19860 ;; Ensure all text down to END (or SECTION-END) belongs
19861 ;; to the newly created item.
19862 (let ((section-end (save-excursion
19863 (or (outline-next-heading) (point)))))
19864 (forward-line)
19865 (funcall shift-text
19866 (+ start-ind (* (1+ delta) bul-len))
19867 (min end section-end)))))))
19868 ;; Case 3. Normal line with ARG: turn each non-item line into
19869 ;; an item.
19870 (arg
19871 (while (< (point) end)
19872 (unless (or (org-at-heading-p) (org-at-item-p))
19873 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19874 (replace-match
19875 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19876 (forward-line)))
19877 ;; Case 4. Normal line without ARG: make the first line of
19878 ;; region an item, and shift indentation of others
19879 ;; lines to set them as item's body.
19880 (t (let* ((bul (org-list-bullet-string "-"))
19881 (bul-len (length bul))
19882 (ref-ind (org-get-indentation)))
19883 (skip-chars-forward " \t")
19884 (insert bul)
19885 (forward-line)
19886 (while (< (point) end)
19887 ;; Ensure that lines less indented than first one
19888 ;; still get included in item body.
19889 (funcall shift-text
19890 (+ ref-ind bul-len)
19891 (min end (save-excursion (or (outline-next-heading)
19892 (point)))))
19893 (forward-line)))))))))
19895 (defun org-toggle-heading (&optional nstars)
19896 "Convert headings to normal text, or items or text to headings.
19897 If there is no active region, only the current line is considered.
19899 With a \\[universal-argument] prefix, convert the whole list at
19900 point into heading.
19902 In a region:
19904 - If the first non blank line is an headline, remove the stars
19905 from all headlines in the region.
19907 - If it is a normal line turn each and every normal line (i.e. not an
19908 heading or an item) in the region into a heading.
19910 - If it is a plain list item, turn all plain list items into headings.
19912 When converting a line into a heading, the number of stars is chosen
19913 such that the lines become children of the current entry. However,
19914 when a prefix argument is given, its value determines the number of
19915 stars to add."
19916 (interactive "P")
19917 (let ((skip-blanks
19918 (function
19919 ;; Return beginning of first non-blank line, starting from
19920 ;; line at POS.
19921 (lambda (pos)
19922 (save-excursion
19923 (goto-char pos)
19924 (while (org-at-comment-p) (forward-line))
19925 (skip-chars-forward " \r\t\n")
19926 (point-at-bol)))))
19927 beg end toggled)
19928 ;; Determine boundaries of changes. If a universal prefix has
19929 ;; been given, put the list in a region. If region ends at a bol,
19930 ;; do not consider the last line to be in the region.
19932 (when (and current-prefix-arg (org-at-item-p))
19933 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19934 (org-mark-element))
19936 (if (org-region-active-p)
19937 (setq beg (funcall skip-blanks (region-beginning))
19938 end (copy-marker (save-excursion
19939 (goto-char (region-end))
19940 (if (bolp) (point) (point-at-eol)))))
19941 (setq beg (funcall skip-blanks (point-at-bol))
19942 end (copy-marker (point-at-eol))))
19943 ;; Ensure inline tasks don't count as headings.
19944 (org-with-limited-levels
19945 (save-excursion
19946 (goto-char beg)
19947 (cond
19948 ;; Case 1. Started at an heading: de-star headings.
19949 ((org-at-heading-p)
19950 (while (< (point) end)
19951 (when (org-at-heading-p t)
19952 (looking-at org-outline-regexp) (replace-match "")
19953 (setq toggled t))
19954 (forward-line)))
19955 ;; Case 2. Started at an item: change items into headlines.
19956 ;; One star will be added by `org-list-to-subtree'.
19957 ((org-at-item-p)
19958 (let* ((stars (make-string
19959 (if nstars
19960 ;; subtract the star that will be added again by
19961 ;; `org-list-to-subtree'
19962 (1- (prefix-numeric-value current-prefix-arg))
19963 (or (org-current-level) 0))
19964 ?*))
19965 (add-stars
19966 (cond (nstars "") ; stars from prefix only
19967 ((equal stars "") "") ; before first heading
19968 (org-odd-levels-only "*") ; inside heading, odd
19969 (t "")))) ; inside heading, oddeven
19970 (while (< (point) end)
19971 (when (org-at-item-p)
19972 ;; Pay attention to cases when region ends before list.
19973 (let* ((struct (org-list-struct))
19974 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19975 (save-restriction
19976 (narrow-to-region (point) list-end)
19977 (insert
19978 (org-list-to-subtree
19979 (org-list-parse-list t)
19980 '(:istart (concat stars add-stars (funcall get-stars depth))
19981 :icount (concat stars add-stars (funcall get-stars depth)))))))
19982 (setq toggled t))
19983 (forward-line))))
19984 ;; Case 3. Started at normal text: make every line an heading,
19985 ;; skipping headlines and items.
19986 (t (let* ((stars (make-string
19987 (if nstars
19988 (prefix-numeric-value current-prefix-arg)
19989 (or (org-current-level) 0))
19990 ?*))
19991 (add-stars
19992 (cond (nstars "") ; stars from prefix only
19993 ((equal stars "") "*") ; before first heading
19994 (org-odd-levels-only "**") ; inside heading, odd
19995 (t "*"))) ; inside heading, oddeven
19996 (rpl (concat stars add-stars " ")))
19997 (while (< (point) end)
19998 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19999 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20000 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20001 (forward-line)))))))
20002 (unless toggled (message "Cannot toggle heading from here"))))
20004 (defun org-meta-return (&optional arg)
20005 "Insert a new heading or wrap a region in a table.
20006 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20007 See the individual commands for more information."
20008 (interactive "P")
20009 (cond
20010 ((run-hook-with-args-until-success 'org-metareturn-hook))
20011 ((or (org-at-drawer-p) (org-at-property-p))
20012 (newline-and-indent))
20013 ((org-at-table-p)
20014 (call-interactively 'org-table-wrap-region))
20015 (t (call-interactively 'org-insert-heading))))
20017 ;;; Menu entries
20019 (defsubst org-in-subtree-not-table-p ()
20020 "Are we in a subtree and not in a table?"
20021 (and (not (org-before-first-heading-p))
20022 (not (org-at-table-p))))
20024 ;; Define the Org-mode menus
20025 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20026 '("Tbl"
20027 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20028 ["Next Field" org-cycle (org-at-table-p)]
20029 ["Previous Field" org-shifttab (org-at-table-p)]
20030 ["Next Row" org-return (org-at-table-p)]
20031 "--"
20032 ["Blank Field" org-table-blank-field (org-at-table-p)]
20033 ["Edit Field" org-table-edit-field (org-at-table-p)]
20034 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20035 "--"
20036 ("Column"
20037 ["Move Column Left" org-metaleft (org-at-table-p)]
20038 ["Move Column Right" org-metaright (org-at-table-p)]
20039 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20040 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20041 ("Row"
20042 ["Move Row Up" org-metaup (org-at-table-p)]
20043 ["Move Row Down" org-metadown (org-at-table-p)]
20044 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20045 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20046 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20047 "--"
20048 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20049 ("Rectangle"
20050 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20051 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20052 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20053 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20054 "--"
20055 ("Calculate"
20056 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20057 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20058 ["Edit Formulas" org-edit-special (org-at-table-p)]
20059 "--"
20060 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20061 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20062 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20063 "--"
20064 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20065 "--"
20066 ["Sum Column/Rectangle" org-table-sum
20067 (or (org-at-table-p) (org-region-active-p))]
20068 ["Which Column?" org-table-current-column (org-at-table-p)])
20069 ["Debug Formulas"
20070 org-table-toggle-formula-debugger
20071 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20072 ["Show Col/Row Numbers"
20073 org-table-toggle-coordinate-overlays
20074 :style toggle
20075 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20076 "--"
20077 ["Create" org-table-create (and (not (org-at-table-p))
20078 org-enable-table-editor)]
20079 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20080 ["Import from File" org-table-import (not (org-at-table-p))]
20081 ["Export to File" org-table-export (org-at-table-p)]
20082 "--"
20083 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20085 (easy-menu-define org-org-menu org-mode-map "Org menu"
20086 '("Org"
20087 ("Show/Hide"
20088 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20089 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20090 ["Sparse Tree..." org-sparse-tree t]
20091 ["Reveal Context" org-reveal t]
20092 ["Show All" show-all t]
20093 "--"
20094 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20095 "--"
20096 ["New Heading" org-insert-heading t]
20097 ("Navigate Headings"
20098 ["Up" outline-up-heading t]
20099 ["Next" outline-next-visible-heading t]
20100 ["Previous" outline-previous-visible-heading t]
20101 ["Next Same Level" outline-forward-same-level t]
20102 ["Previous Same Level" outline-backward-same-level t]
20103 "--"
20104 ["Jump" org-goto t])
20105 ("Edit Structure"
20106 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20107 "--"
20108 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20109 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20110 "--"
20111 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20112 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20113 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20114 "--"
20115 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20116 "--"
20117 ["Copy visible text" org-copy-visible t]
20118 "--"
20119 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20120 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20121 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20122 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20123 "--"
20124 ["Sort Region/Children" org-sort t]
20125 "--"
20126 ["Convert to odd levels" org-convert-to-odd-levels t]
20127 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20128 ("Editing"
20129 ["Emphasis..." org-emphasize t]
20130 ["Edit Source Example" org-edit-special t]
20131 "--"
20132 ["Footnote new/jump" org-footnote-action t]
20133 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20134 ("Archive"
20135 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20136 "--"
20137 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20138 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20139 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20141 "--"
20142 ("Hyperlinks"
20143 ["Store Link (Global)" org-store-link t]
20144 ["Find existing link to here" org-occur-link-in-agenda-files t]
20145 ["Insert Link" org-insert-link t]
20146 ["Follow Link" org-open-at-point t]
20147 "--"
20148 ["Next link" org-next-link t]
20149 ["Previous link" org-previous-link t]
20150 "--"
20151 ["Descriptive Links"
20152 org-toggle-link-display
20153 :style radio
20154 :selected org-descriptive-links
20156 ["Literal Links"
20157 org-toggle-link-display
20158 :style radio
20159 :selected (not org-descriptive-links)])
20160 "--"
20161 ("TODO Lists"
20162 ["TODO/DONE/-" org-todo t]
20163 ("Select keyword"
20164 ["Next keyword" org-shiftright (org-at-heading-p)]
20165 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20166 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20167 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20168 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20169 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20170 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20171 "--"
20172 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20173 :selected org-enforce-todo-dependencies :style toggle :active t]
20174 "Settings for tree at point"
20175 ["Do Children sequentially" org-toggle-ordered-property :style radio
20176 :selected (org-entry-get nil "ORDERED")
20177 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20178 ["Do Children parallel" org-toggle-ordered-property :style radio
20179 :selected (not (org-entry-get nil "ORDERED"))
20180 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20181 "--"
20182 ["Set Priority" org-priority t]
20183 ["Priority Up" org-shiftup t]
20184 ["Priority Down" org-shiftdown t]
20185 "--"
20186 ["Get news from all feeds" org-feed-update-all t]
20187 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20188 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20189 ("TAGS and Properties"
20190 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20191 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20192 "--"
20193 ["Set property" org-set-property (not (org-before-first-heading-p))]
20194 ["Column view of properties" org-columns t]
20195 ["Insert Column View DBlock" org-insert-columns-dblock t])
20196 ("Dates and Scheduling"
20197 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20198 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20199 ("Change Date"
20200 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20201 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20202 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20203 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20204 ["Compute Time Range" org-evaluate-time-range t]
20205 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20206 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20207 "--"
20208 ["Custom time format" org-toggle-time-stamp-overlays
20209 :style radio :selected org-display-custom-times]
20210 "--"
20211 ["Goto Calendar" org-goto-calendar t]
20212 ["Date from Calendar" org-date-from-calendar t]
20213 "--"
20214 ["Start/Restart Timer" org-timer-start t]
20215 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20216 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20217 ["Insert Timer String" org-timer t]
20218 ["Insert Timer Item" org-timer-item t])
20219 ("Logging work"
20220 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20221 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20222 ["Clock out" org-clock-out t]
20223 ["Clock cancel" org-clock-cancel t]
20224 "--"
20225 ["Mark as default task" org-clock-mark-default-task t]
20226 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20227 ["Goto running clock" org-clock-goto t]
20228 "--"
20229 ["Display times" org-clock-display t]
20230 ["Create clock table" org-clock-report t]
20231 "--"
20232 ["Record DONE time"
20233 (progn (setq org-log-done (not org-log-done))
20234 (message "Switching to %s will %s record a timestamp"
20235 (car org-done-keywords)
20236 (if org-log-done "automatically" "not")))
20237 :style toggle :selected org-log-done])
20238 "--"
20239 ["Agenda Command..." org-agenda t]
20240 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20241 ("File List for Agenda")
20242 ("Special views current file"
20243 ["TODO Tree" org-show-todo-tree t]
20244 ["Check Deadlines" org-check-deadlines t]
20245 ["Timeline" org-timeline t]
20246 ["Tags/Property tree" org-match-sparse-tree t])
20247 "--"
20248 ["Export/Publish..." org-export t]
20249 ("LaTeX"
20250 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20251 :selected org-cdlatex-mode]
20252 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20253 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20254 ["Modify math symbol" org-cdlatex-math-modify
20255 (org-inside-LaTeX-fragment-p)]
20256 ["Insert citation" org-reftex-citation t]
20257 "--"
20258 ["Template for BEAMER" (progn (require 'org-beamer)
20259 (org-insert-beamer-options-template)) t])
20260 "--"
20261 ("MobileOrg"
20262 ["Push Files and Views" org-mobile-push t]
20263 ["Get Captured and Flagged" org-mobile-pull t]
20264 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20265 "--"
20266 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20267 "--"
20268 ("Documentation"
20269 ["Show Version" org-version t]
20270 ["Info Documentation" org-info t])
20271 ("Customize"
20272 ["Browse Org Group" org-customize t]
20273 "--"
20274 ["Expand This Menu" org-create-customize-menu
20275 (fboundp 'customize-menu-create)])
20276 ["Send bug report" org-submit-bug-report t]
20277 "--"
20278 ("Refresh/Reload"
20279 ["Refresh setup current buffer" org-mode-restart t]
20280 ["Reload Org (after update)" org-reload t]
20281 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20284 (defun org-info (&optional node)
20285 "Read documentation for Org-mode in the info system.
20286 With optional NODE, go directly to that node."
20287 (interactive)
20288 (info (format "(org)%s" (or node ""))))
20290 ;;;###autoload
20291 (defun org-submit-bug-report ()
20292 "Submit a bug report on Org-mode via mail.
20294 Don't hesitate to report any problems or inaccurate documentation.
20296 If you don't have setup sending mail from (X)Emacs, please copy the
20297 output buffer into your mail program, as it gives us important
20298 information about your Org-mode version and configuration."
20299 (interactive)
20300 (require 'reporter)
20301 (org-load-modules-maybe)
20302 (org-require-autoloaded-modules)
20303 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20304 (reporter-submit-bug-report
20305 "emacs-orgmode@gnu.org"
20306 (org-version nil 'full)
20307 (let (list)
20308 (save-window-excursion
20309 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20310 (delete-other-windows)
20311 (erase-buffer)
20312 (insert "You are about to submit a bug report to the Org-mode mailing list.
20314 We would like to add your full Org-mode and Outline configuration to the
20315 bug report. This greatly simplifies the work of the maintainer and
20316 other experts on the mailing list.
20318 HOWEVER, some variables you have customized may contain private
20319 information. The names of customers, colleagues, or friends, might
20320 appear in the form of file names, tags, todo states, or search strings.
20321 If you answer yes to the prompt, you might want to check and remove
20322 such private information before sending the email.")
20323 (add-text-properties (point-min) (point-max) '(face org-warning))
20324 (when (yes-or-no-p "Include your Org-mode configuration ")
20325 (mapatoms
20326 (lambda (v)
20327 (and (boundp v)
20328 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20329 (or (and (symbol-value v)
20330 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20331 (and
20332 (get v 'custom-type) (get v 'standard-value)
20333 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20334 (push v list)))))
20335 (kill-buffer (get-buffer "*Warn about privacy*"))
20336 list))
20337 nil nil
20338 "Remember to cover the basics, that is, what you expected to happen and
20339 what in fact did happen. You don't know how to make a good report? See
20341 http://orgmode.org/manual/Feedback.html#Feedback
20343 Your bug report will be posted to the Org-mode mailing list.
20344 ------------------------------------------------------------------------")
20345 (save-excursion
20346 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20347 (replace-match "\\1Bug: \\3 [\\2]")))))
20350 (defun org-install-agenda-files-menu ()
20351 (let ((bl (buffer-list)))
20352 (save-excursion
20353 (while bl
20354 (set-buffer (pop bl))
20355 (if (derived-mode-p 'org-mode) (setq bl nil)))
20356 (when (derived-mode-p 'org-mode)
20357 (easy-menu-change
20358 '("Org") "File List for Agenda"
20359 (append
20360 (list
20361 ["Edit File List" (org-edit-agenda-file-list) t]
20362 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20363 ["Remove Current File from List" org-remove-file t]
20364 ["Cycle through agenda files" org-cycle-agenda-files t]
20365 ["Occur in all agenda files" org-occur-in-agenda-files t]
20366 "--")
20367 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20369 ;;;; Documentation
20371 (defun org-require-autoloaded-modules ()
20372 (interactive)
20373 (mapc 'require
20374 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20375 org-docbook org-exp org-html org-icalendar
20376 org-id org-latex
20377 org-publish org-remember org-table
20378 org-timer org-xoxo)))
20380 ;;;###autoload
20381 (defun org-reload (&optional uncompiled)
20382 "Reload all org lisp files.
20383 With prefix arg UNCOMPILED, load the uncompiled versions."
20384 (interactive "P")
20385 (require 'loadhist)
20386 (let* ((org-dir (org-find-library-dir "org"))
20387 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20388 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20389 (remove-re (mapconcat 'identity
20390 (mapcar (lambda (f) (concat "^" f "$"))
20391 (list (if (featurep 'xemacs)
20392 "org-colview"
20393 "org-colview-xemacs")
20394 "org" "org-loaddefs" "org-version"))
20395 "\\|"))
20396 (feats (delete-dups
20397 (mapcar 'file-name-sans-extension
20398 (mapcar 'file-name-nondirectory
20399 (delq nil
20400 (mapcar 'feature-file
20401 features))))))
20402 (lfeat (append
20403 (sort
20404 (setq feats
20405 (delq nil (mapcar
20406 (lambda (f)
20407 (if (and (string-match feature-re f)
20408 (not (string-match remove-re f)))
20409 f nil))
20410 feats)))
20411 'string-lessp)
20412 (list "org-version" "org")))
20413 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20414 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20415 load-uncore load-misses)
20416 (setq load-misses
20417 (delq 't
20418 (mapcar (lambda (f)
20419 (or (org-load-noerror-mustsuffix (concat org-dir f))
20420 (and (string= org-dir contrib-dir)
20421 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20422 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20423 (add-to-list 'load-uncore f 'append)
20426 lfeat)))
20427 (if load-uncore
20428 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20429 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20430 (if load-misses
20431 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20432 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20433 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20435 ;;;###autoload
20436 (defun org-customize ()
20437 "Call the customize function with org as argument."
20438 (interactive)
20439 (org-load-modules-maybe)
20440 (org-require-autoloaded-modules)
20441 (customize-browse 'org))
20443 (defun org-create-customize-menu ()
20444 "Create a full customization menu for Org-mode, insert it into the menu."
20445 (interactive)
20446 (org-load-modules-maybe)
20447 (org-require-autoloaded-modules)
20448 (if (fboundp 'customize-menu-create)
20449 (progn
20450 (easy-menu-change
20451 '("Org") "Customize"
20452 `(["Browse Org group" org-customize t]
20453 "--"
20454 ,(customize-menu-create 'org)
20455 ["Set" Custom-set t]
20456 ["Save" Custom-save t]
20457 ["Reset to Current" Custom-reset-current t]
20458 ["Reset to Saved" Custom-reset-saved t]
20459 ["Reset to Standard Settings" Custom-reset-standard t]))
20460 (message "\"Org\"-menu now contains full customization menu"))
20461 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20463 ;;;; Miscellaneous stuff
20465 ;;; Generally useful functions
20467 (defun org-get-at-bol (property)
20468 "Get text property PROPERTY at beginning of line."
20469 (get-text-property (point-at-bol) property))
20471 (defun org-find-text-property-in-string (prop s)
20472 "Return the first non-nil value of property PROP in string S."
20473 (or (get-text-property 0 prop s)
20474 (get-text-property (or (next-single-property-change 0 prop s) 0)
20475 prop s)))
20477 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20478 "Display the given MESSAGE as a warning."
20479 (if (fboundp 'display-warning)
20480 (display-warning 'org message
20481 (if (featurep 'xemacs) 'warning :warning))
20482 (let ((buf (get-buffer-create "*Org warnings*")))
20483 (with-current-buffer buf
20484 (goto-char (point-max))
20485 (insert "Warning (Org): " message)
20486 (unless (bolp)
20487 (newline)))
20488 (display-buffer buf)
20489 (sit-for 0))))
20491 (defun org-eval (form)
20492 "Eval FORM and return result."
20493 (condition-case error
20494 (eval form)
20495 (error (format "%%![Error: %s]" error))))
20497 (defun org-in-clocktable-p ()
20498 "Check if the cursor is in a clocktable."
20499 (let ((pos (point)) start)
20500 (save-excursion
20501 (end-of-line 1)
20502 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20503 (setq start (match-beginning 0))
20504 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20505 (>= (match-end 0) pos)
20506 start))))
20508 (defun org-in-commented-line ()
20509 "Is point in a line starting with `#'?"
20510 (equal (char-after (point-at-bol)) ?#))
20512 (defun org-in-indented-comment-line ()
20513 "Is point in a line starting with `#' after some white space?"
20514 (save-excursion
20515 (save-match-data
20516 (goto-char (point-at-bol))
20517 (looking-at "[ \t]*#"))))
20519 (defun org-in-verbatim-emphasis ()
20520 (save-match-data
20521 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20523 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20524 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20525 (if (and marker (marker-buffer marker)
20526 (buffer-live-p (marker-buffer marker)))
20527 (progn
20528 (org-pop-to-buffer-same-window (marker-buffer marker))
20529 (if (or (> marker (point-max)) (< marker (point-min)))
20530 (widen))
20531 (goto-char marker)
20532 (org-show-context 'org-goto))
20533 (if bookmark
20534 (bookmark-jump bookmark)
20535 (error "Cannot find location"))))
20537 (defun org-quote-csv-field (s)
20538 "Quote field for inclusion in CSV material."
20539 (if (string-match "[\",]" s)
20540 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20543 (defun org-force-self-insert (N)
20544 "Needed to enforce self-insert under remapping."
20545 (interactive "p")
20546 (self-insert-command N))
20548 (defun org-string-width (s)
20549 "Compute width of string, ignoring invisible characters.
20550 This ignores character with invisibility property `org-link', and also
20551 characters with property `org-cwidth', because these will become invisible
20552 upon the next fontification round."
20553 (let (b l)
20554 (when (or (eq t buffer-invisibility-spec)
20555 (assq 'org-link buffer-invisibility-spec))
20556 (while (setq b (text-property-any 0 (length s)
20557 'invisible 'org-link s))
20558 (setq s (concat (substring s 0 b)
20559 (substring s (or (next-single-property-change
20560 b 'invisible s) (length s)))))))
20561 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20562 (setq s (concat (substring s 0 b)
20563 (substring s (or (next-single-property-change
20564 b 'org-cwidth s) (length s))))))
20565 (setq l (string-width s) b -1)
20566 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20567 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20570 (defun org-shorten-string (s maxlength)
20571 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20572 If the string is shorter or has length MAXLENGTH, just return the
20573 original string. If it is longer, the functions finds a space in the
20574 string, breaks this string off at that locations and adds three dots
20575 as ellipsis. Including the ellipsis, the string will not be longer
20576 than MAXLENGTH. If finding a good breaking point in the string does
20577 not work, the string is just chopped off in the middle of a word
20578 if necessary."
20579 (if (<= (length s) maxlength)
20581 (let* ((n (max (- maxlength 4) 1))
20582 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20583 (if (string-match re s)
20584 (concat (match-string 1 s) "...")
20585 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20587 (defun org-get-indentation (&optional line)
20588 "Get the indentation of the current line, interpreting tabs.
20589 When LINE is given, assume it represents a line and compute its indentation."
20590 (if line
20591 (if (string-match "^ *" (org-remove-tabs line))
20592 (match-end 0))
20593 (save-excursion
20594 (beginning-of-line 1)
20595 (skip-chars-forward " \t")
20596 (current-column))))
20598 (defun org-get-string-indentation (s)
20599 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20600 (let ((n -1) (i 0) (w tab-width) c)
20601 (catch 'exit
20602 (while (< (setq n (1+ n)) (length s))
20603 (setq c (aref s n))
20604 (cond ((= c ?\ ) (setq i (1+ i)))
20605 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20606 (t (throw 'exit t)))))
20609 (defun org-remove-tabs (s &optional width)
20610 "Replace tabulators in S with spaces.
20611 Assumes that s is a single line, starting in column 0."
20612 (setq width (or width tab-width))
20613 (while (string-match "\t" s)
20614 (setq s (replace-match
20615 (make-string
20616 (- (* width (/ (+ (match-beginning 0) width) width))
20617 (match-beginning 0)) ?\ )
20618 t t s)))
20621 (defun org-fix-indentation (line ind)
20622 "Fix indentation in LINE.
20623 IND is a cons cell with target and minimum indentation.
20624 If the current indentation in LINE is smaller than the minimum,
20625 leave it alone. If it is larger than ind, set it to the target."
20626 (let* ((l (org-remove-tabs line))
20627 (i (org-get-indentation l))
20628 (i1 (car ind)) (i2 (cdr ind)))
20629 (if (>= i i2) (setq l (substring line i2)))
20630 (if (> i1 0)
20631 (concat (make-string i1 ?\ ) l)
20632 l)))
20634 (defun org-remove-indentation (code &optional n)
20635 "Remove the maximum common indentation from the lines in CODE.
20636 N may optionally be the number of spaces to remove."
20637 (with-temp-buffer
20638 (insert code)
20639 (org-do-remove-indentation n)
20640 (buffer-string)))
20642 (defun org-do-remove-indentation (&optional n)
20643 "Remove the maximum common indentation from the buffer."
20644 (untabify (point-min) (point-max))
20645 (let ((min 10000) re)
20646 (if n
20647 (setq min n)
20648 (goto-char (point-min))
20649 (while (re-search-forward "^ *[^ \n]" nil t)
20650 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20651 (unless (or (= min 0) (= min 10000))
20652 (setq re (format "^ \\{%d\\}" min))
20653 (goto-char (point-min))
20654 (while (re-search-forward re nil t)
20655 (replace-match "")
20656 (end-of-line 1))
20657 min)))
20659 (defun org-fill-template (template alist)
20660 "Find each %key of ALIST in TEMPLATE and replace it."
20661 (let ((case-fold-search nil)
20662 entry key value)
20663 (setq alist (sort (copy-sequence alist)
20664 (lambda (a b) (< (length (car a)) (length (car b))))))
20665 (while (setq entry (pop alist))
20666 (setq template
20667 (replace-regexp-in-string
20668 (concat "%" (regexp-quote (car entry)))
20669 (or (cdr entry) "") template t t)))
20670 template))
20672 (defun org-base-buffer (buffer)
20673 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20674 (if (not buffer)
20675 buffer
20676 (or (buffer-base-buffer buffer)
20677 buffer)))
20679 (defun org-trim (s)
20680 "Remove whitespace at beginning and end of string."
20681 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20682 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20685 (defun org-wrap (string &optional width lines)
20686 "Wrap string to either a number of lines, or a width in characters.
20687 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20688 that costs. If there is a word longer than WIDTH, the text is actually
20689 wrapped to the length of that word.
20690 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20691 many lines, whatever width that takes.
20692 The return value is a list of lines, without newlines at the end."
20693 (let* ((words (org-split-string string "[ \t\n]+"))
20694 (maxword (apply 'max (mapcar 'org-string-width words)))
20695 w ll)
20696 (cond (width
20697 (org-do-wrap words (max maxword width)))
20698 (lines
20699 (setq w maxword)
20700 (setq ll (org-do-wrap words maxword))
20701 (if (<= (length ll) lines)
20703 (setq ll words)
20704 (while (> (length ll) lines)
20705 (setq w (1+ w))
20706 (setq ll (org-do-wrap words w)))
20707 ll))
20708 (t (error "Cannot wrap this")))))
20710 (defun org-do-wrap (words width)
20711 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20712 (let (lines line)
20713 (while words
20714 (setq line (pop words))
20715 (while (and words (< (+ (length line) (length (car words))) width))
20716 (setq line (concat line " " (pop words))))
20717 (setq lines (push line lines)))
20718 (nreverse lines)))
20720 (defun org-split-string (string &optional separators)
20721 "Splits STRING into substrings at SEPARATORS.
20722 No empty strings are returned if there are matches at the beginning
20723 and end of string."
20724 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20725 (start 0)
20726 notfirst
20727 (list nil))
20728 (while (and (string-match rexp string
20729 (if (and notfirst
20730 (= start (match-beginning 0))
20731 (< start (length string)))
20732 (1+ start) start))
20733 (< (match-beginning 0) (length string)))
20734 (setq notfirst t)
20735 (or (eq (match-beginning 0) 0)
20736 (and (eq (match-beginning 0) (match-end 0))
20737 (eq (match-beginning 0) start))
20738 (setq list
20739 (cons (substring string start (match-beginning 0))
20740 list)))
20741 (setq start (match-end 0)))
20742 (or (eq start (length string))
20743 (setq list
20744 (cons (substring string start)
20745 list)))
20746 (nreverse list)))
20748 (defun org-quote-vert (s)
20749 "Replace \"|\" with \"\\vert\"."
20750 (while (string-match "|" s)
20751 (setq s (replace-match "\\vert" t t s)))
20754 (defun org-uuidgen-p (s)
20755 "Is S an ID created by UUIDGEN?"
20756 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20758 (defun org-in-src-block-p (&optional inside)
20759 "Whether point is in a code source block.
20760 When INSIDE is non-nil, don't consider we are within a src block
20761 when point is at #+BEGIN_SRC or #+END_SRC."
20762 (let ((case-fold-search t) ov)
20763 (or (and (setq ov (overlays-at (point)))
20764 (memq 'org-block-background
20765 (overlay-properties (car ov))))
20766 (and (not inside)
20767 (save-match-data
20768 (save-excursion
20769 (beginning-of-line)
20770 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20772 (defun org-context ()
20773 "Return a list of contexts of the current cursor position.
20774 If several contexts apply, all are returned.
20775 Each context entry is a list with a symbol naming the context, and
20776 two positions indicating start and end of the context. Possible
20777 contexts are:
20779 :headline anywhere in a headline
20780 :headline-stars on the leading stars in a headline
20781 :todo-keyword on a TODO keyword (including DONE) in a headline
20782 :tags on the TAGS in a headline
20783 :priority on the priority cookie in a headline
20784 :item on the first line of a plain list item
20785 :item-bullet on the bullet/number of a plain list item
20786 :checkbox on the checkbox in a plain list item
20787 :table in an org-mode table
20788 :table-special on a special filed in a table
20789 :table-table in a table.el table
20790 :clocktable in a clocktable
20791 :src-block in a source block
20792 :link on a hyperlink
20793 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20794 :target on a <<target>>
20795 :radio-target on a <<<radio-target>>>
20796 :latex-fragment on a LaTeX fragment
20797 :latex-preview on a LaTeX fragment with overlaid preview image
20799 This function expects the position to be visible because it uses font-lock
20800 faces as a help to recognize the following contexts: :table-special, :link,
20801 and :keyword."
20802 (let* ((f (get-text-property (point) 'face))
20803 (faces (if (listp f) f (list f)))
20804 (case-fold-search t)
20805 (p (point)) clist o)
20806 ;; First the large context
20807 (cond
20808 ((org-at-heading-p t)
20809 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20810 (when (progn
20811 (beginning-of-line 1)
20812 (looking-at org-todo-line-tags-regexp))
20813 (push (org-point-in-group p 1 :headline-stars) clist)
20814 (push (org-point-in-group p 2 :todo-keyword) clist)
20815 (push (org-point-in-group p 4 :tags) clist))
20816 (goto-char p)
20817 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20818 (if (looking-at "\\[#[A-Z0-9]\\]")
20819 (push (org-point-in-group p 0 :priority) clist)))
20821 ((org-at-item-p)
20822 (push (org-point-in-group p 2 :item-bullet) clist)
20823 (push (list :item (point-at-bol)
20824 (save-excursion (org-end-of-item) (point)))
20825 clist)
20826 (and (org-at-item-checkbox-p)
20827 (push (org-point-in-group p 0 :checkbox) clist)))
20829 ((org-at-table-p)
20830 (push (list :table (org-table-begin) (org-table-end)) clist)
20831 (if (memq 'org-formula faces)
20832 (push (list :table-special
20833 (previous-single-property-change p 'face)
20834 (next-single-property-change p 'face)) clist)))
20835 ((org-at-table-p 'any)
20836 (push (list :table-table) clist)))
20837 (goto-char p)
20839 (let ((case-fold-search t))
20840 ;; New the "medium" contexts: clocktables, source blocks
20841 (cond ((org-in-clocktable-p)
20842 (push (list :clocktable
20843 (and (or (looking-at "#\\+BEGIN: clocktable")
20844 (search-backward "#+BEGIN: clocktable" nil t))
20845 (match-beginning 0))
20846 (and (re-search-forward "#\\+END:?" nil t)
20847 (match-end 0))) clist))
20848 ((org-in-src-block-p)
20849 (push (list :src-block
20850 (and (or (looking-at "#\\+BEGIN_SRC")
20851 (search-backward "#+BEGIN_SRC" nil t))
20852 (match-beginning 0))
20853 (and (search-forward "#+END_SRC" nil t)
20854 (match-beginning 0))) clist))))
20855 (goto-char p)
20857 ;; Now the small context
20858 (cond
20859 ((org-at-timestamp-p)
20860 (push (org-point-in-group p 0 :timestamp) clist))
20861 ((memq 'org-link faces)
20862 (push (list :link
20863 (previous-single-property-change p 'face)
20864 (next-single-property-change p 'face)) clist))
20865 ((memq 'org-special-keyword faces)
20866 (push (list :keyword
20867 (previous-single-property-change p 'face)
20868 (next-single-property-change p 'face)) clist))
20869 ((org-at-target-p)
20870 (push (org-point-in-group p 0 :target) clist)
20871 (goto-char (1- (match-beginning 0)))
20872 (if (looking-at org-radio-target-regexp)
20873 (push (org-point-in-group p 0 :radio-target) clist))
20874 (goto-char p))
20875 ((setq o (car (delq nil
20876 (mapcar
20877 (lambda (x)
20878 (if (memq x org-latex-fragment-image-overlays) x))
20879 (overlays-at (point))))))
20880 (push (list :latex-fragment
20881 (overlay-start o) (overlay-end o)) clist)
20882 (push (list :latex-preview
20883 (overlay-start o) (overlay-end o)) clist))
20884 ((org-inside-LaTeX-fragment-p)
20885 ;; FIXME: positions wrong.
20886 (push (list :latex-fragment (point) (point)) clist)))
20888 (setq clist (nreverse (delq nil clist)))
20889 clist))
20891 ;; FIXME: Compare with at-regexp-p Do we need both?
20892 (defun org-in-regexp (re &optional nlines visually)
20893 "Check if point is inside a match of regexp.
20894 Normally only the current line is checked, but you can include NLINES extra
20895 lines both before and after point into the search.
20896 If VISUALLY is set, require that the cursor is not after the match but
20897 really on, so that the block visually is on the match."
20898 (catch 'exit
20899 (let ((pos (point))
20900 (eol (point-at-eol (+ 1 (or nlines 0))))
20901 (inc (if visually 1 0)))
20902 (save-excursion
20903 (beginning-of-line (- 1 (or nlines 0)))
20904 (while (re-search-forward re eol t)
20905 (if (and (<= (match-beginning 0) pos)
20906 (>= (+ inc (match-end 0)) pos))
20907 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20909 (defun org-at-regexp-p (regexp)
20910 "Is point inside a match of REGEXP in the current line?"
20911 (catch 'exit
20912 (save-excursion
20913 (let ((pos (point)) (end (point-at-eol)))
20914 (beginning-of-line 1)
20915 (while (re-search-forward regexp end t)
20916 (if (and (<= (match-beginning 0) pos)
20917 (>= (match-end 0) pos))
20918 (throw 'exit t)))
20919 nil))))
20921 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20922 "Non-nil when point is between matches of START-RE and END-RE.
20924 Also return a non-nil value when point is on one of the matches.
20926 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20927 buffer positions. Default values are the positions of headlines
20928 surrounding the point.
20930 The functions returns a cons cell whose car (resp. cdr) is the
20931 position before START-RE (resp. after END-RE)."
20932 (save-match-data
20933 (let ((pos (point))
20934 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20935 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20936 beg end)
20937 (save-excursion
20938 ;; Point is on a block when on START-RE or if START-RE can be
20939 ;; found before it...
20940 (and (or (org-at-regexp-p start-re)
20941 (re-search-backward start-re limit-up t))
20942 (setq beg (match-beginning 0))
20943 ;; ... and END-RE after it...
20944 (goto-char (match-end 0))
20945 (re-search-forward end-re limit-down t)
20946 (> (setq end (match-end 0)) pos)
20947 ;; ... without another START-RE in-between.
20948 (goto-char (match-beginning 0))
20949 (not (re-search-backward start-re (1+ beg) t))
20950 ;; Return value.
20951 (cons beg end))))))
20953 (defun org-in-block-p (names)
20954 "Non-nil when point belongs to a block whose name belongs to NAMES.
20956 NAMES is a list of strings containing names of blocks.
20958 Return first block name matched, or nil. Beware that in case of
20959 nested blocks, the returned name may not belong to the closest
20960 block from point."
20961 (save-match-data
20962 (catch 'exit
20963 (let ((case-fold-search t)
20964 (lim-up (save-excursion (outline-previous-heading)))
20965 (lim-down (save-excursion (outline-next-heading))))
20966 (mapc (lambda (name)
20967 (let ((n (regexp-quote name)))
20968 (when (org-between-regexps-p
20969 (concat "^[ \t]*#\\+begin_" n)
20970 (concat "^[ \t]*#\\+end_" n)
20971 lim-up lim-down)
20972 (throw 'exit n))))
20973 names))
20974 nil)))
20976 (defun org-occur-in-agenda-files (regexp &optional nlines)
20977 "Call `multi-occur' with buffers for all agenda files."
20978 (interactive "sOrg-files matching: \np")
20979 (let* ((files (org-agenda-files))
20980 (tnames (mapcar 'file-truename files))
20981 (extra org-agenda-text-search-extra-files)
20983 (when (eq (car extra) 'agenda-archives)
20984 (setq extra (cdr extra))
20985 (setq files (org-add-archive-files files)))
20986 (while (setq f (pop extra))
20987 (unless (member (file-truename f) tnames)
20988 (add-to-list 'files f 'append)
20989 (add-to-list 'tnames (file-truename f) 'append)))
20990 (multi-occur
20991 (mapcar (lambda (x)
20992 (with-current-buffer
20993 (or (get-file-buffer x) (find-file-noselect x))
20994 (widen)
20995 (current-buffer)))
20996 files)
20997 regexp)))
20999 (if (boundp 'occur-mode-find-occurrence-hook)
21000 ;; Emacs 23
21001 (add-hook 'occur-mode-find-occurrence-hook
21002 (lambda ()
21003 (when (derived-mode-p 'org-mode)
21004 (org-reveal))))
21005 ;; Emacs 22
21006 (defadvice occur-mode-goto-occurrence
21007 (after org-occur-reveal activate)
21008 (and (derived-mode-p 'org-mode) (org-reveal)))
21009 (defadvice occur-mode-goto-occurrence-other-window
21010 (after org-occur-reveal activate)
21011 (and (derived-mode-p 'org-mode) (org-reveal)))
21012 (defadvice occur-mode-display-occurrence
21013 (after org-occur-reveal activate)
21014 (when (derived-mode-p 'org-mode)
21015 (let ((pos (occur-mode-find-occurrence)))
21016 (with-current-buffer (marker-buffer pos)
21017 (save-excursion
21018 (goto-char pos)
21019 (org-reveal)))))))
21021 (defun org-occur-link-in-agenda-files ()
21022 "Create a link and search for it in the agendas.
21023 The link is not stored in `org-stored-links', it is just created
21024 for the search purpose."
21025 (interactive)
21026 (let ((link (condition-case nil
21027 (org-store-link nil)
21028 (error "Unable to create a link to here"))))
21029 (org-occur-in-agenda-files (regexp-quote link))))
21031 (defun org-uniquify (list)
21032 "Remove duplicate elements from LIST."
21033 (let (res)
21034 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21035 res))
21037 (defun org-delete-all (elts list)
21038 "Remove all elements in ELTS from LIST."
21039 (while elts
21040 (setq list (delete (pop elts) list)))
21041 list)
21043 (defun org-count (cl-item cl-seq)
21044 "Count the number of occurrences of ITEM in SEQ.
21045 Taken from `count' in cl-seq.el with all keyword arguments removed."
21046 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21047 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21048 (while (< cl-start cl-end)
21049 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21050 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21051 (setq cl-start (1+ cl-start)))
21052 cl-count))
21054 (defun org-remove-if (predicate seq)
21055 "Remove everything from SEQ that fulfills PREDICATE."
21056 (let (res e)
21057 (while seq
21058 (setq e (pop seq))
21059 (if (not (funcall predicate e)) (push e res)))
21060 (nreverse res)))
21062 (defun org-remove-if-not (predicate seq)
21063 "Remove everything from SEQ that does not fulfill PREDICATE."
21064 (let (res e)
21065 (while seq
21066 (setq e (pop seq))
21067 (if (funcall predicate e) (push e res)))
21068 (nreverse res)))
21070 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21071 "Reduce two-argument FUNCTION across SEQ.
21072 Taken from `reduce' in cl-seq.el with all keyword arguments but
21073 \":initial-value\" removed."
21074 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21075 (cadr (memq :initial-value cl-keys)))
21076 (cl-seq (pop cl-seq))
21077 (t (funcall cl-func)))))
21078 (while cl-seq
21079 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21080 cl-accum))
21082 (defun org-back-over-empty-lines ()
21083 "Move backwards over whitespace, to the beginning of the first empty line.
21084 Returns the number of empty lines passed."
21085 (let ((pos (point)))
21086 (if (cdr (assoc 'heading org-blank-before-new-entry))
21087 (skip-chars-backward " \t\n\r")
21088 (unless (eobp)
21089 (forward-line -1)))
21090 (beginning-of-line 2)
21091 (goto-char (min (point) pos))
21092 (count-lines (point) pos)))
21094 (defun org-skip-whitespace ()
21095 (skip-chars-forward " \t\n\r"))
21097 (defun org-point-in-group (point group &optional context)
21098 "Check if POINT is in match-group GROUP.
21099 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21100 match. If the match group does not exist or point is not inside it,
21101 return nil."
21102 (and (match-beginning group)
21103 (>= point (match-beginning group))
21104 (<= point (match-end group))
21105 (if context
21106 (list context (match-beginning group) (match-end group))
21107 t)))
21109 (defun org-switch-to-buffer-other-window (&rest args)
21110 "Switch to buffer in a second window on the current frame.
21111 In particular, do not allow pop-up frames.
21112 Returns the newly created buffer."
21113 (org-no-popups
21114 (apply 'switch-to-buffer-other-window args)))
21116 (defun org-combine-plists (&rest plists)
21117 "Create a single property list from all plists in PLISTS.
21118 The process starts by copying the first list, and then setting properties
21119 from the other lists. Settings in the last list are the most significant
21120 ones and overrule settings in the other lists."
21121 (let ((rtn (copy-sequence (pop plists)))
21122 p v ls)
21123 (while plists
21124 (setq ls (pop plists))
21125 (while ls
21126 (setq p (pop ls) v (pop ls))
21127 (setq rtn (plist-put rtn p v))))
21128 rtn))
21130 (defun org-replace-escapes (string table)
21131 "Replace %-escapes in STRING with values in TABLE.
21132 TABLE is an association list with keys like \"%a\" and string values.
21133 The sequences in STRING may contain normal field width and padding information,
21134 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21135 so values can contain further %-escapes if they are define later in TABLE."
21136 (let ((tbl (copy-alist table))
21137 (case-fold-search nil)
21138 (pchg 0)
21139 e re rpl)
21140 (while (setq e (pop tbl))
21141 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21142 (when (and (cdr e) (string-match re (cdr e)))
21143 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21144 (safe "SREF"))
21145 (add-text-properties 0 3 (list 'sref sref) safe)
21146 (setcdr e (replace-match safe t t (cdr e)))))
21147 (while (string-match re string)
21148 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21149 (cdr e)))
21150 (setq string (replace-match rpl t t string))))
21151 (while (setq pchg (next-property-change pchg string))
21152 (let ((sref (get-text-property pchg 'sref string)))
21153 (when (and sref (string-match "SREF" string pchg))
21154 (setq string (replace-match sref t t string)))))
21155 string))
21157 (defun org-sublist (list start end)
21158 "Return a section of LIST, from START to END.
21159 Counting starts at 1."
21160 (let (rtn (c start))
21161 (setq list (nthcdr (1- start) list))
21162 (while (and list (<= c end))
21163 (push (pop list) rtn)
21164 (setq c (1+ c)))
21165 (nreverse rtn)))
21167 (defun org-find-base-buffer-visiting (file)
21168 "Like `find-buffer-visiting' but always return the base buffer and
21169 not an indirect buffer."
21170 (let ((buf (or (get-file-buffer file)
21171 (find-buffer-visiting file))))
21172 (if buf
21173 (or (buffer-base-buffer buf) buf)
21174 nil)))
21176 (defun org-image-file-name-regexp (&optional extensions)
21177 "Return regexp matching the file names of images.
21178 If EXTENSIONS is given, only match these."
21179 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21180 (image-file-name-regexp)
21181 (let ((image-file-name-extensions
21182 (or extensions
21183 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21184 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21185 (concat "\\."
21186 (regexp-opt (nconc (mapcar 'upcase
21187 image-file-name-extensions)
21188 image-file-name-extensions)
21190 "\\'"))))
21192 (defun org-file-image-p (file &optional extensions)
21193 "Return non-nil if FILE is an image."
21194 (save-match-data
21195 (string-match (org-image-file-name-regexp extensions) file)))
21197 (defun org-get-cursor-date (&optional with-time)
21198 "Return the date at cursor in as a time.
21199 This works in the calendar and in the agenda, anywhere else it just
21200 returns the current time.
21201 If WITH-TIME is non-nil, returns the time of the event at point (in
21202 the agenda) or the current time of the day."
21203 (let (date day defd tp tm hod mod)
21204 (when with-time
21205 (setq tp (get-text-property (point) 'time))
21206 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21207 (setq hod (string-to-number (match-string 1 tp))
21208 mod (string-to-number (match-string 2 tp))))
21209 (or tp (setq hod (nth 2 (decode-time (current-time)))
21210 mod (nth 1 (decode-time (current-time))))))
21211 (cond
21212 ((eq major-mode 'calendar-mode)
21213 (setq date (calendar-cursor-to-date)
21214 defd (encode-time 0 (or mod 0) (or hod 0)
21215 (nth 1 date) (nth 0 date) (nth 2 date))))
21216 ((eq major-mode 'org-agenda-mode)
21217 (setq day (get-text-property (point) 'day))
21218 (if day
21219 (setq date (calendar-gregorian-from-absolute day)
21220 defd (encode-time 0 (or mod 0) (or hod 0)
21221 (nth 1 date) (nth 0 date) (nth 2 date))))))
21222 (or defd (current-time))))
21224 (defun org-mark-subtree (&optional up)
21225 "Mark the current subtree.
21226 This puts point at the start of the current subtree, and mark at
21227 the end. If a numeric prefix UP is given, move up into the
21228 hierarchy of headlines by UP levels before marking the subtree."
21229 (interactive "P")
21230 (org-with-limited-levels
21231 (cond ((org-at-heading-p) (beginning-of-line))
21232 ((org-before-first-heading-p) (error "Not in a subtree"))
21233 (t (outline-previous-visible-heading 1))))
21234 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21235 (if (org-called-interactively-p 'any)
21236 (call-interactively 'org-mark-element)
21237 (org-mark-element)))
21240 ;;; Macros
21242 ;; Macros are expanded with `org-macro-replace-all', which relies
21243 ;; internally on `org-macro-expand'.
21245 ;; Default templates for expansion are stored in the buffer-local
21246 ;; variable `org-macro-templates'. This variable is updated by
21247 ;; `org-macro-initialize-templates'.
21249 ;; Along with macros defined through #+MACRO: keyword, default
21250 ;; templates include the following hard-coded macros:
21251 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21252 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21254 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21255 ;; {{{title}}} will also be provided.
21258 (defvar org-macro-templates nil
21259 "Alist containing all macro templates in current buffer.
21260 Associations are in the shape of (NAME . TEMPLATE) where NAME
21261 stands for macro's name and template for its replacement value,
21262 both as strings. This is an internal variable. Do not set it
21263 directly, use instead:
21265 #+MACRO: name template")
21266 (make-variable-buffer-local 'org-macro-templates)
21268 (defun org-macro-expand (macro templates)
21269 "Return expanded MACRO, as a string.
21270 MACRO is an object, obtained, for example, with
21271 `org-element-context'. TEMPLATES is an alist of templates used
21272 for expansion. See `org-macro-templates' for a buffer-local
21273 default value. Return nil if no template was found."
21274 (let ((template
21275 ;; Macro names are case-insensitive.
21276 (cdr (assoc-string (org-element-property :key macro) templates t))))
21277 (when template
21278 (let ((value (replace-regexp-in-string
21279 "\\$[0-9]+"
21280 (lambda (arg)
21281 (or (nth (1- (string-to-number (substring arg 1)))
21282 (org-element-property :args macro))
21283 ;; No argument provided: remove
21284 ;; place-holder.
21285 ""))
21286 template)))
21287 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21288 (when (string-match "\\`(eval\\>" value)
21289 (setq value (eval (read value))))
21290 ;; Return string.
21291 (format "%s" (or value ""))))))
21293 (defun org-macro-replace-all (templates)
21294 "Replace all macros in current buffer by their expansion.
21295 TEMPLATES is an alist of templates used for expansion. See
21296 `org-macro-templates' for a buffer-local default value."
21297 (save-excursion
21298 (goto-char (point-min))
21299 (let (record)
21300 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21301 (let ((object (org-element-context)))
21302 (when (eq (org-element-type object) 'macro)
21303 (let* ((value (org-macro-expand object templates))
21304 (begin (org-element-property :begin object))
21305 (signature (list begin
21306 object
21307 (org-element-property :args object))))
21308 ;; Avoid circular dependencies by checking if the same
21309 ;; macro with the same arguments is expanded at the same
21310 ;; position twice.
21311 (if (member signature record)
21312 (error "Circular macro expansion: %s"
21313 (org-element-property :key object))
21314 (when value
21315 (push signature record)
21316 (delete-region
21317 begin
21318 ;; Preserve white spaces after the macro.
21319 (progn (goto-char (org-element-property :end object))
21320 (skip-chars-backward " \t")
21321 (point)))
21322 ;; Leave point before replacement in case of recursive
21323 ;; expansions.
21324 (save-excursion (insert value)))))))))))
21326 (defun org-macro-initialize-templates ()
21327 "Collect macro templates defined in current buffer.
21328 Templates are stored in buffer-local variable
21329 `org-macro-templates'. In addition to buffer-defined macros, the
21330 function installs the following ones: \"property\",
21331 \"time\". and, if the buffer is associated to a file,
21332 \"input-file\" and \"modification-time\"."
21333 (let ((case-fold-search t)
21334 (set-template
21335 (lambda (cell)
21336 ;; Add CELL to `org-macro-templates' if there's no
21337 ;; association matching its name already. Otherwise,
21338 ;; replace old association with the new one in that
21339 ;; variable.
21340 (let ((old-template (assoc (car cell) org-macro-templates)))
21341 (if old-template (setcdr old-template (cdr cell))
21342 (push cell org-macro-templates))))))
21343 ;; Install buffer-local macros.
21344 (org-with-wide-buffer
21345 (goto-char (point-min))
21346 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21347 (let ((element (org-element-at-point)))
21348 (when (eq (org-element-type element) 'keyword)
21349 (let ((value (org-element-property :value element)))
21350 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21351 (funcall set-template
21352 (cons (match-string 1 value)
21353 (or (match-string 2 value) "")))))))))
21354 ;; Install hard-coded macros.
21355 (mapc (lambda (cell) (funcall set-template cell))
21356 (list
21357 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21358 (cons "time" "(eval (format-time-string \"$1\"))")))
21359 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21360 (when (and visited-file (file-exists-p visited-file))
21361 (mapc (lambda (cell) (funcall set-template cell))
21362 (list
21363 (cons "input-file" (file-name-nondirectory visited-file))
21364 (cons "modification-time"
21365 (format "(eval (format-time-string \"$1\" '%s))"
21366 (prin1-to-string
21367 (nth 5 (file-attributes visited-file)))))))))))
21370 ;;; Indentation
21372 (defun org-indent-line ()
21373 "Indent line depending on context."
21374 (interactive)
21375 (let* ((pos (point))
21376 (itemp (org-at-item-p))
21377 (case-fold-search t)
21378 (org-drawer-regexp (or org-drawer-regexp "\000"))
21379 (inline-task-p (and (featurep 'org-inlinetask)
21380 (org-inlinetask-in-task-p)))
21381 (inline-re (and inline-task-p
21382 (org-inlinetask-outline-regexp)))
21383 column)
21384 (if (and orgstruct-is-++ (eq pos (point)))
21385 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21386 (indent-according-to-mode))
21387 (beginning-of-line 1)
21388 (cond
21389 ;; Headings
21390 ((looking-at org-outline-regexp) (setq column 0))
21391 ;; Included files
21392 ((looking-at "#\\+include:") (setq column 0))
21393 ;; Footnote definition
21394 ((looking-at org-footnote-definition-re) (setq column 0))
21395 ;; Literal examples
21396 ((looking-at "[ \t]*:\\( \\|$\\)")
21397 (setq column (org-get-indentation))) ; do nothing
21398 ;; Lists
21399 ((ignore-errors (goto-char (org-in-item-p)))
21400 (setq column (if itemp
21401 (org-get-indentation)
21402 (org-list-item-body-column (point))))
21403 (goto-char pos))
21404 ;; Drawers
21405 ((and (looking-at "[ \t]*:END:")
21406 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21407 (save-excursion
21408 (goto-char (1- (match-beginning 1)))
21409 (setq column (current-column))))
21410 ;; Special blocks
21411 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21412 (save-excursion
21413 (re-search-backward
21414 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21415 (setq column (org-get-indentation (match-string 0))))
21416 ((and (not (looking-at "[ \t]*#\\+begin_"))
21417 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21418 (save-excursion
21419 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21420 (setq column
21421 (cond ((equal (downcase (match-string 1)) "src")
21422 ;; src blocks: let `org-edit-src-exit' handle them
21423 (org-get-indentation))
21424 ((equal (downcase (match-string 1)) "example")
21425 (max (org-get-indentation)
21426 (org-get-indentation (match-string 0))))
21428 (org-get-indentation (match-string 0))))))
21429 ;; This line has nothing special, look at the previous relevant
21430 ;; line to compute indentation
21432 (beginning-of-line 0)
21433 (while (and (not (bobp))
21434 (not (looking-at org-table-line-regexp))
21435 (not (looking-at org-drawer-regexp))
21436 ;; When point started in an inline task, do not move
21437 ;; above task starting line.
21438 (not (and inline-task-p (looking-at inline-re)))
21439 ;; Skip drawers, blocks, empty lines, verbatim,
21440 ;; comments, tables, footnotes definitions, lists,
21441 ;; inline tasks.
21442 (or (and (looking-at "[ \t]*:END:")
21443 (re-search-backward org-drawer-regexp nil t))
21444 (and (looking-at "[ \t]*#\\+end_")
21445 (re-search-backward "[ \t]*#\\+begin_"nil t))
21446 (looking-at "[ \t]*[\n:#|]")
21447 (looking-at org-footnote-definition-re)
21448 (and (ignore-errors (goto-char (org-in-item-p)))
21449 (goto-char
21450 (org-list-get-top-point (org-list-struct))))
21451 (and (not inline-task-p)
21452 (featurep 'org-inlinetask)
21453 (org-inlinetask-in-task-p)
21454 (or (org-inlinetask-goto-beginning) t))))
21455 (beginning-of-line 0))
21456 (cond
21457 ;; There was an heading above.
21458 ((looking-at "\\*+[ \t]+")
21459 (if (not org-adapt-indentation)
21460 (setq column 0)
21461 (goto-char (match-end 0))
21462 (setq column (current-column))))
21463 ;; A drawer had started and is unfinished
21464 ((looking-at org-drawer-regexp)
21465 (goto-char (1- (match-beginning 1)))
21466 (setq column (current-column)))
21467 ;; Else, nothing noticeable found: get indentation and go on.
21468 (t (setq column (org-get-indentation))))))
21469 ;; Now apply indentation and move cursor accordingly
21470 (goto-char pos)
21471 (if (<= (current-column) (current-indentation))
21472 (org-indent-line-to column)
21473 (save-excursion (org-indent-line-to column)))
21474 ;; Special polishing for properties, see `org-property-format'
21475 (setq column (current-column))
21476 (beginning-of-line 1)
21477 (if (looking-at
21478 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21479 (replace-match (concat (match-string 1)
21480 (format org-property-format
21481 (match-string 2) (match-string 3)))
21482 t t))
21483 (org-move-to-column column))))
21485 (defun org-indent-drawer ()
21486 "Indent the drawer at point."
21487 (interactive)
21488 (let ((p (point))
21489 (e (and (save-excursion (re-search-forward ":END:" nil t))
21490 (match-end 0)))
21491 (folded
21492 (save-excursion
21493 (end-of-line)
21494 (when (overlays-at (point))
21495 (member 'invisible (overlay-properties
21496 (car (overlays-at (point)))))))))
21497 (when folded (org-cycle))
21498 (indent-for-tab-command)
21499 (while (and (move-beginning-of-line 2) (< (point) e))
21500 (indent-for-tab-command))
21501 (goto-char p)
21502 (when folded (org-cycle)))
21503 (message "Drawer at point indented"))
21505 (defun org-indent-block ()
21506 "Indent the block at point."
21507 (interactive)
21508 (let ((p (point))
21509 (case-fold-search t)
21510 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21511 (match-end 0)))
21512 (folded
21513 (save-excursion
21514 (end-of-line)
21515 (when (overlays-at (point))
21516 (member 'invisible (overlay-properties
21517 (car (overlays-at (point)))))))))
21518 (when folded (org-cycle))
21519 (indent-for-tab-command)
21520 (while (and (move-beginning-of-line 2) (< (point) e))
21521 (indent-for-tab-command))
21522 (goto-char p)
21523 (when folded (org-cycle)))
21524 (message "Block at point indented"))
21526 (defun org-indent-region (start end)
21527 "Indent region."
21528 (interactive "r")
21529 (save-excursion
21530 (let ((line-end (org-current-line end)))
21531 (goto-char start)
21532 (while (< (org-current-line) line-end)
21533 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21534 (t (call-interactively 'org-indent-line)))
21535 (move-beginning-of-line 2)))))
21538 ;;; Filling
21540 ;; We use our own fill-paragraph and auto-fill functions.
21542 ;; `org-fill-paragraph' relies on adaptive filling and context
21543 ;; checking. Appropriate `fill-prefix' is computed with
21544 ;; `org-adaptive-fill-function'.
21546 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21547 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21548 ;; `org-adaptive-fill-function' value. Internally,
21549 ;; `org-comment-line-break-function' breaks the line.
21551 ;; `org-setup-filling' installs filling and auto-filling related
21552 ;; variables during `org-mode' initialization.
21554 (defun org-setup-filling ()
21555 (interactive)
21556 ;; Prevent auto-fill from inserting unwanted new items.
21557 (when (boundp 'fill-nobreak-predicate)
21558 (org-set-local
21559 'fill-nobreak-predicate
21560 (org-uniquify
21561 (append fill-nobreak-predicate
21562 '(org-fill-paragraph-separate-nobreak-p
21563 org-fill-line-break-nobreak-p)))))
21564 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21565 (org-set-local 'auto-fill-inhibit-regexp nil)
21566 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21567 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21568 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21570 (defvar org-element-paragraph-separate) ; org-element.el
21571 (defun org-fill-paragraph-separate-nobreak-p ()
21572 "Non-nil when a line break at point would insert a new item."
21573 (looking-at (substring org-element-paragraph-separate 1)))
21575 (defun org-fill-line-break-nobreak-p ()
21576 "Non-nil when a line break at point would create an Org line break."
21577 (save-excursion
21578 (skip-chars-backward "[ \t]")
21579 (skip-chars-backward "\\\\")
21580 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21582 (declare-function message-in-body-p "message" ())
21583 (defun org-adaptive-fill-function ()
21584 "Compute a fill prefix for the current line.
21585 Return fill prefix, as a string, or nil if current line isn't
21586 meant to be filled."
21587 (let (prefix)
21588 (when (and (derived-mode-p 'message-mode) (message-in-body-p))
21589 (save-excursion
21590 (beginning-of-line)
21591 (cond ((looking-at message-cite-prefix-regexp)
21592 (setq prefix (match-string-no-properties 0)))
21593 ((looking-at org-outline-regexp)
21594 (setq prefix "")))))
21595 (or prefix
21596 (org-with-wide-buffer
21597 (let* ((p (line-beginning-position))
21598 (element (save-excursion (beginning-of-line)
21599 (org-element-at-point)))
21600 (type (org-element-type element))
21601 (post-affiliated (org-element-property :post-affiliated element)))
21602 (unless (and post-affiliated (< p post-affiliated))
21603 (case type
21604 (comment (looking-at "[ \t]*# ?") (match-string 0))
21605 (footnote-definition "")
21606 ((item plain-list)
21607 (make-string (org-list-item-body-column
21608 (or post-affiliated
21609 (org-element-property :begin element)))
21610 ? ))
21611 (paragraph
21612 ;; Fill prefix is usually the same as the current line,
21613 ;; except if the paragraph is at the beginning of an item.
21614 (let ((parent (org-element-property :parent element)))
21615 (cond ((eq (org-element-type parent) 'item)
21616 (make-string (org-list-item-body-column
21617 (org-element-property :begin parent))
21618 ? ))
21619 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21620 (match-string 0))
21621 (t ""))))
21622 (comment-block
21623 ;; Only fill contents if P is within block boundaries.
21624 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21625 (forward-line)
21626 (point)))
21627 (cend (save-excursion
21628 (goto-char (org-element-property :end element))
21629 (skip-chars-backward " \r\t\n")
21630 (line-beginning-position))))
21631 (when (and (>= p cbeg) (< p cend))
21632 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21633 (match-string 0)
21634 "")))))))))))
21636 (declare-function message-goto-body "message" ())
21637 (defvar message-cite-prefix-regexp) ; From message.el
21638 (defvar org-element-all-objects) ; From org-element.el
21639 (defun org-fill-paragraph (&optional justify)
21640 "Fill element at point, when applicable.
21642 This function only applies to comment blocks, comments, example
21643 blocks and paragraphs. Also, as a special case, re-align table
21644 when point is at one.
21646 If JUSTIFY is non-nil (interactively, with prefix argument),
21647 justify as well. If `sentence-end-double-space' is non-nil, then
21648 period followed by one space does not end a sentence, so don't
21649 break a line there. The variable `fill-column' controls the
21650 width for filling.
21652 For convenience, when point is at a plain list, an item or
21653 a footnote definition, try to fill the first paragraph within."
21654 (interactive)
21655 (if (and (derived-mode-p 'message-mode)
21656 (or (not (message-in-body-p))
21657 (save-excursion (move-beginning-of-line 1)
21658 (looking-at message-cite-prefix-regexp))))
21659 ;; First ensure filling is correct in message-mode.
21660 (let ((fill-paragraph-function
21661 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21662 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21663 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21664 (paragraph-separate
21665 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21666 (fill-paragraph nil))
21667 (save-excursion
21668 ;; Move to end of line in order to get the first paragraph
21669 ;; within a plain list or a footnote definition.
21670 (end-of-line)
21671 (let ((element (org-element-at-point)))
21672 ;; First check if point is in a blank line at the beginning of
21673 ;; the buffer. In that case, ignore filling.
21674 (if (< (point) (org-element-property :begin element)) t
21675 (case (org-element-type element)
21676 ;; Use major mode filling function is src blocks.
21677 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21678 ;; Align Org tables, leave table.el tables as-is.
21679 (table-row (org-table-align) t)
21680 (table
21681 (when (eq (org-element-property :type element) 'org)
21682 (org-table-align))
21684 (paragraph
21685 ;; Paragraphs may contain `line-break' type objects.
21686 (let ((beg (max (point-min)
21687 (org-element-property :contents-begin element)))
21688 (end (min (point-max)
21689 (org-element-property :contents-end element))))
21690 ;; Do nothing if point is at an affiliated keyword.
21691 (if (< (point) beg) t
21692 (when (derived-mode-p 'message-mode)
21693 ;; In `message-mode', do not fill following
21694 ;; citation in current paragraph nor text before
21695 ;; message body.
21696 (let ((body-start (save-excursion (message-goto-body))))
21697 (when body-start (setq beg (max body-start beg))))
21698 (when (save-excursion
21699 (re-search-forward
21700 (concat "^" message-cite-prefix-regexp) end t))
21701 (setq end (match-beginning 0))))
21702 ;; Fill paragraph, taking line breaks into
21703 ;; consideration. For that, slice the paragraph
21704 ;; using line breaks as separators, and fill the
21705 ;; parts in reverse order to avoid messing with
21706 ;; markers.
21707 (save-excursion
21708 (goto-char end)
21709 (mapc
21710 (lambda (pos)
21711 (fill-region-as-paragraph pos (point) justify)
21712 (goto-char pos))
21713 ;; Find the list of ending positions for line
21714 ;; breaks in the current paragraph. Add paragraph
21715 ;; beginning to include first slice.
21716 (nreverse
21717 (cons
21719 (org-element-map
21720 (org-element--parse-objects
21721 beg end nil org-element-all-objects)
21722 'line-break
21723 (lambda (lb) (org-element-property :end lb)))))))
21724 t)))
21725 ;; Contents of `comment-block' type elements should be
21726 ;; filled as plain text, but only if point is within block
21727 ;; markers.
21728 (comment-block
21729 (let* ((case-fold-search t)
21730 (beg (save-excursion
21731 (goto-char (org-element-property :begin element))
21732 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21733 (forward-line)
21734 (point)))
21735 (end (save-excursion
21736 (goto-char (org-element-property :end element))
21737 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21738 (line-beginning-position))))
21739 (when (and (>= (point) beg) (< (point) end))
21740 (fill-region-as-paragraph
21741 (save-excursion
21742 (end-of-line)
21743 (re-search-backward "^[ \t]*$" beg 'move)
21744 (line-beginning-position))
21745 (save-excursion
21746 (beginning-of-line)
21747 (re-search-forward "^[ \t]*$" end 'move)
21748 (line-beginning-position))
21749 justify)))
21751 ;; Fill comments.
21752 (comment (fill-comment-paragraph justify))
21753 ;; Ignore every other element.
21754 (otherwise t)))))))
21756 (defun org-auto-fill-function ()
21757 "Auto-fill function."
21758 ;; Check if auto-filling is meaningful.
21759 (let ((fc (current-fill-column)))
21760 (when (and fc (> (current-column) fc))
21761 (let* ((fill-prefix (org-adaptive-fill-function))
21762 ;; Enforce empty fill prefix, if required. Otherwise, it
21763 ;; will be computed again.
21764 (adaptive-fill-mode (not (equal fill-prefix ""))))
21765 (when fill-prefix (do-auto-fill))))))
21767 (defun org-comment-line-break-function (&optional soft)
21768 "Break line at point and indent, continuing comment if within one.
21769 The inserted newline is marked hard if variable
21770 `use-hard-newlines' is true, unless optional argument SOFT is
21771 non-nil."
21772 (if soft (insert-and-inherit ?\n) (newline 1))
21773 (save-excursion (forward-char -1) (delete-horizontal-space))
21774 (delete-horizontal-space)
21775 (indent-to-left-margin)
21776 (insert-before-markers-and-inherit fill-prefix))
21779 ;;; Comments
21781 ;; Org comments syntax is quite complex. It requires the entire line
21782 ;; to be just a comment. Also, even with the right syntax at the
21783 ;; beginning of line, some some elements (i.e. verse-block or
21784 ;; example-block) don't accept comments. Usual Emacs comment commands
21785 ;; cannot cope with those requirements. Therefore, Org replaces them.
21787 ;; Org still relies on `comment-dwim', but cannot trust
21788 ;; `comment-only-p'. So, `comment-region-function' and
21789 ;; `uncomment-region-function' both point
21790 ;; to`org-comment-or-uncomment-region'. Eventually,
21791 ;; `org-insert-comment' takes care of insertion of comments at the
21792 ;; beginning of line.
21794 ;; `org-setup-comments-handling' install comments related variables
21795 ;; during `org-mode' initialization.
21797 (defun org-setup-comments-handling ()
21798 (interactive)
21799 (org-set-local 'comment-use-syntax nil)
21800 (org-set-local 'comment-start "# ")
21801 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21802 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21803 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21804 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21806 (defun org-insert-comment ()
21807 "Insert an empty comment above current line.
21808 If the line is empty, insert comment at its beginning."
21809 (beginning-of-line)
21810 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21811 (org-indent-line)
21812 (insert "# "))
21814 (defvar comment-empty-lines) ; From newcomment.el.
21815 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21816 "Comment or uncomment each non-blank line in the region.
21817 Uncomment each non-blank line between BEG and END if it only
21818 contains commented lines. Otherwise, comment them."
21819 (save-restriction
21820 ;; Restrict region
21821 (narrow-to-region (save-excursion (goto-char beg)
21822 (skip-chars-forward " \r\t\n" end)
21823 (line-beginning-position))
21824 (save-excursion (goto-char end)
21825 (skip-chars-backward " \r\t\n" beg)
21826 (line-end-position)))
21827 (let ((uncommentp
21828 ;; UNCOMMENTP is non-nil when every non blank line between
21829 ;; BEG and END is a comment.
21830 (save-excursion
21831 (goto-char (point-min))
21832 (while (and (not (eobp))
21833 (let ((element (org-element-at-point)))
21834 (and (eq (org-element-type element) 'comment)
21835 (goto-char (min (point-max)
21836 (org-element-property
21837 :end element)))))))
21838 (eobp))))
21839 (if uncommentp
21840 ;; Only blank lines and comments in region: uncomment it.
21841 (save-excursion
21842 (goto-char (point-min))
21843 (while (not (eobp))
21844 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21845 (replace-match "" nil nil nil 1))
21846 (forward-line)))
21847 ;; Comment each line in region.
21848 (let ((min-indent (point-max)))
21849 ;; First find the minimum indentation across all lines.
21850 (save-excursion
21851 (goto-char (point-min))
21852 (while (and (not (eobp)) (not (zerop min-indent)))
21853 (unless (looking-at "[ \t]*$")
21854 (setq min-indent (min min-indent (current-indentation))))
21855 (forward-line)))
21856 ;; Then loop over all lines.
21857 (save-excursion
21858 (goto-char (point-min))
21859 (while (not (eobp))
21860 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21861 (org-move-to-column min-indent t)
21862 (insert comment-start))
21863 (forward-line))))))))
21866 ;;; Planning
21868 ;; This section contains tools to operate on timestamp objects, as
21869 ;; returned by, e.g. `org-element-context'.
21871 (defun org-timestamp-has-time-p (timestamp)
21872 "Non-nil when TIMESTAMP has a time specified."
21873 (org-element-property :hour-start timestamp))
21875 (defun org-timestamp-format (timestamp format &optional end utc)
21876 "Format a TIMESTAMP element into a string.
21878 FORMAT is a format specifier to be passed to
21879 `format-time-string'.
21881 When optional argument END is non-nil, use end of date-range or
21882 time-range, if possible.
21884 When optional argument UTC is non-nil, time will be expressed as
21885 Universal Time."
21886 (format-time-string
21887 format
21888 (apply 'encode-time
21889 (cons 0
21890 (mapcar
21891 (lambda (prop) (or (org-element-property prop timestamp) 0))
21892 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21893 '(:minute-start :hour-start :day-start :month-start
21894 :year-start)))))
21895 utc))
21897 (defun org-timestamp-split-range (timestamp &optional end)
21898 "Extract a timestamp object from a date or time range.
21900 TIMESTAMP is a timestamp object. END, when non-nil, means extract
21901 the end of the range. Otherwise, extract its start.
21903 Return a new timestamp object sharing the same parent as
21904 TIMESTAMP."
21905 (let ((type (org-element-property :type timestamp)))
21906 (if (memq type '(active inactive diary)) timestamp
21907 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
21908 ;; Set new type.
21909 (org-element-put-property
21910 split-ts :type (if (eq type 'active-range) 'active 'inactive))
21911 ;; Copy start properties over end properties if END is
21912 ;; non-nil. Otherwise, copy end properties over `start' ones.
21913 (let ((p-alist '((:minute-start . :minute-end)
21914 (:hour-start . :hour-end)
21915 (:day-start . :day-end)
21916 (:month-start . :month-end)
21917 (:year-start . :year-end))))
21918 (dolist (p-cell p-alist)
21919 (org-element-put-property
21920 split-ts
21921 (funcall (if end 'car 'cdr) p-cell)
21922 (org-element-property
21923 (funcall (if end 'cdr 'car) p-cell) split-ts)))
21924 ;; Eventually refresh `:raw-value'.
21925 (org-element-put-property split-ts :raw-value nil)
21926 (org-element-put-property
21927 split-ts :raw-value (org-element-interpret-data split-ts)))))))
21929 (defun org-timestamp-translate (timestamp &optional boundary)
21930 "Apply `org-translate-time' on a TIMESTAMP object.
21931 When optional argument BOUNDARY is non-nil, it is either the
21932 symbol `start' or `end'. In this case, only translate the
21933 starting or ending part of TIMESTAMP if it is a date or time
21934 range. Otherwise, translate both parts."
21935 (if (and (not boundary)
21936 (memq (org-element-property :type timestamp)
21937 '(active-range inactive-range)))
21938 (concat
21939 (org-translate-time
21940 (org-element-property :raw-value
21941 (org-timestamp-split-range timestamp)))
21942 "--"
21943 (org-translate-time
21944 (org-element-property :raw-value
21945 (org-timestamp-split-range timestamp t))))
21946 (org-translate-time
21947 (org-element-property
21948 :raw-value
21949 (if (not boundary) timestamp
21950 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
21954 ;;; Other stuff.
21956 (defun org-toggle-fixed-width-section (arg)
21957 "Toggle the fixed-width export.
21958 If there is no active region, the QUOTE keyword at the current headline is
21959 inserted or removed. When present, it causes the text between this headline
21960 and the next to be exported as fixed-width text, and unmodified.
21961 If there is an active region, this command adds or removes a colon as the
21962 first character of this line. If the first character of a line is a colon,
21963 this line is also exported in fixed-width font."
21964 (interactive "P")
21965 (let* ((cc 0)
21966 (regionp (org-region-active-p))
21967 (beg (if regionp (region-beginning) (point)))
21968 (end (if regionp (region-end)))
21969 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21970 (case-fold-search nil)
21971 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21972 off)
21973 (if regionp
21974 (save-excursion
21975 (goto-char beg)
21976 (setq cc (current-column))
21977 (beginning-of-line 1)
21978 (setq off (looking-at re))
21979 (while (> nlines 0)
21980 (setq nlines (1- nlines))
21981 (beginning-of-line 1)
21982 (cond
21983 (arg
21984 (org-move-to-column cc t)
21985 (insert ": \n")
21986 (forward-line -1))
21987 ((and off (looking-at re))
21988 (replace-match "" t t nil 1))
21989 ((not off) (org-move-to-column cc t) (insert ": ")))
21990 (forward-line 1)))
21991 (save-excursion
21992 (org-back-to-heading)
21993 (cond
21994 ((looking-at (format org-heading-keyword-regexp-format
21995 org-quote-string))
21996 (goto-char (match-end 1))
21997 (looking-at (concat " +" org-quote-string))
21998 (replace-match "" t t)
21999 (when (eolp) (insert " ")))
22000 ((looking-at org-outline-regexp)
22001 (goto-char (match-end 0))
22002 (insert org-quote-string " ")))))))
22004 (defun org-reftex-citation ()
22005 "Use reftex-citation to insert a citation into the buffer.
22006 This looks for a line like
22008 #+BIBLIOGRAPHY: foo plain option:-d
22010 and derives from it that foo.bib is the bibliography file relevant
22011 for this document. It then installs the necessary environment for RefTeX
22012 to work in this buffer and calls `reftex-citation' to insert a citation
22013 into the buffer.
22015 Export of such citations to both LaTeX and HTML is handled by the contributed
22016 package org-exp-bibtex by Taru Karttunen."
22017 (interactive)
22018 (let ((reftex-docstruct-symbol 'rds)
22019 (reftex-cite-format "\\cite{%l}")
22020 rds bib)
22021 (save-excursion
22022 (save-restriction
22023 (widen)
22024 (let ((case-fold-search t)
22025 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22026 (if (not (save-excursion
22027 (or (re-search-forward re nil t)
22028 (re-search-backward re nil t))))
22029 (error "No bibliography defined in file")
22030 (setq bib (concat (match-string 1) ".bib")
22031 rds (list (list 'bib bib)))))))
22032 (call-interactively 'reftex-citation)))
22034 ;;;; Functions extending outline functionality
22036 (defun org-beginning-of-line (&optional arg)
22037 "Go to the beginning of the current line. If that is invisible, continue
22038 to a visible line beginning. This makes the function of C-a more intuitive.
22039 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22040 first attempt, and only move to after the tags when the cursor is already
22041 beyond the end of the headline."
22042 (interactive "P")
22043 (let ((pos (point))
22044 (special (if (consp org-special-ctrl-a/e)
22045 (car org-special-ctrl-a/e)
22046 org-special-ctrl-a/e))
22047 refpos)
22048 (if (org-bound-and-true-p visual-line-mode)
22049 (beginning-of-visual-line 1)
22050 (beginning-of-line 1))
22051 (if (and arg (fboundp 'move-beginning-of-line))
22052 (call-interactively 'move-beginning-of-line)
22053 (if (bobp)
22055 (backward-char 1)
22056 (if (org-truely-invisible-p)
22057 (while (and (not (bobp)) (org-truely-invisible-p))
22058 (backward-char 1)
22059 (beginning-of-line 1))
22060 (forward-char 1))))
22061 (when special
22062 (cond
22063 ((and (looking-at org-complex-heading-regexp)
22064 (= (char-after (match-end 1)) ?\ ))
22065 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22066 (point-at-eol)))
22067 (goto-char
22068 (if (eq special t)
22069 (cond ((> pos refpos) refpos)
22070 ((= pos (point)) refpos)
22071 (t (point)))
22072 (cond ((> pos (point)) (point))
22073 ((not (eq last-command this-command)) (point))
22074 (t refpos)))))
22075 ((org-at-item-p)
22076 ;; Being at an item and not looking at an the item means point
22077 ;; was previously moved to beginning of a visual line, which
22078 ;; doesn't contain the item. Therefore, do nothing special,
22079 ;; just stay here.
22080 (when (looking-at org-list-full-item-re)
22081 ;; Set special position at first white space character after
22082 ;; bullet, and check-box, if any.
22083 (let ((after-bullet
22084 (let ((box (match-end 3)))
22085 (if (not box) (match-end 1)
22086 (let ((after (char-after box)))
22087 (if (and after (= after ? )) (1+ box) box))))))
22088 ;; Special case: Move point to special position when
22089 ;; currently after it or at beginning of line.
22090 (if (eq special t)
22091 (when (or (> pos after-bullet) (= (point) pos))
22092 (goto-char after-bullet))
22093 ;; Reversed case: Move point to special position when
22094 ;; point was already at beginning of line and command is
22095 ;; repeated.
22096 (when (and (= (point) pos) (eq last-command this-command))
22097 (goto-char after-bullet))))))))
22098 (org-no-warnings
22099 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22101 (defun org-end-of-line (&optional arg)
22102 "Go to the end of the line.
22103 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22104 tags on the first attempt, and only move to after the tags when
22105 the cursor is already beyond the end of the headline."
22106 (interactive "P")
22107 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22108 org-special-ctrl-a/e))
22109 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22110 'end-of-visual-line)
22111 ((fboundp 'move-end-of-line) 'move-end-of-line)
22112 (t 'end-of-line))))
22113 (if (or (not special) arg) (call-interactively move-fun)
22114 (let* ((element (save-excursion (beginning-of-line)
22115 (org-element-at-point)))
22116 (type (org-element-type element)))
22117 (cond
22118 ((memq type '(headline inlinetask))
22119 (let ((pos (point)))
22120 (beginning-of-line 1)
22121 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22122 (if (eq special t)
22123 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22124 (goto-char (match-beginning 1))
22125 (goto-char (match-end 0)))
22126 (if (or (< pos (match-end 0))
22127 (not (eq this-command last-command)))
22128 (goto-char (match-end 0))
22129 (goto-char (match-beginning 1))))
22130 (call-interactively move-fun))))
22131 ((org-element-property :hiddenp element)
22132 ;; If element is hidden, `move-end-of-line' would put point
22133 ;; after it. Use `end-of-line' to stay on current line.
22134 (call-interactively 'end-of-line))
22135 (t (call-interactively move-fun)))))
22136 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22138 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22139 (define-key org-mode-map "\C-e" 'org-end-of-line)
22141 (defun org-backward-sentence (&optional arg)
22142 "Go to beginning of sentence, or beginning of table field.
22143 This will call `backward-sentence' or `org-table-beginning-of-field',
22144 depending on context."
22145 (interactive "P")
22146 (cond
22147 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22148 (t (call-interactively 'backward-sentence))))
22150 (defun org-forward-sentence (&optional arg)
22151 "Go to end of sentence, or end of table field.
22152 This will call `forward-sentence' or `org-table-end-of-field',
22153 depending on context."
22154 (interactive "P")
22155 (cond
22156 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22157 (t (call-interactively 'forward-sentence))))
22159 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22160 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22162 (defun org-kill-line (&optional arg)
22163 "Kill line, to tags or end of line."
22164 (interactive "P")
22165 (cond
22166 ((or (not org-special-ctrl-k)
22167 (bolp)
22168 (not (org-at-heading-p)))
22169 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22170 org-ctrl-k-protect-subtree)
22171 (if (or (eq org-ctrl-k-protect-subtree 'error)
22172 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22173 (error "C-k aborted - would kill hidden subtree")))
22174 (call-interactively
22175 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22176 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22177 (kill-region (point) (match-beginning 1))
22178 (org-set-tags nil t))
22179 (t (kill-region (point) (point-at-eol)))))
22181 (define-key org-mode-map "\C-k" 'org-kill-line)
22183 (defun org-yank (&optional arg)
22184 "Yank. If the kill is a subtree, treat it specially.
22185 This command will look at the current kill and check if is a single
22186 subtree, or a series of subtrees[1]. If it passes the test, and if the
22187 cursor is at the beginning of a line or after the stars of a currently
22188 empty headline, then the yank is handled specially. How exactly depends
22189 on the value of the following variables, both set by default.
22191 org-yank-folded-subtrees
22192 When set, the subtree(s) will be folded after insertion, but only
22193 if doing so would now swallow text after the yanked text.
22195 org-yank-adjusted-subtrees
22196 When set, the subtree will be promoted or demoted in order to
22197 fit into the local outline tree structure, which means that the level
22198 will be adjusted so that it becomes the smaller one of the two
22199 *visible* surrounding headings.
22201 Any prefix to this command will cause `yank' to be called directly with
22202 no special treatment. In particular, a simple \\[universal-argument] prefix \
22203 will just
22204 plainly yank the text as it is.
22206 \[1] The test checks if the first non-white line is a heading
22207 and if there are no other headings with fewer stars."
22208 (interactive "P")
22209 (org-yank-generic 'yank arg))
22211 (defun org-yank-generic (command arg)
22212 "Perform some yank-like command.
22214 This function implements the behavior described in the `org-yank'
22215 documentation. However, it has been generalized to work for any
22216 interactive command with similar behavior."
22218 ;; pretend to be command COMMAND
22219 (setq this-command command)
22221 (if arg
22222 (call-interactively command)
22224 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22225 (and (org-kill-is-subtree-p)
22226 (or (bolp)
22227 (and (looking-at "[ \t]*$")
22228 (string-match
22229 "\\`\\*+\\'"
22230 (buffer-substring (point-at-bol) (point)))))))
22231 swallowp)
22232 (cond
22233 ((and subtreep org-yank-folded-subtrees)
22234 (let ((beg (point))
22235 end)
22236 (if (and subtreep org-yank-adjusted-subtrees)
22237 (org-paste-subtree nil nil 'for-yank)
22238 (call-interactively command))
22240 (setq end (point))
22241 (goto-char beg)
22242 (when (and (bolp) subtreep
22243 (not (setq swallowp
22244 (org-yank-folding-would-swallow-text beg end))))
22245 (org-with-limited-levels
22246 (or (looking-at org-outline-regexp)
22247 (re-search-forward org-outline-regexp-bol end t))
22248 (while (and (< (point) end) (looking-at org-outline-regexp))
22249 (hide-subtree)
22250 (org-cycle-show-empty-lines 'folded)
22251 (condition-case nil
22252 (outline-forward-same-level 1)
22253 (error (goto-char end))))))
22254 (when swallowp
22255 (message
22256 "Inserted text not folded because that would swallow text"))
22258 (goto-char end)
22259 (skip-chars-forward " \t\n\r")
22260 (beginning-of-line 1)
22261 (push-mark beg 'nomsg)))
22262 ((and subtreep org-yank-adjusted-subtrees)
22263 (let ((beg (point-at-bol)))
22264 (org-paste-subtree nil nil 'for-yank)
22265 (push-mark beg 'nomsg)))
22267 (call-interactively command))))))
22269 (defun org-yank-folding-would-swallow-text (beg end)
22270 "Would hide-subtree at BEG swallow any text after END?"
22271 (let (level)
22272 (org-with-limited-levels
22273 (save-excursion
22274 (goto-char beg)
22275 (when (or (looking-at org-outline-regexp)
22276 (re-search-forward org-outline-regexp-bol end t))
22277 (setq level (org-outline-level)))
22278 (goto-char end)
22279 (skip-chars-forward " \t\r\n\v\f")
22280 (if (or (eobp)
22281 (and (bolp) (looking-at org-outline-regexp)
22282 (<= (org-outline-level) level)))
22283 nil ; Nothing would be swallowed
22284 t))))) ; something would swallow
22286 (define-key org-mode-map "\C-y" 'org-yank)
22288 (defun org-truely-invisible-p ()
22289 "Check if point is at a character currently not visible.
22290 This version does not only check the character property, but also
22291 `visible-mode'."
22292 ;; Early versions of noutline don't have `outline-invisible-p'.
22293 (if (org-bound-and-true-p visible-mode)
22295 (outline-invisible-p)))
22297 (defun org-invisible-p2 ()
22298 "Check if point is at a character currently not visible."
22299 (save-excursion
22300 (if (and (eolp) (not (bobp))) (backward-char 1))
22301 ;; Early versions of noutline don't have `outline-invisible-p'.
22302 (outline-invisible-p)))
22304 (defun org-back-to-heading (&optional invisible-ok)
22305 "Call `outline-back-to-heading', but provide a better error message."
22306 (condition-case nil
22307 (outline-back-to-heading invisible-ok)
22308 (error (error "Before first headline at position %d in buffer %s"
22309 (point) (current-buffer)))))
22311 (defun org-before-first-heading-p ()
22312 "Before first heading?"
22313 (save-excursion
22314 (end-of-line)
22315 (null (re-search-backward org-outline-regexp-bol nil t))))
22317 (defun org-at-heading-p (&optional ignored)
22318 (outline-on-heading-p t))
22319 ;; Compatibility alias with Org versions < 7.8.03
22320 (defalias 'org-on-heading-p 'org-at-heading-p)
22322 (defun org-at-comment-p nil
22323 "Is cursor in a line starting with a # character?"
22324 (save-excursion
22325 (beginning-of-line)
22326 (looking-at "^#")))
22328 (defun org-at-drawer-p nil
22329 "Is cursor at a drawer keyword?"
22330 (save-excursion
22331 (move-beginning-of-line 1)
22332 (looking-at org-drawer-regexp)))
22334 (defun org-at-block-p nil
22335 "Is cursor at a block keyword?"
22336 (save-excursion
22337 (move-beginning-of-line 1)
22338 (looking-at org-block-regexp)))
22340 (defun org-point-at-end-of-empty-headline ()
22341 "If point is at the end of an empty headline, return t, else nil.
22342 If the heading only contains a TODO keyword, it is still still considered
22343 empty."
22344 (and (looking-at "[ \t]*$")
22345 (when org-todo-line-regexp
22346 (save-excursion
22347 (beginning-of-line 1)
22348 (let ((case-fold-search nil))
22349 (looking-at org-todo-line-regexp)
22350 (string= (match-string 3) ""))))))
22352 (defun org-at-heading-or-item-p ()
22353 (or (org-at-heading-p) (org-at-item-p)))
22355 (defun org-at-target-p ()
22356 (or (org-in-regexp org-radio-target-regexp)
22357 (org-in-regexp org-target-regexp)))
22358 ;; Compatibility alias with Org versions < 7.8.03
22359 (defalias 'org-on-target-p 'org-at-target-p)
22361 (defun org-up-heading-all (arg)
22362 "Move to the heading line of which the present line is a subheading.
22363 This function considers both visible and invisible heading lines.
22364 With argument, move up ARG levels."
22365 (if (fboundp 'outline-up-heading-all)
22366 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22367 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22369 (defun org-up-heading-safe ()
22370 "Move to the heading line of which the present line is a subheading.
22371 This version will not throw an error. It will return the level of the
22372 headline found, or nil if no higher level is found.
22374 Also, this function will be a lot faster than `outline-up-heading',
22375 because it relies on stars being the outline starters. This can really
22376 make a significant difference in outlines with very many siblings."
22377 (let (start-level re)
22378 (org-back-to-heading t)
22379 (setq start-level (funcall outline-level))
22380 (if (equal start-level 1)
22382 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22383 (if (re-search-backward re nil t)
22384 (funcall outline-level)))))
22386 (defun org-first-sibling-p ()
22387 "Is this heading the first child of its parents?"
22388 (interactive)
22389 (let ((re org-outline-regexp-bol)
22390 level l)
22391 (unless (org-at-heading-p t)
22392 (error "Not at a heading"))
22393 (setq level (funcall outline-level))
22394 (save-excursion
22395 (if (not (re-search-backward re nil t))
22397 (setq l (funcall outline-level))
22398 (< l level)))))
22400 (defun org-goto-sibling (&optional previous)
22401 "Goto the next sibling, even if it is invisible.
22402 When PREVIOUS is set, go to the previous sibling instead. Returns t
22403 when a sibling was found. When none is found, return nil and don't
22404 move point."
22405 (let ((fun (if previous 're-search-backward 're-search-forward))
22406 (pos (point))
22407 (re org-outline-regexp-bol)
22408 level l)
22409 (when (condition-case nil (org-back-to-heading t) (error nil))
22410 (setq level (funcall outline-level))
22411 (catch 'exit
22412 (or previous (forward-char 1))
22413 (while (funcall fun re nil t)
22414 (setq l (funcall outline-level))
22415 (when (< l level) (goto-char pos) (throw 'exit nil))
22416 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22417 (goto-char pos)
22418 nil))))
22420 (defun org-show-siblings ()
22421 "Show all siblings of the current headline."
22422 (save-excursion
22423 (while (org-goto-sibling) (org-flag-heading nil)))
22424 (save-excursion
22425 (while (org-goto-sibling 'previous)
22426 (org-flag-heading nil))))
22428 (defun org-goto-first-child ()
22429 "Goto the first child, even if it is invisible.
22430 Return t when a child was found. Otherwise don't move point and
22431 return nil."
22432 (let (level (pos (point)) (re org-outline-regexp-bol))
22433 (when (condition-case nil (org-back-to-heading t) (error nil))
22434 (setq level (outline-level))
22435 (forward-char 1)
22436 (if (and (re-search-forward re nil t) (> (outline-level) level))
22437 (progn (goto-char (match-beginning 0)) t)
22438 (goto-char pos) nil))))
22440 (defun org-show-hidden-entry ()
22441 "Show an entry where even the heading is hidden."
22442 (save-excursion
22443 (org-show-entry)))
22445 (defun org-flag-heading (flag &optional entry)
22446 "Flag the current heading. FLAG non-nil means make invisible.
22447 When ENTRY is non-nil, show the entire entry."
22448 (save-excursion
22449 (org-back-to-heading t)
22450 ;; Check if we should show the entire entry
22451 (if entry
22452 (progn
22453 (org-show-entry)
22454 (save-excursion
22455 (and (outline-next-heading)
22456 (org-flag-heading nil))))
22457 (outline-flag-region (max (point-min) (1- (point)))
22458 (save-excursion (outline-end-of-heading) (point))
22459 flag))))
22461 (defun org-get-next-sibling ()
22462 "Move to next heading of the same level, and return point.
22463 If there is no such heading, return nil.
22464 This is like outline-next-sibling, but invisible headings are ok."
22465 (let ((level (funcall outline-level)))
22466 (outline-next-heading)
22467 (while (and (not (eobp)) (> (funcall outline-level) level))
22468 (outline-next-heading))
22469 (if (or (eobp) (< (funcall outline-level) level))
22471 (point))))
22473 (defun org-get-last-sibling ()
22474 "Move to previous heading of the same level, and return point.
22475 If there is no such heading, return nil."
22476 (let ((opoint (point))
22477 (level (funcall outline-level)))
22478 (outline-previous-heading)
22479 (when (and (/= (point) opoint) (outline-on-heading-p t))
22480 (while (and (> (funcall outline-level) level)
22481 (not (bobp)))
22482 (outline-previous-heading))
22483 (if (< (funcall outline-level) level)
22485 (point)))))
22487 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22488 "Goto to the end of a subtree."
22489 ;; This contains an exact copy of the original function, but it uses
22490 ;; `org-back-to-heading', to make it work also in invisible
22491 ;; trees. And is uses an invisible-ok argument.
22492 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22493 ;; Furthermore, when used inside Org, finding the end of a large subtree
22494 ;; with many children and grandchildren etc, this can be much faster
22495 ;; than the outline version.
22496 (org-back-to-heading invisible-ok)
22497 (let ((first t)
22498 (level (funcall outline-level)))
22499 (if (and (derived-mode-p 'org-mode) (< level 1000))
22500 ;; A true heading (not a plain list item), in Org-mode
22501 ;; This means we can easily find the end by looking
22502 ;; only for the right number of stars. Using a regexp to do
22503 ;; this is so much faster than using a Lisp loop.
22504 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22505 (forward-char 1)
22506 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22507 ;; something else, do it the slow way
22508 (while (and (not (eobp))
22509 (or first (> (funcall outline-level) level)))
22510 (setq first nil)
22511 (outline-next-heading)))
22512 (unless to-heading
22513 (if (memq (preceding-char) '(?\n ?\^M))
22514 (progn
22515 ;; Go to end of line before heading
22516 (forward-char -1)
22517 (if (memq (preceding-char) '(?\n ?\^M))
22518 ;; leave blank line before heading
22519 (forward-char -1))))))
22520 (point))
22522 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22523 "Use Org version in org-mode, for dramatic speed-up."
22524 (if (derived-mode-p 'org-mode)
22525 (progn
22526 (org-end-of-subtree nil t)
22527 (unless (eobp) (backward-char 1)))
22528 ad-do-it))
22530 (defun org-end-of-meta-data-and-drawers ()
22531 "Jump to the first text after meta data and drawers in the current entry.
22532 This will move over empty lines, lines with planning time stamps,
22533 clocking lines, and drawers."
22534 (org-back-to-heading t)
22535 (let ((end (save-excursion (outline-next-heading) (point)))
22536 (re (concat "\\(" org-drawer-regexp "\\)"
22537 "\\|" "[ \t]*" org-keyword-time-regexp)))
22538 (forward-line 1)
22539 (while (re-search-forward re end t)
22540 (if (not (match-end 1))
22541 ;; empty or planning line
22542 (forward-line 1)
22543 ;; a drawer, find the end
22544 (re-search-forward "^[ \t]*:END:" end 'move)
22545 (forward-line 1)))
22546 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22547 (point)))
22549 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22550 "Move forward to the arg'th subheading at same level as this one.
22551 Stop at the first and last subheadings of a superior heading.
22552 Normally this only looks at visible headings, but when INVISIBLE-OK is
22553 non-nil it will also look at invisible ones."
22554 (interactive "p")
22555 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22556 (outline-next-heading)
22557 (org-at-heading-p)
22558 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22559 (re (format "^\\*\\{1,%d\\} " level))
22561 (forward-char 1)
22562 (while (> arg 0)
22563 (while (and (re-search-forward re nil 'move)
22564 (setq l (- (match-end 0) (match-beginning 0) 1))
22565 (= l level)
22566 (not invisible-ok)
22567 (progn (backward-char 1) (outline-invisible-p)))
22568 (if (< l level) (setq arg 1)))
22569 (setq arg (1- arg)))
22570 (beginning-of-line 1))))
22572 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22573 "Move backward to the arg'th subheading at same level as this one.
22574 Stop at the first and last subheadings of a superior heading."
22575 (interactive "p")
22576 (if (not (ignore-errors (org-back-to-heading)))
22577 (goto-char (point-min))
22578 (org-at-heading-p)
22579 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22580 (re (format "^\\*\\{1,%d\\} " level))
22582 (while (> arg 0)
22583 (while (and (re-search-backward re nil 'move)
22584 (setq l (- (match-end 0) (match-beginning 0) 1))
22585 (= l level)
22586 (not invisible-ok)
22587 (outline-invisible-p))
22588 (if (< l level) (setq arg 1)))
22589 (setq arg (1- arg))))))
22591 (defun org-forward-element ()
22592 "Move forward by one element.
22593 Move to the next element at the same level, when possible."
22594 (interactive)
22595 (cond ((eobp) (error "Cannot move further down"))
22596 ((org-with-limited-levels (org-at-heading-p))
22597 (let ((origin (point)))
22598 (org-forward-heading-same-level 1)
22599 (unless (org-with-limited-levels (org-at-heading-p))
22600 (goto-char origin)
22601 (error "Cannot move further down"))))
22603 (let* ((elem (org-element-at-point))
22604 (end (org-element-property :end elem))
22605 (parent (org-element-property :parent elem)))
22606 (if (and parent (= (org-element-property :contents-end parent) end))
22607 (goto-char (org-element-property :end parent))
22608 (goto-char end))))))
22610 (defun org-backward-element ()
22611 "Move backward by one element.
22612 Move to the previous element at the same level, when possible."
22613 (interactive)
22614 (cond ((bobp) (error "Cannot move further up"))
22615 ((org-with-limited-levels (org-at-heading-p))
22616 ;; At an headline, move to the previous one, if any, or stay
22617 ;; here.
22618 (let ((origin (point)))
22619 (org-backward-heading-same-level 1)
22620 (unless (org-with-limited-levels (org-at-heading-p))
22621 (goto-char origin)
22622 (error "Cannot move further up"))))
22624 (let* ((trail (org-element-at-point 'keep-trail))
22625 (elem (car trail))
22626 (prev-elem (nth 1 trail))
22627 (beg (org-element-property :begin elem)))
22628 (cond
22629 ;; Move to beginning of current element if point isn't
22630 ;; there already.
22631 ((/= (point) beg) (goto-char beg))
22632 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22633 ((org-before-first-heading-p) (goto-char (point-min)))
22634 (t (org-back-to-heading)))))))
22636 (defun org-up-element ()
22637 "Move to upper element."
22638 (interactive)
22639 (if (org-with-limited-levels (org-at-heading-p))
22640 (unless (org-up-heading-safe) (error "No surrounding element"))
22641 (let* ((elem (org-element-at-point))
22642 (parent (org-element-property :parent elem)))
22643 (if parent (goto-char (org-element-property :begin parent))
22644 (if (org-with-limited-levels (org-before-first-heading-p))
22645 (error "No surrounding element")
22646 (org-with-limited-levels (org-back-to-heading)))))))
22648 (defvar org-element-greater-elements)
22649 (defun org-down-element ()
22650 "Move to inner element."
22651 (interactive)
22652 (let ((element (org-element-at-point)))
22653 (cond
22654 ((memq (org-element-type element) '(plain-list table))
22655 (goto-char (org-element-property :contents-begin element))
22656 (forward-char))
22657 ((memq (org-element-type element) org-element-greater-elements)
22658 ;; If contents are hidden, first disclose them.
22659 (when (org-element-property :hiddenp element) (org-cycle))
22660 (goto-char (or (org-element-property :contents-begin element)
22661 (error "No content for this element"))))
22662 (t (error "No inner element")))))
22664 (defun org-drag-element-backward ()
22665 "Move backward element at point."
22666 (interactive)
22667 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22668 (let* ((trail (org-element-at-point 'keep-trail))
22669 (elem (car trail))
22670 (prev-elem (nth 1 trail)))
22671 ;; Error out if no previous element or previous element is
22672 ;; a parent of the current one.
22673 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22674 (error "Cannot drag element backward")
22675 (let ((pos (point)))
22676 (org-element-swap-A-B prev-elem elem)
22677 (goto-char (+ (org-element-property :begin prev-elem)
22678 (- pos (org-element-property :begin elem)))))))))
22680 (defun org-drag-element-forward ()
22681 "Move forward element at point."
22682 (interactive)
22683 (let* ((pos (point))
22684 (elem (org-element-at-point)))
22685 (when (= (point-max) (org-element-property :end elem))
22686 (error "Cannot drag element forward"))
22687 (goto-char (org-element-property :end elem))
22688 (let ((next-elem (org-element-at-point)))
22689 (when (or (org-element-nested-p elem next-elem)
22690 (and (eq (org-element-type next-elem) 'headline)
22691 (not (eq (org-element-type elem) 'headline))))
22692 (goto-char pos)
22693 (error "Cannot drag element forward"))
22694 ;; Compute new position of point: it's shifted by NEXT-ELEM
22695 ;; body's length (without final blanks) and by the length of
22696 ;; blanks between ELEM and NEXT-ELEM.
22697 (let ((size-next (- (save-excursion
22698 (goto-char (org-element-property :end next-elem))
22699 (skip-chars-backward " \r\t\n")
22700 (forward-line)
22701 ;; Small correction if buffer doesn't end
22702 ;; with a newline character.
22703 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22704 (org-element-property :begin next-elem)))
22705 (size-blank (- (org-element-property :end elem)
22706 (save-excursion
22707 (goto-char (org-element-property :end elem))
22708 (skip-chars-backward " \r\t\n")
22709 (forward-line)
22710 (point)))))
22711 (org-element-swap-A-B elem next-elem)
22712 (goto-char (+ pos size-next size-blank))))))
22714 (defun org-mark-element ()
22715 "Put point at beginning of this element, mark at end.
22717 Interactively, if this command is repeated or (in Transient Mark
22718 mode) if the mark is active, it marks the next element after the
22719 ones already marked."
22720 (interactive)
22721 (let (deactivate-mark)
22722 (if (and (org-called-interactively-p 'any)
22723 (or (and (eq last-command this-command) (mark t))
22724 (and transient-mark-mode mark-active)))
22725 (set-mark
22726 (save-excursion
22727 (goto-char (mark))
22728 (goto-char (org-element-property :end (org-element-at-point)))))
22729 (let ((element (org-element-at-point)))
22730 (end-of-line)
22731 (push-mark (org-element-property :end element) t t)
22732 (goto-char (org-element-property :begin element))))))
22734 (defun org-narrow-to-element ()
22735 "Narrow buffer to current element."
22736 (interactive)
22737 (let ((elem (org-element-at-point)))
22738 (cond
22739 ((eq (car elem) 'headline)
22740 (narrow-to-region
22741 (org-element-property :begin elem)
22742 (org-element-property :end elem)))
22743 ((memq (car elem) org-element-greater-elements)
22744 (narrow-to-region
22745 (org-element-property :contents-begin elem)
22746 (org-element-property :contents-end elem)))
22748 (narrow-to-region
22749 (org-element-property :begin elem)
22750 (org-element-property :end elem))))))
22752 (defun org-transpose-words ()
22753 "Transpose words, using `org-mode' syntax table."
22754 (interactive)
22755 (with-syntax-table org-syntax-table
22756 (call-interactively 'transpose-words)))
22757 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22759 (defun org-transpose-element ()
22760 "Transpose current and previous elements, keeping blank lines between.
22761 Point is moved after both elements."
22762 (interactive)
22763 (org-skip-whitespace)
22764 (let ((end (org-element-property :end (org-element-at-point))))
22765 (org-drag-element-backward)
22766 (goto-char end)))
22768 (defun org-unindent-buffer ()
22769 "Un-indent the visible part of the buffer.
22770 Relative indentation (between items, inside blocks, etc.) isn't
22771 modified."
22772 (interactive)
22773 (unless (eq major-mode 'org-mode)
22774 (error "Cannot un-indent a buffer not in Org mode"))
22775 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22776 unindent-tree ; For byte-compiler.
22777 (unindent-tree
22778 (function
22779 (lambda (contents)
22780 (mapc
22781 (lambda (element)
22782 (if (memq (org-element-type element) '(headline section))
22783 (funcall unindent-tree (org-element-contents element))
22784 (save-excursion
22785 (save-restriction
22786 (narrow-to-region
22787 (org-element-property :begin element)
22788 (org-element-property :end element))
22789 (org-do-remove-indentation)))))
22790 (reverse contents))))))
22791 (funcall unindent-tree (org-element-contents parse-tree))))
22793 (defun org-show-subtree ()
22794 "Show everything after this heading at deeper levels."
22795 (interactive)
22796 (outline-flag-region
22797 (point)
22798 (save-excursion
22799 (org-end-of-subtree t t))
22800 nil))
22802 (defun org-show-entry ()
22803 "Show the body directly following this heading.
22804 Show the heading too, if it is currently invisible."
22805 (interactive)
22806 (save-excursion
22807 (condition-case nil
22808 (progn
22809 (org-back-to-heading t)
22810 (outline-flag-region
22811 (max (point-min) (1- (point)))
22812 (save-excursion
22813 (if (re-search-forward
22814 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22815 (match-beginning 1)
22816 (point-max)))
22817 nil)
22818 (org-cycle-hide-drawers 'children))
22819 (error nil))))
22821 (defun org-make-options-regexp (kwds &optional extra)
22822 "Make a regular expression for keyword lines."
22823 (concat
22824 "^#\\+\\("
22825 (mapconcat 'regexp-quote kwds "\\|")
22826 (if extra (concat "\\|" extra))
22827 "\\):[ \t]*\\(.*\\)"))
22829 ;; Make isearch reveal the necessary context
22830 (defun org-isearch-end ()
22831 "Reveal context after isearch exits."
22832 (when isearch-success ; only if search was successful
22833 (if (featurep 'xemacs)
22834 ;; Under XEmacs, the hook is run in the correct place,
22835 ;; we directly show the context.
22836 (org-show-context 'isearch)
22837 ;; In Emacs the hook runs *before* restoring the overlays.
22838 ;; So we have to use a one-time post-command-hook to do this.
22839 ;; (Emacs 22 has a special variable, see function `org-mode')
22840 (unless (and (boundp 'isearch-mode-end-hook-quit)
22841 isearch-mode-end-hook-quit)
22842 ;; Only when the isearch was not quitted.
22843 (org-add-hook 'post-command-hook 'org-isearch-post-command
22844 'append 'local)))))
22846 (defun org-isearch-post-command ()
22847 "Remove self from hook, and show context."
22848 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22849 (org-show-context 'isearch))
22852 ;;;; Integration with and fixes for other packages
22854 ;;; Imenu support
22856 (defvar org-imenu-markers nil
22857 "All markers currently used by Imenu.")
22858 (make-variable-buffer-local 'org-imenu-markers)
22860 (defun org-imenu-new-marker (&optional pos)
22861 "Return a new marker for use by Imenu, and remember the marker."
22862 (let ((m (make-marker)))
22863 (move-marker m (or pos (point)))
22864 (push m org-imenu-markers)
22867 (defun org-imenu-get-tree ()
22868 "Produce the index for Imenu."
22869 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22870 (setq org-imenu-markers nil)
22871 (let* ((n org-imenu-depth)
22872 (re (concat "^" (org-get-limited-outline-regexp)))
22873 (subs (make-vector (1+ n) nil))
22874 (last-level 0)
22875 m level head)
22876 (save-excursion
22877 (save-restriction
22878 (widen)
22879 (goto-char (point-max))
22880 (while (re-search-backward re nil t)
22881 (setq level (org-reduced-level (funcall outline-level)))
22882 (when (and (<= level n)
22883 (looking-at org-complex-heading-regexp))
22884 (setq head (org-link-display-format
22885 (org-match-string-no-properties 4))
22886 m (org-imenu-new-marker))
22887 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22888 (if (>= level last-level)
22889 (push (cons head m) (aref subs level))
22890 (push (cons head (aref subs (1+ level))) (aref subs level))
22891 (loop for i from (1+ level) to n do (aset subs i nil)))
22892 (setq last-level level)))))
22893 (aref subs 1)))
22895 (eval-after-load "imenu"
22896 '(progn
22897 (add-hook 'imenu-after-jump-hook
22898 (lambda ()
22899 (if (derived-mode-p 'org-mode)
22900 (org-show-context 'org-goto))))))
22902 (defun org-link-display-format (link)
22903 "Replace a link with either the description, or the link target
22904 if no description is present"
22905 (save-match-data
22906 (if (string-match org-bracket-link-analytic-regexp link)
22907 (replace-match (if (match-end 5)
22908 (match-string 5 link)
22909 (concat (match-string 1 link)
22910 (match-string 3 link)))
22911 nil t link)
22912 link)))
22914 (defun org-toggle-link-display ()
22915 "Toggle the literal or descriptive display of links."
22916 (interactive)
22917 (if org-descriptive-links
22918 (progn (org-remove-from-invisibility-spec '(org-link))
22919 (org-restart-font-lock)
22920 (setq org-descriptive-links nil))
22921 (progn (add-to-invisibility-spec '(org-link))
22922 (org-restart-font-lock)
22923 (setq org-descriptive-links t))))
22925 ;; Speedbar support
22927 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22928 "Overlay marking the agenda restriction line in speedbar.")
22929 (overlay-put org-speedbar-restriction-lock-overlay
22930 'face 'org-agenda-restriction-lock)
22931 (overlay-put org-speedbar-restriction-lock-overlay
22932 'help-echo "Agendas are currently limited to this item.")
22933 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22935 (defun org-speedbar-set-agenda-restriction ()
22936 "Restrict future agenda commands to the location at point in speedbar.
22937 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22938 (interactive)
22939 (require 'org-agenda)
22940 (let (p m tp np dir txt)
22941 (cond
22942 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22943 'org-imenu t))
22944 (setq m (get-text-property p 'org-imenu-marker))
22945 (with-current-buffer (marker-buffer m)
22946 (goto-char m)
22947 (org-agenda-set-restriction-lock 'subtree)))
22948 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22949 'speedbar-function 'speedbar-find-file))
22950 (setq tp (previous-single-property-change
22951 (1+ p) 'speedbar-function)
22952 np (next-single-property-change
22953 tp 'speedbar-function)
22954 dir (speedbar-line-directory)
22955 txt (buffer-substring-no-properties (or tp (point-min))
22956 (or np (point-max))))
22957 (with-current-buffer (find-file-noselect
22958 (let ((default-directory dir))
22959 (expand-file-name txt)))
22960 (unless (derived-mode-p 'org-mode)
22961 (error "Cannot restrict to non-Org-mode file"))
22962 (org-agenda-set-restriction-lock 'file)))
22963 (t (error "Don't know how to restrict Org-mode's agenda")))
22964 (move-overlay org-speedbar-restriction-lock-overlay
22965 (point-at-bol) (point-at-eol))
22966 (setq current-prefix-arg nil)
22967 (org-agenda-maybe-redo)))
22969 (eval-after-load "speedbar"
22970 '(progn
22971 (speedbar-add-supported-extension ".org")
22972 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22973 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22974 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22975 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22976 (add-hook 'speedbar-visiting-tag-hook
22977 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22979 ;;; Fixes and Hacks for problems with other packages
22981 ;; Make flyspell not check words in links, to not mess up our keymap
22982 (defun org-mode-flyspell-verify ()
22983 "Don't let flyspell put overlays at active buttons, or on
22984 {todo,all-time,additional-option-like}-keywords."
22985 (let ((pos (max (1- (point)) (point-min)))
22986 (word (thing-at-point 'word)))
22987 (and (not (get-text-property pos 'keymap))
22988 (not (get-text-property pos 'org-no-flyspell))
22989 (not (member word org-todo-keywords-1))
22990 (not (member word org-all-time-keywords))
22991 (not (member word org-options-keywords))
22992 (not (member word (mapcar 'car org-startup-options)))
22993 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22995 (defun org-remove-flyspell-overlays-in (beg end)
22996 "Remove flyspell overlays in region."
22997 (and (org-bound-and-true-p flyspell-mode)
22998 (fboundp 'flyspell-delete-region-overlays)
22999 (flyspell-delete-region-overlays beg end))
23000 (add-text-properties beg end '(org-no-flyspell t)))
23002 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23003 (eval-after-load "bookmark"
23004 '(if (boundp 'bookmark-after-jump-hook)
23005 ;; We can use the hook
23006 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23007 ;; Hook not available, use advice
23008 (defadvice bookmark-jump (after org-make-visible activate)
23009 "Make the position visible."
23010 (org-bookmark-jump-unhide))))
23012 ;; Make sure saveplace shows the location if it was hidden
23013 (eval-after-load "saveplace"
23014 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23015 "Make the position visible."
23016 (org-bookmark-jump-unhide)))
23018 ;; Make sure ecb shows the location if it was hidden
23019 (eval-after-load "ecb"
23020 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23021 "Make hierarchy visible when jumping into location from ECB tree buffer."
23022 (if (derived-mode-p 'org-mode)
23023 (org-show-context))))
23025 (defun org-bookmark-jump-unhide ()
23026 "Unhide the current position, to show the bookmark location."
23027 (and (derived-mode-p 'org-mode)
23028 (or (outline-invisible-p)
23029 (save-excursion (goto-char (max (point-min) (1- (point))))
23030 (outline-invisible-p)))
23031 (org-show-context 'bookmark-jump)))
23033 ;; Make session.el ignore our circular variable
23034 (eval-after-load "session"
23035 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23037 ;;;; Experimental code
23039 (defun org-closed-in-range ()
23040 "Sparse tree of items closed in a certain time range.
23041 Still experimental, may disappear in the future."
23042 (interactive)
23043 ;; Get the time interval from the user.
23044 (let* ((time1 (org-float-time
23045 (org-read-date nil 'to-time nil "Starting date: ")))
23046 (time2 (org-float-time
23047 (org-read-date nil 'to-time nil "End date:")))
23048 ;; callback function
23049 (callback (lambda ()
23050 (let ((time
23051 (org-float-time
23052 (apply 'encode-time
23053 (org-parse-time-string
23054 (match-string 1))))))
23055 ;; check if time in interval
23056 (and (>= time time1) (<= time time2))))))
23057 ;; make tree, check each match with the callback
23058 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23060 ;;;; Finish up
23062 (provide 'org)
23064 (run-hooks 'org-load-hook)
23066 ;;; org.el ends here