ob-lilypond.el: Fix test leftover
[org-mode.git] / lisp / org.el
blobef61ea20d81d15a27047bad655aaf106152209dd
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 "ox-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--parse-objects "org-element"
144 (beg end acc restriction))
145 (declare-function org-element-at-point "org-element" (&optional keep-trail))
146 (declare-function org-element-contents "org-element" (element))
147 (declare-function org-element-context "org-element" (&optional element))
148 (declare-function org-element-interpret-data "org-element"
149 (data &optional parent))
150 (declare-function org-element-map "org-element"
151 (data types fun &optional info first-match no-recursion))
152 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
153 (declare-function org-element-parse-buffer "org-element"
154 (&optional granularity visible-only))
155 (declare-function org-element-property "org-element" (property element))
156 (declare-function org-element-put-property "org-element"
157 (element property value))
158 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
159 (declare-function org-element--parse-objects "org-element"
160 (beg end acc restriction))
161 (declare-function org-element-parse-buffer "org-element"
162 (&optional granularity visible-only))
163 (declare-function org-element-interpret-data "org-element"
164 (data &optional parent))
166 ;; load languages based on value of `org-babel-load-languages'
167 (defvar org-babel-load-languages)
169 ;;;###autoload
170 (defun org-babel-do-load-languages (sym value)
171 "Load the languages defined in `org-babel-load-languages'."
172 (set-default sym value)
173 (mapc (lambda (pair)
174 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
175 (if active
176 (progn
177 (require (intern (concat "ob-" lang))))
178 (progn
179 (funcall 'fmakunbound
180 (intern (concat "org-babel-execute:" lang)))
181 (funcall 'fmakunbound
182 (intern (concat "org-babel-expand-body:" lang)))))))
183 org-babel-load-languages))
185 (defcustom org-babel-load-languages '((emacs-lisp . t))
186 "Languages which can be evaluated in Org-mode buffers.
187 This list can be used to load support for any of the languages
188 below, note that each language will depend on a different set of
189 system executables and/or Emacs modes. When a language is
190 \"loaded\", then code blocks in that language can be evaluated
191 with `org-babel-execute-src-block' bound by default to C-c
192 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
193 be set to remove code block evaluation from the C-c C-c
194 keybinding. By default only Emacs Lisp (which has no
195 requirements) is loaded."
196 :group 'org-babel
197 :set 'org-babel-do-load-languages
198 :version "24.1"
199 :type '(alist :tag "Babel Languages"
200 :key-type
201 (choice
202 (const :tag "Awk" awk)
203 (const :tag "C" C)
204 (const :tag "R" R)
205 (const :tag "Asymptote" asymptote)
206 (const :tag "Calc" calc)
207 (const :tag "Clojure" clojure)
208 (const :tag "CSS" css)
209 (const :tag "Ditaa" ditaa)
210 (const :tag "Dot" dot)
211 (const :tag "Emacs Lisp" emacs-lisp)
212 (const :tag "Fortran" fortran)
213 (const :tag "Gnuplot" gnuplot)
214 (const :tag "Haskell" haskell)
215 (const :tag "IO" io)
216 (const :tag "Java" java)
217 (const :tag "Javascript" js)
218 (const :tag "LaTeX" latex)
219 (const :tag "Ledger" ledger)
220 (const :tag "Lilypond" lilypond)
221 (const :tag "Lisp" lisp)
222 (const :tag "Makefile" makefile)
223 (const :tag "Maxima" maxima)
224 (const :tag "Matlab" matlab)
225 (const :tag "Mscgen" mscgen)
226 (const :tag "Ocaml" ocaml)
227 (const :tag "Octave" octave)
228 (const :tag "Org" org)
229 (const :tag "Perl" perl)
230 (const :tag "Pico Lisp" picolisp)
231 (const :tag "PlantUML" plantuml)
232 (const :tag "Python" python)
233 (const :tag "Ruby" ruby)
234 (const :tag "Sass" sass)
235 (const :tag "Scala" scala)
236 (const :tag "Scheme" scheme)
237 (const :tag "Screen" screen)
238 (const :tag "Shell Script" sh)
239 (const :tag "Shen" shen)
240 (const :tag "Sql" sql)
241 (const :tag "Sqlite" sqlite))
242 :value-type (boolean :tag "Activate" :value t)))
244 ;;;; Customization variables
245 (defcustom org-clone-delete-id nil
246 "Remove ID property of clones of a subtree.
247 When non-nil, clones of a subtree don't inherit the ID property.
248 Otherwise they inherit the ID property with a new unique
249 identifier."
250 :type 'boolean
251 :version "24.1"
252 :group 'org-id)
254 ;;; Version
255 (org-check-version)
257 ;;;###autoload
258 (defun org-version (&optional here full message)
259 "Show the org-mode version in the echo area.
260 With prefix argument HERE, insert it at point.
261 When FULL is non-nil, use a verbose version string.
262 When MESSAGE is non-nil, display a message with the version."
263 (interactive "P")
264 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
265 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
266 (load-suffixes (list ".el"))
267 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
268 (org-trash (or
269 (and (fboundp 'org-release) (fboundp 'org-git-version))
270 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
271 (load-suffixes save-load-suffixes)
272 (org-version (org-release))
273 (git-version (org-git-version))
274 (version (format "Org-mode version %s (%s @ %s)"
275 org-version
276 git-version
277 (if org-install-dir
278 (if (string= org-dir org-install-dir)
279 org-install-dir
280 (concat "mixed installation! " org-install-dir " and " org-dir))
281 "org-loaddefs.el can not be found!")))
282 (_version (if full version org-version)))
283 (if (org-called-interactively-p 'interactive)
284 (if here
285 (insert version)
286 (message version))
287 (if message (message _version))
288 _version)))
290 (defconst org-version (org-version))
292 ;;; Compatibility constants
294 ;;; The custom variables
296 (defgroup org nil
297 "Outline-based notes management and organizer."
298 :tag "Org"
299 :group 'outlines
300 :group 'calendar)
302 (defcustom org-mode-hook nil
303 "Mode hook for Org-mode, run after the mode was turned on."
304 :group 'org
305 :type 'hook)
307 (defcustom org-load-hook nil
308 "Hook that is run after org.el has been loaded."
309 :group 'org
310 :type 'hook)
312 (defcustom org-log-buffer-setup-hook nil
313 "Hook that is run after an Org log buffer is created."
314 :group 'org
315 :version "24.1"
316 :type 'hook)
318 (defvar org-modules) ; defined below
319 (defvar org-modules-loaded nil
320 "Have the modules been loaded already?")
322 (defun org-load-modules-maybe (&optional force)
323 "Load all extensions listed in `org-modules'."
324 (when (or force (not org-modules-loaded))
325 (mapc (lambda (ext)
326 (condition-case nil (require ext)
327 (error (message "Problems while trying to load feature `%s'" ext))))
328 org-modules)
329 (setq org-modules-loaded t)))
331 (defun org-set-modules (var value)
332 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
333 (set var value)
334 (when (featurep 'org)
335 (org-load-modules-maybe 'force)))
337 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
338 "Modules that should always be loaded together with org.el.
340 If a description starts with <C>, the file is not part of Emacs
341 and loading it will require that you have downloaded and properly
342 installed the Org mode distribution.
344 You can also use this system to load external packages (i.e. neither Org
345 core modules, nor modules from the CONTRIB directory). Just add symbols
346 to the end of the list. If the package is called org-xyz.el, then you need
347 to add the symbol `xyz', and the package must have a call to:
349 \(provide 'org-xyz)
351 For export specific modules, see also `org-export-backends'."
352 :group 'org
353 :set 'org-set-modules
354 :type
355 '(set :greedy t
356 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
357 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
358 (const :tag " crypt: Encryption of subtrees" org-crypt)
359 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
360 (const :tag " docview: Links to doc-view buffers" org-docview)
361 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
362 (const :tag " id: Global IDs for identifying entries" org-id)
363 (const :tag " info: Links to Info nodes" org-info)
364 (const :tag " habit: Track your consistency with habits" org-habit)
365 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
366 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
367 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
368 (const :tag " mew Links to Mew folders/messages" org-mew)
369 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
370 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
371 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
372 (const :tag " vm: Links to VM folders/messages" org-vm)
373 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
374 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
375 (const :tag " mouse: Additional mouse support" org-mouse)
377 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
378 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
379 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
380 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
381 (const :tag "C collector: Collect properties into tables" org-collector)
382 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
383 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
384 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
385 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
386 (const :tag "C eval: Include command output as text" org-eval)
387 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
388 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
389 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
390 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
391 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
393 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
395 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
396 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
397 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
398 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
399 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
400 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
401 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
402 (const :tag "C mtags: Support for muse-like tags" org-mtags)
403 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
404 (const :tag "C registry: A registry for Org-mode links" org-registry)
405 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
406 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
407 (const :tag "C secretary: Team management with org-mode" org-secretary)
408 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
409 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
410 (const :tag "C track: Keep up with Org-mode development" org-track)
411 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
412 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
413 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
415 (defvar org-export-registered-backends) ; From ox.el
416 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
417 (defcustom org-export-backends '(ascii html icalendar latex)
418 "List of export back-ends that should be always available.
420 If a description starts with <C>, the file is not part of Emacs
421 and loading it will require that you have downloaded and properly
422 installed the Org mode distribution.
424 Unlike to `org-modules', libraries in this list will not be
425 loaded along with Org, but only once the export framework is
426 needed.
428 This variable needs to be set before org.el is loaded. If you
429 need to make a change while Emacs is running, use the customize
430 interface or run the following code, , where VALUE stands for the
431 new value of the variable, after updating it:
433 \(progn
434 \(setq org-export-registered-backends
435 \(org-remove-if-not
436 \(lambda (backend)
437 \(or (memq backend val)
438 \(catch 'parentp
439 \(mapc
440 \(lambda (b)
441 \(and (org-export-derived-backend-p b (car backend))
442 \(throw 'parentp t)))
443 val)
444 nil)))
445 org-export-registered-backends))
446 \(let ((new-list (mapcar 'car org-export-registered-backends)))
447 \(dolist (backend val)
448 \(cond
449 \((not (load (format \"ox-%s\" backend) t t))
450 \(message \"Problems while trying to load export back-end `%s'\"
451 backend))
452 \((not (memq backend new-list)) (push backend new-list))))
453 \(set-default var new-list)))
455 Adding a back-end to this list will also pull the back-end it
456 depends on, if any."
457 :group 'org
458 :group 'org-export
459 :set (lambda (var val)
460 (if (not (featurep 'ox)) (set-default var val)
461 ;; Any back-end not required anymore (not present in VAL and not
462 ;; a parent of any back-end in the new value) is removed from the
463 ;; list of registered back-ends.
464 (setq org-export-registered-backends
465 (org-remove-if-not
466 (lambda (backend)
467 (or (memq backend val)
468 (catch 'parentp
469 (mapc
470 (lambda (b)
471 (and (org-export-derived-backend-p b (car backend))
472 (throw 'parentp t)))
473 val)
474 nil)))
475 org-export-registered-backends))
476 ;; Now build NEW-LIST of both new back-ends and required
477 ;; parents.
478 (let ((new-list (mapcar 'car org-export-registered-backends)))
479 (dolist (backend val)
480 (cond
481 ((not (load (format "ox-%s" backend) t t))
482 (message "Problems while trying to load export back-end `%s'"
483 backend))
484 ((not (memq backend new-list)) (push backend new-list))))
485 ;; Set VAR to that list with fixed dependencies.
486 (set-default var new-list))))
487 :initialize 'custom-initialize-default
488 :type '(set :greedy t
489 (const :tag " ascii Export buffer to ASCII format" ascii)
490 (const :tag " beamer Export buffer to Beamer presentation" beamer)
491 (const :tag " html Export buffer to HTML format" html)
492 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
493 (const :tag " latex Export buffer to LaTeX format" latex)
494 (const :tag " man Export buffer to MAN format" man)
495 (const :tag " md Export buffer to Markdown format" md)
496 (const :tag " odt Export buffer to ODT format" odt)
497 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
498 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" jsinfo)
499 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
500 (const :tag "C groff Export buffer to Groff format" groff)
501 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)))
503 (eval-after-load 'ox
504 '(mapc
505 (lambda (backend)
506 (condition-case nil (require (intern (format "ox-%s" backend)))
507 (error (message "Problems while trying to load export back-end `%s'"
508 backend))))
509 org-export-backends))
511 (defcustom org-support-shift-select nil
512 "Non-nil means make shift-cursor commands select text when possible.
514 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
515 start selecting a region, or enlarge regions started in this way.
516 In Org-mode, in special contexts, these same keys are used for
517 other purposes, important enough to compete with shift selection.
518 Org tries to balance these needs by supporting `shift-select-mode'
519 outside these special contexts, under control of this variable.
521 The default of this variable is nil, to avoid confusing behavior. Shifted
522 cursor keys will then execute Org commands in the following contexts:
523 - on a headline, changing TODO state (left/right) and priority (up/down)
524 - on a time stamp, changing the time
525 - in a plain list item, changing the bullet type
526 - in a property definition line, switching between allowed values
527 - in the BEGIN line of a clock table (changing the time block).
528 Outside these contexts, the commands will throw an error.
530 When this variable is t and the cursor is not in a special
531 context, Org-mode will support shift-selection for making and
532 enlarging regions. To make this more effective, the bullet
533 cycling will no longer happen anywhere in an item line, but only
534 if the cursor is exactly on the bullet.
536 If you set this variable to the symbol `always', then the keys
537 will not be special in headlines, property lines, and item lines,
538 to make shift selection work there as well. If this is what you
539 want, you can use the following alternative commands: `C-c C-t'
540 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
541 can be used to switch TODO sets, `C-c -' to cycle item bullet
542 types, and properties can be edited by hand or in column view.
544 However, when the cursor is on a timestamp, shift-cursor commands
545 will still edit the time stamp - this is just too good to give up.
547 XEmacs user should have this variable set to nil, because
548 `shift-select-mode' is in Emacs 23 or later only."
549 :group 'org
550 :type '(choice
551 (const :tag "Never" nil)
552 (const :tag "When outside special context" t)
553 (const :tag "Everywhere except timestamps" always)))
555 (defcustom org-loop-over-headlines-in-active-region nil
556 "Shall some commands act upon headlines in the active region?
558 When set to `t', some commands will be performed in all headlines
559 within the active region.
561 When set to `start-level', some commands will be performed in all
562 headlines within the active region, provided that these headlines
563 are of the same level than the first one.
565 When set to a string, those commands will be performed on the
566 matching headlines within the active region. Such string must be
567 a tags/property/todo match as it is used in the agenda tags view.
569 The list of commands is: `org-schedule', `org-deadline',
570 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
571 `org-archive-to-archive-sibling'. The archiving commands skip
572 already archived entries."
573 :type '(choice (const :tag "Don't loop" nil)
574 (const :tag "All headlines in active region" t)
575 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
576 (string :tag "Tags/Property/Todo matcher"))
577 :version "24.1"
578 :group 'org-todo
579 :group 'org-archive)
581 (defgroup org-startup nil
582 "Options concerning startup of Org-mode."
583 :tag "Org Startup"
584 :group 'org)
586 (defcustom org-startup-folded t
587 "Non-nil means entering Org-mode will switch to OVERVIEW.
588 This can also be configured on a per-file basis by adding one of
589 the following lines anywhere in the buffer:
591 #+STARTUP: fold (or `overview', this is equivalent)
592 #+STARTUP: nofold (or `showall', this is equivalent)
593 #+STARTUP: content
594 #+STARTUP: showeverything"
595 :group 'org-startup
596 :type '(choice
597 (const :tag "nofold: show all" nil)
598 (const :tag "fold: overview" t)
599 (const :tag "content: all headlines" content)
600 (const :tag "show everything, even drawers" showeverything)))
602 (defcustom org-startup-truncated t
603 "Non-nil means entering Org-mode will set `truncate-lines'.
604 This is useful since some lines containing links can be very long and
605 uninteresting. Also tables look terrible when wrapped."
606 :group 'org-startup
607 :type 'boolean)
609 (defcustom org-startup-indented nil
610 "Non-nil means turn on `org-indent-mode' on startup.
611 This can also be configured on a per-file basis by adding one of
612 the following lines anywhere in the buffer:
614 #+STARTUP: indent
615 #+STARTUP: noindent"
616 :group 'org-structure
617 :type '(choice
618 (const :tag "Not" nil)
619 (const :tag "Globally (slow on startup in large files)" t)))
621 (defcustom org-use-sub-superscripts t
622 "Non-nil means interpret \"_\" and \"^\" for display.
623 When this option is turned on, you can use TeX-like syntax for sub- and
624 superscripts. Several characters after \"_\" or \"^\" will be
625 considered as a single item - so grouping with {} is normally not
626 needed. For example, the following things will be parsed as single
627 sub- or superscripts.
629 10^24 or 10^tau several digits will be considered 1 item.
630 10^-12 or 10^-tau a leading sign with digits or a word
631 x^2-y^3 will be read as x^2 - y^3, because items are
632 terminated by almost any nonword/nondigit char.
633 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
635 Still, ambiguity is possible - so when in doubt use {} to enclose
636 the sub/superscript. If you set this variable to the symbol
637 `{}', the braces are *required* in order to trigger
638 interpretations as sub/superscript. This can be helpful in
639 documents that need \"_\" frequently in plain text."
640 :group 'org-startup
641 :version "24.1"
642 :type '(choice
643 (const :tag "Always interpret" t)
644 (const :tag "Only with braces" {})
645 (const :tag "Never interpret" nil)))
647 (defcustom org-startup-with-beamer-mode nil
648 "Non-nil means turn on `org-beamer-mode' on startup.
649 This can also be configured on a per-file basis by adding one of
650 the following lines anywhere in the buffer:
652 #+STARTUP: beamer"
653 :group 'org-startup
654 :version "24.1"
655 :type 'boolean)
657 (defcustom org-startup-align-all-tables nil
658 "Non-nil means align all tables when visiting a file.
659 This is useful when the column width in tables is forced with <N> cookies
660 in table fields. Such tables will look correct only after the first re-align.
661 This can also be configured on a per-file basis by adding one of
662 the following lines anywhere in the buffer:
663 #+STARTUP: align
664 #+STARTUP: noalign"
665 :group 'org-startup
666 :type 'boolean)
668 (defcustom org-startup-with-inline-images nil
669 "Non-nil means show inline images when loading a new Org file.
670 This can also be configured on a per-file basis by adding one of
671 the following lines anywhere in the buffer:
672 #+STARTUP: inlineimages
673 #+STARTUP: noinlineimages"
674 :group 'org-startup
675 :version "24.1"
676 :type 'boolean)
678 (defcustom org-insert-mode-line-in-empty-file nil
679 "Non-nil means insert the first line setting Org-mode in empty files.
680 When the function `org-mode' is called interactively in an empty file, this
681 normally means that the file name does not automatically trigger Org-mode.
682 To ensure that the file will always be in Org-mode in the future, a
683 line enforcing Org-mode will be inserted into the buffer, if this option
684 has been set."
685 :group 'org-startup
686 :type 'boolean)
688 (defcustom org-replace-disputed-keys nil
689 "Non-nil means use alternative key bindings for some keys.
690 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
691 These keys are also used by other packages like shift-selection-mode'
692 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
693 If you want to use Org-mode together with one of these other modes,
694 or more generally if you would like to move some Org-mode commands to
695 other keys, set this variable and configure the keys with the variable
696 `org-disputed-keys'.
698 This option is only relevant at load-time of Org-mode, and must be set
699 *before* org.el is loaded. Changing it requires a restart of Emacs to
700 become effective."
701 :group 'org-startup
702 :type 'boolean)
704 (defcustom org-use-extra-keys nil
705 "Non-nil means use extra key sequence definitions for certain commands.
706 This happens automatically if you run XEmacs or if `window-system'
707 is nil. This variable lets you do the same manually. You must
708 set it before loading org.
710 Example: on Carbon Emacs 22 running graphically, with an external
711 keyboard on a Powerbook, the default way of setting M-left might
712 not work for either Alt or ESC. Setting this variable will make
713 it work for ESC."
714 :group 'org-startup
715 :type 'boolean)
717 (if (fboundp 'defvaralias)
718 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
720 (defcustom org-disputed-keys
721 '(([(shift up)] . [(meta p)])
722 ([(shift down)] . [(meta n)])
723 ([(shift left)] . [(meta -)])
724 ([(shift right)] . [(meta +)])
725 ([(control shift right)] . [(meta shift +)])
726 ([(control shift left)] . [(meta shift -)]))
727 "Keys for which Org-mode and other modes compete.
728 This is an alist, cars are the default keys, second element specifies
729 the alternative to use when `org-replace-disputed-keys' is t.
731 Keys can be specified in any syntax supported by `define-key'.
732 The value of this option takes effect only at Org-mode's startup,
733 therefore you'll have to restart Emacs to apply it after changing."
734 :group 'org-startup
735 :type 'alist)
737 (defun org-key (key)
738 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
739 Or return the original if not disputed.
740 Also apply the translations defined in `org-xemacs-key-equivalents'."
741 (when org-replace-disputed-keys
742 (let* ((nkey (key-description key))
743 (x (org-find-if (lambda (x)
744 (equal (key-description (car x)) nkey))
745 org-disputed-keys)))
746 (setq key (if x (cdr x) key))))
747 (when (featurep 'xemacs)
748 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
749 key)
751 (defun org-find-if (predicate seq)
752 (catch 'exit
753 (while seq
754 (if (funcall predicate (car seq))
755 (throw 'exit (car seq))
756 (pop seq)))))
758 (defun org-defkey (keymap key def)
759 "Define a key, possibly translated, as returned by `org-key'."
760 (define-key keymap (org-key key) def))
762 (defcustom org-ellipsis nil
763 "The ellipsis to use in the Org-mode outline.
764 When nil, just use the standard three dots. When a string, use that instead,
765 When a face, use the standard 3 dots, but with the specified face.
766 The change affects only Org-mode (which will then use its own display table).
767 Changing this requires executing `M-x org-mode' in a buffer to become
768 effective."
769 :group 'org-startup
770 :type '(choice (const :tag "Default" nil)
771 (face :tag "Face" :value org-warning)
772 (string :tag "String" :value "...#")))
774 (defvar org-display-table nil
775 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
777 (defgroup org-keywords nil
778 "Keywords in Org-mode."
779 :tag "Org Keywords"
780 :group 'org)
782 (defcustom org-deadline-string "DEADLINE:"
783 "String to mark deadline entries.
784 A deadline is this string, followed by a time stamp. Should be a word,
785 terminated by a colon. You can insert a schedule keyword and
786 a timestamp with \\[org-deadline].
787 Changes become only effective after restarting Emacs."
788 :group 'org-keywords
789 :type 'string)
791 (defcustom org-scheduled-string "SCHEDULED:"
792 "String to mark scheduled TODO entries.
793 A schedule is this string, followed by a time stamp. Should be a word,
794 terminated by a colon. You can insert a schedule keyword and
795 a timestamp with \\[org-schedule].
796 Changes become only effective after restarting Emacs."
797 :group 'org-keywords
798 :type 'string)
800 (defcustom org-closed-string "CLOSED:"
801 "String used as the prefix for timestamps logging closing a TODO entry."
802 :group 'org-keywords
803 :type 'string)
805 (defcustom org-clock-string "CLOCK:"
806 "String used as prefix for timestamps clocking work hours on an item."
807 :group 'org-keywords
808 :type 'string)
810 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
811 org-scheduled-string "\\|"
812 org-deadline-string "\\|"
813 org-closed-string "\\|"
814 org-clock-string "\\)")
815 "Matches a line with planning or clock info.")
817 (defcustom org-comment-string "COMMENT"
818 "Entries starting with this keyword will never be exported.
819 An entry can be toggled between COMMENT and normal with
820 \\[org-toggle-comment].
821 Changes become only effective after restarting Emacs."
822 :group 'org-keywords
823 :type 'string)
825 (defcustom org-quote-string "QUOTE"
826 "Entries starting with this keyword will be exported in fixed-width font.
827 Quoting applies only to the text in the entry following the headline, and does
828 not extend beyond the next headline, even if that is lower level.
829 An entry can be toggled between QUOTE and normal with
830 \\[org-toggle-fixed-width-section]."
831 :group 'org-keywords
832 :type 'string)
834 (defconst org-repeat-re
835 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
836 "Regular expression for specifying repeated events.
837 After a match, group 1 contains the repeat expression.")
839 (defgroup org-structure nil
840 "Options concerning the general structure of Org-mode files."
841 :tag "Org Structure"
842 :group 'org)
844 (defgroup org-reveal-location nil
845 "Options about how to make context of a location visible."
846 :tag "Org Reveal Location"
847 :group 'org-structure)
849 (defconst org-context-choice
850 '(choice
851 (const :tag "Always" t)
852 (const :tag "Never" nil)
853 (repeat :greedy t :tag "Individual contexts"
854 (cons
855 (choice :tag "Context"
856 (const agenda)
857 (const org-goto)
858 (const occur-tree)
859 (const tags-tree)
860 (const link-search)
861 (const mark-goto)
862 (const bookmark-jump)
863 (const isearch)
864 (const default))
865 (boolean))))
866 "Contexts for the reveal options.")
868 (defcustom org-show-hierarchy-above '((default . t))
869 "Non-nil means show full hierarchy when revealing a location.
870 Org-mode often shows locations in an org-mode file which might have
871 been invisible before. When this is set, the hierarchy of headings
872 above the exposed location is shown.
873 Turning this off for example for sparse trees makes them very compact.
874 Instead of t, this can also be an alist specifying this option for different
875 contexts. Valid contexts are
876 agenda when exposing an entry from the agenda
877 org-goto when using the command `org-goto' on key C-c C-j
878 occur-tree when using the command `org-occur' on key C-c /
879 tags-tree when constructing a sparse tree based on tags matches
880 link-search when exposing search matches associated with a link
881 mark-goto when exposing the jump goal of a mark
882 bookmark-jump when exposing a bookmark location
883 isearch when exiting from an incremental search
884 default default for all contexts not set explicitly"
885 :group 'org-reveal-location
886 :type org-context-choice)
888 (defcustom org-show-following-heading '((default . nil))
889 "Non-nil means show following heading when revealing a location.
890 Org-mode often shows locations in an org-mode file which might have
891 been invisible before. When this is set, the heading following the
892 match is shown.
893 Turning this off for example for sparse trees makes them very compact,
894 but makes it harder to edit the location of the match. In such a case,
895 use the command \\[org-reveal] to show more context.
896 Instead of t, this can also be an alist specifying this option for different
897 contexts. See `org-show-hierarchy-above' for valid contexts."
898 :group 'org-reveal-location
899 :type org-context-choice)
901 (defcustom org-show-siblings '((default . nil) (isearch t))
902 "Non-nil means show all sibling heading when revealing a location.
903 Org-mode often shows locations in an org-mode file which might have
904 been invisible before. When this is set, the sibling of the current entry
905 heading are all made visible. If `org-show-hierarchy-above' is t,
906 the same happens on each level of the hierarchy above the current entry.
908 By default this is on for the isearch context, off for all other contexts.
909 Turning this off for example for sparse trees makes them very compact,
910 but makes it harder to edit the location of the match. In such a case,
911 use the command \\[org-reveal] to show more context.
912 Instead of t, this can also be an alist specifying this option for different
913 contexts. See `org-show-hierarchy-above' for valid contexts."
914 :group 'org-reveal-location
915 :type org-context-choice)
917 (defcustom org-show-entry-below '((default . nil))
918 "Non-nil means show the entry below a headline when revealing a location.
919 Org-mode often shows locations in an org-mode file which might have
920 been invisible before. When this is set, the text below the headline that is
921 exposed is also shown.
923 By default this is off for all contexts.
924 Instead of t, this can also be an alist specifying this option for different
925 contexts. See `org-show-hierarchy-above' for valid contexts."
926 :group 'org-reveal-location
927 :type org-context-choice)
929 (defcustom org-indirect-buffer-display 'other-window
930 "How should indirect tree buffers be displayed?
931 This applies to indirect buffers created with the commands
932 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
933 Valid values are:
934 current-window Display in the current window
935 other-window Just display in another window.
936 dedicated-frame Create one new frame, and re-use it each time.
937 new-frame Make a new frame each time. Note that in this case
938 previously-made indirect buffers are kept, and you need to
939 kill these buffers yourself."
940 :group 'org-structure
941 :group 'org-agenda-windows
942 :type '(choice
943 (const :tag "In current window" current-window)
944 (const :tag "In current frame, other window" other-window)
945 (const :tag "Each time a new frame" new-frame)
946 (const :tag "One dedicated frame" dedicated-frame)))
948 (defcustom org-use-speed-commands nil
949 "Non-nil means activate single letter commands at beginning of a headline.
950 This may also be a function to test for appropriate locations where speed
951 commands should be active."
952 :group 'org-structure
953 :type '(choice
954 (const :tag "Never" nil)
955 (const :tag "At beginning of headline stars" t)
956 (function)))
958 (defcustom org-speed-commands-user nil
959 "Alist of additional speed commands.
960 This list will be checked before `org-speed-commands-default'
961 when the variable `org-use-speed-commands' is non-nil
962 and when the cursor is at the beginning of a headline.
963 The car if each entry is a string with a single letter, which must
964 be assigned to `self-insert-command' in the global map.
965 The cdr is either a command to be called interactively, a function
966 to be called, or a form to be evaluated.
967 An entry that is just a list with a single string will be interpreted
968 as a descriptive headline that will be added when listing the speed
969 commands in the Help buffer using the `?' speed command."
970 :group 'org-structure
971 :type '(repeat :value ("k" . ignore)
972 (choice :value ("k" . ignore)
973 (list :tag "Descriptive Headline" (string :tag "Headline"))
974 (cons :tag "Letter and Command"
975 (string :tag "Command letter")
976 (choice
977 (function)
978 (sexp))))))
980 (defgroup org-cycle nil
981 "Options concerning visibility cycling in Org-mode."
982 :tag "Org Cycle"
983 :group 'org-structure)
985 (defcustom org-cycle-skip-children-state-if-no-children t
986 "Non-nil means skip CHILDREN state in entries that don't have any."
987 :group 'org-cycle
988 :type 'boolean)
990 (defcustom org-cycle-max-level nil
991 "Maximum level which should still be subject to visibility cycling.
992 Levels higher than this will, for cycling, be treated as text, not a headline.
993 When `org-odd-levels-only' is set, a value of N in this variable actually
994 means 2N-1 stars as the limiting headline.
995 When nil, cycle all levels.
996 Note that the limiting level of cycling is also influenced by
997 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
998 `org-inlinetask-min-level' is, cycling will be limited to levels one less
999 than its value."
1000 :group 'org-cycle
1001 :type '(choice
1002 (const :tag "No limit" nil)
1003 (integer :tag "Maximum level")))
1005 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1006 "Names of drawers. Drawers are not opened by cycling on the headline above.
1007 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1008 this:
1009 :DRAWERNAME:
1010 .....
1011 :END:
1012 The drawer \"PROPERTIES\" is special for capturing properties through
1013 the property API.
1015 Drawers can be defined on the per-file basis with a line like:
1017 #+DRAWERS: HIDDEN STATE PROPERTIES"
1018 :group 'org-structure
1019 :group 'org-cycle
1020 :type '(repeat (string :tag "Drawer Name")))
1022 (defcustom org-hide-block-startup nil
1023 "Non-nil means entering Org-mode will fold all blocks.
1024 This can also be set in on a per-file basis with
1026 #+STARTUP: hideblocks
1027 #+STARTUP: showblocks"
1028 :group 'org-startup
1029 :group 'org-cycle
1030 :type 'boolean)
1032 (defcustom org-cycle-global-at-bob nil
1033 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1034 This makes it possible to do global cycling without having to use S-TAB or
1035 \\[universal-argument] TAB. For this special case to work, the first line
1036 of the buffer must not be a headline -- it may be empty or some other text.
1037 When used in this way, `org-cycle-hook' is disabled temporarily to make
1038 sure the cursor stays at the beginning of the buffer. When this option is
1039 nil, don't do anything special at the beginning of the buffer."
1040 :group 'org-cycle
1041 :type 'boolean)
1043 (defcustom org-cycle-level-after-item/entry-creation t
1044 "Non-nil means cycle entry level or item indentation in new empty entries.
1046 When the cursor is at the end of an empty headline, i.e with only stars
1047 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1048 and then all possible ancestor states, before returning to the original state.
1049 This makes data entry extremely fast: M-RET to create a new headline,
1050 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1052 When the cursor is at the end of an empty plain list item, one TAB will
1053 make it a subitem, two or more tabs will back up to make this an item
1054 higher up in the item hierarchy."
1055 :group 'org-cycle
1056 :type 'boolean)
1058 (defcustom org-cycle-emulate-tab t
1059 "Where should `org-cycle' emulate TAB.
1060 nil Never
1061 white Only in completely white lines
1062 whitestart Only at the beginning of lines, before the first non-white char
1063 t Everywhere except in headlines
1064 exc-hl-bol Everywhere except at the start of a headline
1065 If TAB is used in a place where it does not emulate TAB, the current subtree
1066 visibility is cycled."
1067 :group 'org-cycle
1068 :type '(choice (const :tag "Never" nil)
1069 (const :tag "Only in completely white lines" white)
1070 (const :tag "Before first char in a line" whitestart)
1071 (const :tag "Everywhere except in headlines" t)
1072 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1075 (defcustom org-cycle-separator-lines 2
1076 "Number of empty lines needed to keep an empty line between collapsed trees.
1077 If you leave an empty line between the end of a subtree and the following
1078 headline, this empty line is hidden when the subtree is folded.
1079 Org-mode will leave (exactly) one empty line visible if the number of
1080 empty lines is equal or larger to the number given in this variable.
1081 So the default 2 means at least 2 empty lines after the end of a subtree
1082 are needed to produce free space between a collapsed subtree and the
1083 following headline.
1085 If the number is negative, and the number of empty lines is at least -N,
1086 all empty lines are shown.
1088 Special case: when 0, never leave empty lines in collapsed view."
1089 :group 'org-cycle
1090 :type 'integer)
1091 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1093 (defcustom org-pre-cycle-hook nil
1094 "Hook that is run before visibility cycling is happening.
1095 The function(s) in this hook must accept a single argument which indicates
1096 the new state that will be set right after running this hook. The
1097 argument is a symbol. Before a global state change, it can have the values
1098 `overview', `content', or `all'. Before a local state change, it can have
1099 the values `folded', `children', or `subtree'."
1100 :group 'org-cycle
1101 :type 'hook)
1103 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1104 org-cycle-hide-drawers
1105 org-cycle-hide-inline-tasks
1106 org-cycle-show-empty-lines
1107 org-optimize-window-after-visibility-change)
1108 "Hook that is run after `org-cycle' has changed the buffer visibility.
1109 The function(s) in this hook must accept a single argument which indicates
1110 the new state that was set by the most recent `org-cycle' command. The
1111 argument is a symbol. After a global state change, it can have the values
1112 `overview', `contents', or `all'. After a local state change, it can have
1113 the values `folded', `children', or `subtree'."
1114 :group 'org-cycle
1115 :type 'hook)
1117 (defgroup org-edit-structure nil
1118 "Options concerning structure editing in Org-mode."
1119 :tag "Org Edit Structure"
1120 :group 'org-structure)
1122 (defcustom org-odd-levels-only nil
1123 "Non-nil means skip even levels and only use odd levels for the outline.
1124 This has the effect that two stars are being added/taken away in
1125 promotion/demotion commands. It also influences how levels are
1126 handled by the exporters.
1127 Changing it requires restart of `font-lock-mode' to become effective
1128 for fontification also in regions already fontified.
1129 You may also set this on a per-file basis by adding one of the following
1130 lines to the buffer:
1132 #+STARTUP: odd
1133 #+STARTUP: oddeven"
1134 :group 'org-edit-structure
1135 :group 'org-appearance
1136 :type 'boolean)
1138 (defcustom org-adapt-indentation t
1139 "Non-nil means adapt indentation to outline node level.
1141 When this variable is set, Org assumes that you write outlines by
1142 indenting text in each node to align with the headline (after the stars).
1143 The following issues are influenced by this variable:
1145 - When this is set and the *entire* text in an entry is indented, the
1146 indentation is increased by one space in a demotion command, and
1147 decreased by one in a promotion command. If any line in the entry
1148 body starts with text at column 0, indentation is not changed at all.
1150 - Property drawers and planning information is inserted indented when
1151 this variable s set. When nil, they will not be indented.
1153 - TAB indents a line relative to context. The lines below a headline
1154 will be indented when this variable is set.
1156 Note that this is all about true indentation, by adding and removing
1157 space characters. See also `org-indent.el' which does level-dependent
1158 indentation in a virtual way, i.e. at display time in Emacs."
1159 :group 'org-edit-structure
1160 :type 'boolean)
1162 (defcustom org-special-ctrl-a/e nil
1163 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1165 When t, `C-a' will bring back the cursor to the beginning of the
1166 headline text, i.e. after the stars and after a possible TODO
1167 keyword. In an item, this will be the position after bullet and
1168 check-box, if any. When the cursor is already at that position,
1169 another `C-a' will bring it to the beginning of the line.
1171 `C-e' will jump to the end of the headline, ignoring the presence
1172 of tags in the headline. A second `C-e' will then jump to the
1173 true end of the line, after any tags. This also means that, when
1174 this variable is non-nil, `C-e' also will never jump beyond the
1175 end of the heading of a folded section, i.e. not after the
1176 ellipses.
1178 When set to the symbol `reversed', the first `C-a' or `C-e' works
1179 normally, going to the true line boundary first. Only a directly
1180 following, identical keypress will bring the cursor to the
1181 special positions.
1183 This may also be a cons cell where the behavior for `C-a' and
1184 `C-e' is set separately."
1185 :group 'org-edit-structure
1186 :type '(choice
1187 (const :tag "off" nil)
1188 (const :tag "on: after stars/bullet and before tags first" t)
1189 (const :tag "reversed: true line boundary first" reversed)
1190 (cons :tag "Set C-a and C-e separately"
1191 (choice :tag "Special C-a"
1192 (const :tag "off" nil)
1193 (const :tag "on: after stars/bullet first" t)
1194 (const :tag "reversed: before stars/bullet first" reversed))
1195 (choice :tag "Special C-e"
1196 (const :tag "off" nil)
1197 (const :tag "on: before tags first" t)
1198 (const :tag "reversed: after tags first" reversed)))))
1199 (if (fboundp 'defvaralias)
1200 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1202 (defcustom org-special-ctrl-k nil
1203 "Non-nil means `C-k' will behave specially in headlines.
1204 When nil, `C-k' will call the default `kill-line' command.
1205 When t, the following will happen while the cursor is in the headline:
1207 - When the cursor is at the beginning of a headline, kill the entire
1208 line and possible the folded subtree below the line.
1209 - When in the middle of the headline text, kill the headline up to the tags.
1210 - When after the headline text, kill the tags."
1211 :group 'org-edit-structure
1212 :type 'boolean)
1214 (defcustom org-ctrl-k-protect-subtree nil
1215 "Non-nil means, do not delete a hidden subtree with C-k.
1216 When set to the symbol `error', simply throw an error when C-k is
1217 used to kill (part-of) a headline that has hidden text behind it.
1218 Any other non-nil value will result in a query to the user, if it is
1219 OK to kill that hidden subtree. When nil, kill without remorse."
1220 :group 'org-edit-structure
1221 :version "24.1"
1222 :type '(choice
1223 (const :tag "Do not protect hidden subtrees" nil)
1224 (const :tag "Protect hidden subtrees with a security query" t)
1225 (const :tag "Never kill a hidden subtree with C-k" error)))
1227 (defcustom org-catch-invisible-edits nil
1228 "Check if in invisible region before inserting or deleting a character.
1229 Valid values are:
1231 nil Do not check, so just do invisible edits.
1232 error Throw an error and do nothing.
1233 show Make point visible, and do the requested edit.
1234 show-and-error Make point visible, then throw an error and abort the edit.
1235 smart Make point visible, and do insertion/deletion if it is
1236 adjacent to visible text and the change feels predictable.
1237 Never delete a previously invisible character or add in the
1238 middle or right after an invisible region. Basically, this
1239 allows insertion and backward-delete right before ellipses.
1240 FIXME: maybe in this case we should not even show?"
1241 :group 'org-edit-structure
1242 :version "24.1"
1243 :type '(choice
1244 (const :tag "Do not check" nil)
1245 (const :tag "Throw error when trying to edit" error)
1246 (const :tag "Unhide, but do not do the edit" show-and-error)
1247 (const :tag "Show invisible part and do the edit" show)
1248 (const :tag "Be smart and do the right thing" smart)))
1250 (defcustom org-yank-folded-subtrees t
1251 "Non-nil means when yanking subtrees, fold them.
1252 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1253 it starts with a heading and all other headings in it are either children
1254 or siblings, then fold all the subtrees. However, do this only if no
1255 text after the yank would be swallowed into a folded tree by this action."
1256 :group 'org-edit-structure
1257 :type 'boolean)
1259 (defcustom org-yank-adjusted-subtrees nil
1260 "Non-nil means when yanking subtrees, adjust the level.
1261 With this setting, `org-paste-subtree' is used to insert the subtree, see
1262 this function for details."
1263 :group 'org-edit-structure
1264 :type 'boolean)
1266 (defcustom org-M-RET-may-split-line '((default . t))
1267 "Non-nil means M-RET will split the line at the cursor position.
1268 When nil, it will go to the end of the line before making a
1269 new line.
1270 You may also set this option in a different way for different
1271 contexts. Valid contexts are:
1273 headline when creating a new headline
1274 item when creating a new item
1275 table in a table field
1276 default the value to be used for all contexts not explicitly
1277 customized"
1278 :group 'org-structure
1279 :group 'org-table
1280 :type '(choice
1281 (const :tag "Always" t)
1282 (const :tag "Never" nil)
1283 (repeat :greedy t :tag "Individual contexts"
1284 (cons
1285 (choice :tag "Context"
1286 (const headline)
1287 (const item)
1288 (const table)
1289 (const default))
1290 (boolean)))))
1293 (defcustom org-insert-heading-respect-content nil
1294 "Non-nil means insert new headings after the current subtree.
1295 When nil, the new heading is created directly after the current line.
1296 The commands \\[org-insert-heading-respect-content] and
1297 \\[org-insert-todo-heading-respect-content] turn this variable on
1298 for the duration of the command."
1299 :group 'org-structure
1300 :type 'boolean)
1302 (defcustom org-blank-before-new-entry '((heading . auto)
1303 (plain-list-item . auto))
1304 "Should `org-insert-heading' leave a blank line before new heading/item?
1305 The value is an alist, with `heading' and `plain-list-item' as CAR,
1306 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1307 which case Org will look at the surrounding headings/items and try to
1308 make an intelligent decision whether to insert a blank line or not.
1310 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1311 set, the setting here is ignored and no empty line is inserted, to avoid
1312 breaking the list structure."
1313 :group 'org-edit-structure
1314 :type '(list
1315 (cons (const heading)
1316 (choice (const :tag "Never" nil)
1317 (const :tag "Always" t)
1318 (const :tag "Auto" auto)))
1319 (cons (const plain-list-item)
1320 (choice (const :tag "Never" nil)
1321 (const :tag "Always" t)
1322 (const :tag "Auto" auto)))))
1324 (defcustom org-insert-heading-hook nil
1325 "Hook being run after inserting a new heading."
1326 :group 'org-edit-structure
1327 :type 'hook)
1329 (defcustom org-enable-fixed-width-editor t
1330 "Non-nil means lines starting with \":\" are treated as fixed-width.
1331 This currently only means they are never auto-wrapped.
1332 When nil, such lines will be treated like ordinary lines.
1333 See also the QUOTE keyword."
1334 :group 'org-edit-structure
1335 :type 'boolean)
1337 (defcustom org-goto-auto-isearch t
1338 "Non-nil means typing characters in `org-goto' starts incremental search.
1339 When nil, you can use these keybindings to navigate the buffer:
1341 q Quit the org-goto interface
1342 n Go to the next visible heading
1343 p Go to the previous visible heading
1344 f Go one heading forward on same level
1345 b Go one heading backward on same level
1346 u Go one heading up"
1347 :group 'org-edit-structure
1348 :type 'boolean)
1350 (defgroup org-sparse-trees nil
1351 "Options concerning sparse trees in Org-mode."
1352 :tag "Org Sparse Trees"
1353 :group 'org-structure)
1355 (defcustom org-highlight-sparse-tree-matches t
1356 "Non-nil means highlight all matches that define a sparse tree.
1357 The highlights will automatically disappear the next time the buffer is
1358 changed by an edit command."
1359 :group 'org-sparse-trees
1360 :type 'boolean)
1362 (defcustom org-remove-highlights-with-change t
1363 "Non-nil means any change to the buffer will remove temporary highlights.
1364 Such highlights are created by `org-occur' and `org-clock-display'.
1365 When nil, `C-c C-c needs to be used to get rid of the highlights.
1366 The highlights created by `org-preview-latex-fragment' always need
1367 `C-c C-c' to be removed."
1368 :group 'org-sparse-trees
1369 :group 'org-time
1370 :type 'boolean)
1373 (defcustom org-occur-hook '(org-first-headline-recenter)
1374 "Hook that is run after `org-occur' has constructed a sparse tree.
1375 This can be used to recenter the window to show as much of the structure
1376 as possible."
1377 :group 'org-sparse-trees
1378 :type 'hook)
1380 (defgroup org-imenu-and-speedbar nil
1381 "Options concerning imenu and speedbar in Org-mode."
1382 :tag "Org Imenu and Speedbar"
1383 :group 'org-structure)
1385 (defcustom org-imenu-depth 2
1386 "The maximum level for Imenu access to Org-mode headlines.
1387 This also applied for speedbar access."
1388 :group 'org-imenu-and-speedbar
1389 :type 'integer)
1391 (defgroup org-table nil
1392 "Options concerning tables in Org-mode."
1393 :tag "Org Table"
1394 :group 'org)
1396 (defcustom org-enable-table-editor 'optimized
1397 "Non-nil means lines starting with \"|\" are handled by the table editor.
1398 When nil, such lines will be treated like ordinary lines.
1400 When equal to the symbol `optimized', the table editor will be optimized to
1401 do the following:
1402 - Automatic overwrite mode in front of whitespace in table fields.
1403 This makes the structure of the table stay in tact as long as the edited
1404 field does not exceed the column width.
1405 - Minimize the number of realigns. Normally, the table is aligned each time
1406 TAB or RET are pressed to move to another field. With optimization this
1407 happens only if changes to a field might have changed the column width.
1408 Optimization requires replacing the functions `self-insert-command',
1409 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1410 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1411 very good at guessing when a re-align will be necessary, but you can always
1412 force one with \\[org-ctrl-c-ctrl-c].
1414 If you would like to use the optimized version in Org-mode, but the
1415 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1417 This variable can be used to turn on and off the table editor during a session,
1418 but in order to toggle optimization, a restart is required.
1420 See also the variable `org-table-auto-blank-field'."
1421 :group 'org-table
1422 :type '(choice
1423 (const :tag "off" nil)
1424 (const :tag "on" t)
1425 (const :tag "on, optimized" optimized)))
1427 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1428 (version<= emacs-version "24.1"))
1429 "Non-nil means cluster self-insert commands for undo when possible.
1430 If this is set, then, like in the Emacs command loop, 20 consecutive
1431 characters will be undone together.
1432 This is configurable, because there is some impact on typing performance."
1433 :group 'org-table
1434 :type 'boolean)
1436 (defcustom org-table-tab-recognizes-table.el t
1437 "Non-nil means TAB will automatically notice a table.el table.
1438 When it sees such a table, it moves point into it and - if necessary -
1439 calls `table-recognize-table'."
1440 :group 'org-table-editing
1441 :type 'boolean)
1443 (defgroup org-link nil
1444 "Options concerning links in Org-mode."
1445 :tag "Org Link"
1446 :group 'org)
1448 (defvar org-link-abbrev-alist-local nil
1449 "Buffer-local version of `org-link-abbrev-alist', which see.
1450 The value of this is taken from the #+LINK lines.")
1451 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1453 (defcustom org-link-abbrev-alist nil
1454 "Alist of link abbreviations.
1455 The car of each element is a string, to be replaced at the start of a link.
1456 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1457 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1459 [[linkkey:tag][description]]
1461 The 'linkkey' must be a word word, starting with a letter, followed
1462 by letters, numbers, '-' or '_'.
1464 If REPLACE is a string, the tag will simply be appended to create the link.
1465 If the string contains \"%s\", the tag will be inserted there. If the string
1466 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1467 at that point (see the function `url-hexify-string'). If the string contains
1468 the specifier \"%(my-function)\", then the custom function `my-function' will
1469 be invoked: this function takes the tag as its only argument and must return
1470 a string.
1472 REPLACE may also be a function that will be called with the tag as the
1473 only argument to create the link, which should be returned as a string.
1475 See the manual for examples."
1476 :group 'org-link
1477 :type '(repeat
1478 (cons
1479 (string :tag "Protocol")
1480 (choice
1481 (string :tag "Format")
1482 (function)))))
1484 (defcustom org-descriptive-links t
1485 "Non-nil means Org will display descriptive links.
1486 E.g. [[http://orgmode.org][Org website]] will be displayed as
1487 \"Org Website\", hiding the link itself and just displaying its
1488 description. When set to `nil', Org will display the full links
1489 literally.
1491 You can interactively set the value of this variable by calling
1492 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1493 :group 'org-link
1494 :type 'boolean)
1496 (defcustom org-link-file-path-type 'adaptive
1497 "How the path name in file links should be stored.
1498 Valid values are:
1500 relative Relative to the current directory, i.e. the directory of the file
1501 into which the link is being inserted.
1502 absolute Absolute path, if possible with ~ for home directory.
1503 noabbrev Absolute path, no abbreviation of home directory.
1504 adaptive Use relative path for files in the current directory and sub-
1505 directories of it. For other files, use an absolute path."
1506 :group 'org-link
1507 :type '(choice
1508 (const relative)
1509 (const absolute)
1510 (const noabbrev)
1511 (const adaptive)))
1513 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1514 "Types of links that should be activated in Org-mode files.
1515 This is a list of symbols, each leading to the activation of a certain link
1516 type. In principle, it does not hurt to turn on most link types - there may
1517 be a small gain when turning off unused link types. The types are:
1519 bracket The recommended [[link][description]] or [[link]] links with hiding.
1520 angle Links in angular brackets that may contain whitespace like
1521 <bbdb:Carsten Dominik>.
1522 plain Plain links in normal text, no whitespace, like http://google.com.
1523 radio Text that is matched by a radio target, see manual for details.
1524 tag Tag settings in a headline (link to tag search).
1525 date Time stamps (link to calendar).
1526 footnote Footnote labels.
1528 Changing this variable requires a restart of Emacs to become effective."
1529 :group 'org-link
1530 :type '(set :greedy t
1531 (const :tag "Double bracket links" bracket)
1532 (const :tag "Angular bracket links" angle)
1533 (const :tag "Plain text links" plain)
1534 (const :tag "Radio target matches" radio)
1535 (const :tag "Tags" tag)
1536 (const :tag "Timestamps" date)
1537 (const :tag "Footnotes" footnote)))
1539 (defcustom org-make-link-description-function nil
1540 "Function to use for generating link descriptions from links.
1541 When nil, the link location will be used. This function must take
1542 two parameters: the first one is the link, the second one is the
1543 description generated by `org-insert-link'. The function should
1544 return the description to use."
1545 :group 'org-link
1546 :type 'function)
1548 (defgroup org-link-store nil
1549 "Options concerning storing links in Org-mode."
1550 :tag "Org Store Link"
1551 :group 'org-link)
1553 (defcustom org-url-hexify-p t
1554 "When non-nil, hexify URL when creating a link."
1555 :type 'boolean
1556 :version "24.3"
1557 :group 'org-link-store)
1559 (defcustom org-email-link-description-format "Email %c: %.30s"
1560 "Format of the description part of a link to an email or usenet message.
1561 The following %-escapes will be replaced by corresponding information:
1563 %F full \"From\" field
1564 %f name, taken from \"From\" field, address if no name
1565 %T full \"To\" field
1566 %t first name in \"To\" field, address if no name
1567 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1568 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1569 %s subject
1570 %d date
1571 %m message-id.
1573 You may use normal field width specification between the % and the letter.
1574 This is for example useful to limit the length of the subject.
1576 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1577 :group 'org-link-store
1578 :type 'string)
1580 (defcustom org-from-is-user-regexp
1581 (let (r1 r2)
1582 (when (and user-mail-address (not (string= user-mail-address "")))
1583 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1584 (when (and user-full-name (not (string= user-full-name "")))
1585 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1586 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1587 "Regexp matched against the \"From:\" header of an email or usenet message.
1588 It should match if the message is from the user him/herself."
1589 :group 'org-link-store
1590 :type 'regexp)
1592 (defcustom org-context-in-file-links t
1593 "Non-nil means file links from `org-store-link' contain context.
1594 A search string will be added to the file name with :: as separator and
1595 used to find the context when the link is activated by the command
1596 `org-open-at-point'. When this option is t, the entire active region
1597 will be placed in the search string of the file link. If set to a
1598 positive integer, only the first n lines of context will be stored.
1600 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1601 negates this setting for the duration of the command."
1602 :group 'org-link-store
1603 :type '(choice boolean integer))
1605 (defcustom org-keep-stored-link-after-insertion nil
1606 "Non-nil means keep link in list for entire session.
1608 The command `org-store-link' adds a link pointing to the current
1609 location to an internal list. These links accumulate during a session.
1610 The command `org-insert-link' can be used to insert links into any
1611 Org-mode file (offering completion for all stored links). When this
1612 option is nil, every link which has been inserted once using \\[org-insert-link]
1613 will be removed from the list, to make completing the unused links
1614 more efficient."
1615 :group 'org-link-store
1616 :type 'boolean)
1618 (defgroup org-link-follow nil
1619 "Options concerning following links in Org-mode."
1620 :tag "Org Follow Link"
1621 :group 'org-link)
1623 (defcustom org-link-translation-function nil
1624 "Function to translate links with different syntax to Org syntax.
1625 This can be used to translate links created for example by the Planner
1626 or emacs-wiki packages to Org syntax.
1627 The function must accept two parameters, a TYPE containing the link
1628 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1629 which is everything after the link protocol. It should return a cons
1630 with possibly modified values of type and path.
1631 Org contains a function for this, so if you set this variable to
1632 `org-translate-link-from-planner', you should be able follow many
1633 links created by planner."
1634 :group 'org-link-follow
1635 :type 'function)
1637 (defcustom org-follow-link-hook nil
1638 "Hook that is run after a link has been followed."
1639 :group 'org-link-follow
1640 :type 'hook)
1642 (defcustom org-tab-follows-link nil
1643 "Non-nil means on links TAB will follow the link.
1644 Needs to be set before org.el is loaded.
1645 This really should not be used, it does not make sense, and the
1646 implementation is bad."
1647 :group 'org-link-follow
1648 :type 'boolean)
1650 (defcustom org-return-follows-link nil
1651 "Non-nil means on links RET will follow the link."
1652 :group 'org-link-follow
1653 :type 'boolean)
1655 (defcustom org-mouse-1-follows-link
1656 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1657 "Non-nil means mouse-1 on a link will follow the link.
1658 A longer mouse click will still set point. Does not work on XEmacs.
1659 Needs to be set before org.el is loaded."
1660 :group 'org-link-follow
1661 :type 'boolean)
1663 (defcustom org-mark-ring-length 4
1664 "Number of different positions to be recorded in the ring.
1665 Changing this requires a restart of Emacs to work correctly."
1666 :group 'org-link-follow
1667 :type 'integer)
1669 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1670 "Non-nil means internal links in Org files must exactly match a headline.
1671 When nil, the link search tries to match a phrase with all words
1672 in the search text."
1673 :group 'org-link-follow
1674 :version "24.1"
1675 :type '(choice
1676 (const :tag "Use fuzzy text search" nil)
1677 (const :tag "Match only exact headline" t)
1678 (const :tag "Match exact headline or query to create it"
1679 query-to-create)))
1681 (defcustom org-link-frame-setup
1682 '((vm . vm-visit-folder-other-frame)
1683 (vm-imap . vm-visit-imap-folder-other-frame)
1684 (gnus . org-gnus-no-new-news)
1685 (file . find-file-other-window)
1686 (wl . wl-other-frame))
1687 "Setup the frame configuration for following links.
1688 When following a link with Emacs, it may often be useful to display
1689 this link in another window or frame. This variable can be used to
1690 set this up for the different types of links.
1691 For VM, use any of
1692 `vm-visit-folder'
1693 `vm-visit-folder-other-window'
1694 `vm-visit-folder-other-frame'
1695 For Gnus, use any of
1696 `gnus'
1697 `gnus-other-frame'
1698 `org-gnus-no-new-news'
1699 For FILE, use any of
1700 `find-file'
1701 `find-file-other-window'
1702 `find-file-other-frame'
1703 For Wanderlust use any of
1704 `wl'
1705 `wl-other-frame'
1706 For the calendar, use the variable `calendar-setup'.
1707 For BBDB, it is currently only possible to display the matches in
1708 another window."
1709 :group 'org-link-follow
1710 :type '(list
1711 (cons (const vm)
1712 (choice
1713 (const vm-visit-folder)
1714 (const vm-visit-folder-other-window)
1715 (const vm-visit-folder-other-frame)))
1716 (cons (const gnus)
1717 (choice
1718 (const gnus)
1719 (const gnus-other-frame)
1720 (const org-gnus-no-new-news)))
1721 (cons (const file)
1722 (choice
1723 (const find-file)
1724 (const find-file-other-window)
1725 (const find-file-other-frame)))
1726 (cons (const wl)
1727 (choice
1728 (const wl)
1729 (const wl-other-frame)))))
1731 (defcustom org-display-internal-link-with-indirect-buffer nil
1732 "Non-nil means use indirect buffer to display infile links.
1733 Activating internal links (from one location in a file to another location
1734 in the same file) normally just jumps to the location. When the link is
1735 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1736 is displayed in
1737 another window. When this option is set, the other window actually displays
1738 an indirect buffer clone of the current buffer, to avoid any visibility
1739 changes to the current buffer."
1740 :group 'org-link-follow
1741 :type 'boolean)
1743 (defcustom org-open-non-existing-files nil
1744 "Non-nil means `org-open-file' will open non-existing files.
1745 When nil, an error will be generated.
1746 This variable applies only to external applications because they
1747 might choke on non-existing files. If the link is to a file that
1748 will be opened in Emacs, the variable is ignored."
1749 :group 'org-link-follow
1750 :type 'boolean)
1752 (defcustom org-open-directory-means-index-dot-org nil
1753 "Non-nil means a link to a directory really means to index.org.
1754 When nil, following a directory link will run dired or open a finder/explorer
1755 window on that directory."
1756 :group 'org-link-follow
1757 :type 'boolean)
1759 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1760 "Function and arguments to call for following mailto links.
1761 This is a list with the first element being a Lisp function, and the
1762 remaining elements being arguments to the function. In string arguments,
1763 %a will be replaced by the address, and %s will be replaced by the subject
1764 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1765 :group 'org-link-follow
1766 :type '(choice
1767 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1768 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1769 (const :tag "message-mail" (message-mail "%a" "%s"))
1770 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1772 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1773 "Non-nil means ask for confirmation before executing shell links.
1774 Shell links can be dangerous: just think about a link
1776 [[shell:rm -rf ~/*][Google Search]]
1778 This link would show up in your Org-mode document as \"Google Search\",
1779 but really it would remove your entire home directory.
1780 Therefore we advise against setting this variable to nil.
1781 Just change it to `y-or-n-p' if you want to confirm with a
1782 single keystroke rather than having to type \"yes\"."
1783 :group 'org-link-follow
1784 :type '(choice
1785 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1786 (const :tag "with y-or-n (faster)" y-or-n-p)
1787 (const :tag "no confirmation (dangerous)" nil)))
1788 (put 'org-confirm-shell-link-function
1789 'safe-local-variable
1790 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1792 (defcustom org-confirm-shell-link-not-regexp ""
1793 "A regexp to skip confirmation for shell links."
1794 :group 'org-link-follow
1795 :version "24.1"
1796 :type 'regexp)
1798 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1799 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1800 Elisp links can be dangerous: just think about a link
1802 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1804 This link would show up in your Org-mode document as \"Google Search\",
1805 but really it would remove your entire home directory.
1806 Therefore we advise against setting this variable to nil.
1807 Just change it to `y-or-n-p' if you want to confirm with a
1808 single keystroke rather than having to type \"yes\"."
1809 :group 'org-link-follow
1810 :type '(choice
1811 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1812 (const :tag "with y-or-n (faster)" y-or-n-p)
1813 (const :tag "no confirmation (dangerous)" nil)))
1814 (put 'org-confirm-shell-link-function
1815 'safe-local-variable
1816 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1818 (defcustom org-confirm-elisp-link-not-regexp ""
1819 "A regexp to skip confirmation for Elisp links."
1820 :group 'org-link-follow
1821 :version "24.1"
1822 :type 'regexp)
1824 (defconst org-file-apps-defaults-gnu
1825 '((remote . emacs)
1826 (system . mailcap)
1827 (t . mailcap))
1828 "Default file applications on a UNIX or GNU/Linux system.
1829 See `org-file-apps'.")
1831 (defconst org-file-apps-defaults-macosx
1832 '((remote . emacs)
1833 (t . "open %s")
1834 (system . "open %s")
1835 ("ps.gz" . "gv %s")
1836 ("eps.gz" . "gv %s")
1837 ("dvi" . "xdvi %s")
1838 ("fig" . "xfig %s"))
1839 "Default file applications on a MacOS X system.
1840 The system \"open\" is known as a default, but we use X11 applications
1841 for some files for which the OS does not have a good default.
1842 See `org-file-apps'.")
1844 (defconst org-file-apps-defaults-windowsnt
1845 (list
1846 '(remote . emacs)
1847 (cons t
1848 (list (if (featurep 'xemacs)
1849 'mswindows-shell-execute
1850 'w32-shell-execute)
1851 "open" 'file))
1852 (cons 'system
1853 (list (if (featurep 'xemacs)
1854 'mswindows-shell-execute
1855 'w32-shell-execute)
1856 "open" 'file)))
1857 "Default file applications on a Windows NT system.
1858 The system \"open\" is used for most files.
1859 See `org-file-apps'.")
1861 (defcustom org-file-apps
1863 (auto-mode . emacs)
1864 ("\\.mm\\'" . default)
1865 ("\\.x?html?\\'" . default)
1866 ("\\.pdf\\'" . default)
1868 "External applications for opening `file:path' items in a document.
1869 Org-mode uses system defaults for different file types, but
1870 you can use this variable to set the application for a given file
1871 extension. The entries in this list are cons cells where the car identifies
1872 files and the cdr the corresponding command. Possible values for the
1873 file identifier are
1874 \"string\" A string as a file identifier can be interpreted in different
1875 ways, depending on its contents:
1877 - Alphanumeric characters only:
1878 Match links with this file extension.
1879 Example: (\"pdf\" . \"evince %s\")
1880 to open PDFs with evince.
1882 - Regular expression: Match links where the
1883 filename matches the regexp. If you want to
1884 use groups here, use shy groups.
1886 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1887 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1888 to open *.html and *.xhtml with firefox.
1890 - Regular expression which contains (non-shy) groups:
1891 Match links where the whole link, including \"::\", and
1892 anything after that, matches the regexp.
1893 In a custom command string, %1, %2, etc. are replaced with
1894 the parts of the link that were matched by the groups.
1895 For backwards compatibility, if a command string is given
1896 that does not use any of the group matches, this case is
1897 handled identically to the second one (i.e. match against
1898 file name only).
1899 In a custom lisp form, you can access the group matches with
1900 (match-string n link).
1902 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1903 to open [[file:document.pdf::5]] with evince at page 5.
1905 `directory' Matches a directory
1906 `remote' Matches a remote file, accessible through tramp or efs.
1907 Remote files most likely should be visited through Emacs
1908 because external applications cannot handle such paths.
1909 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1910 so all files Emacs knows how to handle. Using this with
1911 command `emacs' will open most files in Emacs. Beware that this
1912 will also open html files inside Emacs, unless you add
1913 (\"html\" . default) to the list as well.
1914 t Default for files not matched by any of the other options.
1915 `system' The system command to open files, like `open' on Windows
1916 and Mac OS X, and mailcap under GNU/Linux. This is the command
1917 that will be selected if you call `C-c C-o' with a double
1918 \\[universal-argument] \\[universal-argument] prefix.
1920 Possible values for the command are:
1921 `emacs' The file will be visited by the current Emacs process.
1922 `default' Use the default application for this file type, which is the
1923 association for t in the list, most likely in the system-specific
1924 part.
1925 This can be used to overrule an unwanted setting in the
1926 system-specific variable.
1927 `system' Use the system command for opening files, like \"open\".
1928 This command is specified by the entry whose car is `system'.
1929 Most likely, the system-specific version of this variable
1930 does define this command, but you can overrule/replace it
1931 here.
1932 string A command to be executed by a shell; %s will be replaced
1933 by the path to the file.
1934 sexp A Lisp form which will be evaluated. The file path will
1935 be available in the Lisp variable `file'.
1936 For more examples, see the system specific constants
1937 `org-file-apps-defaults-macosx'
1938 `org-file-apps-defaults-windowsnt'
1939 `org-file-apps-defaults-gnu'."
1940 :group 'org-link-follow
1941 :type '(repeat
1942 (cons (choice :value ""
1943 (string :tag "Extension")
1944 (const :tag "System command to open files" system)
1945 (const :tag "Default for unrecognized files" t)
1946 (const :tag "Remote file" remote)
1947 (const :tag "Links to a directory" directory)
1948 (const :tag "Any files that have Emacs modes"
1949 auto-mode))
1950 (choice :value ""
1951 (const :tag "Visit with Emacs" emacs)
1952 (const :tag "Use default" default)
1953 (const :tag "Use the system command" system)
1954 (string :tag "Command")
1955 (sexp :tag "Lisp form")))))
1957 (defcustom org-doi-server-url "http://dx.doi.org/"
1958 "The URL of the DOI server."
1959 :type 'string
1960 :version "24.3"
1961 :group 'org-link-follow)
1963 (defgroup org-refile nil
1964 "Options concerning refiling entries in Org-mode."
1965 :tag "Org Refile"
1966 :group 'org)
1968 (defcustom org-directory "~/org"
1969 "Directory with org files.
1970 This is just a default location to look for Org files. There is no need
1971 at all to put your files into this directory. It is only used in the
1972 following situations:
1974 1. When a capture template specifies a target file that is not an
1975 absolute path. The path will then be interpreted relative to
1976 `org-directory'
1977 2. When a capture note is filed away in an interactive way (when exiting the
1978 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1979 with `org-directory' as the default path."
1980 :group 'org-refile
1981 :group 'org-remember
1982 :group 'org-capture
1983 :type 'directory)
1985 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1986 "Default target for storing notes.
1987 Used as a fall back file for org-remember.el and org-capture.el, for
1988 templates that do not specify a target file."
1989 :group 'org-refile
1990 :group 'org-remember
1991 :group 'org-capture
1992 :type '(choice
1993 (const :tag "Default from remember-data-file" nil)
1994 file))
1996 (defcustom org-goto-interface 'outline
1997 "The default interface to be used for `org-goto'.
1998 Allowed values are:
1999 outline The interface shows an outline of the relevant file
2000 and the correct heading is found by moving through
2001 the outline or by searching with incremental search.
2002 outline-path-completion Headlines in the current buffer are offered via
2003 completion. This is the interface also used by
2004 the refile command."
2005 :group 'org-refile
2006 :type '(choice
2007 (const :tag "Outline" outline)
2008 (const :tag "Outline-path-completion" outline-path-completion)))
2010 (defcustom org-goto-max-level 5
2011 "Maximum target level when running `org-goto' with refile interface."
2012 :group 'org-refile
2013 :type 'integer)
2015 (defcustom org-reverse-note-order nil
2016 "Non-nil means store new notes at the beginning of a file or entry.
2017 When nil, new notes will be filed to the end of a file or entry.
2018 This can also be a list with cons cells of regular expressions that
2019 are matched against file names, and values."
2020 :group 'org-remember
2021 :group 'org-capture
2022 :group 'org-refile
2023 :type '(choice
2024 (const :tag "Reverse always" t)
2025 (const :tag "Reverse never" nil)
2026 (repeat :tag "By file name regexp"
2027 (cons regexp boolean))))
2029 (defcustom org-log-refile nil
2030 "Information to record when a task is refiled.
2032 Possible values are:
2034 nil Don't add anything
2035 time Add a time stamp to the task
2036 note Prompt for a note and add it with template `org-log-note-headings'
2038 This option can also be set with on a per-file-basis with
2040 #+STARTUP: nologrefile
2041 #+STARTUP: logrefile
2042 #+STARTUP: lognoterefile
2044 You can have local logging settings for a subtree by setting the LOGGING
2045 property to one or more of these keywords.
2047 When bulk-refiling from the agenda, the value `note' is forbidden and
2048 will temporarily be changed to `time'."
2049 :group 'org-refile
2050 :group 'org-progress
2051 :version "24.1"
2052 :type '(choice
2053 (const :tag "No logging" nil)
2054 (const :tag "Record timestamp" time)
2055 (const :tag "Record timestamp with note." note)))
2057 (defcustom org-refile-targets nil
2058 "Targets for refiling entries with \\[org-refile].
2059 This is a list of cons cells. Each cell contains:
2060 - a specification of the files to be considered, either a list of files,
2061 or a symbol whose function or variable value will be used to retrieve
2062 a file name or a list of file names. If you use `org-agenda-files' for
2063 that, all agenda files will be scanned for targets. Nil means consider
2064 headings in the current buffer.
2065 - A specification of how to find candidate refile targets. This may be
2066 any of:
2067 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2068 This tag has to be present in all target headlines, inheritance will
2069 not be considered.
2070 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2071 todo keyword.
2072 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2073 headlines that are refiling targets.
2074 - a cons cell (:level . N). Any headline of level N is considered a target.
2075 Note that, when `org-odd-levels-only' is set, level corresponds to
2076 order in hierarchy, not to the number of stars.
2077 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2078 Note that, when `org-odd-levels-only' is set, level corresponds to
2079 order in hierarchy, not to the number of stars.
2081 Each element of this list generates a set of possible targets.
2082 The union of these sets is presented (with completion) to
2083 the user by `org-refile'.
2085 You can set the variable `org-refile-target-verify-function' to a function
2086 to verify each headline found by the simple criteria above.
2088 When this variable is nil, all top-level headlines in the current buffer
2089 are used, equivalent to the value `((nil . (:level . 1))'."
2090 :group 'org-refile
2091 :type '(repeat
2092 (cons
2093 (choice :value org-agenda-files
2094 (const :tag "All agenda files" org-agenda-files)
2095 (const :tag "Current buffer" nil)
2096 (function) (variable) (file))
2097 (choice :tag "Identify target headline by"
2098 (cons :tag "Specific tag" (const :value :tag) (string))
2099 (cons :tag "TODO keyword" (const :value :todo) (string))
2100 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2101 (cons :tag "Level number" (const :value :level) (integer))
2102 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2104 (defcustom org-refile-target-verify-function nil
2105 "Function to verify if the headline at point should be a refile target.
2106 The function will be called without arguments, with point at the
2107 beginning of the headline. It should return t and leave point
2108 where it is if the headline is a valid target for refiling.
2110 If the target should not be selected, the function must return nil.
2111 In addition to this, it may move point to a place from where the search
2112 should be continued. For example, the function may decide that the entire
2113 subtree of the current entry should be excluded and move point to the end
2114 of the subtree."
2115 :group 'org-refile
2116 :type 'function)
2118 (defcustom org-refile-use-cache nil
2119 "Non-nil means cache refile targets to speed up the process.
2120 The cache for a particular file will be updated automatically when
2121 the buffer has been killed, or when any of the marker used for flagging
2122 refile targets no longer points at a live buffer.
2123 If you have added new entries to a buffer that might themselves be targets,
2124 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2125 find that easier, `C-u C-u C-u C-c C-w'."
2126 :group 'org-refile
2127 :version "24.1"
2128 :type 'boolean)
2130 (defcustom org-refile-use-outline-path nil
2131 "Non-nil means provide refile targets as paths.
2132 So a level 3 headline will be available as level1/level2/level3.
2134 When the value is `file', also include the file name (without directory)
2135 into the path. In this case, you can also stop the completion after
2136 the file name, to get entries inserted as top level in the file.
2138 When `full-file-path', include the full file path."
2139 :group 'org-refile
2140 :type '(choice
2141 (const :tag "Not" nil)
2142 (const :tag "Yes" t)
2143 (const :tag "Start with file name" file)
2144 (const :tag "Start with full file path" full-file-path)))
2146 (defcustom org-outline-path-complete-in-steps t
2147 "Non-nil means complete the outline path in hierarchical steps.
2148 When Org-mode uses the refile interface to select an outline path
2149 \(see variable `org-refile-use-outline-path'), the completion of
2150 the path can be done is a single go, or if can be done in steps down
2151 the headline hierarchy. Going in steps is probably the best if you
2152 do not use a special completion package like `ido' or `icicles'.
2153 However, when using these packages, going in one step can be very
2154 fast, while still showing the whole path to the entry."
2155 :group 'org-refile
2156 :type 'boolean)
2158 (defcustom org-refile-allow-creating-parent-nodes nil
2159 "Non-nil means allow to create new nodes as refile targets.
2160 New nodes are then created by adding \"/new node name\" to the completion
2161 of an existing node. When the value of this variable is `confirm',
2162 new node creation must be confirmed by the user (recommended)
2163 When nil, the completion must match an existing entry.
2165 Note that, if the new heading is not seen by the criteria
2166 listed in `org-refile-targets', multiple instances of the same
2167 heading would be created by trying again to file under the new
2168 heading."
2169 :group 'org-refile
2170 :type '(choice
2171 (const :tag "Never" nil)
2172 (const :tag "Always" t)
2173 (const :tag "Prompt for confirmation" confirm)))
2175 (defcustom org-refile-active-region-within-subtree nil
2176 "Non-nil means also refile active region within a subtree.
2178 By default `org-refile' doesn't allow refiling regions if they
2179 don't contain a set of subtrees, but it might be convenient to
2180 do so sometimes: in that case, the first line of the region is
2181 converted to a headline before refiling."
2182 :group 'org-refile
2183 :version "24.1"
2184 :type 'boolean)
2186 (defgroup org-todo nil
2187 "Options concerning TODO items in Org-mode."
2188 :tag "Org TODO"
2189 :group 'org)
2191 (defgroup org-progress nil
2192 "Options concerning Progress logging in Org-mode."
2193 :tag "Org Progress"
2194 :group 'org-time)
2196 (defvar org-todo-interpretation-widgets
2197 '((:tag "Sequence (cycling hits every state)" sequence)
2198 (:tag "Type (cycling directly to DONE)" type))
2199 "The available interpretation symbols for customizing `org-todo-keywords'.
2200 Interested libraries should add to this list.")
2202 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2203 "List of TODO entry keyword sequences and their interpretation.
2204 \\<org-mode-map>This is a list of sequences.
2206 Each sequence starts with a symbol, either `sequence' or `type',
2207 indicating if the keywords should be interpreted as a sequence of
2208 action steps, or as different types of TODO items. The first
2209 keywords are states requiring action - these states will select a headline
2210 for inclusion into the global TODO list Org-mode produces. If one of
2211 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2212 signify that no further action is necessary. If \"|\" is not found,
2213 the last keyword is treated as the only DONE state of the sequence.
2215 The command \\[org-todo] cycles an entry through these states, and one
2216 additional state where no keyword is present. For details about this
2217 cycling, see the manual.
2219 TODO keywords and interpretation can also be set on a per-file basis with
2220 the special #+SEQ_TODO and #+TYP_TODO lines.
2222 Each keyword can optionally specify a character for fast state selection
2223 \(in combination with the variable `org-use-fast-todo-selection')
2224 and specifiers for state change logging, using the same syntax that
2225 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2226 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2227 indicates to record a time stamp each time this state is selected.
2229 Each keyword may also specify if a timestamp or a note should be
2230 recorded when entering or leaving the state, by adding additional
2231 characters in the parenthesis after the keyword. This looks like this:
2232 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2233 record only the time of the state change. With X and Y being either
2234 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2235 Y when leaving the state if and only if the *target* state does not
2236 define X. You may omit any of the fast-selection key or X or /Y,
2237 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2239 For backward compatibility, this variable may also be just a list
2240 of keywords. In this case the interpretation (sequence or type) will be
2241 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2242 :group 'org-todo
2243 :group 'org-keywords
2244 :type '(choice
2245 (repeat :tag "Old syntax, just keywords"
2246 (string :tag "Keyword"))
2247 (repeat :tag "New syntax"
2248 (cons
2249 (choice
2250 :tag "Interpretation"
2251 ;;Quick and dirty way to see
2252 ;;`org-todo-interpretations'. This takes the
2253 ;;place of item arguments
2254 :convert-widget
2255 (lambda (widget)
2256 (widget-put widget
2257 :args (mapcar
2258 #'(lambda (x)
2259 (widget-convert
2260 (cons 'const x)))
2261 org-todo-interpretation-widgets))
2262 widget))
2263 (repeat
2264 (string :tag "Keyword"))))))
2266 (defvar org-todo-keywords-1 nil
2267 "All TODO and DONE keywords active in a buffer.")
2268 (make-variable-buffer-local 'org-todo-keywords-1)
2269 (defvar org-todo-keywords-for-agenda nil)
2270 (defvar org-done-keywords-for-agenda nil)
2271 (defvar org-drawers-for-agenda nil)
2272 (defvar org-todo-keyword-alist-for-agenda nil)
2273 (defvar org-tag-alist-for-agenda nil)
2274 (defvar org-agenda-contributing-files nil)
2275 (defvar org-not-done-keywords nil)
2276 (make-variable-buffer-local 'org-not-done-keywords)
2277 (defvar org-done-keywords nil)
2278 (make-variable-buffer-local 'org-done-keywords)
2279 (defvar org-todo-heads nil)
2280 (make-variable-buffer-local 'org-todo-heads)
2281 (defvar org-todo-sets nil)
2282 (make-variable-buffer-local 'org-todo-sets)
2283 (defvar org-todo-log-states nil)
2284 (make-variable-buffer-local 'org-todo-log-states)
2285 (defvar org-todo-kwd-alist nil)
2286 (make-variable-buffer-local 'org-todo-kwd-alist)
2287 (defvar org-todo-key-alist nil)
2288 (make-variable-buffer-local 'org-todo-key-alist)
2289 (defvar org-todo-key-trigger nil)
2290 (make-variable-buffer-local 'org-todo-key-trigger)
2292 (defcustom org-todo-interpretation 'sequence
2293 "Controls how TODO keywords are interpreted.
2294 This variable is in principle obsolete and is only used for
2295 backward compatibility, if the interpretation of todo keywords is
2296 not given already in `org-todo-keywords'. See that variable for
2297 more information."
2298 :group 'org-todo
2299 :group 'org-keywords
2300 :type '(choice (const sequence)
2301 (const type)))
2303 (defcustom org-use-fast-todo-selection t
2304 "Non-nil means use the fast todo selection scheme with C-c C-t.
2305 This variable describes if and under what circumstances the cycling
2306 mechanism for TODO keywords will be replaced by a single-key, direct
2307 selection scheme.
2309 When nil, fast selection is never used.
2311 When the symbol `prefix', it will be used when `org-todo' is called
2312 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2313 `C-u t' in an agenda buffer.
2315 When t, fast selection is used by default. In this case, the prefix
2316 argument forces cycling instead.
2318 In all cases, the special interface is only used if access keys have
2319 actually been assigned by the user, i.e. if keywords in the configuration
2320 are followed by a letter in parenthesis, like TODO(t)."
2321 :group 'org-todo
2322 :type '(choice
2323 (const :tag "Never" nil)
2324 (const :tag "By default" t)
2325 (const :tag "Only with C-u C-c C-t" prefix)))
2327 (defcustom org-provide-todo-statistics t
2328 "Non-nil means update todo statistics after insert and toggle.
2329 ALL-HEADLINES means update todo statistics by including headlines
2330 with no TODO keyword as well, counting them as not done.
2331 A list of TODO keywords means the same, but skip keywords that are
2332 not in this list.
2334 When this is set, todo statistics is updated in the parent of the
2335 current entry each time a todo state is changed."
2336 :group 'org-todo
2337 :type '(choice
2338 (const :tag "Yes, only for TODO entries" t)
2339 (const :tag "Yes, including all entries" 'all-headlines)
2340 (repeat :tag "Yes, for TODOs in this list"
2341 (string :tag "TODO keyword"))
2342 (other :tag "No TODO statistics" nil)))
2344 (defcustom org-hierarchical-todo-statistics t
2345 "Non-nil means TODO statistics covers just direct children.
2346 When nil, all entries in the subtree are considered.
2347 This has only an effect if `org-provide-todo-statistics' is set.
2348 To set this to nil for only a single subtree, use a COOKIE_DATA
2349 property and include the word \"recursive\" into the value."
2350 :group 'org-todo
2351 :type 'boolean)
2353 (defcustom org-after-todo-state-change-hook nil
2354 "Hook which is run after the state of a TODO item was changed.
2355 The new state (a string with a TODO keyword, or nil) is available in the
2356 Lisp variable `org-state'."
2357 :group 'org-todo
2358 :type 'hook)
2360 (defvar org-blocker-hook nil
2361 "Hook for functions that are allowed to block a state change.
2363 Functions in this hook should not modify the buffer.
2364 Each function gets as its single argument a property list,
2365 see `org-trigger-hook' for more information about this list.
2367 If any of the functions in this hook returns nil, the state change
2368 is blocked.")
2370 (defvar org-trigger-hook nil
2371 "Hook for functions that are triggered by a state change.
2373 Each function gets as its single argument a property list with at
2374 least the following elements:
2376 (:type type-of-change :position pos-at-entry-start
2377 :from old-state :to new-state)
2379 Depending on the type, more properties may be present.
2381 This mechanism is currently implemented for:
2383 TODO state changes
2384 ------------------
2385 :type todo-state-change
2386 :from previous state (keyword as a string), or nil, or a symbol
2387 'todo' or 'done', to indicate the general type of state.
2388 :to new state, like in :from")
2390 (defcustom org-enforce-todo-dependencies nil
2391 "Non-nil means undone TODO entries will block switching the parent to DONE.
2392 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2393 be blocked if any prior sibling is not yet done.
2394 Finally, if the parent is blocked because of ordered siblings of its own,
2395 the child will also be blocked."
2396 :set (lambda (var val)
2397 (set var val)
2398 (if val
2399 (add-hook 'org-blocker-hook
2400 'org-block-todo-from-children-or-siblings-or-parent)
2401 (remove-hook 'org-blocker-hook
2402 'org-block-todo-from-children-or-siblings-or-parent)))
2403 :group 'org-todo
2404 :type 'boolean)
2406 (defcustom org-enforce-todo-checkbox-dependencies nil
2407 "Non-nil means unchecked boxes will block switching the parent to DONE.
2408 When this is nil, checkboxes have no influence on switching TODO states.
2409 When non-nil, you first need to check off all check boxes before the TODO
2410 entry can be switched to DONE.
2411 This variable needs to be set before org.el is loaded, and you need to
2412 restart Emacs after a change to make the change effective. The only way
2413 to change is while Emacs is running is through the customize interface."
2414 :set (lambda (var val)
2415 (set var val)
2416 (if val
2417 (add-hook 'org-blocker-hook
2418 'org-block-todo-from-checkboxes)
2419 (remove-hook 'org-blocker-hook
2420 'org-block-todo-from-checkboxes)))
2421 :group 'org-todo
2422 :type 'boolean)
2424 (defcustom org-treat-insert-todo-heading-as-state-change nil
2425 "Non-nil means inserting a TODO heading is treated as state change.
2426 So when the command \\[org-insert-todo-heading] is used, state change
2427 logging will apply if appropriate. When nil, the new TODO item will
2428 be inserted directly, and no logging will take place."
2429 :group 'org-todo
2430 :type 'boolean)
2432 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2433 "Non-nil means switching TODO states with S-cursor counts as state change.
2434 This is the default behavior. However, setting this to nil allows a
2435 convenient way to select a TODO state and bypass any logging associated
2436 with that."
2437 :group 'org-todo
2438 :type 'boolean)
2440 (defcustom org-todo-state-tags-triggers nil
2441 "Tag changes that should be triggered by TODO state changes.
2442 This is a list. Each entry is
2444 (state-change (tag . flag) .......)
2446 State-change can be a string with a state, and empty string to indicate the
2447 state that has no TODO keyword, or it can be one of the symbols `todo'
2448 or `done', meaning any not-done or done state, respectively."
2449 :group 'org-todo
2450 :group 'org-tags
2451 :type '(repeat
2452 (cons (choice :tag "When changing to"
2453 (const :tag "Not-done state" todo)
2454 (const :tag "Done state" done)
2455 (string :tag "State"))
2456 (repeat
2457 (cons :tag "Tag action"
2458 (string :tag "Tag")
2459 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2461 (defcustom org-log-done nil
2462 "Information to record when a task moves to the DONE state.
2464 Possible values are:
2466 nil Don't add anything, just change the keyword
2467 time Add a time stamp to the task
2468 note Prompt for a note and add it with template `org-log-note-headings'
2470 This option can also be set with on a per-file-basis with
2472 #+STARTUP: nologdone
2473 #+STARTUP: logdone
2474 #+STARTUP: lognotedone
2476 You can have local logging settings for a subtree by setting the LOGGING
2477 property to one or more of these keywords."
2478 :group 'org-todo
2479 :group 'org-progress
2480 :type '(choice
2481 (const :tag "No logging" nil)
2482 (const :tag "Record CLOSED timestamp" time)
2483 (const :tag "Record CLOSED timestamp with note." note)))
2485 ;; Normalize old uses of org-log-done.
2486 (cond
2487 ((eq org-log-done t) (setq org-log-done 'time))
2488 ((and (listp org-log-done) (memq 'done org-log-done))
2489 (setq org-log-done 'note)))
2491 (defcustom org-log-reschedule nil
2492 "Information to record when the scheduling date of a tasks is modified.
2494 Possible values are:
2496 nil Don't add anything, just change the date
2497 time Add a time stamp to the task
2498 note Prompt for a note and add it with template `org-log-note-headings'
2500 This option can also be set with on a per-file-basis with
2502 #+STARTUP: nologreschedule
2503 #+STARTUP: logreschedule
2504 #+STARTUP: lognotereschedule"
2505 :group 'org-todo
2506 :group 'org-progress
2507 :type '(choice
2508 (const :tag "No logging" nil)
2509 (const :tag "Record timestamp" time)
2510 (const :tag "Record timestamp with note." note)))
2512 (defcustom org-log-redeadline nil
2513 "Information to record when the deadline date of a tasks is modified.
2515 Possible values are:
2517 nil Don't add anything, just change the date
2518 time Add a time stamp to the task
2519 note Prompt for a note and add it with template `org-log-note-headings'
2521 This option can also be set with on a per-file-basis with
2523 #+STARTUP: nologredeadline
2524 #+STARTUP: logredeadline
2525 #+STARTUP: lognoteredeadline
2527 You can have local logging settings for a subtree by setting the LOGGING
2528 property to one or more of these keywords."
2529 :group 'org-todo
2530 :group 'org-progress
2531 :type '(choice
2532 (const :tag "No logging" nil)
2533 (const :tag "Record timestamp" time)
2534 (const :tag "Record timestamp with note." note)))
2536 (defcustom org-log-note-clock-out nil
2537 "Non-nil means record a note when clocking out of an item.
2538 This can also be configured on a per-file basis by adding one of
2539 the following lines anywhere in the buffer:
2541 #+STARTUP: lognoteclock-out
2542 #+STARTUP: nolognoteclock-out"
2543 :group 'org-todo
2544 :group 'org-progress
2545 :type 'boolean)
2547 (defcustom org-log-done-with-time t
2548 "Non-nil means the CLOSED time stamp will contain date and time.
2549 When nil, only the date will be recorded."
2550 :group 'org-progress
2551 :type 'boolean)
2553 (defcustom org-log-note-headings
2554 '((done . "CLOSING NOTE %t")
2555 (state . "State %-12s from %-12S %t")
2556 (note . "Note taken on %t")
2557 (reschedule . "Rescheduled from %S on %t")
2558 (delschedule . "Not scheduled, was %S on %t")
2559 (redeadline . "New deadline from %S on %t")
2560 (deldeadline . "Removed deadline, was %S on %t")
2561 (refile . "Refiled on %t")
2562 (clock-out . ""))
2563 "Headings for notes added to entries.
2564 The value is an alist, with the car being a symbol indicating the note
2565 context, and the cdr is the heading to be used. The heading may also be the
2566 empty string.
2567 %t in the heading will be replaced by a time stamp.
2568 %T will be an active time stamp instead the default inactive one
2569 %d will be replaced by a short-format time stamp.
2570 %D will be replaced by an active short-format time stamp.
2571 %s will be replaced by the new TODO state, in double quotes.
2572 %S will be replaced by the old TODO state, in double quotes.
2573 %u will be replaced by the user name.
2574 %U will be replaced by the full user name.
2576 In fact, it is not a good idea to change the `state' entry, because
2577 agenda log mode depends on the format of these entries."
2578 :group 'org-todo
2579 :group 'org-progress
2580 :type '(list :greedy t
2581 (cons (const :tag "Heading when closing an item" done) string)
2582 (cons (const :tag
2583 "Heading when changing todo state (todo sequence only)"
2584 state) string)
2585 (cons (const :tag "Heading when just taking a note" note) string)
2586 (cons (const :tag "Heading when clocking out" clock-out) string)
2587 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2588 (cons (const :tag "Heading when rescheduling" reschedule) string)
2589 (cons (const :tag "Heading when changing deadline" redeadline) string)
2590 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2591 (cons (const :tag "Heading when refiling" refile) string)))
2593 (unless (assq 'note org-log-note-headings)
2594 (push '(note . "%t") org-log-note-headings))
2596 (defcustom org-log-into-drawer nil
2597 "Non-nil means insert state change notes and time stamps into a drawer.
2598 When nil, state changes notes will be inserted after the headline and
2599 any scheduling and clock lines, but not inside a drawer.
2601 The value of this variable should be the name of the drawer to use.
2602 LOGBOOK is proposed as the default drawer for this purpose, you can
2603 also set this to a string to define the drawer of your choice.
2605 A value of t is also allowed, representing \"LOGBOOK\".
2607 A value of t or nil can also be set with on a per-file-basis with
2609 #+STARTUP: logdrawer
2610 #+STARTUP: nologdrawer
2612 If this variable is set, `org-log-state-notes-insert-after-drawers'
2613 will be ignored.
2615 You can set the property LOG_INTO_DRAWER to overrule this setting for
2616 a subtree."
2617 :group 'org-todo
2618 :group 'org-progress
2619 :type '(choice
2620 (const :tag "Not into a drawer" nil)
2621 (const :tag "LOGBOOK" t)
2622 (string :tag "Other")))
2624 (if (fboundp 'defvaralias)
2625 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2627 (defun org-log-into-drawer ()
2628 "Return the value of `org-log-into-drawer', but let properties overrule.
2629 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2630 used instead of the default value."
2631 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2632 (cond
2633 ((not p) org-log-into-drawer)
2634 ((equal p "nil") nil)
2635 ((equal p "t") "LOGBOOK")
2636 (t p))))
2638 (defcustom org-log-state-notes-insert-after-drawers nil
2639 "Non-nil means insert state change notes after any drawers in entry.
2640 Only the drawers that *immediately* follow the headline and the
2641 deadline/scheduled line are skipped.
2642 When nil, insert notes right after the heading and perhaps the line
2643 with deadline/scheduling if present.
2645 This variable will have no effect if `org-log-into-drawer' is
2646 set."
2647 :group 'org-todo
2648 :group 'org-progress
2649 :type 'boolean)
2651 (defcustom org-log-states-order-reversed t
2652 "Non-nil means the latest state note will be directly after heading.
2653 When nil, the state change notes will be ordered according to time.
2655 This option can also be set with on a per-file-basis with
2657 #+STARTUP: logstatesreversed
2658 #+STARTUP: nologstatesreversed"
2659 :group 'org-todo
2660 :group 'org-progress
2661 :type 'boolean)
2663 (defcustom org-todo-repeat-to-state nil
2664 "The TODO state to which a repeater should return the repeating task.
2665 By default this is the first task in a TODO sequence, or the previous state
2666 in a TODO_TYP set. But you can specify another task here.
2667 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2668 :group 'org-todo
2669 :version "24.1"
2670 :type '(choice (const :tag "Head of sequence" nil)
2671 (string :tag "Specific state")))
2673 (defcustom org-log-repeat 'time
2674 "Non-nil means record moving through the DONE state when triggering repeat.
2675 An auto-repeating task is immediately switched back to TODO when
2676 marked DONE. If you are not logging state changes (by adding \"@\"
2677 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2678 record a closing note, there will be no record of the task moving
2679 through DONE. This variable forces taking a note anyway.
2681 nil Don't force a record
2682 time Record a time stamp
2683 note Prompt for a note and add it with template `org-log-note-headings'
2685 This option can also be set with on a per-file-basis with
2687 #+STARTUP: nologrepeat
2688 #+STARTUP: logrepeat
2689 #+STARTUP: lognoterepeat
2691 You can have local logging settings for a subtree by setting the LOGGING
2692 property to one or more of these keywords."
2693 :group 'org-todo
2694 :group 'org-progress
2695 :type '(choice
2696 (const :tag "Don't force a record" nil)
2697 (const :tag "Force recording the DONE state" time)
2698 (const :tag "Force recording a note with the DONE state" note)))
2701 (defgroup org-priorities nil
2702 "Priorities in Org-mode."
2703 :tag "Org Priorities"
2704 :group 'org-todo)
2706 (defcustom org-enable-priority-commands t
2707 "Non-nil means priority commands are active.
2708 When nil, these commands will be disabled, so that you never accidentally
2709 set a priority."
2710 :group 'org-priorities
2711 :type 'boolean)
2713 (defcustom org-highest-priority ?A
2714 "The highest priority of TODO items. A character like ?A, ?B etc.
2715 Must have a smaller ASCII number than `org-lowest-priority'."
2716 :group 'org-priorities
2717 :type 'character)
2719 (defcustom org-lowest-priority ?C
2720 "The lowest priority of TODO items. A character like ?A, ?B etc.
2721 Must have a larger ASCII number than `org-highest-priority'."
2722 :group 'org-priorities
2723 :type 'character)
2725 (defcustom org-default-priority ?B
2726 "The default priority of TODO items.
2727 This is the priority an item gets if no explicit priority is given.
2728 When starting to cycle on an empty priority the first step in the cycle
2729 depends on `org-priority-start-cycle-with-default'. The resulting first
2730 step priority must not exceed the range from `org-highest-priority' to
2731 `org-lowest-priority' which means that `org-default-priority' has to be
2732 in this range exclusive or inclusive the range boundaries. Else the
2733 first step refuses to set the default and the second will fall back
2734 to (depending on the command used) the highest or lowest priority."
2735 :group 'org-priorities
2736 :type 'character)
2738 (defcustom org-priority-start-cycle-with-default t
2739 "Non-nil means start with default priority when starting to cycle.
2740 When this is nil, the first step in the cycle will be (depending on the
2741 command used) one higher or lower than the default priority.
2742 See also `org-default-priority'."
2743 :group 'org-priorities
2744 :type 'boolean)
2746 (defcustom org-get-priority-function nil
2747 "Function to extract the priority from a string.
2748 The string is normally the headline. If this is nil Org computes the
2749 priority from the priority cookie like [#A] in the headline. It returns
2750 an integer, increasing by 1000 for each priority level.
2751 The user can set a different function here, which should take a string
2752 as an argument and return the numeric priority."
2753 :group 'org-priorities
2754 :version "24.1"
2755 :type 'function)
2757 (defgroup org-time nil
2758 "Options concerning time stamps and deadlines in Org-mode."
2759 :tag "Org Time"
2760 :group 'org)
2762 (defcustom org-insert-labeled-timestamps-at-point nil
2763 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2764 When nil, these labeled time stamps are forces into the second line of an
2765 entry, just after the headline. When scheduling from the global TODO list,
2766 the time stamp will always be forced into the second line."
2767 :group 'org-time
2768 :type 'boolean)
2770 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2771 "Formats for `format-time-string' which are used for time stamps.
2772 It is not recommended to change this constant.")
2774 (defcustom org-time-stamp-rounding-minutes '(0 5)
2775 "Number of minutes to round time stamps to.
2776 These are two values, the first applies when first creating a time stamp.
2777 The second applies when changing it with the commands `S-up' and `S-down'.
2778 When changing the time stamp, this means that it will change in steps
2779 of N minutes, as given by the second value.
2781 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2782 numbers should be factors of 60, so for example 5, 10, 15.
2784 When this is larger than 1, you can still force an exact time stamp by using
2785 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2786 and by using a prefix arg to `S-up/down' to specify the exact number
2787 of minutes to shift."
2788 :group 'org-time
2789 :get #'(lambda (var) ; Make sure both elements are there
2790 (if (integerp (default-value var))
2791 (list (default-value var) 5)
2792 (default-value var)))
2793 :type '(list
2794 (integer :tag "when inserting times")
2795 (integer :tag "when modifying times")))
2797 ;; Normalize old customizations of this variable.
2798 (when (integerp org-time-stamp-rounding-minutes)
2799 (setq org-time-stamp-rounding-minutes
2800 (list org-time-stamp-rounding-minutes
2801 org-time-stamp-rounding-minutes)))
2803 (defcustom org-display-custom-times nil
2804 "Non-nil means overlay custom formats over all time stamps.
2805 The formats are defined through the variable `org-time-stamp-custom-formats'.
2806 To turn this on on a per-file basis, insert anywhere in the file:
2807 #+STARTUP: customtime"
2808 :group 'org-time
2809 :set 'set-default
2810 :type 'sexp)
2811 (make-variable-buffer-local 'org-display-custom-times)
2813 (defcustom org-time-stamp-custom-formats
2814 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2815 "Custom formats for time stamps. See `format-time-string' for the syntax.
2816 These are overlaid over the default ISO format if the variable
2817 `org-display-custom-times' is set. Time like %H:%M should be at the
2818 end of the second format. The custom formats are also honored by export
2819 commands, if custom time display is turned on at the time of export."
2820 :group 'org-time
2821 :type 'sexp)
2823 (defun org-time-stamp-format (&optional long inactive)
2824 "Get the right format for a time string."
2825 (let ((f (if long (cdr org-time-stamp-formats)
2826 (car org-time-stamp-formats))))
2827 (if inactive
2828 (concat "[" (substring f 1 -1) "]")
2829 f)))
2831 (defcustom org-time-clocksum-format
2832 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2833 "The format string used when creating CLOCKSUM lines.
2834 This is also used when Org mode generates a time duration.
2836 The value can be a single format string containing two
2837 %-sequences, which will be filled with the number of hours and
2838 minutes in that order.
2840 Alternatively, the value can be a plist associating any of the
2841 keys :years, :months, :weeks, :days, :hours or :minutes with
2842 format strings. The time duration is formatted using only the
2843 time components that are needed and concatenating the results.
2844 If a time unit in absent, it falls back to the next smallest
2845 unit.
2847 The keys :require-years, :require-months, :require-days,
2848 :require-weeks, :require-hours, :require-minutes are also
2849 meaningful. A non-nil value for these keys indicates that the
2850 corresponding time component should always be included, even if
2851 its value is 0.
2854 For example,
2856 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2857 :require-minutes t)
2859 means durations longer than a day will be expressed in days,
2860 hours and minutes, and durations less than a day will always be
2861 expressed in hours and minutes (even for durations less than an
2862 hour).
2864 The value
2866 \(:days \"%dd\" :minutes \"%dm\")
2868 means durations longer than a day will be expressed in days and
2869 minutes, and durations less than a day will be expressed entirely
2870 in minutes (even for durations longer than an hour)."
2871 :group 'org-time
2872 :group 'org-clock
2873 :version "24.3"
2874 :type '(choice (string :tag "Format string")
2875 (set :tag "Plist"
2876 (group :inline t (const :tag "Years" :years)
2877 (string :tag "Format string"))
2878 (group :inline t
2879 (const :tag "Always show years" :require-years)
2880 (const t))
2881 (group :inline t (const :tag "Months" :months)
2882 (string :tag "Format string"))
2883 (group :inline t
2884 (const :tag "Always show months" :require-months)
2885 (const t))
2886 (group :inline t (const :tag "Weeks" :weeks)
2887 (string :tag "Format string"))
2888 (group :inline t
2889 (const :tag "Always show weeks" :require-weeks)
2890 (const t))
2891 (group :inline t (const :tag "Days" :days)
2892 (string :tag "Format string"))
2893 (group :inline t
2894 (const :tag "Always show days" :require-days)
2895 (const t))
2896 (group :inline t (const :tag "Hours" :hours)
2897 (string :tag "Format string"))
2898 (group :inline t
2899 (const :tag "Always show hours" :require-hours)
2900 (const t))
2901 (group :inline t (const :tag "Minutes" :minutes)
2902 (string :tag "Format string"))
2903 (group :inline t
2904 (const :tag "Always show minutes" :require-minutes)
2905 (const t)))))
2907 (defcustom org-time-clocksum-use-fractional nil
2908 "When non-nil, \\[org-clock-display] uses fractional times.
2909 See `org-time-clocksum-format' for more on time clock formats."
2910 :group 'org-time
2911 :group 'org-clock
2912 :version "24.3"
2913 :type 'boolean)
2915 (defcustom org-time-clocksum-use-effort-durations t
2916 "When non-nil, \\[org-clock-display] uses effort durations.
2917 E.g. by default, one day is considered to be a 8 hours effort,
2918 so a task that has been clocked for 16 hours will be displayed
2919 as during 2 days in the clock display or in the clocktable.
2921 See `org-effort-durations' on how to set effort durations
2922 and `org-time-clocksum-format' for more on time clock formats."
2923 :group 'org-time
2924 :group 'org-clock
2925 :version "24.3"
2926 :type 'boolean)
2928 (defcustom org-time-clocksum-fractional-format "%.2f"
2929 "The format string used when creating CLOCKSUM lines,
2930 or when Org mode generates a time duration, if
2931 `org-time-clocksum-use-fractional' is enabled.
2933 The value can be a single format string containing one
2934 %-sequence, which will be filled with the number of hours as
2935 a float.
2937 Alternatively, the value can be a plist associating any of the
2938 keys :years, :months, :weeks, :days, :hours or :minutes with
2939 a format string. The time duration is formatted using the
2940 largest time unit which gives a non-zero integer part. If all
2941 specified formats have zero integer part, the smallest time unit
2942 is used."
2943 :group 'org-time
2944 :type '(choice (string :tag "Format string")
2945 (set (group :inline t (const :tag "Years" :years)
2946 (string :tag "Format string"))
2947 (group :inline t (const :tag "Months" :months)
2948 (string :tag "Format string"))
2949 (group :inline t (const :tag "Weeks" :weeks)
2950 (string :tag "Format string"))
2951 (group :inline t (const :tag "Days" :days)
2952 (string :tag "Format string"))
2953 (group :inline t (const :tag "Hours" :hours)
2954 (string :tag "Format string"))
2955 (group :inline t (const :tag "Minutes" :minutes)
2956 (string :tag "Format string")))))
2958 (defcustom org-deadline-warning-days 14
2959 "Number of days before expiration during which a deadline becomes active.
2960 This variable governs the display in sparse trees and in the agenda.
2961 When 0 or negative, it means use this number (the absolute value of it)
2962 even if a deadline has a different individual lead time specified.
2964 Custom commands can set this variable in the options section."
2965 :group 'org-time
2966 :group 'org-agenda-daily/weekly
2967 :type 'integer)
2969 (defcustom org-scheduled-delay-days 0
2970 "Number of days before a scheduled item becomes active.
2971 This variable governs the display in sparse trees and in the agenda.
2972 The default value (i.e. 0) means: don't delay scheduled item.
2973 When negative, it means use this number (the absolute value of it)
2974 even if a scheduled item has a different individual delay time
2975 specified.
2977 Custom commands can set this variable in the options section."
2978 :group 'org-time
2979 :group 'org-agenda-daily/weekly
2980 :version "24.3"
2981 :type 'integer)
2983 (defcustom org-read-date-prefer-future t
2984 "Non-nil means assume future for incomplete date input from user.
2985 This affects the following situations:
2986 1. The user gives a month but not a year.
2987 For example, if it is April and you enter \"feb 2\", this will be read
2988 as Feb 2, *next* year. \"May 5\", however, will be this year.
2989 2. The user gives a day, but no month.
2990 For example, if today is the 15th, and you enter \"3\", Org-mode will
2991 read this as the third of *next* month. However, if you enter \"17\",
2992 it will be considered as *this* month.
2994 If you set this variable to the symbol `time', then also the following
2995 will work:
2997 3. If the user gives a time.
2998 If the time is before now, it will be interpreted as tomorrow.
3000 Currently none of this works for ISO week specifications.
3002 When this option is nil, the current day, month and year will always be
3003 used as defaults.
3005 See also `org-agenda-jump-prefer-future'."
3006 :group 'org-time
3007 :type '(choice
3008 (const :tag "Never" nil)
3009 (const :tag "Check month and day" t)
3010 (const :tag "Check month, day, and time" time)))
3012 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3013 "Should the agenda jump command prefer the future for incomplete dates?
3014 The default is to do the same as configured in `org-read-date-prefer-future'.
3015 But you can also set a deviating value here.
3016 This may t or nil, or the symbol `org-read-date-prefer-future'."
3017 :group 'org-agenda
3018 :group 'org-time
3019 :version "24.1"
3020 :type '(choice
3021 (const :tag "Use org-read-date-prefer-future"
3022 org-read-date-prefer-future)
3023 (const :tag "Never" nil)
3024 (const :tag "Always" t)))
3026 (defcustom org-read-date-force-compatible-dates t
3027 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3029 Depending on the system Emacs is running on, certain dates cannot
3030 be represented with the type used internally to represent time.
3031 Dates between 1970-1-1 and 2038-1-1 can always be represented
3032 correctly. Some systems allow for earlier dates, some for later,
3033 some for both. One way to find out it to insert any date into an
3034 Org buffer, putting the cursor on the year and hitting S-up and
3035 S-down to test the range.
3037 When this variable is set to t, the date/time prompt will not let
3038 you specify dates outside the 1970-2037 range, so it is certain that
3039 these dates will work in whatever version of Emacs you are
3040 running, and also that you can move a file from one Emacs implementation
3041 to another. WHenever Org is forcing the year for you, it will display
3042 a message and beep.
3044 When this variable is nil, Org will check if the date is
3045 representable in the specific Emacs implementation you are using.
3046 If not, it will force a year, usually the current year, and beep
3047 to remind you. Currently this setting is not recommended because
3048 the likelihood that you will open your Org files in an Emacs that
3049 has limited date range is not negligible.
3051 A workaround for this problem is to use diary sexp dates for time
3052 stamps outside of this range."
3053 :group 'org-time
3054 :version "24.1"
3055 :type 'boolean)
3057 (defcustom org-read-date-display-live t
3058 "Non-nil means display current interpretation of date prompt live.
3059 This display will be in an overlay, in the minibuffer."
3060 :group 'org-time
3061 :type 'boolean)
3063 (defcustom org-read-date-popup-calendar t
3064 "Non-nil means pop up a calendar when prompting for a date.
3065 In the calendar, the date can be selected with mouse-1. However, the
3066 minibuffer will also be active, and you can simply enter the date as well.
3067 When nil, only the minibuffer will be available."
3068 :group 'org-time
3069 :type 'boolean)
3070 (if (fboundp 'defvaralias)
3071 (defvaralias 'org-popup-calendar-for-date-prompt
3072 'org-read-date-popup-calendar))
3074 (make-obsolete-variable
3075 'org-read-date-minibuffer-setup-hook
3076 "Set `org-read-date-minibuffer-local-map' instead." "24.3")
3077 (defcustom org-read-date-minibuffer-setup-hook nil
3078 "Hook to be used to set up keys for the date/time interface.
3079 Add key definitions to `minibuffer-local-map', which will be a
3080 temporary copy.
3082 WARNING: This option is obsolete, you should use
3083 `org-read-date-minibuffer-local-map' to set up keys."
3084 :group 'org-time
3085 :type 'hook)
3087 (defcustom org-extend-today-until 0
3088 "The hour when your day really ends. Must be an integer.
3089 This has influence for the following applications:
3090 - When switching the agenda to \"today\". It it is still earlier than
3091 the time given here, the day recognized as TODAY is actually yesterday.
3092 - When a date is read from the user and it is still before the time given
3093 here, the current date and time will be assumed to be yesterday, 23:59.
3094 Also, timestamps inserted in capture templates follow this rule.
3096 IMPORTANT: This is a feature whose implementation is and likely will
3097 remain incomplete. Really, it is only here because past midnight seems to
3098 be the favorite working time of John Wiegley :-)"
3099 :group 'org-time
3100 :type 'integer)
3102 (defcustom org-use-effective-time nil
3103 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3104 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3105 \"effective time\" of any timestamps between midnight and 8am will be
3106 23:59 of the previous day."
3107 :group 'org-time
3108 :version "24.1"
3109 :type 'boolean)
3111 (defcustom org-use-last-clock-out-time-as-effective-time nil
3112 "When non-nil, use the last clock out time for `org-todo'.
3113 Note that this option has precedence over the combined use of
3114 `org-use-effective-time' and `org-extend-today-until'."
3115 :group 'org-time
3116 ;; :version "24.3"
3117 :type 'boolean)
3119 (defcustom org-edit-timestamp-down-means-later nil
3120 "Non-nil means S-down will increase the time in a time stamp.
3121 When nil, S-up will increase."
3122 :group 'org-time
3123 :type 'boolean)
3125 (defcustom org-calendar-follow-timestamp-change t
3126 "Non-nil means make the calendar window follow timestamp changes.
3127 When a timestamp is modified and the calendar window is visible, it will be
3128 moved to the new date."
3129 :group 'org-time
3130 :type 'boolean)
3132 (defgroup org-tags nil
3133 "Options concerning tags in Org-mode."
3134 :tag "Org Tags"
3135 :group 'org)
3137 (defcustom org-tag-alist nil
3138 "List of tags allowed in Org-mode files.
3139 When this list is nil, Org-mode will base TAG input on what is already in the
3140 buffer.
3141 The value of this variable is an alist, the car of each entry must be a
3142 keyword as a string, the cdr may be a character that is used to select
3143 that tag through the fast-tag-selection interface.
3144 See the manual for details."
3145 :group 'org-tags
3146 :type '(repeat
3147 (choice
3148 (cons (string :tag "Tag name")
3149 (character :tag "Access char"))
3150 (list :tag "Start radio group"
3151 (const :startgroup)
3152 (option (string :tag "Group description")))
3153 (list :tag "End radio group"
3154 (const :endgroup)
3155 (option (string :tag "Group description")))
3156 (const :tag "New line" (:newline)))))
3158 (defcustom org-tag-persistent-alist nil
3159 "List of tags that will always appear in all Org-mode files.
3160 This is in addition to any in buffer settings or customizations
3161 of `org-tag-alist'.
3162 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3163 The value of this variable is an alist, the car of each entry must be a
3164 keyword as a string, the cdr may be a character that is used to select
3165 that tag through the fast-tag-selection interface.
3166 See the manual for details.
3167 To disable these tags on a per-file basis, insert anywhere in the file:
3168 #+STARTUP: noptag"
3169 :group 'org-tags
3170 :type '(repeat
3171 (choice
3172 (cons (string :tag "Tag name")
3173 (character :tag "Access char"))
3174 (const :tag "Start radio group" (:startgroup))
3175 (const :tag "End radio group" (:endgroup))
3176 (const :tag "New line" (:newline)))))
3178 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3179 "If non-nil, always offer completion for all tags of all agenda files.
3180 Instead of customizing this variable directly, you might want to
3181 set it locally for capture buffers, because there no list of
3182 tags in that file can be created dynamically (there are none).
3184 (add-hook 'org-capture-mode-hook
3185 (lambda ()
3186 (set (make-local-variable
3187 'org-complete-tags-always-offer-all-agenda-tags)
3188 t)))"
3189 :group 'org-tags
3190 :version "24.1"
3191 :type 'boolean)
3193 (defvar org-file-tags nil
3194 "List of tags that can be inherited by all entries in the file.
3195 The tags will be inherited if the variable `org-use-tag-inheritance'
3196 says they should be.
3197 This variable is populated from #+FILETAGS lines.")
3199 (defcustom org-use-fast-tag-selection 'auto
3200 "Non-nil means use fast tag selection scheme.
3201 This is a special interface to select and deselect tags with single keys.
3202 When nil, fast selection is never used.
3203 When the symbol `auto', fast selection is used if and only if selection
3204 characters for tags have been configured, either through the variable
3205 `org-tag-alist' or through a #+TAGS line in the buffer.
3206 When t, fast selection is always used and selection keys are assigned
3207 automatically if necessary."
3208 :group 'org-tags
3209 :type '(choice
3210 (const :tag "Always" t)
3211 (const :tag "Never" nil)
3212 (const :tag "When selection characters are configured" 'auto)))
3214 (defcustom org-fast-tag-selection-single-key nil
3215 "Non-nil means fast tag selection exits after first change.
3216 When nil, you have to press RET to exit it.
3217 During fast tag selection, you can toggle this flag with `C-c'.
3218 This variable can also have the value `expert'. In this case, the window
3219 displaying the tags menu is not even shown, until you press C-c again."
3220 :group 'org-tags
3221 :type '(choice
3222 (const :tag "No" nil)
3223 (const :tag "Yes" t)
3224 (const :tag "Expert" expert)))
3226 (defvar org-fast-tag-selection-include-todo nil
3227 "Non-nil means fast tags selection interface will also offer TODO states.
3228 This is an undocumented feature, you should not rely on it.")
3230 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3231 "The column to which tags should be indented in a headline.
3232 If this number is positive, it specifies the column. If it is negative,
3233 it means that the tags should be flushright to that column. For example,
3234 -80 works well for a normal 80 character screen.
3235 When 0, place tags directly after headline text, with only one space in
3236 between."
3237 :group 'org-tags
3238 :type 'integer)
3240 (defcustom org-auto-align-tags t
3241 "Non-nil keeps tags aligned when modifying headlines.
3242 Some operations (i.e. demoting) change the length of a headline and
3243 therefore shift the tags around. With this option turned on, after
3244 each such operation the tags are again aligned to `org-tags-column'."
3245 :group 'org-tags
3246 :type 'boolean)
3248 (defcustom org-use-tag-inheritance t
3249 "Non-nil means tags in levels apply also for sublevels.
3250 When nil, only the tags directly given in a specific line apply there.
3251 This may also be a list of tags that should be inherited, or a regexp that
3252 matches tags that should be inherited. Additional control is possible
3253 with the variable `org-tags-exclude-from-inheritance' which gives an
3254 explicit list of tags to be excluded from inheritance, even if the value of
3255 `org-use-tag-inheritance' would select it for inheritance.
3257 If this option is t, a match early-on in a tree can lead to a large
3258 number of matches in the subtree when constructing the agenda or creating
3259 a sparse tree. If you only want to see the first match in a tree during
3260 a search, check out the variable `org-tags-match-list-sublevels'."
3261 :group 'org-tags
3262 :type '(choice
3263 (const :tag "Not" nil)
3264 (const :tag "Always" t)
3265 (repeat :tag "Specific tags" (string :tag "Tag"))
3266 (regexp :tag "Tags matched by regexp")))
3268 (defcustom org-tags-exclude-from-inheritance nil
3269 "List of tags that should never be inherited.
3270 This is a way to exclude a few tags from inheritance. For way to do
3271 the opposite, to actively allow inheritance for selected tags,
3272 see the variable `org-use-tag-inheritance'."
3273 :group 'org-tags
3274 :type '(repeat (string :tag "Tag")))
3276 (defun org-tag-inherit-p (tag)
3277 "Check if TAG is one that should be inherited."
3278 (cond
3279 ((member tag org-tags-exclude-from-inheritance) nil)
3280 ((eq org-use-tag-inheritance t) t)
3281 ((not org-use-tag-inheritance) nil)
3282 ((stringp org-use-tag-inheritance)
3283 (string-match org-use-tag-inheritance tag))
3284 ((listp org-use-tag-inheritance)
3285 (member tag org-use-tag-inheritance))
3286 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3288 (defcustom org-tags-match-list-sublevels t
3289 "Non-nil means list also sublevels of headlines matching a search.
3290 This variable applies to tags/property searches, and also to stuck
3291 projects because this search is based on a tags match as well.
3293 When set to the symbol `indented', sublevels are indented with
3294 leading dots.
3296 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3297 the sublevels of a headline matching a tag search often also match
3298 the same search. Listing all of them can create very long lists.
3299 Setting this variable to nil causes subtrees of a match to be skipped.
3301 This variable is semi-obsolete and probably should always be true. It
3302 is better to limit inheritance to certain tags using the variables
3303 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3304 :group 'org-tags
3305 :type '(choice
3306 (const :tag "No, don't list them" nil)
3307 (const :tag "Yes, do list them" t)
3308 (const :tag "List them, indented with leading dots" indented)))
3310 (defcustom org-tags-sort-function nil
3311 "When set, tags are sorted using this function as a comparator."
3312 :group 'org-tags
3313 :type '(choice
3314 (const :tag "No sorting" nil)
3315 (const :tag "Alphabetical" string<)
3316 (const :tag "Reverse alphabetical" string>)
3317 (function :tag "Custom function" nil)))
3319 (defvar org-tags-history nil
3320 "History of minibuffer reads for tags.")
3321 (defvar org-last-tags-completion-table nil
3322 "The last used completion table for tags.")
3323 (defvar org-after-tags-change-hook nil
3324 "Hook that is run after the tags in a line have changed.")
3326 (defgroup org-properties nil
3327 "Options concerning properties in Org-mode."
3328 :tag "Org Properties"
3329 :group 'org)
3331 (defcustom org-property-format "%-10s %s"
3332 "How property key/value pairs should be formatted by `indent-line'.
3333 When `indent-line' hits a property definition, it will format the line
3334 according to this format, mainly to make sure that the values are
3335 lined-up with respect to each other."
3336 :group 'org-properties
3337 :type 'string)
3339 (defcustom org-properties-postprocess-alist nil
3340 "Alist of properties and functions to adjust inserted values.
3341 Elements of this alist must be of the form
3343 ([string] [function])
3345 where [string] must be a property name and [function] must be a
3346 lambda expression: this lambda expression must take one argument,
3347 the value to adjust, and return the new value as a string.
3349 For example, this element will allow the property \"Remaining\"
3350 to be updated wrt the relation between the \"Effort\" property
3351 and the clock summary:
3353 ((\"Remaining\" (lambda(value)
3354 (let ((clocksum (org-clock-sum-current-item))
3355 (effort (org-duration-string-to-minutes
3356 (org-entry-get (point) \"Effort\"))))
3357 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3358 :group 'org-properties
3359 :version "24.1"
3360 :type '(alist :key-type (string :tag "Property")
3361 :value-type (function :tag "Function")))
3363 (defcustom org-use-property-inheritance nil
3364 "Non-nil means properties apply also for sublevels.
3366 This setting is chiefly used during property searches. Turning it on can
3367 cause significant overhead when doing a search, which is why it is not
3368 on by default.
3370 When nil, only the properties directly given in the current entry count.
3371 When t, every property is inherited. The value may also be a list of
3372 properties that should have inheritance, or a regular expression matching
3373 properties that should be inherited.
3375 However, note that some special properties use inheritance under special
3376 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3377 and the properties ending in \"_ALL\" when they are used as descriptor
3378 for valid values of a property.
3380 Note for programmers:
3381 When querying an entry with `org-entry-get', you can control if inheritance
3382 should be used. By default, `org-entry-get' looks only at the local
3383 properties. You can request inheritance by setting the inherit argument
3384 to t (to force inheritance) or to `selective' (to respect the setting
3385 in this variable)."
3386 :group 'org-properties
3387 :type '(choice
3388 (const :tag "Not" nil)
3389 (const :tag "Always" t)
3390 (repeat :tag "Specific properties" (string :tag "Property"))
3391 (regexp :tag "Properties matched by regexp")))
3393 (defun org-property-inherit-p (property)
3394 "Check if PROPERTY is one that should be inherited."
3395 (cond
3396 ((eq org-use-property-inheritance t) t)
3397 ((not org-use-property-inheritance) nil)
3398 ((stringp org-use-property-inheritance)
3399 (string-match org-use-property-inheritance property))
3400 ((listp org-use-property-inheritance)
3401 (member property org-use-property-inheritance))
3402 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3404 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3405 "The default column format, if no other format has been defined.
3406 This variable can be set on the per-file basis by inserting a line
3408 #+COLUMNS: %25ITEM ....."
3409 :group 'org-properties
3410 :type 'string)
3412 (defcustom org-columns-ellipses ".."
3413 "The ellipses to be used when a field in column view is truncated.
3414 When this is the empty string, as many characters as possible are shown,
3415 but then there will be no visual indication that the field has been truncated.
3416 When this is a string of length N, the last N characters of a truncated
3417 field are replaced by this string. If the column is narrower than the
3418 ellipses string, only part of the ellipses string will be shown."
3419 :group 'org-properties
3420 :type 'string)
3422 (defcustom org-columns-modify-value-for-display-function nil
3423 "Function that modifies values for display in column view.
3424 For example, it can be used to cut out a certain part from a time stamp.
3425 The function must take 2 arguments:
3427 column-title The title of the column (*not* the property name)
3428 value The value that should be modified.
3430 The function should return the value that should be displayed,
3431 or nil if the normal value should be used."
3432 :group 'org-properties
3433 :type 'function)
3435 (defcustom org-effort-property "Effort"
3436 "The property that is being used to keep track of effort estimates.
3437 Effort estimates given in this property need to have the format H:MM."
3438 :group 'org-properties
3439 :group 'org-progress
3440 :type '(string :tag "Property"))
3442 (defconst org-global-properties-fixed
3443 '(("VISIBILITY_ALL" . "folded children content all")
3444 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3445 "List of property/value pairs that can be inherited by any entry.
3447 These are fixed values, for the preset properties. The user variable
3448 that can be used to add to this list is `org-global-properties'.
3450 The entries in this list are cons cells where the car is a property
3451 name and cdr is a string with the value. If the value represents
3452 multiple items like an \"_ALL\" property, separate the items by
3453 spaces.")
3455 (defcustom org-global-properties nil
3456 "List of property/value pairs that can be inherited by any entry.
3458 This list will be combined with the constant `org-global-properties-fixed'.
3460 The entries in this list are cons cells where the car is a property
3461 name and cdr is a string with the value.
3463 You can set buffer-local values for the same purpose in the variable
3464 `org-file-properties' this by adding lines like
3466 #+PROPERTY: NAME VALUE"
3467 :group 'org-properties
3468 :type '(repeat
3469 (cons (string :tag "Property")
3470 (string :tag "Value"))))
3472 (defvar org-file-properties nil
3473 "List of property/value pairs that can be inherited by any entry.
3474 Valid for the current buffer.
3475 This variable is populated from #+PROPERTY lines.")
3476 (make-variable-buffer-local 'org-file-properties)
3478 (defgroup org-agenda nil
3479 "Options concerning agenda views in Org-mode."
3480 :tag "Org Agenda"
3481 :group 'org)
3483 (defvar org-category nil
3484 "Variable used by org files to set a category for agenda display.
3485 Such files should use a file variable to set it, for example
3487 # -*- mode: org; org-category: \"ELisp\"
3489 or contain a special line
3491 #+CATEGORY: ELisp
3493 If the file does not specify a category, then file's base name
3494 is used instead.")
3495 (make-variable-buffer-local 'org-category)
3496 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3498 (defcustom org-agenda-files nil
3499 "The files to be used for agenda display.
3500 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3501 \\[org-remove-file]. You can also use customize to edit the list.
3503 If an entry is a directory, all files in that directory that are matched by
3504 `org-agenda-file-regexp' will be part of the file list.
3506 If the value of the variable is not a list but a single file name, then
3507 the list of agenda files is actually stored and maintained in that file, one
3508 agenda file per line. In this file paths can be given relative to
3509 `org-directory'. Tilde expansion and environment variable substitution
3510 are also made."
3511 :group 'org-agenda
3512 :type '(choice
3513 (repeat :tag "List of files and directories" file)
3514 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3516 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3517 "Regular expression to match files for `org-agenda-files'.
3518 If any element in the list in that variable contains a directory instead
3519 of a normal file, all files in that directory that are matched by this
3520 regular expression will be included."
3521 :group 'org-agenda
3522 :type 'regexp)
3524 (defcustom org-agenda-text-search-extra-files nil
3525 "List of extra files to be searched by text search commands.
3526 These files will be search in addition to the agenda files by the
3527 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3528 Note that these files will only be searched for text search commands,
3529 not for the other agenda views like todo lists, tag searches or the weekly
3530 agenda. This variable is intended to list notes and possibly archive files
3531 that should also be searched by these two commands.
3532 In fact, if the first element in the list is the symbol `agenda-archives',
3533 than all archive files of all agenda files will be added to the search
3534 scope."
3535 :group 'org-agenda
3536 :type '(set :greedy t
3537 (const :tag "Agenda Archives" agenda-archives)
3538 (repeat :inline t (file))))
3540 (if (fboundp 'defvaralias)
3541 (defvaralias 'org-agenda-multi-occur-extra-files
3542 'org-agenda-text-search-extra-files))
3544 (defcustom org-agenda-skip-unavailable-files nil
3545 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3546 A nil value means to remove them, after a query, from the list."
3547 :group 'org-agenda
3548 :type 'boolean)
3550 (defcustom org-calendar-to-agenda-key [?c]
3551 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3552 The command `org-calendar-goto-agenda' will be bound to this key. The
3553 default is the character `c' because then `c' can be used to switch back and
3554 forth between agenda and calendar."
3555 :group 'org-agenda
3556 :type 'sexp)
3558 (defcustom org-calendar-insert-diary-entry-key [?i]
3559 "The key to be installed in `calendar-mode-map' for adding diary entries.
3560 This option is irrelevant until `org-agenda-diary-file' has been configured
3561 to point to an Org-mode file. When that is the case, the command
3562 `org-agenda-diary-entry' will be bound to the key given here, by default
3563 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3564 if you want to continue doing this, you need to change this to a different
3565 key."
3566 :group 'org-agenda
3567 :type 'sexp)
3569 (defcustom org-agenda-diary-file 'diary-file
3570 "File to which to add new entries with the `i' key in agenda and calendar.
3571 When this is the symbol `diary-file', the functionality in the Emacs
3572 calendar will be used to add entries to the `diary-file'. But when this
3573 points to a file, `org-agenda-diary-entry' will be used instead."
3574 :group 'org-agenda
3575 :type '(choice
3576 (const :tag "The standard Emacs diary file" diary-file)
3577 (file :tag "Special Org file diary entries")))
3579 (eval-after-load "calendar"
3580 '(progn
3581 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3582 'org-calendar-goto-agenda)
3583 (add-hook 'calendar-mode-hook
3584 (lambda ()
3585 (unless (eq org-agenda-diary-file 'diary-file)
3586 (define-key calendar-mode-map
3587 org-calendar-insert-diary-entry-key
3588 'org-agenda-diary-entry))))))
3590 (defgroup org-latex nil
3591 "Options for embedding LaTeX code into Org-mode."
3592 :tag "Org LaTeX"
3593 :group 'org)
3595 (defcustom org-format-latex-options
3596 '(:foreground default :background default :scale 1.0
3597 :html-foreground "Black" :html-background "Transparent"
3598 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3599 "Options for creating images from LaTeX fragments.
3600 This is a property list with the following properties:
3601 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3602 `default' means use the foreground of the default face.
3603 `auto' means use the foreground from the text face.
3604 :background the background color, or \"Transparent\".
3605 `default' means use the background of the default face.
3606 `auto' means use the background from the text face.
3607 :scale a scaling factor for the size of the images, to get more pixels
3608 :html-foreground, :html-background, :html-scale
3609 the same numbers for HTML export.
3610 :matchers a list indicating which matchers should be used to
3611 find LaTeX fragments. Valid members of this list are:
3612 \"begin\" find environments
3613 \"$1\" find single characters surrounded by $.$
3614 \"$\" find math expressions surrounded by $...$
3615 \"$$\" find math expressions surrounded by $$....$$
3616 \"\\(\" find math expressions surrounded by \\(...\\)
3617 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3618 :group 'org-latex
3619 :type 'plist)
3621 (defcustom org-format-latex-signal-error t
3622 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3623 When nil, just push out a message."
3624 :group 'org-latex
3625 :version "24.1"
3626 :type 'boolean)
3628 (defcustom org-latex-to-mathml-jar-file nil
3629 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3630 Use this to specify additional executable file say a jar file.
3632 When using MathToWeb as the converter, specify the full-path to
3633 your mathtoweb.jar file."
3634 :group 'org-latex
3635 :version "24.1"
3636 :type '(choice
3637 (const :tag "None" nil)
3638 (file :tag "JAR file" :must-match t)))
3640 (defcustom org-latex-to-mathml-convert-command nil
3641 "Command to convert LaTeX fragments to MathML.
3642 Replace format-specifiers in the command as noted below and use
3643 `shell-command' to convert LaTeX to MathML.
3644 %j: Executable file in fully expanded form as specified by
3645 `org-latex-to-mathml-jar-file'.
3646 %I: Input LaTeX file in fully expanded form
3647 %o: Output MathML file
3648 This command is used by `org-create-math-formula'.
3650 When using MathToWeb as the converter, set this to
3651 \"java -jar %j -unicode -force -df %o %I\"."
3652 :group 'org-latex
3653 :version "24.1"
3654 :type '(choice
3655 (const :tag "None" nil)
3656 (string :tag "\nShell command")))
3658 (defcustom org-latex-create-formula-image-program 'dvipng
3659 "Program to convert LaTeX fragments with.
3661 dvipng Process the LaTeX fragments to dvi file, then convert
3662 dvi files to png files using dvipng.
3663 This will also include processing of non-math environments.
3664 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3665 to convert pdf files to png files"
3666 :group 'org-latex
3667 :version "24.1"
3668 :type '(choice
3669 (const :tag "dvipng" dvipng)
3670 (const :tag "imagemagick" imagemagick)))
3672 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3673 "Path to store latex preview images.
3674 A relative path here creates many directories relative to the
3675 processed org files paths. An absolute path puts all preview
3676 images at the same place."
3677 :group 'org-latex
3678 :version "24.3"
3679 :type 'string)
3681 (defun org-format-latex-mathml-available-p ()
3682 "Return t if `org-latex-to-mathml-convert-command' is usable."
3683 (save-match-data
3684 (when (and (boundp 'org-latex-to-mathml-convert-command)
3685 org-latex-to-mathml-convert-command)
3686 (let ((executable (car (split-string
3687 org-latex-to-mathml-convert-command))))
3688 (when (executable-find executable)
3689 (if (string-match
3690 "%j" org-latex-to-mathml-convert-command)
3691 (file-readable-p org-latex-to-mathml-jar-file)
3692 t))))))
3694 (defcustom org-format-latex-header "\\documentclass{article}
3695 \\usepackage[usenames]{color}
3696 \\usepackage{amsmath}
3697 \\usepackage[mathscr]{eucal}
3698 \\pagestyle{empty} % do not remove
3699 \[PACKAGES]
3700 \[DEFAULT-PACKAGES]
3701 % The settings below are copied from fullpage.sty
3702 \\setlength{\\textwidth}{\\paperwidth}
3703 \\addtolength{\\textwidth}{-3cm}
3704 \\setlength{\\oddsidemargin}{1.5cm}
3705 \\addtolength{\\oddsidemargin}{-2.54cm}
3706 \\setlength{\\evensidemargin}{\\oddsidemargin}
3707 \\setlength{\\textheight}{\\paperheight}
3708 \\addtolength{\\textheight}{-\\headheight}
3709 \\addtolength{\\textheight}{-\\headsep}
3710 \\addtolength{\\textheight}{-\\footskip}
3711 \\addtolength{\\textheight}{-3cm}
3712 \\setlength{\\topmargin}{1.5cm}
3713 \\addtolength{\\topmargin}{-2.54cm}"
3714 "The document header used for processing LaTeX fragments.
3715 It is imperative that this header make sure that no page number
3716 appears on the page. The package defined in the variables
3717 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3718 will either replace the placeholder \"[PACKAGES]\" in this
3719 header, or they will be appended."
3720 :group 'org-latex
3721 :type 'string)
3723 (defun org-set-packages-alist (var val)
3724 "Set the packages alist and make sure it has 3 elements per entry."
3725 (set var (mapcar (lambda (x)
3726 (if (and (consp x) (= (length x) 2))
3727 (list (car x) (nth 1 x) t)
3729 val)))
3731 (defun org-get-packages-alist (var)
3732 "Get the packages alist and make sure it has 3 elements per entry."
3733 (mapcar (lambda (x)
3734 (if (and (consp x) (= (length x) 2))
3735 (list (car x) (nth 1 x) t)
3737 (default-value var)))
3739 (defcustom org-latex-default-packages-alist
3740 '(("AUTO" "inputenc" t)
3741 ("T1" "fontenc" t)
3742 ("" "fixltx2e" nil)
3743 ("" "graphicx" t)
3744 ("" "longtable" nil)
3745 ("" "float" nil)
3746 ("" "wrapfig" nil)
3747 ("" "soul" t)
3748 ("" "textcomp" t)
3749 ("" "marvosym" t)
3750 ("" "wasysym" t)
3751 ("" "latexsym" t)
3752 ("" "amssymb" t)
3753 ("" "hyperref" nil)
3754 "\\tolerance=1000")
3755 "Alist of default packages to be inserted in the header.
3757 Change this only if one of the packages here causes an
3758 incompatibility with another package you are using.
3760 The packages in this list are needed by one part or another of
3761 Org mode to function properly:
3763 - inputenc, fontenc: for basic font and character selection
3764 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3765 symbols used for interpreting the entities in `org-entities'.
3766 You can skip some of these packages if you don't use any of the
3767 symbols in it.
3768 - graphicx: for including images
3769 - float, wrapfig: for figure placement
3770 - longtable: for long tables
3771 - hyperref: for cross references
3773 Therefore you should not modify this variable unless you know
3774 what you are doing. The one reason to change it anyway is that
3775 you might be loading some other package that conflicts with one
3776 of the default packages. Each cell is of the format
3777 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3778 the package also needs to be included when compiling LaTeX
3779 snippets into images for inclusion into non-LaTeX output."
3780 :group 'org-latex
3781 :group 'org-export-latex
3782 :set 'org-set-packages-alist
3783 :get 'org-get-packages-alist
3784 :version "24.1"
3785 :type '(repeat
3786 (choice
3787 (list :tag "options/package pair"
3788 (string :tag "options")
3789 (string :tag "package")
3790 (boolean :tag "Snippet"))
3791 (string :tag "A line of LaTeX"))))
3793 (defcustom org-latex-packages-alist nil
3794 "Alist of packages to be inserted in every LaTeX header.
3796 These will be inserted after `org-latex-default-packages-alist'.
3797 Each cell is of the format:
3799 \(\"options\" \"package\" snippet-flag)
3801 SNIPPET-FLAG, when t, indicates that this package is also needed
3802 when turning LaTeX snippets into images for inclusion into
3803 non-LaTeX output.
3805 Make sure that you only list packages here which:
3807 - you want in every file
3808 - do not conflict with the setup in `org-format-latex-header'.
3809 - do not conflict with the default packages in
3810 `org-latex-default-packages-alist'."
3811 :group 'org-latex
3812 :group 'org-export-latex
3813 :set 'org-set-packages-alist
3814 :get 'org-get-packages-alist
3815 :type '(repeat
3816 (choice
3817 (list :tag "options/package pair"
3818 (string :tag "options")
3819 (string :tag "package")
3820 (boolean :tag "Snippet"))
3821 (string :tag "A line of LaTeX"))))
3823 (defgroup org-appearance nil
3824 "Settings for Org-mode appearance."
3825 :tag "Org Appearance"
3826 :group 'org)
3828 (defcustom org-level-color-stars-only nil
3829 "Non-nil means fontify only the stars in each headline.
3830 When nil, the entire headline is fontified.
3831 Changing it requires restart of `font-lock-mode' to become effective
3832 also in regions already fontified."
3833 :group 'org-appearance
3834 :type 'boolean)
3836 (defcustom org-hide-leading-stars nil
3837 "Non-nil means hide the first N-1 stars in a headline.
3838 This works by using the face `org-hide' for these stars. This
3839 face is white for a light background, and black for a dark
3840 background. You may have to customize the face `org-hide' to
3841 make this work.
3842 Changing it requires restart of `font-lock-mode' to become effective
3843 also in regions already fontified.
3844 You may also set this on a per-file basis by adding one of the following
3845 lines to the buffer:
3847 #+STARTUP: hidestars
3848 #+STARTUP: showstars"
3849 :group 'org-appearance
3850 :type 'boolean)
3852 (defcustom org-hidden-keywords nil
3853 "List of symbols corresponding to keywords to be hidden the org buffer.
3854 For example, a value '(title) for this list will make the document's title
3855 appear in the buffer without the initial #+TITLE: keyword."
3856 :group 'org-appearance
3857 :version "24.1"
3858 :type '(set (const :tag "#+AUTHOR" author)
3859 (const :tag "#+DATE" date)
3860 (const :tag "#+EMAIL" email)
3861 (const :tag "#+TITLE" title)))
3863 (defcustom org-custom-properties nil
3864 "List of properties (as strings) with a special meaning.
3865 The default use of these custom properties is to let the user
3866 hide them with `org-toggle-custom-properties-visibility'."
3867 :group 'org-properties
3868 :group 'org-appearance
3869 :version "24.3"
3870 :type '(repeat (string :tag "Property Name")))
3872 (defcustom org-fontify-done-headline nil
3873 "Non-nil means change the face of a headline if it is marked DONE.
3874 Normally, only the TODO/DONE keyword indicates the state of a headline.
3875 When this is non-nil, the headline after the keyword is set to the
3876 `org-headline-done' as an additional indication."
3877 :group 'org-appearance
3878 :type 'boolean)
3880 (defcustom org-fontify-emphasized-text t
3881 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3882 Changing this variable requires a restart of Emacs to take effect."
3883 :group 'org-appearance
3884 :type 'boolean)
3886 (defcustom org-fontify-whole-heading-line nil
3887 "Non-nil means fontify the whole line for headings.
3888 This is useful when setting a background color for the
3889 org-level-* faces."
3890 :group 'org-appearance
3891 :type 'boolean)
3893 (defcustom org-hide-emphasis-markers nil
3894 "Non-nil mean font-lock should hide the emphasis marker characters."
3895 :group 'org-appearance
3896 :type 'boolean)
3898 (defcustom org-pretty-entities nil
3899 "Non-nil means show entities as UTF8 characters.
3900 When nil, the \\name form remains in the buffer."
3901 :group 'org-appearance
3902 :version "24.1"
3903 :type 'boolean)
3905 (defcustom org-pretty-entities-include-sub-superscripts t
3906 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3907 :group 'org-appearance
3908 :version "24.1"
3909 :type 'boolean)
3911 (defvar org-emph-re nil
3912 "Regular expression for matching emphasis.
3913 After a match, the match groups contain these elements:
3914 0 The match of the full regular expression, including the characters
3915 before and after the proper match
3916 1 The character before the proper match, or empty at beginning of line
3917 2 The proper match, including the leading and trailing markers
3918 3 The leading marker like * or /, indicating the type of highlighting
3919 4 The text between the emphasis markers, not including the markers
3920 5 The character after the match, empty at the end of a line")
3921 (defvar org-verbatim-re nil
3922 "Regular expression for matching verbatim text.")
3923 (defvar org-emphasis-regexp-components) ; defined just below
3924 (defvar org-emphasis-alist) ; defined just below
3925 (defun org-set-emph-re (var val)
3926 "Set variable and compute the emphasis regular expression."
3927 (set var val)
3928 (when (and (boundp 'org-emphasis-alist)
3929 (boundp 'org-emphasis-regexp-components)
3930 org-emphasis-alist org-emphasis-regexp-components)
3931 (let* ((e org-emphasis-regexp-components)
3932 (pre (car e))
3933 (post (nth 1 e))
3934 (border (nth 2 e))
3935 (body (nth 3 e))
3936 (nl (nth 4 e))
3937 (body1 (concat body "*?"))
3938 (markers (mapconcat 'car org-emphasis-alist ""))
3939 (vmarkers (mapconcat
3940 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3941 org-emphasis-alist "")))
3942 ;; make sure special characters appear at the right position in the class
3943 (if (string-match "\\^" markers)
3944 (setq markers (concat (replace-match "" t t markers) "^")))
3945 (if (string-match "-" markers)
3946 (setq markers (concat (replace-match "" t t markers) "-")))
3947 (if (string-match "\\^" vmarkers)
3948 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3949 (if (string-match "-" vmarkers)
3950 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3951 (if (> nl 0)
3952 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3953 (int-to-string nl) "\\}")))
3954 ;; Make the regexp
3955 (setq org-emph-re
3956 (concat "\\([" pre "]\\|^\\)"
3957 "\\("
3958 "\\([" markers "]\\)"
3959 "\\("
3960 "[^" border "]\\|"
3961 "[^" border "]"
3962 body1
3963 "[^" border "]"
3964 "\\)"
3965 "\\3\\)"
3966 "\\([" post "]\\|$\\)"))
3967 (setq org-verbatim-re
3968 (concat "\\([" pre "]\\|^\\)"
3969 "\\("
3970 "\\([" vmarkers "]\\)"
3971 "\\("
3972 "[^" border "]\\|"
3973 "[^" border "]"
3974 body1
3975 "[^" border "]"
3976 "\\)"
3977 "\\3\\)"
3978 "\\([" post "]\\|$\\)")))))
3980 (defcustom org-emphasis-regexp-components
3981 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3982 "Components used to build the regular expression for emphasis.
3983 This is a list with five entries. Terminology: In an emphasis string
3984 like \" *strong word* \", we call the initial space PREMATCH, the final
3985 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3986 and \"trong wor\" is the body. The different components in this variable
3987 specify what is allowed/forbidden in each part:
3989 pre Chars allowed as prematch. Beginning of line will be allowed too.
3990 post Chars allowed as postmatch. End of line will be allowed too.
3991 border The chars *forbidden* as border characters.
3992 body-regexp A regexp like \".\" to match a body character. Don't use
3993 non-shy groups here, and don't allow newline here.
3994 newline The maximum number of newlines allowed in an emphasis exp.
3996 Use customize to modify this, or restart Emacs after changing it."
3997 :group 'org-appearance
3998 :set 'org-set-emph-re
3999 :type '(list
4000 (sexp :tag "Allowed chars in pre ")
4001 (sexp :tag "Allowed chars in post ")
4002 (sexp :tag "Forbidden chars in border ")
4003 (sexp :tag "Regexp for body ")
4004 (integer :tag "number of newlines allowed")
4005 (option (boolean :tag "Please ignore this button"))))
4007 (defcustom org-emphasis-alist
4008 `(("*" bold "<b>" "</b>")
4009 ("/" italic "<i>" "</i>")
4010 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4011 ("=" org-code "<code>" "</code>" verbatim)
4012 ("~" org-verbatim "<code>" "</code>" verbatim)
4013 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4014 "<del>" "</del>")
4016 "Special syntax for emphasized text.
4017 Text starting and ending with a special character will be emphasized, for
4018 example *bold*, _underlined_ and /italic/. This variable sets the marker
4019 characters, the face to be used by font-lock for highlighting in Org-mode
4020 Emacs buffers, and the HTML tags to be used for this.
4021 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4022 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
4023 Use customize to modify this, or restart Emacs after changing it."
4024 :group 'org-appearance
4025 :set 'org-set-emph-re
4026 :type '(repeat
4027 (list
4028 (string :tag "Marker character")
4029 (choice
4030 (face :tag "Font-lock-face")
4031 (plist :tag "Face property list"))
4032 (string :tag "HTML start tag")
4033 (string :tag "HTML end tag")
4034 (option (const verbatim)))))
4036 (defvar org-syntax-table
4037 (let ((st (make-syntax-table)))
4038 (mapc (lambda(c) (modify-syntax-entry
4039 (string-to-char (car c)) "w p" st))
4040 org-emphasis-alist)
4041 st))
4043 (defvar org-protecting-blocks
4044 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
4045 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4046 This is needed for font-lock setup.")
4048 ;;; Miscellaneous options
4050 (defgroup org-completion nil
4051 "Completion in Org-mode."
4052 :tag "Org Completion"
4053 :group 'org)
4055 (defcustom org-completion-use-ido nil
4056 "Non-nil means use ido completion wherever possible.
4057 Note that `ido-mode' must be active for this variable to be relevant.
4058 If you decide to turn this variable on, you might well want to turn off
4059 `org-outline-path-complete-in-steps'.
4060 See also `org-completion-use-iswitchb'."
4061 :group 'org-completion
4062 :type 'boolean)
4064 (defcustom org-completion-use-iswitchb nil
4065 "Non-nil means use iswitchb completion wherever possible.
4066 Note that `iswitchb-mode' must be active for this variable to be relevant.
4067 If you decide to turn this variable on, you might well want to turn off
4068 `org-outline-path-complete-in-steps'.
4069 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4070 :group 'org-completion
4071 :type 'boolean)
4073 (defcustom org-completion-fallback-command 'hippie-expand
4074 "The expansion command called by \\[pcomplete] in normal context.
4075 Normal means, no org-mode-specific context."
4076 :group 'org-completion
4077 :type 'function)
4079 ;;; Functions and variables from their packages
4080 ;; Declared here to avoid compiler warnings
4082 ;; XEmacs only
4083 (defvar outline-mode-menu-heading)
4084 (defvar outline-mode-menu-show)
4085 (defvar outline-mode-menu-hide)
4086 (defvar zmacs-regions) ; XEmacs regions
4088 ;; Emacs only
4089 (defvar mark-active)
4091 ;; Various packages
4092 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4093 (declare-function calendar-forward-day "cal-move" (arg))
4094 (declare-function calendar-goto-date "cal-move" (date))
4095 (declare-function calendar-goto-today "cal-move" ())
4096 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4097 (defvar calc-embedded-close-formula)
4098 (defvar calc-embedded-open-formula)
4099 (declare-function cdlatex-tab "ext:cdlatex" ())
4100 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4101 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4102 (defvar font-lock-unfontify-region-function)
4103 (declare-function iswitchb-read-buffer "iswitchb"
4104 (prompt &optional default require-match start matches-set))
4105 (defvar iswitchb-temp-buflist)
4106 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4107 (defvar org-agenda-tags-todo-honor-ignore-options)
4108 (declare-function org-agenda-skip "org-agenda" ())
4109 (declare-function
4110 org-agenda-format-item "org-agenda"
4111 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4112 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4113 (declare-function org-agenda-change-all-lines "org-agenda"
4114 (newhead hdmarker &optional fixface just-this))
4115 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4116 (declare-function org-agenda-maybe-redo "org-agenda" ())
4117 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4118 (beg end))
4119 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4120 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4121 "org-agenda" (&optional end))
4122 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4123 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4124 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4125 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4126 (declare-function org-indent-mode "org-indent" (&optional arg))
4127 (declare-function parse-time-string "parse-time" (string))
4128 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4129 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4130 (defvar remember-data-file)
4131 (defvar texmathp-why)
4132 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4133 (declare-function table--at-cell-p "table" (position &optional object at-column))
4135 (defvar org-latex-regexps)
4137 ;;; Autoload and prepare some org modules
4139 ;; Some table stuff that needs to be defined here, because it is used
4140 ;; by the functions setting up org-mode or checking for table context.
4142 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4143 "Detect an org-type or table-type table.")
4144 (defconst org-table-line-regexp "^[ \t]*|"
4145 "Detect an org-type table line.")
4146 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4147 "Detect an org-type table line.")
4148 (defconst org-table-hline-regexp "^[ \t]*|-"
4149 "Detect an org-type table hline.")
4150 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4151 "Detect a table-type table hline.")
4152 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4153 "Detect the first line outside a table when searching from within it.
4154 This works for both table types.")
4156 ;; Autoload the functions in org-table.el that are needed by functions here.
4158 (eval-and-compile
4159 (org-autoload "org-table"
4160 '(org-table-begin org-table-blank-field org-table-end)))
4162 ;;;###autoload
4163 (defun turn-on-orgtbl ()
4164 "Unconditionally turn on `orgtbl-mode'."
4165 (require 'org-table)
4166 (orgtbl-mode 1))
4168 (defun org-at-table-p (&optional table-type)
4169 "Return t if the cursor is inside an org-type table.
4170 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4171 (if org-enable-table-editor
4172 (save-excursion
4173 (beginning-of-line 1)
4174 (looking-at (if table-type org-table-any-line-regexp
4175 org-table-line-regexp)))
4176 nil))
4177 (defsubst org-table-p () (org-at-table-p))
4179 (defun org-at-table.el-p ()
4180 "Return t if and only if we are at a table.el table."
4181 (and (org-at-table-p 'any)
4182 (save-excursion
4183 (goto-char (org-table-begin 'any))
4184 (looking-at org-table1-hline-regexp))))
4185 (defun org-table-recognize-table.el ()
4186 "If there is a table.el table nearby, recognize it and move into it."
4187 (if org-table-tab-recognizes-table.el
4188 (if (org-at-table.el-p)
4189 (progn
4190 (beginning-of-line 1)
4191 (if (looking-at org-table-dataline-regexp)
4193 (if (looking-at org-table1-hline-regexp)
4194 (progn
4195 (beginning-of-line 2)
4196 (if (looking-at org-table-any-border-regexp)
4197 (beginning-of-line -1)))))
4198 (if (re-search-forward "|" (org-table-end t) t)
4199 (progn
4200 (require 'table)
4201 (if (table--at-cell-p (point))
4203 (message "recognizing table.el table...")
4204 (table-recognize-table)
4205 (message "recognizing table.el table...done")))
4206 (error "This should not happen"))
4208 nil)
4209 nil))
4211 (defun org-at-table-hline-p ()
4212 "Return t if the cursor is inside a hline in a table."
4213 (if org-enable-table-editor
4214 (save-excursion
4215 (beginning-of-line 1)
4216 (looking-at org-table-hline-regexp))
4217 nil))
4219 (defvar org-table-clean-did-remove-column nil)
4221 (defun org-table-map-tables (function &optional quietly)
4222 "Apply FUNCTION to the start of all tables in the buffer."
4223 (save-excursion
4224 (save-restriction
4225 (widen)
4226 (goto-char (point-min))
4227 (while (re-search-forward org-table-any-line-regexp nil t)
4228 (unless quietly
4229 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4230 (beginning-of-line 1)
4231 (when (and (looking-at org-table-line-regexp)
4232 ;; Exclude tables in src/example/verbatim/clocktable blocks
4233 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4234 (save-excursion (funcall function))
4235 (or (looking-at org-table-line-regexp)
4236 (forward-char 1)))
4237 (re-search-forward org-table-any-border-regexp nil 1))))
4238 (unless quietly (message "Mapping tables: done")))
4240 ;; Declare and autoload functions from ox.el and al.
4242 (declare-function org-export-get-environment "ox"
4243 (&optional backend subtreep ext-plist))
4244 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4246 ;; Declare and autoload functions from org-agenda.el
4248 (eval-and-compile
4249 (org-autoload "org-agenda"
4250 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4252 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4253 (declare-function org-clock-update-mode-line "org-clock" ())
4254 (declare-function org-resolve-clocks "org-clock"
4255 (&optional also-non-dangling-p prompt last-valid))
4256 (defvar org-clock-start-time)
4257 (defvar org-clock-marker (make-marker)
4258 "Marker recording the last clock-in.")
4259 (defvar org-clock-hd-marker (make-marker)
4260 "Marker recording the last clock-in, but the headline position.")
4261 (defvar org-clock-heading ""
4262 "The heading of the current clock entry.")
4263 (defun org-clock-is-active ()
4264 "Return non-nil if clock is currently running.
4265 The return value is actually the clock marker."
4266 (marker-buffer org-clock-marker))
4268 (eval-and-compile
4269 (org-autoload "org-clock" '(org-clock-remove-overlays
4270 org-clock-update-time-maybe
4271 org-clocktable-shift)))
4273 (defun org-check-running-clock ()
4274 "Check if the current buffer contains the running clock.
4275 If yes, offer to stop it and to save the buffer with the changes."
4276 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4277 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4278 (buffer-name))))
4279 (org-clock-out)
4280 (when (y-or-n-p "Save changed buffer?")
4281 (save-buffer))))
4283 (defun org-clocktable-try-shift (dir n)
4284 "Check if this line starts a clock table, if yes, shift the time block."
4285 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4286 (org-clocktable-shift dir n)))
4288 ;;;###autoload
4289 (defun org-clock-persistence-insinuate ()
4290 "Set up hooks for clock persistence."
4291 (require 'org-clock)
4292 (add-hook 'org-mode-hook 'org-clock-load)
4293 (add-hook 'kill-emacs-hook 'org-clock-save))
4295 ;; Define the variable already here, to make sure we have it.
4296 (defvar org-indent-mode nil
4297 "Non-nil if Org-Indent mode is enabled.
4298 Use the command `org-indent-mode' to change this variable.")
4300 ;; Autoload archiving code
4301 ;; The stuff that is needed for cycling and tags has to be defined here.
4303 (defgroup org-archive nil
4304 "Options concerning archiving in Org-mode."
4305 :tag "Org Archive"
4306 :group 'org-structure)
4308 (defcustom org-archive-location "%s_archive::"
4309 "The location where subtrees should be archived.
4311 The value of this variable is a string, consisting of two parts,
4312 separated by a double-colon. The first part is a filename and
4313 the second part is a headline.
4315 When the filename is omitted, archiving happens in the same file.
4316 %s in the filename will be replaced by the current file
4317 name (without the directory part). Archiving to a different file
4318 is useful to keep archived entries from contributing to the
4319 Org-mode Agenda.
4321 The archived entries will be filed as subtrees of the specified
4322 headline. When the headline is omitted, the subtrees are simply
4323 filed away at the end of the file, as top-level entries. Also in
4324 the heading you can use %s to represent the file name, this can be
4325 useful when using the same archive for a number of different files.
4327 Here are a few examples:
4328 \"%s_archive::\"
4329 If the current file is Projects.org, archive in file
4330 Projects.org_archive, as top-level trees. This is the default.
4332 \"::* Archived Tasks\"
4333 Archive in the current file, under the top-level headline
4334 \"* Archived Tasks\".
4336 \"~/org/archive.org::\"
4337 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4339 \"~/org/archive.org::* From %s\"
4340 Archive in file ~/org/archive.org (absolute path), under headlines
4341 \"From FILENAME\" where file name is the current file name.
4343 \"~/org/datetree.org::datetree/* Finished Tasks\"
4344 The \"datetree/\" string is special, signifying to archive
4345 items to the datetree. Items are placed in either the CLOSED
4346 date of the item, or the current date if there is no CLOSED date.
4347 The heading will be a subentry to the current date. There doesn't
4348 need to be a heading, but there always needs to be a slash after
4349 datetree. For example, to store archived items directly in the
4350 datetree, use \"~/org/datetree.org::datetree/\".
4352 \"basement::** Finished Tasks\"
4353 Archive in file ./basement (relative path), as level 3 trees
4354 below the level 2 heading \"** Finished Tasks\".
4356 You may set this option on a per-file basis by adding to the buffer a
4357 line like
4359 #+ARCHIVE: basement::** Finished Tasks
4361 You may also define it locally for a subtree by setting an ARCHIVE property
4362 in the entry. If such a property is found in an entry, or anywhere up
4363 the hierarchy, it will be used."
4364 :group 'org-archive
4365 :type 'string)
4367 (defcustom org-archive-tag "ARCHIVE"
4368 "The tag that marks a subtree as archived.
4369 An archived subtree does not open during visibility cycling, and does
4370 not contribute to the agenda listings.
4371 After changing this, font-lock must be restarted in the relevant buffers to
4372 get the proper fontification."
4373 :group 'org-archive
4374 :group 'org-keywords
4375 :type 'string)
4377 (defcustom org-agenda-skip-archived-trees t
4378 "Non-nil means the agenda will skip any items located in archived trees.
4379 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4380 variable is no longer recommended, you should leave it at the value t.
4381 Instead, use the key `v' to cycle the archives-mode in the agenda."
4382 :group 'org-archive
4383 :group 'org-agenda-skip
4384 :type 'boolean)
4386 (defcustom org-columns-skip-archived-trees t
4387 "Non-nil means ignore archived trees when creating column view."
4388 :group 'org-archive
4389 :group 'org-properties
4390 :type 'boolean)
4392 (defcustom org-cycle-open-archived-trees nil
4393 "Non-nil means `org-cycle' will open archived trees.
4394 An archived tree is a tree marked with the tag ARCHIVE.
4395 When nil, archived trees will stay folded. You can still open them with
4396 normal outline commands like `show-all', but not with the cycling commands."
4397 :group 'org-archive
4398 :group 'org-cycle
4399 :type 'boolean)
4401 (defcustom org-sparse-tree-open-archived-trees nil
4402 "Non-nil means sparse tree construction shows matches in archived trees.
4403 When nil, matches in these trees are highlighted, but the trees are kept in
4404 collapsed state."
4405 :group 'org-archive
4406 :group 'org-sparse-trees
4407 :type 'boolean)
4409 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4410 "The default date type when building a sparse tree.
4411 When this is nil, a date is a scheduled or a deadline timestamp.
4412 Otherwise, these types are allowed:
4414 all: all timestamps
4415 active: only active timestamps (<...>)
4416 inactive: only inactive timestamps (<...)
4417 scheduled: only scheduled timestamps
4418 deadline: only deadline timestamps"
4419 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4420 (const :tag "All timestamps" all)
4421 (const :tag "Only active timestamps" active)
4422 (const :tag "Only inactive timestamps" inactive)
4423 (const :tag "Only scheduled timestamps" scheduled)
4424 (const :tag "Only deadline timestamps" deadline))
4425 :version "24.3"
4426 :group 'org-sparse-trees)
4428 (defun org-cycle-hide-archived-subtrees (state)
4429 "Re-hide all archived subtrees after a visibility state change."
4430 (when (and (not org-cycle-open-archived-trees)
4431 (not (memq state '(overview folded))))
4432 (save-excursion
4433 (let* ((globalp (memq state '(contents all)))
4434 (beg (if globalp (point-min) (point)))
4435 (end (if globalp (point-max) (org-end-of-subtree t))))
4436 (org-hide-archived-subtrees beg end)
4437 (goto-char beg)
4438 (if (looking-at (concat ".*:" org-archive-tag ":"))
4439 (message "%s" (substitute-command-keys
4440 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4442 (defun org-force-cycle-archived ()
4443 "Cycle subtree even if it is archived."
4444 (interactive)
4445 (setq this-command 'org-cycle)
4446 (let ((org-cycle-open-archived-trees t))
4447 (call-interactively 'org-cycle)))
4449 (defun org-hide-archived-subtrees (beg end)
4450 "Re-hide all archived subtrees after a visibility state change."
4451 (save-excursion
4452 (let* ((re (concat ":" org-archive-tag ":")))
4453 (goto-char beg)
4454 (while (re-search-forward re end t)
4455 (when (org-at-heading-p)
4456 (org-flag-subtree t)
4457 (org-end-of-subtree t))))))
4459 (declare-function outline-end-of-heading "outline" ())
4460 (declare-function outline-flag-region "outline" (from to flag))
4461 (defun org-flag-subtree (flag)
4462 (save-excursion
4463 (org-back-to-heading t)
4464 (outline-end-of-heading)
4465 (outline-flag-region (point)
4466 (progn (org-end-of-subtree t) (point))
4467 flag)))
4469 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4471 (eval-and-compile
4472 (org-autoload "org-archive"
4473 '(org-add-archive-files)))
4475 ;; Autoload Column View Code
4477 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4478 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4479 (declare-function org-columns-compute "org-colview" (property))
4481 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4482 '(org-columns-number-to-string
4483 org-columns-get-format-and-top-level
4484 org-columns-compute
4485 org-columns-remove-overlays))
4487 ;; Autoload ID code
4489 (declare-function org-id-store-link "org-id")
4490 (declare-function org-id-locations-load "org-id")
4491 (declare-function org-id-locations-save "org-id")
4492 (defvar org-id-track-globally)
4493 (org-autoload "org-id"
4494 '(org-id-new
4495 org-id-copy
4496 org-id-get-with-outline-path-completion
4497 org-id-get-with-outline-drilling))
4499 ;;; Variables for pre-computed regular expressions, all buffer local
4501 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4502 "Matches first line of a hidden block.")
4503 (make-variable-buffer-local 'org-drawer-regexp)
4504 (defvar org-todo-regexp nil
4505 "Matches any of the TODO state keywords.")
4506 (make-variable-buffer-local 'org-todo-regexp)
4507 (defvar org-not-done-regexp nil
4508 "Matches any of the TODO state keywords except the last one.")
4509 (make-variable-buffer-local 'org-not-done-regexp)
4510 (defvar org-not-done-heading-regexp nil
4511 "Matches a TODO headline that is not done.")
4512 (make-variable-buffer-local 'org-not-done-regexp)
4513 (defvar org-todo-line-regexp nil
4514 "Matches a headline and puts TODO state into group 2 if present.")
4515 (make-variable-buffer-local 'org-todo-line-regexp)
4516 (defvar org-complex-heading-regexp nil
4517 "Matches a headline and puts everything into groups:
4518 group 1: the stars
4519 group 2: The todo keyword, maybe
4520 group 3: Priority cookie
4521 group 4: True headline
4522 group 5: Tags")
4523 (make-variable-buffer-local 'org-complex-heading-regexp)
4524 (defvar org-complex-heading-regexp-format nil
4525 "Printf format to make regexp to match an exact headline.
4526 This regexp will match the headline of any node which has the
4527 exact headline text that is put into the format, but may have any
4528 TODO state, priority and tags.")
4529 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4530 (defvar org-todo-line-tags-regexp nil
4531 "Matches a headline and puts TODO state into group 2 if present.
4532 Also put tags into group 4 if tags are present.")
4533 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4534 (defvar org-ds-keyword-length 12
4535 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4536 (make-variable-buffer-local 'org-ds-keyword-length)
4537 (defvar org-deadline-regexp nil
4538 "Matches the DEADLINE keyword.")
4539 (make-variable-buffer-local 'org-deadline-regexp)
4540 (defvar org-deadline-time-regexp nil
4541 "Matches the DEADLINE keyword together with a time stamp.")
4542 (make-variable-buffer-local 'org-deadline-time-regexp)
4543 (defvar org-deadline-line-regexp nil
4544 "Matches the DEADLINE keyword and the rest of the line.")
4545 (make-variable-buffer-local 'org-deadline-line-regexp)
4546 (defvar org-scheduled-regexp nil
4547 "Matches the SCHEDULED keyword.")
4548 (make-variable-buffer-local 'org-scheduled-regexp)
4549 (defvar org-scheduled-time-regexp nil
4550 "Matches the SCHEDULED keyword together with a time stamp.")
4551 (make-variable-buffer-local 'org-scheduled-time-regexp)
4552 (defvar org-closed-time-regexp nil
4553 "Matches the CLOSED keyword together with a time stamp.")
4554 (make-variable-buffer-local 'org-closed-time-regexp)
4556 (defvar org-keyword-time-regexp nil
4557 "Matches any of the 4 keywords, together with the time stamp.")
4558 (make-variable-buffer-local 'org-keyword-time-regexp)
4559 (defvar org-keyword-time-not-clock-regexp nil
4560 "Matches any of the 3 keywords, together with the time stamp.")
4561 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4562 (defvar org-maybe-keyword-time-regexp nil
4563 "Matches a timestamp, possibly preceded by a keyword.")
4564 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4565 (defvar org-all-time-keywords nil
4566 "List of time keywords.")
4567 (make-variable-buffer-local 'org-all-time-keywords)
4569 (defconst org-plain-time-of-day-regexp
4570 (concat
4571 "\\(\\<[012]?[0-9]"
4572 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4573 "\\(--?"
4574 "\\(\\<[012]?[0-9]"
4575 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4576 "\\)?")
4577 "Regular expression to match a plain time or time range.
4578 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4579 groups carry important information:
4580 0 the full match
4581 1 the first time, range or not
4582 8 the second time, if it is a range.")
4584 (defconst org-plain-time-extension-regexp
4585 (concat
4586 "\\(\\<[012]?[0-9]"
4587 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4588 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4589 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4590 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4591 groups carry important information:
4592 0 the full match
4593 7 hours of duration
4594 9 minutes of duration")
4596 (defconst org-stamp-time-of-day-regexp
4597 (concat
4598 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4599 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4600 "\\(--?"
4601 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4602 "Regular expression to match a timestamp time or time range.
4603 After a match, the following groups carry important information:
4604 0 the full match
4605 1 date plus weekday, for back referencing to make sure both times are on the same day
4606 2 the first time, range or not
4607 4 the second time, if it is a range.")
4609 (defconst org-startup-options
4610 '(("fold" org-startup-folded t)
4611 ("overview" org-startup-folded t)
4612 ("nofold" org-startup-folded nil)
4613 ("showall" org-startup-folded nil)
4614 ("showeverything" org-startup-folded showeverything)
4615 ("content" org-startup-folded content)
4616 ("indent" org-startup-indented t)
4617 ("noindent" org-startup-indented nil)
4618 ("hidestars" org-hide-leading-stars t)
4619 ("showstars" org-hide-leading-stars nil)
4620 ("odd" org-odd-levels-only t)
4621 ("oddeven" org-odd-levels-only nil)
4622 ("align" org-startup-align-all-tables t)
4623 ("noalign" org-startup-align-all-tables nil)
4624 ("inlineimages" org-startup-with-inline-images t)
4625 ("noinlineimages" org-startup-with-inline-images nil)
4626 ("customtime" org-display-custom-times t)
4627 ("logdone" org-log-done time)
4628 ("lognotedone" org-log-done note)
4629 ("nologdone" org-log-done nil)
4630 ("lognoteclock-out" org-log-note-clock-out t)
4631 ("nolognoteclock-out" org-log-note-clock-out nil)
4632 ("logrepeat" org-log-repeat state)
4633 ("lognoterepeat" org-log-repeat note)
4634 ("logdrawer" org-log-into-drawer t)
4635 ("nologdrawer" org-log-into-drawer nil)
4636 ("logstatesreversed" org-log-states-order-reversed t)
4637 ("nologstatesreversed" org-log-states-order-reversed nil)
4638 ("nologrepeat" org-log-repeat nil)
4639 ("logreschedule" org-log-reschedule time)
4640 ("lognotereschedule" org-log-reschedule note)
4641 ("nologreschedule" org-log-reschedule nil)
4642 ("logredeadline" org-log-redeadline time)
4643 ("lognoteredeadline" org-log-redeadline note)
4644 ("nologredeadline" org-log-redeadline nil)
4645 ("logrefile" org-log-refile time)
4646 ("lognoterefile" org-log-refile note)
4647 ("nologrefile" org-log-refile nil)
4648 ("fninline" org-footnote-define-inline t)
4649 ("nofninline" org-footnote-define-inline nil)
4650 ("fnlocal" org-footnote-section nil)
4651 ("fnauto" org-footnote-auto-label t)
4652 ("fnprompt" org-footnote-auto-label nil)
4653 ("fnconfirm" org-footnote-auto-label confirm)
4654 ("fnplain" org-footnote-auto-label plain)
4655 ("fnadjust" org-footnote-auto-adjust t)
4656 ("nofnadjust" org-footnote-auto-adjust nil)
4657 ("constcgs" constants-unit-system cgs)
4658 ("constSI" constants-unit-system SI)
4659 ("noptag" org-tag-persistent-alist nil)
4660 ("hideblocks" org-hide-block-startup t)
4661 ("nohideblocks" org-hide-block-startup nil)
4662 ("beamer" org-startup-with-beamer-mode t)
4663 ("entitiespretty" org-pretty-entities t)
4664 ("entitiesplain" org-pretty-entities nil))
4665 "Variable associated with STARTUP options for org-mode.
4666 Each element is a list of three items: the startup options (as written
4667 in the #+STARTUP line), the corresponding variable, and the value to set
4668 this variable to if the option is found. An optional forth element PUSH
4669 means to push this value onto the list in the variable.")
4671 (defun org-update-property-plist (key val props)
4672 "Update PROPS with KEY and VAL."
4673 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4674 (key (if appending (substring key 0 (- (length key) 1)) key))
4675 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4676 (previous (cdr (assoc key props))))
4677 (if appending
4678 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4679 (cons (cons key val) remainder))))
4681 (defconst org-block-regexp
4682 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4683 "Regular expression for hiding blocks.")
4684 (defconst org-heading-keyword-regexp-format
4685 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4686 "Printf format for a regexp matching an headline with some keyword.
4687 This regexp will match the headline of any node which has the
4688 exact keyword that is put into the format. The keyword isn't in
4689 any group by default, but the stars and the body are.")
4690 (defconst org-heading-keyword-maybe-regexp-format
4691 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4692 "Printf format for a regexp matching an headline, possibly with some keyword.
4693 This regexp can match any headline with the specified keyword, or
4694 without a keyword. The keyword isn't in any group by default,
4695 but the stars and the body are.")
4697 (defun org-set-regexps-and-options ()
4698 "Precompute regular expressions for current buffer."
4699 (when (derived-mode-p 'org-mode)
4700 (org-set-local 'org-todo-kwd-alist nil)
4701 (org-set-local 'org-todo-key-alist nil)
4702 (org-set-local 'org-todo-key-trigger nil)
4703 (org-set-local 'org-todo-keywords-1 nil)
4704 (org-set-local 'org-done-keywords nil)
4705 (org-set-local 'org-todo-heads nil)
4706 (org-set-local 'org-todo-sets nil)
4707 (org-set-local 'org-todo-log-states nil)
4708 (org-set-local 'org-file-properties nil)
4709 (org-set-local 'org-file-tags nil)
4710 (let ((re (org-make-options-regexp
4711 '("CATEGORY" "TODO" "COLUMNS"
4712 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4713 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4714 "OPTIONS")
4715 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4716 (splitre "[ \t]+")
4717 (scripts org-use-sub-superscripts)
4718 kwds kws0 kwsa key log value cat arch tags const links hw dws
4719 tail sep kws1 prio props ftags drawers beamer-p
4720 ext-setup-or-nil setup-contents (start 0))
4721 (save-excursion
4722 (save-restriction
4723 (widen)
4724 (goto-char (point-min))
4725 (while (or (and ext-setup-or-nil
4726 (string-match re ext-setup-or-nil start)
4727 (setq start (match-end 0)))
4728 (and (setq ext-setup-or-nil nil start 0)
4729 (re-search-forward re nil t)))
4730 (setq key (upcase (match-string 1 ext-setup-or-nil))
4731 value (org-match-string-no-properties 2 ext-setup-or-nil))
4732 (if (stringp value) (setq value (org-trim value)))
4733 (cond
4734 ((equal key "CATEGORY")
4735 (setq cat value))
4736 ((member key '("SEQ_TODO" "TODO"))
4737 (push (cons 'sequence (org-split-string value splitre)) kwds))
4738 ((equal key "TYP_TODO")
4739 (push (cons 'type (org-split-string value splitre)) kwds))
4740 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4741 ;; general TODO-like setup
4742 (push (cons (intern (downcase (match-string 1 key)))
4743 (org-split-string value splitre)) kwds))
4744 ((equal key "TAGS")
4745 (setq tags (append tags (if tags '("\\n") nil)
4746 (org-split-string value splitre))))
4747 ((equal key "COLUMNS")
4748 (org-set-local 'org-columns-default-format value))
4749 ((equal key "LINK")
4750 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4751 (push (cons (match-string 1 value)
4752 (org-trim (match-string 2 value)))
4753 links)))
4754 ((equal key "PRIORITIES")
4755 (setq prio (org-split-string value " +")))
4756 ((equal key "PROPERTY")
4757 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4758 (setq props (org-update-property-plist (match-string 1 value)
4759 (match-string 2 value)
4760 props))))
4761 ((equal key "FILETAGS")
4762 (when (string-match "\\S-" value)
4763 (setq ftags
4764 (append
4765 ftags
4766 (apply 'append
4767 (mapcar (lambda (x) (org-split-string x ":"))
4768 (org-split-string value)))))))
4769 ((equal key "DRAWERS")
4770 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4771 ((equal key "CONSTANTS")
4772 (setq const (append const (org-split-string value splitre))))
4773 ((equal key "STARTUP")
4774 (let ((opts (org-split-string value splitre))
4775 l var val)
4776 (while (setq l (pop opts))
4777 (when (setq l (assoc l org-startup-options))
4778 (setq var (nth 1 l) val (nth 2 l))
4779 (if (not (nth 3 l))
4780 (set (make-local-variable var) val)
4781 (if (not (listp (symbol-value var)))
4782 (set (make-local-variable var) nil))
4783 (set (make-local-variable var) (symbol-value var))
4784 (add-to-list var val))))))
4785 ((equal key "ARCHIVE")
4786 (setq arch value)
4787 (remove-text-properties 0 (length arch)
4788 '(face t fontified t) arch))
4789 ((equal key "LATEX_CLASS")
4790 (setq beamer-p (equal value "beamer")))
4791 ((equal key "OPTIONS")
4792 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4793 (setq scripts (read (match-string 2 value)))))
4794 ((equal key "SETUPFILE")
4795 (setq setup-contents (org-file-contents
4796 (expand-file-name
4797 (org-remove-double-quotes value))
4798 'noerror))
4799 (if (not ext-setup-or-nil)
4800 (setq ext-setup-or-nil setup-contents start 0)
4801 (setq ext-setup-or-nil
4802 (concat (substring ext-setup-or-nil 0 start)
4803 "\n" setup-contents "\n"
4804 (substring ext-setup-or-nil start)))))))
4805 ;; search for property blocks
4806 (goto-char (point-min))
4807 (while (re-search-forward org-block-regexp nil t)
4808 (when (equal "PROPERTY" (upcase (match-string 1)))
4809 (setq value (replace-regexp-in-string
4810 "[\n\r]" " " (match-string 4)))
4811 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4812 (setq props (org-update-property-plist (match-string 1 value)
4813 (match-string 2 value)
4814 props)))))))
4815 (org-set-local 'org-use-sub-superscripts scripts)
4816 (when cat
4817 (org-set-local 'org-category (intern cat))
4818 (push (cons "CATEGORY" cat) props))
4819 (when prio
4820 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4821 (setq prio (mapcar 'string-to-char prio))
4822 (org-set-local 'org-highest-priority (nth 0 prio))
4823 (org-set-local 'org-lowest-priority (nth 1 prio))
4824 (org-set-local 'org-default-priority (nth 2 prio)))
4825 (and props (org-set-local 'org-file-properties (nreverse props)))
4826 (and ftags (org-set-local 'org-file-tags
4827 (mapcar 'org-add-prop-inherited ftags)))
4828 (and drawers (org-set-local 'org-drawers drawers))
4829 (and arch (org-set-local 'org-archive-location arch))
4830 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4831 ;; Process the TODO keywords
4832 (unless kwds
4833 ;; Use the global values as if they had been given locally.
4834 (setq kwds (default-value 'org-todo-keywords))
4835 (if (stringp (car kwds))
4836 (setq kwds (list (cons org-todo-interpretation
4837 (default-value 'org-todo-keywords)))))
4838 (setq kwds (reverse kwds)))
4839 (setq kwds (nreverse kwds))
4840 (let (inter kws kw)
4841 (while (setq kws (pop kwds))
4842 (let ((kws (or
4843 (run-hook-with-args-until-success
4844 'org-todo-setup-filter-hook kws)
4845 kws)))
4846 (setq inter (pop kws) sep (member "|" kws)
4847 kws0 (delete "|" (copy-sequence kws))
4848 kwsa nil
4849 kws1 (mapcar
4850 (lambda (x)
4851 ;; 1 2
4852 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4853 (progn
4854 (setq kw (match-string 1 x)
4855 key (and (match-end 2) (match-string 2 x))
4856 log (org-extract-log-state-settings x))
4857 (push (cons kw (and key (string-to-char key))) kwsa)
4858 (and log (push log org-todo-log-states))
4860 (error "Invalid TODO keyword %s" x)))
4861 kws0)
4862 kwsa (if kwsa (append '((:startgroup))
4863 (nreverse kwsa)
4864 '((:endgroup))))
4865 hw (car kws1)
4866 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4867 tail (list inter hw (car dws) (org-last dws))))
4868 (add-to-list 'org-todo-heads hw 'append)
4869 (push kws1 org-todo-sets)
4870 (setq org-done-keywords (append org-done-keywords dws nil))
4871 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4872 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4873 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4874 (setq org-todo-sets (nreverse org-todo-sets)
4875 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4876 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4877 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4878 ;; Process the constants
4879 (when const
4880 (let (e cst)
4881 (while (setq e (pop const))
4882 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4883 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4884 (setq org-table-formula-constants-local cst)))
4886 ;; Process the tags.
4887 (when tags
4888 (let (e tgs)
4889 (while (setq e (pop tags))
4890 (cond
4891 ((equal e "{") (push '(:startgroup) tgs))
4892 ((equal e "}") (push '(:endgroup) tgs))
4893 ((equal e "\\n") (push '(:newline) tgs))
4894 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4895 (push (cons (match-string 1 e)
4896 (string-to-char (match-string 2 e)))
4897 tgs))
4898 (t (push (list e) tgs))))
4899 (org-set-local 'org-tag-alist nil)
4900 (while (setq e (pop tgs))
4901 (or (and (stringp (car e))
4902 (assoc (car e) org-tag-alist))
4903 (push e org-tag-alist)))))
4905 ;; Compute the regular expressions and other local variables.
4906 ;; Using `org-outline-regexp-bol' would complicate them much,
4907 ;; because of the fixed white space at the end of that string.
4908 (if (not org-done-keywords)
4909 (setq org-done-keywords (and org-todo-keywords-1
4910 (list (org-last org-todo-keywords-1)))))
4911 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4912 (length org-scheduled-string)
4913 (length org-clock-string)
4914 (length org-closed-string)))
4915 org-drawer-regexp
4916 (concat "^[ \t]*:\\("
4917 (mapconcat 'regexp-quote org-drawers "\\|")
4918 "\\):[ \t]*$")
4919 org-not-done-keywords
4920 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4921 org-todo-regexp
4922 (concat "\\("
4923 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4924 "\\)")
4925 org-not-done-regexp
4926 (concat "\\("
4927 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4928 "\\)")
4929 org-not-done-heading-regexp
4930 (format org-heading-keyword-regexp-format org-not-done-regexp)
4931 org-todo-line-regexp
4932 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4933 org-complex-heading-regexp
4934 (concat "^\\(\\*+\\)"
4935 "\\(?: +" org-todo-regexp "\\)?"
4936 "\\(?: +\\(\\[#.\\]\\)\\)?"
4937 "\\(?: +\\(.*?\\)\\)??"
4938 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4939 "[ \t]*$")
4940 org-complex-heading-regexp-format
4941 (concat "^\\(\\*+\\)"
4942 "\\(?: +" org-todo-regexp "\\)?"
4943 "\\(?: +\\(\\[#.\\]\\)\\)?"
4944 "\\(?: +"
4945 ;; Stats cookies can be stuck to body.
4946 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4947 "\\(%s\\)"
4948 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4949 "\\)"
4950 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4951 "[ \t]*$")
4952 org-todo-line-tags-regexp
4953 (concat "^\\(\\*+\\)"
4954 "\\(?: +" org-todo-regexp "\\)?"
4955 "\\(?: +\\(.*?\\)\\)??"
4956 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4957 "[ \t]*$")
4958 org-deadline-regexp (concat "\\<" org-deadline-string)
4959 org-deadline-time-regexp
4960 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4961 org-deadline-line-regexp
4962 (concat "\\<\\(" org-deadline-string "\\).*")
4963 org-scheduled-regexp
4964 (concat "\\<" org-scheduled-string)
4965 org-scheduled-time-regexp
4966 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4967 org-closed-time-regexp
4968 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4969 org-keyword-time-regexp
4970 (concat "\\<\\(" org-scheduled-string
4971 "\\|" org-deadline-string
4972 "\\|" org-closed-string
4973 "\\|" org-clock-string "\\)"
4974 " *[[<]\\([^]>]+\\)[]>]")
4975 org-keyword-time-not-clock-regexp
4976 (concat "\\<\\(" org-scheduled-string
4977 "\\|" org-deadline-string
4978 "\\|" org-closed-string
4979 "\\)"
4980 " *[[<]\\([^]>]+\\)[]>]")
4981 org-maybe-keyword-time-regexp
4982 (concat "\\(\\<\\(" org-scheduled-string
4983 "\\|" org-deadline-string
4984 "\\|" org-closed-string
4985 "\\|" org-clock-string "\\)\\)?"
4986 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4987 org-all-time-keywords
4988 (mapcar (lambda (w) (substring w 0 -1))
4989 (list org-scheduled-string org-deadline-string
4990 org-clock-string org-closed-string)))
4991 (org-set-font-lock-defaults))))
4993 (defun org-file-contents (file &optional noerror)
4994 "Return the contents of FILE, as a string."
4995 (if (or (not file)
4996 (not (file-readable-p file)))
4997 (if noerror
4998 (progn
4999 (message "Cannot read file \"%s\"" file)
5000 (ding) (sit-for 2)
5002 (error "Cannot read file \"%s\"" file))
5003 (with-temp-buffer
5004 (insert-file-contents file)
5005 (buffer-string))))
5007 (defun org-extract-log-state-settings (x)
5008 "Extract the log state setting from a TODO keyword string.
5009 This will extract info from a string like \"WAIT(w@/!)\"."
5010 (let (kw key log1 log2)
5011 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5012 (setq kw (match-string 1 x)
5013 key (and (match-end 2) (match-string 2 x))
5014 log1 (and (match-end 3) (match-string 3 x))
5015 log2 (and (match-end 4) (match-string 4 x)))
5016 (and (or log1 log2)
5017 (list kw
5018 (and log1 (if (equal log1 "!") 'time 'note))
5019 (and log2 (if (equal log2 "!") 'time 'note)))))))
5021 (defun org-remove-keyword-keys (list)
5022 "Remove a pair of parenthesis at the end of each string in LIST."
5023 (mapcar (lambda (x)
5024 (if (string-match "(.*)$" x)
5025 (substring x 0 (match-beginning 0))
5027 list))
5029 (defun org-assign-fast-keys (alist)
5030 "Assign fast keys to a keyword-key alist.
5031 Respect keys that are already there."
5032 (let (new e (alt ?0))
5033 (while (setq e (pop alist))
5034 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5035 (cdr e)) ;; Key already assigned.
5036 (push e new)
5037 (let ((clist (string-to-list (downcase (car e))))
5038 (used (append new alist)))
5039 (when (= (car clist) ?@)
5040 (pop clist))
5041 (while (and clist (rassoc (car clist) used))
5042 (pop clist))
5043 (unless clist
5044 (while (rassoc alt used)
5045 (incf alt)))
5046 (push (cons (car e) (or (car clist) alt)) new))))
5047 (nreverse new)))
5049 ;;; Some variables used in various places
5051 (defvar org-window-configuration nil
5052 "Used in various places to store a window configuration.")
5053 (defvar org-selected-window nil
5054 "Used in various places to store a window configuration.")
5055 (defvar org-finish-function nil
5056 "Function to be called when `C-c C-c' is used.
5057 This is for getting out of special buffers like capture.")
5060 ;; FIXME: Occasionally check by commenting these, to make sure
5061 ;; no other functions uses these, forgetting to let-bind them.
5062 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5063 (defvar org-last-state)
5064 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5066 ;; Defined somewhere in this file, but used before definition.
5067 (defvar org-entities) ;; defined in org-entities.el
5068 (defvar org-struct-menu)
5069 (defvar org-org-menu)
5070 (defvar org-tbl-menu)
5072 ;;;; Define the Org-mode
5074 ;; We use a before-change function to check if a table might need
5075 ;; an update.
5076 (defvar org-table-may-need-update t
5077 "Indicates that a table might need an update.
5078 This variable is set by `org-before-change-function'.
5079 `org-table-align' sets it back to nil.")
5080 (defun org-before-change-function (beg end)
5081 "Every change indicates that a table might need an update."
5082 (setq org-table-may-need-update t))
5083 (defvar org-mode-map)
5084 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5085 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5086 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5087 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5088 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5089 (defvar org-table-buffer-is-an nil)
5091 (defvar bidi-paragraph-direction)
5092 (defvar buffer-face-mode-face)
5094 (require 'outline)
5095 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5096 (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"))
5097 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5099 ;; Other stuff we need.
5100 (require 'time-date)
5101 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5102 (require 'easymenu)
5103 (require 'overlay)
5105 ;; (require 'org-macs) moved higher up in the file before it is first used
5106 (require 'org-entities)
5107 ;; (require 'org-compat) moved higher up in the file before it is first used
5108 (require 'org-faces)
5109 (require 'org-list)
5110 (require 'org-pcomplete)
5111 (require 'org-src)
5112 (require 'org-footnote)
5114 ;; babel
5115 (require 'ob)
5117 ;;;###autoload
5118 (define-derived-mode org-mode outline-mode "Org"
5119 "Outline-based notes management and organizer, alias
5120 \"Carsten's outline-mode for keeping track of everything.\"
5122 Org-mode develops organizational tasks around a NOTES file which
5123 contains information about projects as plain text. Org-mode is
5124 implemented on top of outline-mode, which is ideal to keep the content
5125 of large files well structured. It supports ToDo items, deadlines and
5126 time stamps, which magically appear in the diary listing of the Emacs
5127 calendar. Tables are easily created with a built-in table editor.
5128 Plain text URL-like links connect to websites, emails (VM), Usenet
5129 messages (Gnus), BBDB entries, and any files related to the project.
5130 For printing and sharing of notes, an Org-mode file (or a part of it)
5131 can be exported as a structured ASCII or HTML file.
5133 The following commands are available:
5135 \\{org-mode-map}"
5137 ;; Get rid of Outline menus, they are not needed
5138 ;; Need to do this here because define-derived-mode sets up
5139 ;; the keymap so late. Still, it is a waste to call this each time
5140 ;; we switch another buffer into org-mode.
5141 (if (featurep 'xemacs)
5142 (when (boundp 'outline-mode-menu-heading)
5143 ;; Assume this is Greg's port, it uses easymenu
5144 (easy-menu-remove outline-mode-menu-heading)
5145 (easy-menu-remove outline-mode-menu-show)
5146 (easy-menu-remove outline-mode-menu-hide))
5147 (define-key org-mode-map [menu-bar headings] 'undefined)
5148 (define-key org-mode-map [menu-bar hide] 'undefined)
5149 (define-key org-mode-map [menu-bar show] 'undefined))
5151 (org-load-modules-maybe)
5152 (easy-menu-add org-org-menu)
5153 (easy-menu-add org-tbl-menu)
5154 (org-install-agenda-files-menu)
5155 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5156 (add-to-invisibility-spec '(org-cwidth))
5157 (add-to-invisibility-spec '(org-hide-block . t))
5158 (when (featurep 'xemacs)
5159 (org-set-local 'line-move-ignore-invisible t))
5160 (org-set-local 'outline-regexp org-outline-regexp)
5161 (org-set-local 'outline-level 'org-outline-level)
5162 (setq bidi-paragraph-direction 'left-to-right)
5163 (when (and org-ellipsis
5164 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5165 (fboundp 'make-glyph-code))
5166 (unless org-display-table
5167 (setq org-display-table (make-display-table)))
5168 (set-display-table-slot
5169 org-display-table 4
5170 (vconcat (mapcar
5171 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5172 org-ellipsis)))
5173 (if (stringp org-ellipsis) org-ellipsis "..."))))
5174 (setq buffer-display-table org-display-table))
5175 (org-set-regexps-and-options)
5176 (when (and org-tag-faces (not org-tags-special-faces-re))
5177 ;; tag faces set outside customize.... force initialization.
5178 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5179 ;; Calc embedded
5180 (org-set-local 'calc-embedded-open-mode "# ")
5181 (modify-syntax-entry ?@ "w")
5182 (modify-syntax-entry ?\" "\"")
5183 (if org-startup-truncated (setq truncate-lines t))
5184 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5185 (org-set-local 'font-lock-unfontify-region-function
5186 'org-unfontify-region)
5187 ;; Activate before-change-function
5188 (org-set-local 'org-table-may-need-update t)
5189 (org-add-hook 'before-change-functions 'org-before-change-function nil
5190 'local)
5191 ;; Check for running clock before killing a buffer
5192 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5193 ;; Initialize macros templates.
5194 (org-macro-initialize-templates)
5195 ;; Initialize radio targets.
5196 (org-update-radio-target-regexp)
5197 ;; Indentation.
5198 (org-set-local 'indent-line-function 'org-indent-line)
5199 (org-set-local 'indent-region-function 'org-indent-region)
5200 ;; Filling and auto-filling.
5201 (org-setup-filling)
5202 ;; Comments.
5203 (org-setup-comments-handling)
5204 ;; Beginning/end of defun
5205 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5206 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5207 ;; Next error for sparse trees
5208 (org-set-local 'next-error-function 'org-occur-next-match)
5209 ;; Make sure dependence stuff works reliably, even for users who set it
5210 ;; too late :-(
5211 (if org-enforce-todo-dependencies
5212 (add-hook 'org-blocker-hook
5213 'org-block-todo-from-children-or-siblings-or-parent)
5214 (remove-hook 'org-blocker-hook
5215 'org-block-todo-from-children-or-siblings-or-parent))
5216 (if org-enforce-todo-checkbox-dependencies
5217 (add-hook 'org-blocker-hook
5218 'org-block-todo-from-checkboxes)
5219 (remove-hook 'org-blocker-hook
5220 'org-block-todo-from-checkboxes))
5222 ;; Align options lines
5223 (org-set-local
5224 'align-mode-rules-list
5225 '((org-in-buffer-settings
5226 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5227 (modes . '(org-mode)))))
5229 ;; Imenu
5230 (org-set-local 'imenu-create-index-function
5231 'org-imenu-get-tree)
5233 ;; Make isearch reveal context
5234 (if (or (featurep 'xemacs)
5235 (not (boundp 'outline-isearch-open-invisible-function)))
5236 ;; Emacs 21 and XEmacs make use of the hook
5237 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5238 ;; Emacs 22 deals with this through a special variable
5239 (org-set-local 'outline-isearch-open-invisible-function
5240 (lambda (&rest ignore) (org-show-context 'isearch))))
5242 ;; Setup the pcomplete hooks
5243 (set (make-local-variable 'pcomplete-command-completion-function)
5244 'org-pcomplete-initial)
5245 (set (make-local-variable 'pcomplete-command-name-function)
5246 'org-command-at-point)
5247 (set (make-local-variable 'pcomplete-default-completion-function)
5248 'ignore)
5249 (set (make-local-variable 'pcomplete-parse-arguments-function)
5250 'org-parse-arguments)
5251 (set (make-local-variable 'pcomplete-termination-string) "")
5252 (when (>= emacs-major-version 23)
5253 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5255 ;; If empty file that did not turn on org-mode automatically, make it to.
5256 (if (and org-insert-mode-line-in-empty-file
5257 (org-called-interactively-p 'any)
5258 (= (point-min) (point-max)))
5259 (insert "# -*- mode: org -*-\n\n"))
5260 (unless org-inhibit-startup
5261 (and org-startup-with-beamer-mode (org-beamer-mode))
5262 (when org-startup-align-all-tables
5263 (let ((bmp (buffer-modified-p)))
5264 (org-table-map-tables 'org-table-align 'quietly)
5265 (set-buffer-modified-p bmp)))
5266 (when org-startup-with-inline-images
5267 (org-display-inline-images))
5268 (unless org-inhibit-startup-visibility-stuff
5269 (org-set-startup-visibility)))
5270 ;; Try to set org-hide correctly
5271 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5273 (when (fboundp 'abbrev-table-put)
5274 (abbrev-table-put org-mode-abbrev-table
5275 :parents (list text-mode-abbrev-table)))
5277 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5280 (defun org-find-invisible-foreground ()
5281 (let ((candidates (remove
5282 "unspecified-bg"
5283 (nconc
5284 (list (face-background 'default)
5285 (face-background 'org-default))
5286 (mapcar
5287 (lambda (alist)
5288 (when (boundp alist)
5289 (cdr (assoc 'background-color (symbol-value alist)))))
5290 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5291 (list (face-foreground 'org-hide))))))
5292 (car (remove nil candidates))))
5294 (defun org-current-time (&optional rounding-minutes)
5295 "Current time, possibly rounded to ROUNDING-MINUTES.
5296 When ROUNDING-MINUTES is not an integer, fall back on the car of
5297 `org-time-stamp-rounding-minutes'."
5298 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5299 (car org-time-stamp-rounding-minutes)))
5300 (time (decode-time)))
5301 (if (> r 1)
5302 (apply 'encode-time
5303 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5304 (nthcdr 2 time)))
5305 (current-time))))
5307 (defun org-today ()
5308 "Return today date, considering `org-extend-today-until'."
5309 (time-to-days
5310 (time-subtract (current-time)
5311 (list 0 (* 3600 org-extend-today-until) 0))))
5313 ;;;; Font-Lock stuff, including the activators
5315 (defvar org-mouse-map (make-sparse-keymap))
5316 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5317 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5318 (when org-mouse-1-follows-link
5319 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5320 (when org-tab-follows-link
5321 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5322 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5324 (require 'font-lock)
5326 (defconst org-non-link-chars "]\t\n\r<>")
5327 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5328 "shell" "elisp" "doi" "message"))
5329 (defvar org-link-types-re nil
5330 "Matches a link that has a url-like prefix like \"http:\"")
5331 (defvar org-link-re-with-space nil
5332 "Matches a link with spaces, optional angular brackets around it.")
5333 (defvar org-link-re-with-space2 nil
5334 "Matches a link with spaces, optional angular brackets around it.")
5335 (defvar org-link-re-with-space3 nil
5336 "Matches a link with spaces, only for internal part in bracket links.")
5337 (defvar org-angle-link-re nil
5338 "Matches link with angular brackets, spaces are allowed.")
5339 (defvar org-plain-link-re nil
5340 "Matches plain link, without spaces.")
5341 (defvar org-bracket-link-regexp nil
5342 "Matches a link in double brackets.")
5343 (defvar org-bracket-link-analytic-regexp nil
5344 "Regular expression used to analyze links.
5345 Here is what the match groups contain after a match:
5346 1: http:
5347 2: http
5348 3: path
5349 4: [desc]
5350 5: desc")
5351 (defvar org-bracket-link-analytic-regexp++ nil
5352 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5353 (defvar org-any-link-re nil
5354 "Regular expression matching any link.")
5356 (defconst org-match-sexp-depth 3
5357 "Number of stacked braces for sub/superscript matching.")
5359 (defun org-create-multibrace-regexp (left right n)
5360 "Create a regular expression which will match a balanced sexp.
5361 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5362 as single character strings.
5363 The regexp returned will match the entire expression including the
5364 delimiters. It will also define a single group which contains the
5365 match except for the outermost delimiters. The maximum depth of
5366 stacked delimiters is N. Escaping delimiters is not possible."
5367 (let* ((nothing (concat "[^" left right "]*?"))
5368 (or "\\|")
5369 (re nothing)
5370 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5371 (while (> n 1)
5372 (setq n (1- n)
5373 re (concat re or next)
5374 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5375 (concat left "\\(" re "\\)" right)))
5377 (defvar org-match-substring-regexp
5378 (concat
5379 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5380 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5381 "\\|"
5382 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5383 "\\|"
5384 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5385 "The regular expression matching a sub- or superscript.")
5387 (defvar org-match-substring-with-braces-regexp
5388 (concat
5389 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5390 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5391 "\\)")
5392 "The regular expression matching a sub- or superscript, forcing braces.")
5394 (defun org-make-link-regexps ()
5395 "Update the link regular expressions.
5396 This should be called after the variable `org-link-types' has changed."
5397 (setq org-link-types-re
5398 (concat
5399 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5400 org-link-re-with-space
5401 (concat
5402 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5403 "\\([^" org-non-link-chars " ]"
5404 "[^" org-non-link-chars "]*"
5405 "[^" org-non-link-chars " ]\\)>?")
5406 org-link-re-with-space2
5407 (concat
5408 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5409 "\\([^" org-non-link-chars " ]"
5410 "[^\t\n\r]*"
5411 "[^" org-non-link-chars " ]\\)>?")
5412 org-link-re-with-space3
5413 (concat
5414 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5415 "\\([^" org-non-link-chars " ]"
5416 "[^\t\n\r]*\\)")
5417 org-angle-link-re
5418 (concat
5419 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5420 "\\([^" org-non-link-chars " ]"
5421 "[^" org-non-link-chars "]*"
5422 "\\)>")
5423 org-plain-link-re
5424 (concat
5425 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5426 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5427 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5428 org-bracket-link-regexp
5429 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5430 org-bracket-link-analytic-regexp
5431 (concat
5432 "\\[\\["
5433 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5434 "\\([^]]+\\)"
5435 "\\]"
5436 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5437 "\\]")
5438 org-bracket-link-analytic-regexp++
5439 (concat
5440 "\\[\\["
5441 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5442 "\\([^]]+\\)"
5443 "\\]"
5444 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5445 "\\]")
5446 org-any-link-re
5447 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5448 org-angle-link-re "\\)\\|\\("
5449 org-plain-link-re "\\)")))
5451 (org-make-link-regexps)
5453 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5454 "Regular expression for fast time stamp matching.")
5455 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5456 "Regular expression for fast time stamp matching.")
5457 (defconst org-ts-regexp0
5458 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5459 "Regular expression matching time strings for analysis.
5460 This one does not require the space after the date, so it can be used
5461 on a string that terminates immediately after the date.")
5462 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5463 "Regular expression matching time strings for analysis.")
5464 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5465 "Regular expression matching time stamps, with groups.")
5466 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5467 "Regular expression matching time stamps (also [..]), with groups.")
5468 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5469 "Regular expression matching a time stamp range.")
5470 (defconst org-tr-regexp-both
5471 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5472 "Regular expression matching a time stamp range.")
5473 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5474 org-ts-regexp "\\)?")
5475 "Regular expression matching a time stamp or time stamp range.")
5476 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5477 org-ts-regexp-both "\\)?")
5478 "Regular expression matching a time stamp or time stamp range.
5479 The time stamps may be either active or inactive.")
5481 (defvar org-emph-face nil)
5483 (defun org-do-emphasis-faces (limit)
5484 "Run through the buffer and add overlays to emphasized strings."
5485 (let (rtn a)
5486 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5487 (if (not (= (char-after (match-beginning 3))
5488 (char-after (match-beginning 4))))
5489 (progn
5490 (setq rtn t)
5491 (setq a (assoc (match-string 3) org-emphasis-alist))
5492 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5493 'face
5494 (nth 1 a))
5495 (and (nth 4 a)
5496 (org-remove-flyspell-overlays-in
5497 (match-beginning 0) (match-end 0)))
5498 (add-text-properties (match-beginning 2) (match-end 2)
5499 '(font-lock-multiline t org-emphasis t))
5500 (when org-hide-emphasis-markers
5501 (add-text-properties (match-end 4) (match-beginning 5)
5502 '(invisible org-link))
5503 (add-text-properties (match-beginning 3) (match-end 3)
5504 '(invisible org-link)))))
5505 (backward-char 1))
5506 rtn))
5508 (defun org-emphasize (&optional char)
5509 "Insert or change an emphasis, i.e. a font like bold or italic.
5510 If there is an active region, change that region to a new emphasis.
5511 If there is no region, just insert the marker characters and position
5512 the cursor between them.
5513 CHAR should be either the marker character, or the first character of the
5514 HTML tag associated with that emphasis. If CHAR is a space, the means
5515 to remove the emphasis of the selected region.
5516 If char is not given (for example in an interactive call) it
5517 will be prompted for."
5518 (interactive)
5519 (let ((eal org-emphasis-alist) e det
5520 (erc org-emphasis-regexp-components)
5521 (prompt "")
5522 (string "") beg end move tag c s)
5523 (if (org-region-active-p)
5524 (setq beg (region-beginning) end (region-end)
5525 string (buffer-substring beg end))
5526 (setq move t))
5528 (while (setq e (pop eal))
5529 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5530 c (aref tag 0))
5531 (push (cons c (string-to-char (car e))) det)
5532 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5533 (substring tag 1)))))
5534 (setq det (nreverse det))
5535 (unless char
5536 (message "%s" (concat "Emphasis marker or tag:" prompt))
5537 (setq char (read-char-exclusive)))
5538 (setq char (or (cdr (assoc char det)) char))
5539 (if (equal char ?\ )
5540 (setq s "" move nil)
5541 (unless (assoc (char-to-string char) org-emphasis-alist)
5542 (error "No such emphasis marker: \"%c\"" char))
5543 (setq s (char-to-string char)))
5544 (while (and (> (length string) 1)
5545 (equal (substring string 0 1) (substring string -1))
5546 (assoc (substring string 0 1) org-emphasis-alist))
5547 (setq string (substring string 1 -1)))
5548 (setq string (concat s string s))
5549 (if beg (delete-region beg end))
5550 (unless (or (bolp)
5551 (string-match (concat "[" (nth 0 erc) "\n]")
5552 (char-to-string (char-before (point)))))
5553 (insert " "))
5554 (unless (or (eobp)
5555 (string-match (concat "[" (nth 1 erc) "\n]")
5556 (char-to-string (char-after (point)))))
5557 (insert " ") (backward-char 1))
5558 (insert string)
5559 (and move (backward-char 1))))
5561 (defconst org-nonsticky-props
5562 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5564 (defsubst org-rear-nonsticky-at (pos)
5565 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5567 (defun org-activate-plain-links (limit)
5568 "Run through the buffer and add overlays to links."
5569 (catch 'exit
5570 (let (f hl)
5571 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5572 (not (org-in-src-block-p)))
5573 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5574 (setq f (get-text-property (match-beginning 0) 'face))
5575 (setq hl (org-match-string-no-properties 0))
5576 (if (or (eq f 'org-tag)
5577 (and (listp f) (memq 'org-tag f)))
5579 (add-text-properties (match-beginning 0) (match-end 0)
5580 (list 'mouse-face 'highlight
5581 'face 'org-link
5582 'htmlize-link `(:uri ,hl)
5583 'keymap org-mouse-map))
5584 (org-rear-nonsticky-at (match-end 0)))
5585 t))))
5587 (defun org-activate-code (limit)
5588 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5589 (progn
5590 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5591 (remove-text-properties (match-beginning 0) (match-end 0)
5592 '(display t invisible t intangible t))
5593 t)))
5595 (defcustom org-src-fontify-natively nil
5596 "When non-nil, fontify code in code blocks."
5597 :type 'boolean
5598 :version "24.1"
5599 :group 'org-appearance
5600 :group 'org-babel)
5602 (defcustom org-allow-promoting-top-level-subtree nil
5603 "When non-nil, allow promoting a top level subtree.
5604 The leading star of the top level headline will be replaced
5605 by a #."
5606 :type 'boolean
5607 :version "24.1"
5608 :group 'org-appearance)
5610 (defun org-fontify-meta-lines-and-blocks (limit)
5611 (condition-case nil
5612 (org-fontify-meta-lines-and-blocks-1 limit)
5613 (error (message "org-mode fontification error"))))
5615 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5616 "Fontify #+ lines and blocks, in the correct ways."
5617 (let ((case-fold-search t))
5618 (if (re-search-forward
5619 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5620 limit t)
5621 (let ((beg (match-beginning 0))
5622 (block-start (match-end 0))
5623 (block-end nil)
5624 (lang (match-string 7))
5625 (beg1 (line-beginning-position 2))
5626 (dc1 (downcase (match-string 2)))
5627 (dc3 (downcase (match-string 3)))
5628 end end1 quoting block-type ovl)
5629 (cond
5630 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5631 ;; a single line of backend-specific content
5632 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5633 (remove-text-properties (match-beginning 0) (match-end 0)
5634 '(display t invisible t intangible t))
5635 (add-text-properties (match-beginning 1) (match-end 3)
5636 '(font-lock-fontified t face org-meta-line))
5637 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5638 '(font-lock-fontified t face org-block))
5639 ; for backend-specific code
5641 ((and (match-end 4) (equal dc3 "+begin"))
5642 ;; Truly a block
5643 (setq block-type (downcase (match-string 5))
5644 quoting (member block-type org-protecting-blocks))
5645 (when (re-search-forward
5646 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5647 nil t) ;; on purpose, we look further than LIMIT
5648 (setq end (min (point-max) (match-end 0))
5649 end1 (min (point-max) (1- (match-beginning 0))))
5650 (setq block-end (match-beginning 0))
5651 (when quoting
5652 (remove-text-properties beg end
5653 '(display t invisible t intangible t)))
5654 (add-text-properties
5655 beg end
5656 '(font-lock-fontified t font-lock-multiline t))
5657 (add-text-properties beg beg1 '(face org-meta-line))
5658 (add-text-properties end1 (min (point-max) (1+ end))
5659 '(face org-meta-line)) ; for end_src
5660 (cond
5661 ((and lang (not (string= lang "")) org-src-fontify-natively)
5662 (org-src-font-lock-fontify-block lang block-start block-end)
5663 ;; remove old background overlays
5664 (mapc (lambda (ov)
5665 (if (eq (overlay-get ov 'face) 'org-block-background)
5666 (delete-overlay ov)))
5667 (overlays-at (/ (+ beg1 block-end) 2)))
5668 ;; add a background overlay
5669 (setq ovl (make-overlay beg1 block-end))
5670 (overlay-put ovl 'face 'org-block-background)
5671 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5672 (quoting
5673 (add-text-properties beg1 (min (point-max) (1+ end1))
5674 '(face org-block))) ; end of source block
5675 ((not org-fontify-quote-and-verse-blocks))
5676 ((string= block-type "quote")
5677 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5678 ((string= block-type "verse")
5679 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5680 (add-text-properties beg beg1 '(face org-block-begin-line))
5681 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5682 '(face org-block-end-line))
5684 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5685 (add-text-properties
5686 beg (match-end 3)
5687 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5688 '(font-lock-fontified t invisible t)
5689 '(font-lock-fontified t face org-document-info-keyword)))
5690 (add-text-properties
5691 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5692 (if (string-equal dc1 "+title:")
5693 '(font-lock-fontified t face org-document-title)
5694 '(font-lock-fontified t face org-document-info))))
5695 ((or (equal dc1 "+results")
5696 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5697 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5698 "+call:" "+header:" "+headers:" "+name:"))
5699 (and (match-end 4) (equal dc3 "+attr")))
5700 (add-text-properties
5701 beg (match-end 0)
5702 '(font-lock-fontified t face org-meta-line))
5704 ((member dc3 '(" " ""))
5705 (add-text-properties
5706 beg (match-end 0)
5707 '(font-lock-fontified t face font-lock-comment-face)))
5708 ((not (member (char-after beg) '(?\ ?\t)))
5709 ;; just any other in-buffer setting, but not indented
5710 (add-text-properties
5711 beg (match-end 0)
5712 '(font-lock-fontified t face org-meta-line))
5714 (t nil))))))
5716 (defun org-activate-angle-links (limit)
5717 "Run through the buffer and add overlays to links."
5718 (if (and (re-search-forward org-angle-link-re limit t)
5719 (not (org-in-src-block-p)))
5720 (progn
5721 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5722 (add-text-properties (match-beginning 0) (match-end 0)
5723 (list 'mouse-face 'highlight
5724 'keymap org-mouse-map))
5725 (org-rear-nonsticky-at (match-end 0))
5726 t)))
5728 (defun org-activate-footnote-links (limit)
5729 "Run through the buffer and add overlays to footnotes."
5730 (let ((fn (org-footnote-next-reference-or-definition limit)))
5731 (when fn
5732 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5733 (org-remove-flyspell-overlays-in beg end)
5734 (add-text-properties beg end
5735 (list 'mouse-face 'highlight
5736 'keymap org-mouse-map
5737 'help-echo
5738 (if (= (point-at-bol) beg)
5739 "Footnote definition"
5740 "Footnote reference")
5741 'font-lock-fontified t
5742 'font-lock-multiline t
5743 'face 'org-footnote))))))
5745 (defun org-activate-bracket-links (limit)
5746 "Run through the buffer and add overlays to bracketed links."
5747 (if (and (re-search-forward org-bracket-link-regexp limit t)
5748 (not (org-in-src-block-p)))
5749 (let* ((hl (org-match-string-no-properties 1))
5750 (help (concat "LINK: " hl))
5751 ;; FIXME: Above we should remove the escapes. But that
5752 ;; requires another match, protecting match data, a lot
5753 ;; of overhead for font-lock.
5754 (ip (org-maybe-intangible
5755 (list 'invisible 'org-link
5756 'keymap org-mouse-map 'mouse-face 'highlight
5757 'font-lock-multiline t 'help-echo help
5758 'htmlize-link `(:uri ,hl))))
5759 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5760 'font-lock-multiline t 'help-echo help
5761 'htmlize-link `(:uri ,hl))))
5762 ;; We need to remove the invisible property here. Table narrowing
5763 ;; may have made some of this invisible.
5764 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5765 (remove-text-properties (match-beginning 0) (match-end 0)
5766 '(invisible nil))
5767 (if (match-end 3)
5768 (progn
5769 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5770 (org-rear-nonsticky-at (match-beginning 3))
5771 (add-text-properties (match-beginning 3) (match-end 3) vp)
5772 (org-rear-nonsticky-at (match-end 3))
5773 (add-text-properties (match-end 3) (match-end 0) ip)
5774 (org-rear-nonsticky-at (match-end 0)))
5775 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5776 (org-rear-nonsticky-at (match-beginning 1))
5777 (add-text-properties (match-beginning 1) (match-end 1) vp)
5778 (org-rear-nonsticky-at (match-end 1))
5779 (add-text-properties (match-end 1) (match-end 0) ip)
5780 (org-rear-nonsticky-at (match-end 0)))
5781 t)))
5783 (defun org-activate-dates (limit)
5784 "Run through the buffer and add overlays to dates."
5785 (if (re-search-forward org-tsr-regexp-both limit t)
5786 (progn
5787 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5788 (add-text-properties (match-beginning 0) (match-end 0)
5789 (list 'mouse-face 'highlight
5790 'keymap org-mouse-map))
5791 (org-rear-nonsticky-at (match-end 0))
5792 (when org-display-custom-times
5793 (if (match-end 3)
5794 (org-display-custom-time (match-beginning 3) (match-end 3)))
5795 (org-display-custom-time (match-beginning 1) (match-end 1)))
5796 t)))
5798 (defvar org-target-link-regexp nil
5799 "Regular expression matching radio targets in plain text.")
5800 (make-variable-buffer-local 'org-target-link-regexp)
5801 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5802 "Regular expression matching a link target.")
5803 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5804 "Regular expression matching a radio target.")
5805 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5806 "Regular expression matching any target.")
5808 (defun org-activate-target-links (limit)
5809 "Run through the buffer and add overlays to target matches."
5810 (when org-target-link-regexp
5811 (let ((case-fold-search t))
5812 (if (re-search-forward org-target-link-regexp limit t)
5813 (progn
5814 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5815 (add-text-properties (match-beginning 0) (match-end 0)
5816 (list 'mouse-face 'highlight
5817 'keymap org-mouse-map
5818 'help-echo "Radio target link"
5819 'org-linked-text t))
5820 (org-rear-nonsticky-at (match-end 0))
5821 t)))))
5823 (defun org-update-radio-target-regexp ()
5824 "Find all radio targets in this file and update the regular expression."
5825 (interactive)
5826 (when (memq 'radio org-activate-links)
5827 (setq org-target-link-regexp
5828 (org-make-target-link-regexp (org-all-targets 'radio)))
5829 (org-restart-font-lock)))
5831 (defun org-hide-wide-columns (limit)
5832 (let (s e)
5833 (setq s (text-property-any (point) (or limit (point-max))
5834 'org-cwidth t))
5835 (when s
5836 (setq e (next-single-property-change s 'org-cwidth))
5837 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5838 (goto-char e)
5839 t)))
5841 (defvar org-match-substring-regexp)
5842 (defvar org-match-substring-with-braces-regexp)
5844 (defun org-restart-font-lock ()
5845 "Restart `font-lock-mode', to force refontification."
5846 (when (and (boundp 'font-lock-mode) font-lock-mode)
5847 (font-lock-mode -1)
5848 (font-lock-mode 1)))
5850 (defun org-all-targets (&optional radio)
5851 "Return a list of all targets in this file.
5852 When optional argument RADIO is non-nil, only find radio
5853 targets."
5854 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5855 (save-excursion
5856 (goto-char (point-min))
5857 (while (re-search-forward re nil t)
5858 ;; Make sure point is really within the object.
5859 (backward-char)
5860 (let ((obj (org-element-context)))
5861 (when (memq (org-element-type obj) '(radio-target target))
5862 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5863 rtn)))
5865 (defun org-make-target-link-regexp (targets)
5866 "Make regular expression matching all strings in TARGETS.
5867 The regular expression finds the targets also if there is a line break
5868 between words."
5869 (and targets
5870 (concat
5871 "\\<\\("
5872 (mapconcat
5873 (lambda (x)
5874 (setq x (regexp-quote x))
5875 (while (string-match " +" x)
5876 (setq x (replace-match "\\s-+" t t x)))
5878 targets
5879 "\\|")
5880 "\\)\\>")))
5882 (defun org-activate-tags (limit)
5883 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5884 (progn
5885 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5886 (add-text-properties (match-beginning 1) (match-end 1)
5887 (list 'mouse-face 'highlight
5888 'keymap org-mouse-map))
5889 (org-rear-nonsticky-at (match-end 1))
5890 t)))
5892 (defun org-outline-level ()
5893 "Compute the outline level of the heading at point.
5894 If this is called at a normal headline, the level is the number of stars.
5895 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5896 (save-excursion
5897 (if (not (condition-case nil
5898 (org-back-to-heading t)
5899 (error nil)))
5901 (looking-at org-outline-regexp)
5902 (1- (- (match-end 0) (match-beginning 0))))))
5904 (defvar org-font-lock-keywords nil)
5906 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5907 "Regular expression matching a property line.")
5909 (defvar org-font-lock-hook nil
5910 "Functions to be called for special font lock stuff.")
5912 (defvar org-font-lock-set-keywords-hook nil
5913 "Functions that can manipulate `org-font-lock-extra-keywords'.
5914 This is called after `org-font-lock-extra-keywords' is defined, but before
5915 it is installed to be used by font lock. This can be useful if something
5916 needs to be inserted at a specific position in the font-lock sequence.")
5918 (defun org-font-lock-hook (limit)
5919 "Run `org-font-lock-hook' within LIMIT."
5920 (run-hook-with-args 'org-font-lock-hook limit))
5922 (defun org-set-font-lock-defaults ()
5923 "Set font lock defaults for the current buffer."
5924 (let* ((em org-fontify-emphasized-text)
5925 (lk org-activate-links)
5926 (org-font-lock-extra-keywords
5927 (list
5928 ;; Call the hook
5929 '(org-font-lock-hook)
5930 ;; Headlines
5931 `(,(if org-fontify-whole-heading-line
5932 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5933 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5934 (1 (org-get-level-face 1))
5935 (2 (org-get-level-face 2))
5936 (3 (org-get-level-face 3)))
5937 ;; Table lines
5938 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5939 (1 'org-table t))
5940 ;; Table internals
5941 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5942 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5943 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5944 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5945 ;; Drawers
5946 (list org-drawer-regexp '(0 'org-special-keyword t))
5947 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5948 ;; Properties
5949 (list org-property-re
5950 '(1 'org-special-keyword t)
5951 '(3 'org-property-value t))
5952 ;; Links
5953 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5954 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5955 (if (memq 'plain lk) '(org-activate-plain-links))
5956 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5957 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5958 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5959 (if (memq 'footnote lk) '(org-activate-footnote-links))
5960 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5961 '(org-hide-wide-columns (0 nil append))
5962 ;; TODO keyword
5963 (list (format org-heading-keyword-regexp-format
5964 org-todo-regexp)
5965 '(2 (org-get-todo-face 2) t))
5966 ;; DONE
5967 (if org-fontify-done-headline
5968 (list (format org-heading-keyword-regexp-format
5969 (concat
5970 "\\(?:"
5971 (mapconcat 'regexp-quote org-done-keywords "\\|")
5972 "\\)"))
5973 '(2 'org-headline-done t))
5974 nil)
5975 ;; Priorities
5976 '(org-font-lock-add-priority-faces)
5977 ;; Tags
5978 '(org-font-lock-add-tag-faces)
5979 ;; Special keywords
5980 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5981 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5982 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5983 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5984 ;; Emphasis
5985 (if em
5986 (if (featurep 'xemacs)
5987 '(org-do-emphasis-faces (0 nil append))
5988 '(org-do-emphasis-faces)))
5989 ;; Checkboxes
5990 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5991 1 'org-checkbox prepend)
5992 (if (cdr (assq 'checkbox org-list-automatic-rules))
5993 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5994 (0 (org-get-checkbox-statistics-face) t)))
5995 ;; Description list items
5996 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5997 1 'org-list-dt prepend)
5998 ;; ARCHIVEd headings
5999 (list (concat
6000 org-outline-regexp-bol
6001 "\\(.*:" org-archive-tag ":.*\\)")
6002 '(1 'org-archived prepend))
6003 ;; Specials
6004 '(org-fontify-entities)
6005 '(org-raise-scripts)
6006 ;; Code
6007 '(org-activate-code (1 'org-code t))
6008 ;; COMMENT
6009 (list (format org-heading-keyword-regexp-format
6010 (concat "\\("
6011 org-comment-string "\\|" org-quote-string
6012 "\\)"))
6013 '(2 'org-special-keyword t))
6014 ;; Blocks and meta lines
6015 '(org-fontify-meta-lines-and-blocks)
6017 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6018 (run-hooks 'org-font-lock-set-keywords-hook)
6019 ;; Now set the full font-lock-keywords
6020 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6021 (org-set-local 'font-lock-defaults
6022 '(org-font-lock-keywords t nil nil backward-paragraph))
6023 (kill-local-variable 'font-lock-keywords) nil))
6025 (defun org-toggle-pretty-entities ()
6026 "Toggle the composition display of entities as UTF8 characters."
6027 (interactive)
6028 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6029 (org-restart-font-lock)
6030 (if org-pretty-entities
6031 (message "Entities are displayed as UTF8 characters")
6032 (save-restriction
6033 (widen)
6034 (org-decompose-region (point-min) (point-max))
6035 (message "Entities are displayed plain"))))
6037 (defvar org-custom-properties-overlays nil
6038 "List of overlays used for custom properties.")
6039 (make-variable-buffer-local 'org-custom-properties-overlays)
6041 (defun org-toggle-custom-properties-visibility ()
6042 "Display or hide properties in `org-custom-properties'."
6043 (interactive)
6044 (if org-custom-properties-overlays
6045 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6046 (setq org-custom-properties-overlays nil))
6047 (unless (not org-custom-properties)
6048 (save-excursion
6049 (save-restriction
6050 (widen)
6051 (goto-char (point-min))
6052 (while (re-search-forward org-property-re nil t)
6053 (mapc (lambda(p)
6054 (when (equal p (substring (match-string 1) 1 -1))
6055 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6056 (overlay-put o 'invisible t)
6057 (overlay-put o 'org-custom-property t)
6058 (push o org-custom-properties-overlays))))
6059 org-custom-properties)))))))
6061 (defun org-fontify-entities (limit)
6062 "Find an entity to fontify."
6063 (let (ee)
6064 (when org-pretty-entities
6065 (catch 'match
6066 (while (re-search-forward
6067 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6068 limit t)
6069 (if (and (not (org-in-indented-comment-line))
6070 (setq ee (org-entity-get (match-string 1)))
6071 (= (length (nth 6 ee)) 1))
6072 (let*
6073 ((end (if (equal (match-string 2) "{}")
6074 (match-end 2)
6075 (match-end 1))))
6076 (add-text-properties
6077 (match-beginning 0) end
6078 (list 'font-lock-fontified t))
6079 (compose-region (match-beginning 0) end
6080 (nth 6 ee) nil)
6081 (backward-char 1)
6082 (throw 'match t))))
6083 nil))))
6085 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6086 "Fontify string S like in Org-mode."
6087 (with-temp-buffer
6088 (insert s)
6089 (let ((org-odd-levels-only odd-levels))
6090 (org-mode)
6091 (font-lock-fontify-buffer)
6092 (buffer-string))))
6094 (defvar org-m nil)
6095 (defvar org-l nil)
6096 (defvar org-f nil)
6097 (defun org-get-level-face (n)
6098 "Get the right face for match N in font-lock matching of headlines."
6099 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6100 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6101 (if org-cycle-level-faces
6102 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6103 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6104 (cond
6105 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6106 ((eq n 2) org-f)
6107 (t (if org-level-color-stars-only nil org-f))))
6110 (defun org-get-todo-face (kwd)
6111 "Get the right face for a TODO keyword KWD.
6112 If KWD is a number, get the corresponding match group."
6113 (if (numberp kwd) (setq kwd (match-string kwd)))
6114 (or (org-face-from-face-or-color
6115 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6116 (and (member kwd org-done-keywords) 'org-done)
6117 'org-todo))
6119 (defun org-face-from-face-or-color (context inherit face-or-color)
6120 "Create a face list that inherits INHERIT, but sets the foreground color.
6121 When FACE-OR-COLOR is not a string, just return it."
6122 (if (stringp face-or-color)
6123 (list :inherit inherit
6124 (cdr (assoc context org-faces-easy-properties))
6125 face-or-color)
6126 face-or-color))
6128 (defun org-font-lock-add-tag-faces (limit)
6129 "Add the special tag faces."
6130 (when (and org-tag-faces org-tags-special-faces-re)
6131 (while (re-search-forward org-tags-special-faces-re limit t)
6132 (add-text-properties (match-beginning 1) (match-end 1)
6133 (list 'face (org-get-tag-face 1)
6134 'font-lock-fontified t))
6135 (backward-char 1))))
6137 (defun org-font-lock-add-priority-faces (limit)
6138 "Add the special priority faces."
6139 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6140 (when (save-match-data (org-at-heading-p))
6141 (add-text-properties
6142 (match-beginning 0) (match-end 0)
6143 (list 'face (or (org-face-from-face-or-color
6144 'priority 'org-priority
6145 (cdr (assoc (char-after (match-beginning 1))
6146 org-priority-faces)))
6147 'org-priority)
6148 'font-lock-fontified t)))))
6150 (defun org-get-tag-face (kwd)
6151 "Get the right face for a TODO keyword KWD.
6152 If KWD is a number, get the corresponding match group."
6153 (if (numberp kwd) (setq kwd (match-string kwd)))
6154 (or (org-face-from-face-or-color
6155 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6156 'org-tag))
6158 (defun org-unfontify-region (beg end &optional maybe_loudly)
6159 "Remove fontification and activation overlays from links."
6160 (font-lock-default-unfontify-region beg end)
6161 (let* ((buffer-undo-list t)
6162 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6163 (inhibit-modification-hooks t)
6164 deactivate-mark buffer-file-name buffer-file-truename)
6165 (org-decompose-region beg end)
6166 (remove-text-properties beg end
6167 '(mouse-face t keymap t org-linked-text t
6168 invisible t intangible t
6169 org-no-flyspell t org-emphasis t))
6170 (org-remove-font-lock-display-properties beg end)))
6172 (defconst org-script-display '(((raise -0.3) (height 0.7))
6173 ((raise 0.3) (height 0.7))
6174 ((raise -0.5))
6175 ((raise 0.5)))
6176 "Display properties for showing superscripts and subscripts.")
6178 (defun org-remove-font-lock-display-properties (beg end)
6179 "Remove specific display properties that have been added by font lock.
6180 The will remove the raise properties that are used to show superscripts
6181 and subscripts."
6182 (let (next prop)
6183 (while (< beg end)
6184 (setq next (next-single-property-change beg 'display nil end)
6185 prop (get-text-property beg 'display))
6186 (if (member prop org-script-display)
6187 (put-text-property beg next 'display nil))
6188 (setq beg next))))
6190 (defun org-raise-scripts (limit)
6191 "Add raise properties to sub/superscripts."
6192 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6193 (if (re-search-forward
6194 (if (eq org-use-sub-superscripts t)
6195 org-match-substring-regexp
6196 org-match-substring-with-braces-regexp)
6197 limit t)
6198 (let* ((pos (point)) table-p comment-p
6199 (mpos (match-beginning 3))
6200 (emph-p (get-text-property mpos 'org-emphasis))
6201 (link-p (get-text-property mpos 'mouse-face))
6202 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6203 (goto-char (point-at-bol))
6204 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6205 comment-p (org-looking-at-p "[ \t]*#"))
6206 (goto-char pos)
6207 ;; FIXME: Should we go back one character here, for a_b^c
6208 ;; (goto-char (1- pos)) ;????????????????????
6209 (if (or comment-p emph-p link-p keyw-p)
6211 (put-text-property (match-beginning 3) (match-end 0)
6212 'display
6213 (if (equal (char-after (match-beginning 2)) ?^)
6214 (nth (if table-p 3 1) org-script-display)
6215 (nth (if table-p 2 0) org-script-display)))
6216 (add-text-properties (match-beginning 2) (match-end 2)
6217 (list 'invisible t
6218 'org-dwidth t 'org-dwidth-n 1))
6219 (if (and (eq (char-after (match-beginning 3)) ?{)
6220 (eq (char-before (match-end 3)) ?}))
6221 (progn
6222 (add-text-properties
6223 (match-beginning 3) (1+ (match-beginning 3))
6224 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6225 (add-text-properties
6226 (1- (match-end 3)) (match-end 3)
6227 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6228 t)))))
6230 ;;;; Visibility cycling, including org-goto and indirect buffer
6232 ;;; Cycling
6234 (defvar org-cycle-global-status nil)
6235 (make-variable-buffer-local 'org-cycle-global-status)
6236 (defvar org-cycle-subtree-status nil)
6237 (make-variable-buffer-local 'org-cycle-subtree-status)
6239 (defvar org-inlinetask-min-level)
6241 ;;;###autoload
6242 (defun org-cycle (&optional arg)
6243 "TAB-action and visibility cycling for Org-mode.
6245 This is the command invoked in Org-mode by the TAB key. Its main purpose
6246 is outline visibility cycling, but it also invokes other actions
6247 in special contexts.
6249 - When this function is called with a prefix argument, rotate the entire
6250 buffer through 3 states (global cycling)
6251 1. OVERVIEW: Show only top-level headlines.
6252 2. CONTENTS: Show all headlines of all levels, but no body text.
6253 3. SHOW ALL: Show everything.
6254 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6255 determined by the variable `org-startup-folded', and by any VISIBILITY
6256 properties in the buffer.
6257 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6258 including any drawers.
6260 - When inside a table, re-align the table and move to the next field.
6262 - When point is at the beginning of a headline, rotate the subtree started
6263 by this line through 3 different states (local cycling)
6264 1. FOLDED: Only the main headline is shown.
6265 2. CHILDREN: The main headline and the direct children are shown.
6266 From this state, you can move to one of the children
6267 and zoom in further.
6268 3. SUBTREE: Show the entire subtree, including body text.
6269 If there is no subtree, switch directly from CHILDREN to FOLDED.
6271 - When point is at the beginning of an empty headline and the variable
6272 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6273 of the headline by demoting and promoting it to likely levels. This
6274 speeds up creation document structure by pressing TAB once or several
6275 times right after creating a new headline.
6277 - When there is a numeric prefix, go up to a heading with level ARG, do
6278 a `show-subtree' and return to the previous cursor position. If ARG
6279 is negative, go up that many levels.
6281 - When point is not at the beginning of a headline, execute the global
6282 binding for TAB, which is re-indenting the line. See the option
6283 `org-cycle-emulate-tab' for details.
6285 - Special case: if point is at the beginning of the buffer and there is
6286 no headline in line 1, this function will act as if called with prefix arg
6287 (C-u TAB, same as S-TAB) also when called without prefix arg.
6288 But only if also the variable `org-cycle-global-at-bob' is t."
6289 (interactive "P")
6290 (org-load-modules-maybe)
6291 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6292 (and org-cycle-level-after-item/entry-creation
6293 (or (org-cycle-level)
6294 (org-cycle-item-indentation))))
6295 (let* (message-log-max ; Don't populate the *Messages* buffer
6296 (limit-level
6297 (or org-cycle-max-level
6298 (and (boundp 'org-inlinetask-min-level)
6299 org-inlinetask-min-level
6300 (1- org-inlinetask-min-level))))
6301 (nstars (and limit-level
6302 (if org-odd-levels-only
6303 (and limit-level (1- (* limit-level 2)))
6304 limit-level)))
6305 (org-outline-regexp
6306 (if (not (derived-mode-p 'org-mode))
6307 outline-regexp
6308 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6309 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6310 (not (looking-at org-outline-regexp))))
6311 (org-cycle-hook
6312 (if bob-special
6313 (delq 'org-optimize-window-after-visibility-change
6314 (copy-sequence org-cycle-hook))
6315 org-cycle-hook))
6316 (pos (point)))
6318 (if (or bob-special (equal arg '(4)))
6319 ;; special case: use global cycling
6320 (setq arg t))
6322 (cond
6324 ((equal arg '(16))
6325 (setq last-command 'dummy)
6326 (org-set-startup-visibility)
6327 (message "Startup visibility, plus VISIBILITY properties"))
6329 ((equal arg '(64))
6330 (show-all)
6331 (message "Entire buffer visible, including drawers"))
6333 ;; Table: enter it or move to the next field.
6334 ((org-at-table-p 'any)
6335 (if (org-at-table.el-p)
6336 (message "Use C-c ' to edit table.el tables")
6337 (if arg (org-table-edit-field t)
6338 (org-table-justify-field-maybe)
6339 (call-interactively 'org-table-next-field))))
6341 ((run-hook-with-args-until-success
6342 'org-tab-after-check-for-table-hook))
6344 ;; Global cycling: delegate to `org-cycle-internal-global'.
6345 ((eq arg t) (org-cycle-internal-global))
6347 ;; Drawers: delegate to `org-flag-drawer'.
6348 ((and org-drawers org-drawer-regexp
6349 (save-excursion
6350 (beginning-of-line 1)
6351 (looking-at org-drawer-regexp)))
6352 (org-flag-drawer ; toggle block visibility
6353 (not (get-char-property (match-end 0) 'invisible))))
6355 ;; Show-subtree, ARG levels up from here.
6356 ((integerp arg)
6357 (save-excursion
6358 (org-back-to-heading)
6359 (outline-up-heading (if (< arg 0) (- arg)
6360 (- (funcall outline-level) arg)))
6361 (org-show-subtree)))
6363 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6364 ((and (featurep 'org-inlinetask)
6365 (org-inlinetask-at-task-p)
6366 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6367 (org-inlinetask-toggle-visibility))
6369 ((org-try-cdlatex-tab))
6371 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6372 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6373 (save-excursion (beginning-of-line 1)
6374 (looking-at org-outline-regexp)))
6375 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6376 (org-cycle-internal-local))
6378 ;; From there: TAB emulation and template completion.
6379 (buffer-read-only (org-back-to-heading))
6381 ((run-hook-with-args-until-success
6382 'org-tab-after-check-for-cycling-hook))
6384 ((org-try-structure-completion))
6386 ((run-hook-with-args-until-success
6387 'org-tab-before-tab-emulation-hook))
6389 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6390 (or (not (bolp))
6391 (not (looking-at org-outline-regexp))))
6392 (call-interactively (global-key-binding "\t")))
6394 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6395 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6396 (or (and (eq org-cycle-emulate-tab 'white)
6397 (= (match-end 0) (point-at-eol)))
6398 (and (eq org-cycle-emulate-tab 'whitestart)
6399 (>= (match-end 0) pos))))
6401 (eq org-cycle-emulate-tab t))
6402 (call-interactively (global-key-binding "\t")))
6404 (t (save-excursion
6405 (org-back-to-heading)
6406 (org-cycle)))))))
6408 (defun org-cycle-internal-global ()
6409 "Do the global cycling action."
6410 ;; Hack to avoid display of messages for .org attachments in Gnus
6411 (let (message-log-max ; Don't populate the *Messages* buffer
6412 (ga (string-match "\\*fontification" (buffer-name))))
6413 (cond
6414 ((and (eq last-command this-command)
6415 (eq org-cycle-global-status 'overview))
6416 ;; We just created the overview - now do table of contents
6417 ;; This can be slow in very large buffers, so indicate action
6418 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6419 (unless ga (message "CONTENTS..."))
6420 (org-content)
6421 (unless ga (message "CONTENTS...done"))
6422 (setq org-cycle-global-status 'contents)
6423 (run-hook-with-args 'org-cycle-hook 'contents))
6425 ((and (eq last-command this-command)
6426 (eq org-cycle-global-status 'contents))
6427 ;; We just showed the table of contents - now show everything
6428 (run-hook-with-args 'org-pre-cycle-hook 'all)
6429 (show-all)
6430 (unless ga (message "SHOW ALL"))
6431 (setq org-cycle-global-status 'all)
6432 (run-hook-with-args 'org-cycle-hook 'all))
6435 ;; Default action: go to overview
6436 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6437 (org-overview)
6438 (unless ga (message "OVERVIEW"))
6439 (setq org-cycle-global-status 'overview)
6440 (run-hook-with-args 'org-cycle-hook 'overview)))))
6442 (defun org-cycle-internal-local ()
6443 "Do the local cycling action."
6444 (let (message-log-max ; Don't populate the *Messages* buffer
6445 (goal-column 0) eoh eol eos has-children children-skipped struct)
6446 ;; First, determine end of headline (EOH), end of subtree or item
6447 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6448 (save-excursion
6449 (if (org-at-item-p)
6450 (progn
6451 (beginning-of-line)
6452 (setq struct (org-list-struct))
6453 (setq eoh (point-at-eol))
6454 (setq eos (org-list-get-item-end-before-blank (point) struct))
6455 (setq has-children (org-list-has-child-p (point) struct)))
6456 (org-back-to-heading)
6457 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6458 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6459 (setq has-children
6460 (or (save-excursion
6461 (let ((level (funcall outline-level)))
6462 (outline-next-heading)
6463 (and (org-at-heading-p t)
6464 (> (funcall outline-level) level))))
6465 (save-excursion
6466 (org-list-search-forward (org-item-beginning-re) eos t)))))
6467 ;; Determine end invisible part of buffer (EOL)
6468 (beginning-of-line 2)
6469 ;; XEmacs doesn't have `next-single-char-property-change'
6470 (if (featurep 'xemacs)
6471 (while (and (not (eobp)) ;; this is like `next-line'
6472 (get-char-property (1- (point)) 'invisible))
6473 (beginning-of-line 2))
6474 (while (and (not (eobp)) ;; this is like `next-line'
6475 (get-char-property (1- (point)) 'invisible))
6476 (goto-char (next-single-char-property-change (point) 'invisible))
6477 (and (eolp) (beginning-of-line 2))))
6478 (setq eol (point)))
6479 ;; Find out what to do next and set `this-command'
6480 (cond
6481 ((= eos eoh)
6482 ;; Nothing is hidden behind this heading
6483 (unless (org-before-first-heading-p)
6484 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6485 (message "EMPTY ENTRY")
6486 (setq org-cycle-subtree-status nil)
6487 (save-excursion
6488 (goto-char eos)
6489 (outline-next-heading)
6490 (if (outline-invisible-p) (org-flag-heading nil))))
6491 ((and (or (>= eol eos)
6492 (not (string-match "\\S-" (buffer-substring eol eos))))
6493 (or has-children
6494 (not (setq children-skipped
6495 org-cycle-skip-children-state-if-no-children))))
6496 ;; Entire subtree is hidden in one line: children view
6497 (unless (org-before-first-heading-p)
6498 (run-hook-with-args 'org-pre-cycle-hook 'children))
6499 (if (org-at-item-p)
6500 (org-list-set-item-visibility (point-at-bol) struct 'children)
6501 (org-show-entry)
6502 (org-with-limited-levels (show-children))
6503 ;; FIXME: This slows down the func way too much.
6504 ;; How keep drawers hidden in subtree anyway?
6505 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6506 ;; (org-cycle-hide-drawers 'subtree))
6508 ;; Fold every list in subtree to top-level items.
6509 (when (eq org-cycle-include-plain-lists 'integrate)
6510 (save-excursion
6511 (org-back-to-heading)
6512 (while (org-list-search-forward (org-item-beginning-re) eos t)
6513 (beginning-of-line 1)
6514 (let* ((struct (org-list-struct))
6515 (prevs (org-list-prevs-alist struct))
6516 (end (org-list-get-bottom-point struct)))
6517 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6518 (org-list-get-all-items (point) struct prevs))
6519 (goto-char end))))))
6520 (message "CHILDREN")
6521 (save-excursion
6522 (goto-char eos)
6523 (outline-next-heading)
6524 (if (outline-invisible-p) (org-flag-heading nil)))
6525 (setq org-cycle-subtree-status 'children)
6526 (unless (org-before-first-heading-p)
6527 (run-hook-with-args 'org-cycle-hook 'children)))
6528 ((or children-skipped
6529 (and (eq last-command this-command)
6530 (eq org-cycle-subtree-status 'children)))
6531 ;; We just showed the children, or no children are there,
6532 ;; now show everything.
6533 (unless (org-before-first-heading-p)
6534 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6535 (outline-flag-region eoh eos nil)
6536 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6537 (setq org-cycle-subtree-status 'subtree)
6538 (unless (org-before-first-heading-p)
6539 (run-hook-with-args 'org-cycle-hook 'subtree)))
6541 ;; Default action: hide the subtree.
6542 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6543 (outline-flag-region eoh eos t)
6544 (message "FOLDED")
6545 (setq org-cycle-subtree-status 'folded)
6546 (unless (org-before-first-heading-p)
6547 (run-hook-with-args 'org-cycle-hook 'folded))))))
6549 ;;;###autoload
6550 (defun org-global-cycle (&optional arg)
6551 "Cycle the global visibility. For details see `org-cycle'.
6552 With \\[universal-argument] prefix arg, switch to startup visibility.
6553 With a numeric prefix, show all headlines up to that level."
6554 (interactive "P")
6555 (let ((org-cycle-include-plain-lists
6556 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6557 (cond
6558 ((integerp arg)
6559 (show-all)
6560 (hide-sublevels arg)
6561 (setq org-cycle-global-status 'contents))
6562 ((equal arg '(4))
6563 (org-set-startup-visibility)
6564 (message "Startup visibility, plus VISIBILITY properties."))
6566 (org-cycle '(4))))))
6568 (defun org-set-startup-visibility ()
6569 "Set the visibility required by startup options and properties."
6570 (cond
6571 ((eq org-startup-folded t)
6572 (org-cycle '(4)))
6573 ((eq org-startup-folded 'content)
6574 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6575 (org-cycle '(4)) (org-cycle '(4)))))
6576 (unless (eq org-startup-folded 'showeverything)
6577 (if org-hide-block-startup (org-hide-block-all))
6578 (org-set-visibility-according-to-property 'no-cleanup)
6579 (org-cycle-hide-archived-subtrees 'all)
6580 (org-cycle-hide-drawers 'all)
6581 (org-cycle-show-empty-lines t)))
6583 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6584 "Switch subtree visibilities according to :VISIBILITY: property."
6585 (interactive)
6586 (let (org-show-entry-below state)
6587 (save-excursion
6588 (goto-char (point-min))
6589 (while (re-search-forward
6590 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6591 nil t)
6592 (setq state (match-string 1))
6593 (save-excursion
6594 (org-back-to-heading t)
6595 (hide-subtree)
6596 (org-reveal)
6597 (cond
6598 ((equal state '("fold" "folded"))
6599 (hide-subtree))
6600 ((equal state "children")
6601 (org-show-hidden-entry)
6602 (show-children))
6603 ((equal state "content")
6604 (save-excursion
6605 (save-restriction
6606 (org-narrow-to-subtree)
6607 (org-content))))
6608 ((member state '("all" "showall"))
6609 (show-subtree)))))
6610 (unless no-cleanup
6611 (org-cycle-hide-archived-subtrees 'all)
6612 (org-cycle-hide-drawers 'all)
6613 (org-cycle-show-empty-lines 'all)))))
6615 ;; This function uses outline-regexp instead of the more fundamental
6616 ;; org-outline-regexp so that org-cycle-global works outside of Org
6617 ;; buffers, where outline-regexp is needed.
6618 (defun org-overview ()
6619 "Switch to overview mode, showing only top-level headlines.
6620 Really, this shows all headlines with level equal or greater than the level
6621 of the first headline in the buffer. This is important, because if the
6622 first headline is not level one, then (hide-sublevels 1) gives confusing
6623 results."
6624 (interactive)
6625 (let ((level (save-excursion
6626 (goto-char (point-min))
6627 (if (re-search-forward (concat "^" outline-regexp) nil t)
6628 (progn
6629 (goto-char (match-beginning 0))
6630 (funcall outline-level))))))
6631 (and level (hide-sublevels level))))
6633 (defun org-content (&optional arg)
6634 "Show all headlines in the buffer, like a table of contents.
6635 With numerical argument N, show content up to level N."
6636 (interactive "P")
6637 (save-excursion
6638 ;; Visit all headings and show their offspring
6639 (and (integerp arg) (org-overview))
6640 (goto-char (point-max))
6641 (catch 'exit
6642 (while (and (progn (condition-case nil
6643 (outline-previous-visible-heading 1)
6644 (error (goto-char (point-min))))
6646 (looking-at org-outline-regexp))
6647 (if (integerp arg)
6648 (show-children (1- arg))
6649 (show-branches))
6650 (if (bobp) (throw 'exit nil))))))
6653 (defun org-optimize-window-after-visibility-change (state)
6654 "Adjust the window after a change in outline visibility.
6655 This function is the default value of the hook `org-cycle-hook'."
6656 (when (get-buffer-window (current-buffer))
6657 (cond
6658 ((eq state 'content) nil)
6659 ((eq state 'all) nil)
6660 ((eq state 'folded) nil)
6661 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6662 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6664 (defun org-remove-empty-overlays-at (pos)
6665 "Remove outline overlays that do not contain non-white stuff."
6666 (mapc
6667 (lambda (o)
6668 (and (eq 'outline (overlay-get o 'invisible))
6669 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6670 (overlay-end o))))
6671 (delete-overlay o)))
6672 (overlays-at pos)))
6674 (defun org-clean-visibility-after-subtree-move ()
6675 "Fix visibility issues after moving a subtree."
6676 ;; First, find a reasonable region to look at:
6677 ;; Start two siblings above, end three below
6678 (let* ((beg (save-excursion
6679 (and (org-get-last-sibling)
6680 (org-get-last-sibling))
6681 (point)))
6682 (end (save-excursion
6683 (and (org-get-next-sibling)
6684 (org-get-next-sibling)
6685 (org-get-next-sibling))
6686 (if (org-at-heading-p)
6687 (point-at-eol)
6688 (point))))
6689 (level (looking-at "\\*+"))
6690 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6691 (save-excursion
6692 (save-restriction
6693 (narrow-to-region beg end)
6694 (when re
6695 ;; Properly fold already folded siblings
6696 (goto-char (point-min))
6697 (while (re-search-forward re nil t)
6698 (if (and (not (outline-invisible-p))
6699 (save-excursion
6700 (goto-char (point-at-eol)) (outline-invisible-p)))
6701 (hide-entry))))
6702 (org-cycle-show-empty-lines 'overview)
6703 (org-cycle-hide-drawers 'overview)))))
6705 (defun org-cycle-show-empty-lines (state)
6706 "Show empty lines above all visible headlines.
6707 The region to be covered depends on STATE when called through
6708 `org-cycle-hook'. Lisp program can use t for STATE to get the
6709 entire buffer covered. Note that an empty line is only shown if there
6710 are at least `org-cycle-separator-lines' empty lines before the headline."
6711 (when (not (= org-cycle-separator-lines 0))
6712 (save-excursion
6713 (let* ((n (abs org-cycle-separator-lines))
6714 (re (cond
6715 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6716 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6717 (t (let ((ns (number-to-string (- n 2))))
6718 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6719 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6720 beg end b e)
6721 (cond
6722 ((memq state '(overview contents t))
6723 (setq beg (point-min) end (point-max)))
6724 ((memq state '(children folded))
6725 (setq beg (point) end (progn (org-end-of-subtree t t)
6726 (beginning-of-line 2)
6727 (point)))))
6728 (when beg
6729 (goto-char beg)
6730 (while (re-search-forward re end t)
6731 (unless (get-char-property (match-end 1) 'invisible)
6732 (setq e (match-end 1))
6733 (if (< org-cycle-separator-lines 0)
6734 (setq b (save-excursion
6735 (goto-char (match-beginning 0))
6736 (org-back-over-empty-lines)
6737 (if (save-excursion
6738 (goto-char (max (point-min) (1- (point))))
6739 (org-at-heading-p))
6740 (1- (point))
6741 (point))))
6742 (setq b (match-beginning 1)))
6743 (outline-flag-region b e nil)))))))
6744 ;; Never hide empty lines at the end of the file.
6745 (save-excursion
6746 (goto-char (point-max))
6747 (outline-previous-heading)
6748 (outline-end-of-heading)
6749 (if (and (looking-at "[ \t\n]+")
6750 (= (match-end 0) (point-max)))
6751 (outline-flag-region (point) (match-end 0) nil))))
6753 (defun org-show-empty-lines-in-parent ()
6754 "Move to the parent and re-show empty lines before visible headlines."
6755 (save-excursion
6756 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6757 (org-cycle-show-empty-lines context))))
6759 (defun org-files-list ()
6760 "Return `org-agenda-files' list, plus all open org-mode files.
6761 This is useful for operations that need to scan all of a user's
6762 open and agenda-wise Org files."
6763 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6764 (dolist (buf (buffer-list))
6765 (with-current-buffer buf
6766 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6767 (let ((file (expand-file-name (buffer-file-name))))
6768 (unless (member file files)
6769 (push file files))))))
6770 files))
6772 (defsubst org-entry-beginning-position ()
6773 "Return the beginning position of the current entry."
6774 (save-excursion (outline-back-to-heading t) (point)))
6776 (defsubst org-entry-end-position ()
6777 "Return the end position of the current entry."
6778 (save-excursion (outline-next-heading) (point)))
6780 (defun org-cycle-hide-drawers (state)
6781 "Re-hide all drawers after a visibility state change."
6782 (when (and (derived-mode-p 'org-mode)
6783 (not (memq state '(overview folded contents))))
6784 (save-excursion
6785 (let* ((globalp (memq state '(contents all)))
6786 (beg (if globalp (point-min) (point)))
6787 (end (if globalp (point-max)
6788 (if (eq state 'children)
6789 (save-excursion (outline-next-heading) (point))
6790 (org-end-of-subtree t)))))
6791 (goto-char beg)
6792 (while (re-search-forward org-drawer-regexp end t)
6793 (org-flag-drawer t))))))
6795 (defun org-cycle-hide-inline-tasks (state)
6796 "Re-hide inline task when switching to 'contents visibility state."
6797 (when (and (eq state 'contents)
6798 (boundp 'org-inlinetask-min-level)
6799 org-inlinetask-min-level)
6800 (hide-sublevels (1- org-inlinetask-min-level))))
6802 (defun org-flag-drawer (flag)
6803 "When FLAG is non-nil, hide the drawer we are within.
6804 Otherwise make it visible."
6805 (save-excursion
6806 (beginning-of-line 1)
6807 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6808 (let ((b (match-end 0)))
6809 (if (re-search-forward
6810 "^[ \t]*:END:"
6811 (save-excursion (outline-next-heading) (point)) t)
6812 (outline-flag-region b (point-at-eol) flag)
6813 (error ":END: line missing at position %s" b))))))
6815 (defun org-subtree-end-visible-p ()
6816 "Is the end of the current subtree visible?"
6817 (pos-visible-in-window-p
6818 (save-excursion (org-end-of-subtree t) (point))))
6820 (defun org-first-headline-recenter (&optional N)
6821 "Move cursor to the first headline and recenter the headline.
6822 Optional argument N means put the headline into the Nth line of the window."
6823 (goto-char (point-min))
6824 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6825 (beginning-of-line)
6826 (recenter (prefix-numeric-value N))))
6828 ;;; Saving and restoring visibility
6830 (defun org-outline-overlay-data (&optional use-markers)
6831 "Return a list of the locations of all outline overlays.
6832 These are overlays with the `invisible' property value `outline'.
6833 The return value is a list of cons cells, with start and stop
6834 positions for each overlay.
6835 If USE-MARKERS is set, return the positions as markers."
6836 (let (beg end)
6837 (save-excursion
6838 (save-restriction
6839 (widen)
6840 (delq nil
6841 (mapcar (lambda (o)
6842 (when (eq (overlay-get o 'invisible) 'outline)
6843 (setq beg (overlay-start o)
6844 end (overlay-end o))
6845 (and beg end (> end beg)
6846 (if use-markers
6847 (cons (move-marker (make-marker) beg)
6848 (move-marker (make-marker) end))
6849 (cons beg end)))))
6850 (overlays-in (point-min) (point-max))))))))
6852 (defun org-set-outline-overlay-data (data)
6853 "Create visibility overlays for all positions in DATA.
6854 DATA should have been made by `org-outline-overlay-data'."
6855 (let (o)
6856 (save-excursion
6857 (save-restriction
6858 (widen)
6859 (show-all)
6860 (mapc (lambda (c)
6861 (outline-flag-region (car c) (cdr c) t))
6862 data)))))
6864 ;;; Folding of blocks
6866 (defvar org-hide-block-overlays nil
6867 "Overlays hiding blocks.")
6868 (make-variable-buffer-local 'org-hide-block-overlays)
6870 (defun org-block-map (function &optional start end)
6871 "Call FUNCTION at the head of all source blocks in the current buffer.
6872 Optional arguments START and END can be used to limit the range."
6873 (let ((start (or start (point-min)))
6874 (end (or end (point-max))))
6875 (save-excursion
6876 (goto-char start)
6877 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6878 (save-excursion
6879 (save-match-data
6880 (goto-char (match-beginning 0))
6881 (funcall function)))))))
6883 (defun org-hide-block-toggle-all ()
6884 "Toggle the visibility of all blocks in the current buffer."
6885 (org-block-map #'org-hide-block-toggle))
6887 (defun org-hide-block-all ()
6888 "Fold all blocks in the current buffer."
6889 (interactive)
6890 (org-show-block-all)
6891 (org-block-map #'org-hide-block-toggle-maybe))
6893 (defun org-show-block-all ()
6894 "Unfold all blocks in the current buffer."
6895 (interactive)
6896 (mapc 'delete-overlay org-hide-block-overlays)
6897 (setq org-hide-block-overlays nil))
6899 (defun org-hide-block-toggle-maybe ()
6900 "Toggle visibility of block at point."
6901 (interactive)
6902 (let ((case-fold-search t))
6903 (if (save-excursion
6904 (beginning-of-line 1)
6905 (looking-at org-block-regexp))
6906 (progn (org-hide-block-toggle)
6907 t) ;; to signal that we took action
6908 nil))) ;; to signal that we did not
6910 (defun org-hide-block-toggle (&optional force)
6911 "Toggle the visibility of the current block."
6912 (interactive)
6913 (save-excursion
6914 (beginning-of-line)
6915 (if (re-search-forward org-block-regexp nil t)
6916 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6917 (end (match-end 0)) ;; end of entire body
6919 (if (memq t (mapcar (lambda (overlay)
6920 (eq (overlay-get overlay 'invisible)
6921 'org-hide-block))
6922 (overlays-at start)))
6923 (if (or (not force) (eq force 'off))
6924 (mapc (lambda (ov)
6925 (when (member ov org-hide-block-overlays)
6926 (setq org-hide-block-overlays
6927 (delq ov org-hide-block-overlays)))
6928 (when (eq (overlay-get ov 'invisible)
6929 'org-hide-block)
6930 (delete-overlay ov)))
6931 (overlays-at start)))
6932 (setq ov (make-overlay start end))
6933 (overlay-put ov 'invisible 'org-hide-block)
6934 ;; make the block accessible to isearch
6935 (overlay-put
6936 ov 'isearch-open-invisible
6937 (lambda (ov)
6938 (when (member ov org-hide-block-overlays)
6939 (setq org-hide-block-overlays
6940 (delq ov org-hide-block-overlays)))
6941 (when (eq (overlay-get ov 'invisible)
6942 'org-hide-block)
6943 (delete-overlay ov))))
6944 (push ov org-hide-block-overlays)))
6945 (error "Not looking at a source block"))))
6947 ;; org-tab-after-check-for-cycling-hook
6948 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6949 ;; Remove overlays when changing major mode
6950 (add-hook 'org-mode-hook
6951 (lambda () (org-add-hook 'change-major-mode-hook
6952 'org-show-block-all 'append 'local)))
6954 ;;; Org-goto
6956 (defvar org-goto-window-configuration nil)
6957 (defvar org-goto-marker nil)
6958 (defvar org-goto-map)
6959 (defun org-goto-map ()
6960 "Set the keymap `org-goto'."
6961 (setq org-goto-map
6962 (let ((map (make-sparse-keymap)))
6963 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6964 mouse-drag-region universal-argument org-occur))
6965 cmd)
6966 (while (setq cmd (pop cmds))
6967 (substitute-key-definition cmd cmd map global-map)))
6968 (suppress-keymap map)
6969 (org-defkey map "\C-m" 'org-goto-ret)
6970 (org-defkey map [(return)] 'org-goto-ret)
6971 (org-defkey map [(left)] 'org-goto-left)
6972 (org-defkey map [(right)] 'org-goto-right)
6973 (org-defkey map [(control ?g)] 'org-goto-quit)
6974 (org-defkey map "\C-i" 'org-cycle)
6975 (org-defkey map [(tab)] 'org-cycle)
6976 (org-defkey map [(down)] 'outline-next-visible-heading)
6977 (org-defkey map [(up)] 'outline-previous-visible-heading)
6978 (if org-goto-auto-isearch
6979 (if (fboundp 'define-key-after)
6980 (define-key-after map [t] 'org-goto-local-auto-isearch)
6981 nil)
6982 (org-defkey map "q" 'org-goto-quit)
6983 (org-defkey map "n" 'outline-next-visible-heading)
6984 (org-defkey map "p" 'outline-previous-visible-heading)
6985 (org-defkey map "f" 'outline-forward-same-level)
6986 (org-defkey map "b" 'outline-backward-same-level)
6987 (org-defkey map "u" 'outline-up-heading))
6988 (org-defkey map "/" 'org-occur)
6989 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6990 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6991 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6992 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6993 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6994 map)))
6996 (defconst org-goto-help
6997 "Browse buffer copy, to find location or copy text.%s
6998 RET=jump to location C-g=quit and return to previous location
6999 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7001 (defvar org-goto-start-pos) ; dynamically scoped parameter
7003 ;; FIXME: Docstring does not mention both interfaces
7004 (defun org-goto (&optional alternative-interface)
7005 "Look up a different location in the current file, keeping current visibility.
7007 When you want look-up or go to a different location in a
7008 document, the fastest way is often to fold the entire buffer and
7009 then dive into the tree. This method has the disadvantage, that
7010 the previous location will be folded, which may not be what you
7011 want.
7013 This command works around this by showing a copy of the current
7014 buffer in an indirect buffer, in overview mode. You can dive
7015 into the tree in that copy, use org-occur and incremental search
7016 to find a location. When pressing RET or `Q', the command
7017 returns to the original buffer in which the visibility is still
7018 unchanged. After RET it will also jump to the location selected
7019 in the indirect buffer and expose the headline hierarchy above.
7021 With a prefix argument, use the alternative interface: e.g. if
7022 `org-goto-interface' is 'outline use 'outline-path-completion."
7023 (interactive "P")
7024 (org-goto-map)
7025 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7026 (org-refile-use-outline-path t)
7027 (org-refile-target-verify-function nil)
7028 (interface
7029 (if (not alternative-interface)
7030 org-goto-interface
7031 (if (eq org-goto-interface 'outline)
7032 'outline-path-completion
7033 'outline)))
7034 (org-goto-start-pos (point))
7035 (selected-point
7036 (if (eq interface 'outline)
7037 (car (org-get-location (current-buffer) org-goto-help))
7038 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7039 (org-refile-check-position pa)
7040 (nth 3 pa)))))
7041 (if selected-point
7042 (progn
7043 (org-mark-ring-push org-goto-start-pos)
7044 (goto-char selected-point)
7045 (if (or (outline-invisible-p) (org-invisible-p2))
7046 (org-show-context 'org-goto)))
7047 (message "Quit"))))
7049 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7050 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7051 (defvar org-goto-local-auto-isearch-map) ; defined below
7053 (defun org-get-location (buf help)
7054 "Let the user select a location in the Org-mode buffer BUF.
7055 This function uses a recursive edit. It returns the selected position
7056 or nil."
7057 (org-no-popups
7058 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7059 (isearch-hide-immediately nil)
7060 (isearch-search-fun-function
7061 (lambda () 'org-goto-local-search-headings))
7062 (org-goto-selected-point org-goto-exit-command))
7063 (save-excursion
7064 (save-window-excursion
7065 (delete-other-windows)
7066 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7067 (org-pop-to-buffer-same-window
7068 (condition-case nil
7069 (make-indirect-buffer (current-buffer) "*org-goto*")
7070 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7071 (with-output-to-temp-buffer "*Org Help*"
7072 (princ (format help (if org-goto-auto-isearch
7073 " Just type for auto-isearch."
7074 " n/p/f/b/u to navigate, q to quit."))))
7075 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7076 (setq buffer-read-only nil)
7077 (let ((org-startup-truncated t)
7078 (org-startup-folded nil)
7079 (org-startup-align-all-tables nil))
7080 (org-mode)
7081 (org-overview))
7082 (setq buffer-read-only t)
7083 (if (and (boundp 'org-goto-start-pos)
7084 (integer-or-marker-p org-goto-start-pos))
7085 (let ((org-show-hierarchy-above t)
7086 (org-show-siblings t)
7087 (org-show-following-heading t))
7088 (goto-char org-goto-start-pos)
7089 (and (outline-invisible-p) (org-show-context)))
7090 (goto-char (point-min)))
7091 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7092 (message "Select location and press RET")
7093 (use-local-map org-goto-map)
7094 (recursive-edit)))
7095 (kill-buffer "*org-goto*")
7096 (cons org-goto-selected-point org-goto-exit-command))))
7098 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7099 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7100 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7101 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7103 (defun org-goto-local-search-headings (string bound noerror)
7104 "Search and make sure that any matches are in headlines."
7105 (catch 'return
7106 (while (if isearch-forward
7107 (search-forward string bound noerror)
7108 (search-backward string bound noerror))
7109 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7110 (and (member :headline context)
7111 (not (member :tags context))))
7112 (throw 'return (point))))))
7114 (defun org-goto-local-auto-isearch ()
7115 "Start isearch."
7116 (interactive)
7117 (goto-char (point-min))
7118 (let ((keys (this-command-keys)))
7119 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7120 (isearch-mode t)
7121 (isearch-process-search-char (string-to-char keys)))))
7123 (defun org-goto-ret (&optional arg)
7124 "Finish `org-goto' by going to the new location."
7125 (interactive "P")
7126 (setq org-goto-selected-point (point)
7127 org-goto-exit-command 'return)
7128 (throw 'exit nil))
7130 (defun org-goto-left ()
7131 "Finish `org-goto' by going to the new location."
7132 (interactive)
7133 (if (org-at-heading-p)
7134 (progn
7135 (beginning-of-line 1)
7136 (setq org-goto-selected-point (point)
7137 org-goto-exit-command 'left)
7138 (throw 'exit nil))
7139 (error "Not on a heading")))
7141 (defun org-goto-right ()
7142 "Finish `org-goto' by going to the new location."
7143 (interactive)
7144 (if (org-at-heading-p)
7145 (progn
7146 (setq org-goto-selected-point (point)
7147 org-goto-exit-command 'right)
7148 (throw 'exit nil))
7149 (error "Not on a heading")))
7151 (defun org-goto-quit ()
7152 "Finish `org-goto' without cursor motion."
7153 (interactive)
7154 (setq org-goto-selected-point nil)
7155 (setq org-goto-exit-command 'quit)
7156 (throw 'exit nil))
7158 ;;; Indirect buffer display of subtrees
7160 (defvar org-indirect-dedicated-frame nil
7161 "This is the frame being used for indirect tree display.")
7162 (defvar org-last-indirect-buffer nil)
7164 (defun org-tree-to-indirect-buffer (&optional arg)
7165 "Create indirect buffer and narrow it to current subtree.
7166 With a numerical prefix ARG, go up to this level and then take that tree.
7167 If ARG is negative, go up that many levels.
7169 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7170 indirect buffer previously made with this command, to avoid proliferation of
7171 indirect buffers. However, when you call the command with a \
7172 \\[universal-argument] prefix, or
7173 when `org-indirect-buffer-display' is `new-frame', the last buffer
7174 is kept so that you can work with several indirect buffers at the same time.
7175 If `org-indirect-buffer-display' is `dedicated-frame', the \
7176 \\[universal-argument] prefix also
7177 requests that a new frame be made for the new buffer, so that the dedicated
7178 frame is not changed."
7179 (interactive "P")
7180 (let ((cbuf (current-buffer))
7181 (cwin (selected-window))
7182 (pos (point))
7183 beg end level heading ibuf)
7184 (save-excursion
7185 (org-back-to-heading t)
7186 (when (numberp arg)
7187 (setq level (org-outline-level))
7188 (if (< arg 0) (setq arg (+ level arg)))
7189 (while (> (setq level (org-outline-level)) arg)
7190 (org-up-heading-safe)))
7191 (setq beg (point)
7192 heading (org-get-heading))
7193 (org-end-of-subtree t t)
7194 (if (org-at-heading-p) (backward-char 1))
7195 (setq end (point)))
7196 (if (and (buffer-live-p org-last-indirect-buffer)
7197 (not (eq org-indirect-buffer-display 'new-frame))
7198 (not arg))
7199 (kill-buffer org-last-indirect-buffer))
7200 (setq ibuf (org-get-indirect-buffer cbuf)
7201 org-last-indirect-buffer ibuf)
7202 (cond
7203 ((or (eq org-indirect-buffer-display 'new-frame)
7204 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7205 (select-frame (make-frame))
7206 (delete-other-windows)
7207 (org-pop-to-buffer-same-window ibuf)
7208 (org-set-frame-title heading))
7209 ((eq org-indirect-buffer-display 'dedicated-frame)
7210 (raise-frame
7211 (select-frame (or (and org-indirect-dedicated-frame
7212 (frame-live-p org-indirect-dedicated-frame)
7213 org-indirect-dedicated-frame)
7214 (setq org-indirect-dedicated-frame (make-frame)))))
7215 (delete-other-windows)
7216 (org-pop-to-buffer-same-window ibuf)
7217 (org-set-frame-title (concat "Indirect: " heading)))
7218 ((eq org-indirect-buffer-display 'current-window)
7219 (org-pop-to-buffer-same-window ibuf))
7220 ((eq org-indirect-buffer-display 'other-window)
7221 (pop-to-buffer ibuf))
7222 (t (error "Invalid value")))
7223 (if (featurep 'xemacs)
7224 (save-excursion (org-mode) (turn-on-font-lock)))
7225 (narrow-to-region beg end)
7226 (show-all)
7227 (goto-char pos)
7228 (run-hook-with-args 'org-cycle-hook 'all)
7229 (and (window-live-p cwin) (select-window cwin))))
7231 (defun org-get-indirect-buffer (&optional buffer)
7232 (setq buffer (or buffer (current-buffer)))
7233 (let ((n 1) (base (buffer-name buffer)) bname)
7234 (while (buffer-live-p
7235 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7236 (setq n (1+ n)))
7237 (condition-case nil
7238 (make-indirect-buffer buffer bname 'clone)
7239 (error (make-indirect-buffer buffer bname)))))
7241 (defun org-set-frame-title (title)
7242 "Set the title of the current frame to the string TITLE."
7243 ;; FIXME: how to name a single frame in XEmacs???
7244 (unless (featurep 'xemacs)
7245 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7247 ;;;; Structure editing
7249 ;;; Inserting headlines
7251 (defun org-previous-line-empty-p ()
7252 (save-excursion
7253 (and (not (bobp))
7254 (or (beginning-of-line 0) t)
7255 (save-match-data
7256 (looking-at "[ \t]*$")))))
7258 (defun org-insert-heading (&optional force-heading invisible-ok)
7259 "Insert a new heading or item with same depth at point.
7260 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7261 If point is at the beginning of a headline, insert a sibling before the
7262 current headline. If point is not at the beginning, split the line,
7263 create the new headline with the text in the current line after point
7264 \(but see also the variable `org-M-RET-may-split-line').
7266 With a double prefix arg, force the heading to be inserted at the
7267 end of the parent subtree.
7269 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7270 This is important for non-interactive uses of the command."
7271 (interactive "P")
7272 (if (or (= (buffer-size) 0)
7273 (and (not (save-excursion
7274 (and (ignore-errors (org-back-to-heading invisible-ok))
7275 (org-at-heading-p))))
7276 (or force-heading (not (org-in-item-p)))))
7277 (progn
7278 (insert "\n* ")
7279 (run-hooks 'org-insert-heading-hook))
7280 (when (or force-heading (not (org-insert-item)))
7281 (let* ((empty-line-p nil)
7282 (level nil)
7283 (on-heading (org-at-heading-p))
7284 (head (save-excursion
7285 (condition-case nil
7286 (progn
7287 (org-back-to-heading invisible-ok)
7288 (when (and (not on-heading)
7289 (featurep 'org-inlinetask)
7290 (integerp org-inlinetask-min-level)
7291 (>= (length (match-string 0))
7292 org-inlinetask-min-level))
7293 ;; Find a heading level before the inline task
7294 (while (and (setq level (org-up-heading-safe))
7295 (>= level org-inlinetask-min-level)))
7296 (if (org-at-heading-p)
7297 (org-back-to-heading invisible-ok)
7298 (error "This should not happen")))
7299 (setq empty-line-p (org-previous-line-empty-p))
7300 (match-string 0))
7301 (error "*"))))
7302 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7303 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7304 pos hide-previous previous-pos)
7305 (cond
7306 ((and (org-at-heading-p) (bolp)
7307 (or (bobp)
7308 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7309 ;; insert before the current line
7310 (open-line (if blank 2 1)))
7311 ((and (bolp)
7312 (not org-insert-heading-respect-content)
7313 (or (bobp)
7314 (save-excursion
7315 (backward-char 1) (not (outline-invisible-p)))))
7316 ;; insert right here
7317 nil)
7319 ;; somewhere in the line
7320 (save-excursion
7321 (setq previous-pos (point-at-bol))
7322 (end-of-line)
7323 (setq hide-previous (outline-invisible-p)))
7324 (and org-insert-heading-respect-content (org-show-subtree))
7325 (let ((split
7326 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7327 (save-excursion
7328 (let ((p (point)))
7329 (goto-char (point-at-bol))
7330 (and (looking-at org-complex-heading-regexp)
7331 (match-beginning 4)
7332 (> p (match-beginning 4)))))))
7333 tags pos)
7334 (cond
7335 (org-insert-heading-respect-content
7336 (if (not (equal force-heading '(16)))
7337 (org-end-of-subtree nil t)
7338 (org-up-heading-safe)
7339 (org-end-of-subtree nil t))
7340 (when (featurep 'org-inlinetask)
7341 (while (and (not (eobp))
7342 (looking-at "\\(\\*+\\)[ \t]+")
7343 (>= (length (match-string 1))
7344 org-inlinetask-min-level))
7345 (org-end-of-subtree nil t)))
7346 (or (bolp) (newline))
7347 (or (org-previous-line-empty-p)
7348 (and blank (newline)))
7349 (open-line 1))
7350 ((org-at-heading-p)
7351 (when hide-previous
7352 (show-children)
7353 (org-show-entry))
7354 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7355 (setq tags (and (match-end 2) (match-string 2)))
7356 (and (match-end 1)
7357 (delete-region (match-beginning 1) (match-end 1)))
7358 (setq pos (point-at-bol))
7359 (or split (end-of-line 1))
7360 (delete-horizontal-space)
7361 (if (string-match "\\`\\*+\\'"
7362 (buffer-substring (point-at-bol) (point)))
7363 (insert " "))
7364 (newline (if blank 2 1))
7365 (when tags
7366 (save-excursion
7367 (goto-char pos)
7368 (end-of-line 1)
7369 (insert " " tags)
7370 (org-set-tags nil 'align))))
7372 (or split (end-of-line 1))
7373 (newline (if blank 2 1)))))))
7374 (insert head) (just-one-space)
7375 (setq pos (point))
7376 (end-of-line 1)
7377 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7378 (when (and org-insert-heading-respect-content hide-previous)
7379 (save-excursion
7380 (goto-char previous-pos)
7381 (hide-subtree)))
7382 (run-hooks 'org-insert-heading-hook)))))
7384 (defun org-get-heading (&optional no-tags no-todo)
7385 "Return the heading of the current entry, without the stars.
7386 When NO-TAGS is non-nil, don't include tags.
7387 When NO-TODO is non-nil, don't include TODO keywords."
7388 (save-excursion
7389 (org-back-to-heading t)
7390 (cond
7391 ((and no-tags no-todo)
7392 (looking-at org-complex-heading-regexp)
7393 (match-string 4))
7394 (no-tags
7395 (looking-at (concat org-outline-regexp
7396 "\\(.*?\\)"
7397 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7398 (match-string 1))
7399 (no-todo
7400 (looking-at org-todo-line-regexp)
7401 (match-string 3))
7402 (t (looking-at org-heading-regexp)
7403 (match-string 2)))))
7405 (defun org-heading-components ()
7406 "Return the components of the current heading.
7407 This is a list with the following elements:
7408 - the level as an integer
7409 - the reduced level, different if `org-odd-levels-only' is set.
7410 - the TODO keyword, or nil
7411 - the priority character, like ?A, or nil if no priority is given
7412 - the headline text itself, or the tags string if no headline text
7413 - the tags string, or nil."
7414 (save-excursion
7415 (org-back-to-heading t)
7416 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7417 (list (length (match-string 1))
7418 (org-reduced-level (length (match-string 1)))
7419 (org-match-string-no-properties 2)
7420 (and (match-end 3) (aref (match-string 3) 2))
7421 (org-match-string-no-properties 4)
7422 (org-match-string-no-properties 5)))))
7424 (defun org-get-entry ()
7425 "Get the entry text, after heading, entire subtree."
7426 (save-excursion
7427 (org-back-to-heading t)
7428 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7430 (defun org-insert-heading-after-current ()
7431 "Insert a new heading with same level as current, after current subtree."
7432 (interactive)
7433 (org-back-to-heading)
7434 (org-insert-heading)
7435 (org-move-subtree-down)
7436 (end-of-line 1))
7438 (defun org-insert-heading-respect-content ()
7439 (interactive)
7440 (let ((org-insert-heading-respect-content t))
7441 (org-insert-heading t)))
7443 (defun org-insert-todo-heading-respect-content (&optional force-state)
7444 (interactive "P")
7445 (let ((org-insert-heading-respect-content t))
7446 (org-insert-todo-heading force-state t)))
7448 (defun org-insert-todo-heading (arg &optional force-heading)
7449 "Insert a new heading with the same level and TODO state as current heading.
7450 If the heading has no TODO state, or if the state is DONE, use the first
7451 state (TODO by default). Also one prefix arg, force first state. With two
7452 prefix args, force inserting at the end of the parent subtree."
7453 (interactive "P")
7454 (when (or force-heading (not (org-insert-item 'checkbox)))
7455 (org-insert-heading (or (and (equal arg '(16)) '(16))
7456 force-heading))
7457 (save-excursion
7458 (org-back-to-heading)
7459 (outline-previous-heading)
7460 (looking-at org-todo-line-regexp))
7461 (let*
7462 ((new-mark-x
7463 (if (or arg
7464 (not (match-beginning 2))
7465 (member (match-string 2) org-done-keywords))
7466 (car org-todo-keywords-1)
7467 (match-string 2)))
7468 (new-mark
7470 (run-hook-with-args-until-success
7471 'org-todo-get-default-hook new-mark-x nil)
7472 new-mark-x)))
7473 (beginning-of-line 1)
7474 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7475 (if org-treat-insert-todo-heading-as-state-change
7476 (org-todo new-mark)
7477 (insert new-mark " "))))
7478 (when org-provide-todo-statistics
7479 (org-update-parent-todo-statistics))))
7481 (defun org-insert-subheading (arg)
7482 "Insert a new subheading and demote it.
7483 Works for outline headings and for plain lists alike."
7484 (interactive "P")
7485 (org-insert-heading arg)
7486 (cond
7487 ((org-at-heading-p) (org-do-demote))
7488 ((org-at-item-p) (org-indent-item))))
7490 (defun org-insert-todo-subheading (arg)
7491 "Insert a new subheading with TODO keyword or checkbox and demote it.
7492 Works for outline headings and for plain lists alike."
7493 (interactive "P")
7494 (org-insert-todo-heading arg)
7495 (cond
7496 ((org-at-heading-p) (org-do-demote))
7497 ((org-at-item-p) (org-indent-item))))
7499 ;;; Promotion and Demotion
7501 (defvar org-after-demote-entry-hook nil
7502 "Hook run after an entry has been demoted.
7503 The cursor will be at the beginning of the entry.
7504 When a subtree is being demoted, the hook will be called for each node.")
7506 (defvar org-after-promote-entry-hook nil
7507 "Hook run after an entry has been promoted.
7508 The cursor will be at the beginning of the entry.
7509 When a subtree is being promoted, the hook will be called for each node.")
7511 (defun org-promote-subtree ()
7512 "Promote the entire subtree.
7513 See also `org-promote'."
7514 (interactive)
7515 (save-excursion
7516 (org-with-limited-levels (org-map-tree 'org-promote)))
7517 (org-fix-position-after-promote))
7519 (defun org-demote-subtree ()
7520 "Demote the entire subtree. See `org-demote'.
7521 See also `org-promote'."
7522 (interactive)
7523 (save-excursion
7524 (org-with-limited-levels (org-map-tree 'org-demote)))
7525 (org-fix-position-after-promote))
7528 (defun org-do-promote ()
7529 "Promote the current heading higher up the tree.
7530 If the region is active in `transient-mark-mode', promote all headings
7531 in the region."
7532 (interactive)
7533 (save-excursion
7534 (if (org-region-active-p)
7535 (org-map-region 'org-promote (region-beginning) (region-end))
7536 (org-promote)))
7537 (org-fix-position-after-promote))
7539 (defun org-do-demote ()
7540 "Demote the current heading lower down the tree.
7541 If the region is active in `transient-mark-mode', demote all headings
7542 in the region."
7543 (interactive)
7544 (save-excursion
7545 (if (org-region-active-p)
7546 (org-map-region 'org-demote (region-beginning) (region-end))
7547 (org-demote)))
7548 (org-fix-position-after-promote))
7550 (defun org-fix-position-after-promote ()
7551 "Make sure that after pro/demotion cursor position is right."
7552 (let ((pos (point)))
7553 (when (save-excursion
7554 (beginning-of-line 1)
7555 (looking-at org-todo-line-regexp)
7556 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7557 (cond ((eobp) (insert " "))
7558 ((eolp) (insert " "))
7559 ((equal (char-after) ?\ ) (forward-char 1))))))
7561 (defun org-current-level ()
7562 "Return the level of the current entry, or nil if before the first headline.
7563 The level is the number of stars at the beginning of the headline."
7564 (save-excursion
7565 (org-with-limited-levels
7566 (if (ignore-errors (org-back-to-heading t))
7567 (funcall outline-level)))))
7569 (defun org-get-previous-line-level ()
7570 "Return the outline depth of the last headline before the current line.
7571 Returns 0 for the first headline in the buffer, and nil if before the
7572 first headline."
7573 (let ((current-level (org-current-level))
7574 (prev-level (when (> (line-number-at-pos) 1)
7575 (save-excursion
7576 (beginning-of-line 0)
7577 (org-current-level)))))
7578 (cond ((null current-level) nil) ; Before first headline
7579 ((null prev-level) 0) ; At first headline
7580 (prev-level))))
7582 (defun org-reduced-level (l)
7583 "Compute the effective level of a heading.
7584 This takes into account the setting of `org-odd-levels-only'."
7585 (cond
7586 ((zerop l) 0)
7587 (org-odd-levels-only (1+ (floor (/ l 2))))
7588 (t l)))
7590 (defun org-level-increment ()
7591 "Return the number of stars that will be added or removed at a
7592 time to headlines when structure editing, based on the value of
7593 `org-odd-levels-only'."
7594 (if org-odd-levels-only 2 1))
7596 (defun org-get-valid-level (level &optional change)
7597 "Rectify a level change under the influence of `org-odd-levels-only'
7598 LEVEL is a current level, CHANGE is by how much the level should be
7599 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7600 even level numbers will become the next higher odd number."
7601 (if org-odd-levels-only
7602 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7603 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7604 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7605 (max 1 (+ level (or change 0)))))
7607 (if (boundp 'define-obsolete-function-alias)
7608 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7609 (define-obsolete-function-alias 'org-get-legal-level
7610 'org-get-valid-level)
7611 (define-obsolete-function-alias 'org-get-legal-level
7612 'org-get-valid-level "23.1")))
7614 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7615 ;; ̀org-with-limited-levels'
7616 (defun org-promote ()
7617 "Promote the current heading higher up the tree.
7618 If the region is active in `transient-mark-mode', promote all headings
7619 in the region."
7620 (org-back-to-heading t)
7621 (let* ((level (save-match-data (funcall outline-level)))
7622 (after-change-functions (remove 'flyspell-after-change-function
7623 after-change-functions))
7624 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7625 (diff (abs (- level (length up-head) -1))))
7626 (cond ((and (= level 1) org-called-with-limited-levels
7627 org-allow-promoting-top-level-subtree)
7628 (replace-match "# " nil t))
7629 ((= level 1)
7630 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7631 (t (replace-match up-head nil t)))
7632 ;; Fixup tag positioning
7633 (unless (= level 1)
7634 (and org-auto-align-tags (org-set-tags nil t))
7635 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7636 (run-hooks 'org-after-promote-entry-hook)))
7638 (defun org-demote ()
7639 "Demote the current heading lower down the tree.
7640 If the region is active in `transient-mark-mode', demote all headings
7641 in the region."
7642 (org-back-to-heading t)
7643 (let* ((level (save-match-data (funcall outline-level)))
7644 (after-change-functions (remove 'flyspell-after-change-function
7645 after-change-functions))
7646 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7647 (diff (abs (- level (length down-head) -1))))
7648 (replace-match down-head nil t)
7649 ;; Fixup tag positioning
7650 (and org-auto-align-tags (org-set-tags nil t))
7651 (if org-adapt-indentation (org-fixup-indentation diff))
7652 (run-hooks 'org-after-demote-entry-hook)))
7654 (defun org-cycle-level ()
7655 "Cycle the level of an empty headline through possible states.
7656 This goes first to child, then to parent, level, then up the hierarchy.
7657 After top level, it switches back to sibling level."
7658 (interactive)
7659 (let ((org-adapt-indentation nil))
7660 (when (org-point-at-end-of-empty-headline)
7661 (setq this-command 'org-cycle-level) ; Only needed for caching
7662 (let ((cur-level (org-current-level))
7663 (prev-level (org-get-previous-line-level)))
7664 (cond
7665 ;; If first headline in file, promote to top-level.
7666 ((= prev-level 0)
7667 (loop repeat (/ (- cur-level 1) (org-level-increment))
7668 do (org-do-promote)))
7669 ;; If same level as prev, demote one.
7670 ((= prev-level cur-level)
7671 (org-do-demote))
7672 ;; If parent is top-level, promote to top level if not already.
7673 ((= prev-level 1)
7674 (loop repeat (/ (- cur-level 1) (org-level-increment))
7675 do (org-do-promote)))
7676 ;; If top-level, return to prev-level.
7677 ((= cur-level 1)
7678 (loop repeat (/ (- prev-level 1) (org-level-increment))
7679 do (org-do-demote)))
7680 ;; If less than prev-level, promote one.
7681 ((< cur-level prev-level)
7682 (org-do-promote))
7683 ;; If deeper than prev-level, promote until higher than
7684 ;; prev-level.
7685 ((> cur-level prev-level)
7686 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7687 do (org-do-promote))))
7688 t))))
7690 (defun org-map-tree (fun)
7691 "Call FUN for every heading underneath the current one."
7692 (org-back-to-heading)
7693 (let ((level (funcall outline-level)))
7694 (save-excursion
7695 (funcall fun)
7696 (while (and (progn
7697 (outline-next-heading)
7698 (> (funcall outline-level) level))
7699 (not (eobp)))
7700 (funcall fun)))))
7702 (defun org-map-region (fun beg end)
7703 "Call FUN for every heading between BEG and END."
7704 (let ((org-ignore-region t))
7705 (save-excursion
7706 (setq end (copy-marker end))
7707 (goto-char beg)
7708 (if (and (re-search-forward org-outline-regexp-bol nil t)
7709 (< (point) end))
7710 (funcall fun))
7711 (while (and (progn
7712 (outline-next-heading)
7713 (< (point) end))
7714 (not (eobp)))
7715 (funcall fun)))))
7717 (defvar org-property-end-re) ; silence byte-compiler
7718 (defun org-fixup-indentation (diff)
7719 "Change the indentation in the current entry by DIFF.
7720 However, if any line in the current entry has no indentation, or if it
7721 would end up with no indentation after the change, nothing at all is done."
7722 (save-excursion
7723 (let ((end (save-excursion (outline-next-heading)
7724 (point-marker)))
7725 (prohibit (if (> diff 0)
7726 "^\\S-"
7727 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7728 col)
7729 (unless (save-excursion (end-of-line 1)
7730 (re-search-forward prohibit end t))
7731 (while (and (< (point) end)
7732 (re-search-forward "^[ \t]+" end t))
7733 (goto-char (match-end 0))
7734 (setq col (current-column))
7735 (if (< diff 0) (replace-match ""))
7736 (org-indent-to-column (+ diff col))))
7737 (move-marker end nil))))
7739 (defun org-convert-to-odd-levels ()
7740 "Convert an org-mode file with all levels allowed to one with odd levels.
7741 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7742 level 5 etc."
7743 (interactive)
7744 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7745 (let ((outline-level 'org-outline-level)
7746 (org-odd-levels-only nil) n)
7747 (save-excursion
7748 (goto-char (point-min))
7749 (while (re-search-forward "^\\*\\*+ " nil t)
7750 (setq n (- (length (match-string 0)) 2))
7751 (while (>= (setq n (1- n)) 0)
7752 (org-demote))
7753 (end-of-line 1))))))
7755 (defun org-convert-to-oddeven-levels ()
7756 "Convert an org-mode file with only odd levels to one with odd/even levels.
7757 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7758 file contains a section with an even level, conversion would
7759 destroy the structure of the file. An error is signaled in this
7760 case."
7761 (interactive)
7762 (goto-char (point-min))
7763 ;; First check if there are no even levels
7764 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7765 (org-show-context t)
7766 (error "Not all levels are odd in this file. Conversion not possible"))
7767 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7768 (let ((outline-regexp org-outline-regexp)
7769 (outline-level 'org-outline-level)
7770 (org-odd-levels-only nil) n)
7771 (save-excursion
7772 (goto-char (point-min))
7773 (while (re-search-forward "^\\*\\*+ " nil t)
7774 (setq n (/ (1- (length (match-string 0))) 2))
7775 (while (>= (setq n (1- n)) 0)
7776 (org-promote))
7777 (end-of-line 1))))))
7779 (defun org-tr-level (n)
7780 "Make N odd if required."
7781 (if org-odd-levels-only (1+ (/ n 2)) n))
7783 ;;; Vertical tree motion, cutting and pasting of subtrees
7785 (defun org-move-subtree-up (&optional arg)
7786 "Move the current subtree up past ARG headlines of the same level."
7787 (interactive "p")
7788 (org-move-subtree-down (- (prefix-numeric-value arg))))
7790 (defun org-move-subtree-down (&optional arg)
7791 "Move the current subtree down past ARG headlines of the same level."
7792 (interactive "p")
7793 (setq arg (prefix-numeric-value arg))
7794 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7795 'org-get-last-sibling))
7796 (ins-point (make-marker))
7797 (cnt (abs arg))
7798 (col (current-column))
7799 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7800 ;; Select the tree
7801 (org-back-to-heading)
7802 (setq beg0 (point))
7803 (save-excursion
7804 (setq ne-beg (org-back-over-empty-lines))
7805 (setq beg (point)))
7806 (save-match-data
7807 (save-excursion (outline-end-of-heading)
7808 (setq folded (outline-invisible-p)))
7809 (outline-end-of-subtree))
7810 (outline-next-heading)
7811 (setq ne-end (org-back-over-empty-lines))
7812 (setq end (point))
7813 (goto-char beg0)
7814 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7815 ;; include less whitespace
7816 (save-excursion
7817 (goto-char beg)
7818 (forward-line (- ne-beg ne-end))
7819 (setq beg (point))))
7820 ;; Find insertion point, with error handling
7821 (while (> cnt 0)
7822 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7823 (progn (goto-char beg0)
7824 (error "Cannot move past superior level or buffer limit")))
7825 (setq cnt (1- cnt)))
7826 (if (> arg 0)
7827 ;; Moving forward - still need to move over subtree
7828 (progn (org-end-of-subtree t t)
7829 (save-excursion
7830 (org-back-over-empty-lines)
7831 (or (bolp) (newline)))))
7832 (setq ne-ins (org-back-over-empty-lines))
7833 (move-marker ins-point (point))
7834 (setq txt (buffer-substring beg end))
7835 (org-save-markers-in-region beg end)
7836 (delete-region beg end)
7837 (org-remove-empty-overlays-at beg)
7838 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7839 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7840 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7841 (let ((bbb (point)))
7842 (insert-before-markers txt)
7843 (org-reinstall-markers-in-region bbb)
7844 (move-marker ins-point bbb))
7845 (or (bolp) (insert "\n"))
7846 (setq ins-end (point))
7847 (goto-char ins-point)
7848 (org-skip-whitespace)
7849 (when (and (< arg 0)
7850 (org-first-sibling-p)
7851 (> ne-ins ne-beg))
7852 ;; Move whitespace back to beginning
7853 (save-excursion
7854 (goto-char ins-end)
7855 (let ((kill-whole-line t))
7856 (kill-line (- ne-ins ne-beg)) (point)))
7857 (insert (make-string (- ne-ins ne-beg) ?\n)))
7858 (move-marker ins-point nil)
7859 (if folded
7860 (hide-subtree)
7861 (org-show-entry)
7862 (show-children)
7863 (org-cycle-hide-drawers 'children))
7864 (org-clean-visibility-after-subtree-move)
7865 ;; move back to the initial column we were at
7866 (move-to-column col)))
7868 (defvar org-subtree-clip ""
7869 "Clipboard for cut and paste of subtrees.
7870 This is actually only a copy of the kill, because we use the normal kill
7871 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7873 (defvar org-subtree-clip-folded nil
7874 "Was the last copied subtree folded?
7875 This is used to fold the tree back after pasting.")
7877 (defun org-cut-subtree (&optional n)
7878 "Cut the current subtree into the clipboard.
7879 With prefix arg N, cut this many sequential subtrees.
7880 This is a short-hand for marking the subtree and then cutting it."
7881 (interactive "p")
7882 (org-copy-subtree n 'cut))
7884 (defun org-copy-subtree (&optional n cut force-store-markers)
7885 "Cut the current subtree into the clipboard.
7886 With prefix arg N, cut this many sequential subtrees.
7887 This is a short-hand for marking the subtree and then copying it.
7888 If CUT is non-nil, actually cut the subtree.
7889 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7890 of some markers in the region, even if CUT is non-nil. This is
7891 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7892 (interactive "p")
7893 (let (beg end folded (beg0 (point)))
7894 (if (org-called-interactively-p 'any)
7895 (org-back-to-heading nil) ; take what looks like a subtree
7896 (org-back-to-heading t)) ; take what is really there
7897 (setq beg (point))
7898 (skip-chars-forward " \t\r\n")
7899 (save-match-data
7900 (save-excursion (outline-end-of-heading)
7901 (setq folded (outline-invisible-p)))
7902 (condition-case nil
7903 (org-forward-heading-same-level (1- n) t)
7904 (error nil))
7905 (org-end-of-subtree t t))
7906 (setq end (point))
7907 (goto-char beg0)
7908 (when (> end beg)
7909 (setq org-subtree-clip-folded folded)
7910 (when (or cut force-store-markers)
7911 (org-save-markers-in-region beg end))
7912 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7913 (setq org-subtree-clip (current-kill 0))
7914 (message "%s: Subtree(s) with %d characters"
7915 (if cut "Cut" "Copied")
7916 (length org-subtree-clip)))))
7918 (defun org-paste-subtree (&optional level tree for-yank)
7919 "Paste the clipboard as a subtree, with modification of headline level.
7920 The entire subtree is promoted or demoted in order to match a new headline
7921 level.
7923 If the cursor is at the beginning of a headline, the same level as
7924 that headline is used to paste the tree
7926 If not, the new level is derived from the *visible* headings
7927 before and after the insertion point, and taken to be the inferior headline
7928 level of the two. So if the previous visible heading is level 3 and the
7929 next is level 4 (or vice versa), level 4 will be used for insertion.
7930 This makes sure that the subtree remains an independent subtree and does
7931 not swallow low level entries.
7933 You can also force a different level, either by using a numeric prefix
7934 argument, or by inserting the heading marker by hand. For example, if the
7935 cursor is after \"*****\", then the tree will be shifted to level 5.
7937 If optional TREE is given, use this text instead of the kill ring.
7939 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7940 move back over whitespace before inserting, and move point to the end of
7941 the inserted text when done."
7942 (interactive "P")
7943 (setq tree (or tree (and kill-ring (current-kill 0))))
7944 (unless (org-kill-is-subtree-p tree)
7945 (error "%s"
7946 (substitute-command-keys
7947 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7948 (org-with-limited-levels
7949 (let* ((visp (not (outline-invisible-p)))
7950 (txt tree)
7951 (^re_ "\\(\\*+\\)[ \t]*")
7952 (old-level (if (string-match org-outline-regexp-bol txt)
7953 (- (match-end 0) (match-beginning 0) 1)
7954 -1))
7955 (force-level (cond (level (prefix-numeric-value level))
7956 ((and (looking-at "[ \t]*$")
7957 (string-match
7958 "^\\*+$" (buffer-substring
7959 (point-at-bol) (point))))
7960 (- (match-end 1) (match-beginning 1)))
7961 ((and (bolp)
7962 (looking-at org-outline-regexp))
7963 (- (match-end 0) (point) 1))))
7964 (previous-level (save-excursion
7965 (condition-case nil
7966 (progn
7967 (outline-previous-visible-heading 1)
7968 (if (looking-at ^re_)
7969 (- (match-end 0) (match-beginning 0) 1)
7971 (error 1))))
7972 (next-level (save-excursion
7973 (condition-case nil
7974 (progn
7975 (or (looking-at org-outline-regexp)
7976 (outline-next-visible-heading 1))
7977 (if (looking-at ^re_)
7978 (- (match-end 0) (match-beginning 0) 1)
7980 (error 1))))
7981 (new-level (or force-level (max previous-level next-level)))
7982 (shift (if (or (= old-level -1)
7983 (= new-level -1)
7984 (= old-level new-level))
7986 (- new-level old-level)))
7987 (delta (if (> shift 0) -1 1))
7988 (func (if (> shift 0) 'org-demote 'org-promote))
7989 (org-odd-levels-only nil)
7990 beg end newend)
7991 ;; Remove the forced level indicator
7992 (if force-level
7993 (delete-region (point-at-bol) (point)))
7994 ;; Paste
7995 (beginning-of-line (if (bolp) 1 2))
7996 (setq beg (point))
7997 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7998 (insert-before-markers txt)
7999 (unless (string-match "\n\\'" txt) (insert "\n"))
8000 (setq newend (point))
8001 (org-reinstall-markers-in-region beg)
8002 (setq end (point))
8003 (goto-char beg)
8004 (skip-chars-forward " \t\n\r")
8005 (setq beg (point))
8006 (if (and (outline-invisible-p) visp)
8007 (save-excursion (outline-show-heading)))
8008 ;; Shift if necessary
8009 (unless (= shift 0)
8010 (save-restriction
8011 (narrow-to-region beg end)
8012 (while (not (= shift 0))
8013 (org-map-region func (point-min) (point-max))
8014 (setq shift (+ delta shift)))
8015 (goto-char (point-min))
8016 (setq newend (point-max))))
8017 (when (or (org-called-interactively-p 'interactive) for-yank)
8018 (message "Clipboard pasted as level %d subtree" new-level))
8019 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8020 kill-ring
8021 (eq org-subtree-clip (current-kill 0))
8022 org-subtree-clip-folded)
8023 ;; The tree was folded before it was killed/copied
8024 (hide-subtree))
8025 (and for-yank (goto-char newend)))))
8027 (defun org-kill-is-subtree-p (&optional txt)
8028 "Check if the current kill is an outline subtree, or a set of trees.
8029 Returns nil if kill does not start with a headline, or if the first
8030 headline level is not the largest headline level in the tree.
8031 So this will actually accept several entries of equal levels as well,
8032 which is OK for `org-paste-subtree'.
8033 If optional TXT is given, check this string instead of the current kill."
8034 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8035 (re (org-get-limited-outline-regexp))
8036 (^re (concat "^" re))
8037 (start-level (and kill
8038 (string-match
8039 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8040 kill)
8041 (- (match-end 2) (match-beginning 2) 1)))
8042 (start (1+ (or (match-beginning 2) -1))))
8043 (if (not start-level)
8044 (progn
8045 nil) ;; does not even start with a heading
8046 (catch 'exit
8047 (while (setq start (string-match ^re kill (1+ start)))
8048 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8049 (throw 'exit nil)))
8050 t))))
8052 (defvar org-markers-to-move nil
8053 "Markers that should be moved with a cut-and-paste operation.
8054 Those markers are stored together with their positions relative to
8055 the start of the region.")
8057 (defun org-save-markers-in-region (beg end)
8058 "Check markers in region.
8059 If these markers are between BEG and END, record their position relative
8060 to BEG, so that after moving the block of text, we can put the markers back
8061 into place.
8062 This function gets called just before an entry or tree gets cut from the
8063 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8064 called immediately, to move the markers with the entries."
8065 (setq org-markers-to-move nil)
8066 (when (featurep 'org-clock)
8067 (org-clock-save-markers-for-cut-and-paste beg end))
8068 (when (featurep 'org-agenda)
8069 (org-agenda-save-markers-for-cut-and-paste beg end)))
8071 (defun org-check-and-save-marker (marker beg end)
8072 "Check if MARKER is between BEG and END.
8073 If yes, remember the marker and the distance to BEG."
8074 (when (and (marker-buffer marker)
8075 (equal (marker-buffer marker) (current-buffer)))
8076 (if (and (>= marker beg) (< marker end))
8077 (push (cons marker (- marker beg)) org-markers-to-move))))
8079 (defun org-reinstall-markers-in-region (beg)
8080 "Move all remembered markers to their position relative to BEG."
8081 (mapc (lambda (x)
8082 (move-marker (car x) (+ beg (cdr x))))
8083 org-markers-to-move)
8084 (setq org-markers-to-move nil))
8086 (defun org-narrow-to-subtree ()
8087 "Narrow buffer to the current subtree."
8088 (interactive)
8089 (save-excursion
8090 (save-match-data
8091 (org-with-limited-levels
8092 (narrow-to-region
8093 (progn (org-back-to-heading t) (point))
8094 (progn (org-end-of-subtree t t)
8095 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8096 (point)))))))
8098 (defun org-narrow-to-block ()
8099 "Narrow buffer to the current block."
8100 (interactive)
8101 (let* ((case-fold-search t)
8102 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8103 "^[ \t]*#\\+end_.*")))
8104 (if blockp
8105 (narrow-to-region (car blockp) (cdr blockp))
8106 (error "Not in a block"))))
8108 (eval-when-compile
8109 (defvar org-property-drawer-re))
8111 (defvar org-property-start-re) ;; defined below
8112 (defun org-clone-subtree-with-time-shift (n &optional shift)
8113 "Clone the task (subtree) at point N times.
8114 The clones will be inserted as siblings.
8116 In interactive use, the user will be prompted for the number of
8117 clones to be produced, and for a time SHIFT, which may be a
8118 repeater as used in time stamps, for example `+3d'.
8120 When a valid repeater is given and the entry contains any time
8121 stamps, the clones will become a sequence in time, with time
8122 stamps in the subtree shifted for each clone produced. If SHIFT
8123 is nil or the empty string, time stamps will be left alone. The
8124 ID property of the original subtree is removed.
8126 If the original subtree did contain time stamps with a repeater,
8127 the following will happen:
8128 - the repeater will be removed in each clone
8129 - an additional clone will be produced, with the current, unshifted
8130 date(s) in the entry.
8131 - the original entry will be placed *after* all the clones, with
8132 repeater intact.
8133 - the start days in the repeater in the original entry will be shifted
8134 to past the last clone.
8135 In this way you can spell out a number of instances of a repeating task,
8136 and still retain the repeater to cover future instances of the task."
8137 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8138 (let (beg end template task idprop
8139 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8140 (drawer-re org-drawer-regexp))
8141 (if (not (and (integerp n) (> n 0)))
8142 (error "Invalid number of replications %s" n))
8143 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8144 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8145 shift)))
8146 (error "Invalid shift specification %s" shift))
8147 (when doshift
8148 (setq shift-n (string-to-number (match-string 1 shift))
8149 shift-what (cdr (assoc (match-string 2 shift)
8150 '(("d" . day) ("w" . week)
8151 ("m" . month) ("y" . year))))))
8152 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8153 (setq nmin 1 nmax n)
8154 (org-back-to-heading t)
8155 (setq beg (point))
8156 (setq idprop (org-entry-get nil "ID"))
8157 (org-end-of-subtree t t)
8158 (or (bolp) (insert "\n"))
8159 (setq end (point))
8160 (setq template (buffer-substring beg end))
8161 (when (and doshift
8162 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8163 (delete-region beg end)
8164 (setq end beg)
8165 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8166 (goto-char end)
8167 (loop for n from nmin to nmax do
8168 ;; prepare clone
8169 (with-temp-buffer
8170 (insert template)
8171 (org-mode)
8172 (goto-char (point-min))
8173 (org-show-subtree)
8174 (and idprop (if org-clone-delete-id
8175 (org-entry-delete nil "ID")
8176 (org-id-get-create t)))
8177 (unless (= n 0)
8178 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8179 (kill-whole-line))
8180 (goto-char (point-min))
8181 (while (re-search-forward drawer-re nil t)
8182 (mapc (lambda (d)
8183 (org-remove-empty-drawer-at d (point))) org-drawers)))
8184 (goto-char (point-min))
8185 (when doshift
8186 (while (re-search-forward org-ts-regexp-both nil t)
8187 (org-timestamp-change (* n shift-n) shift-what))
8188 (unless (= n n-no-remove)
8189 (goto-char (point-min))
8190 (while (re-search-forward org-ts-regexp nil t)
8191 (save-excursion
8192 (goto-char (match-beginning 0))
8193 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8194 (delete-region (match-beginning 1) (match-end 1)))))))
8195 (setq task (buffer-string)))
8196 (insert task))
8197 (goto-char beg)))
8199 ;;; Outline Sorting
8201 (defun org-sort (with-case)
8202 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8203 Optional argument WITH-CASE means sort case-sensitively."
8204 (interactive "P")
8205 (cond
8206 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8207 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8209 (org-call-with-arg 'org-sort-entries with-case))))
8211 (defun org-sort-remove-invisible (s)
8212 (remove-text-properties 0 (length s) org-rm-props s)
8213 (while (string-match org-bracket-link-regexp s)
8214 (setq s (replace-match (if (match-end 2)
8215 (match-string 3 s)
8216 (match-string 1 s)) t t s)))
8219 (defvar org-priority-regexp) ; defined later in the file
8221 (defvar org-after-sorting-entries-or-items-hook nil
8222 "Hook that is run after a bunch of entries or items have been sorted.
8223 When children are sorted, the cursor is in the parent line when this
8224 hook gets called. When a region or a plain list is sorted, the cursor
8225 will be in the first entry of the sorted region/list.")
8227 (defun org-sort-entries
8228 (&optional with-case sorting-type getkey-func compare-func property)
8229 "Sort entries on a certain level of an outline tree.
8230 If there is an active region, the entries in the region are sorted.
8231 Else, if the cursor is before the first entry, sort the top-level items.
8232 Else, the children of the entry at point are sorted.
8234 Sorting can be alphabetically, numerically, by date/time as given by
8235 a time stamp, by a property or by priority.
8237 The command prompts for the sorting type unless it has been given to the
8238 function through the SORTING-TYPE argument, which needs to be a character,
8239 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8240 precise meaning of each character:
8242 n Numerically, by converting the beginning of the entry/item to a number.
8243 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8244 o By order of TODO keywords.
8245 t By date/time, either the first active time stamp in the entry, or, if
8246 none exist, by the first inactive one.
8247 s By the scheduled date/time.
8248 d By deadline date/time.
8249 c By creation time, which is assumed to be the first inactive time stamp
8250 at the beginning of a line.
8251 p By priority according to the cookie.
8252 r By the value of a property.
8254 Capital letters will reverse the sort order.
8256 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8257 called with point at the beginning of the record. It must return either
8258 a string or a number that should serve as the sorting key for that record.
8260 Comparing entries ignores case by default. However, with an optional argument
8261 WITH-CASE, the sorting considers case as well."
8262 (interactive "P")
8263 (let ((case-func (if with-case 'identity 'downcase))
8264 (cmstr
8265 ;; The clock marker is lost when using `sort-subr', let's
8266 ;; store the clocking string.
8267 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8268 (save-excursion
8269 (goto-char org-clock-marker)
8270 (looking-back "^.*") (match-string-no-properties 0))))
8271 start beg end stars re re2
8272 txt what tmp)
8273 ;; Find beginning and end of region to sort
8274 (cond
8275 ((org-region-active-p)
8276 ;; we will sort the region
8277 (setq end (region-end)
8278 what "region")
8279 (goto-char (region-beginning))
8280 (if (not (org-at-heading-p)) (outline-next-heading))
8281 (setq start (point)))
8282 ((or (org-at-heading-p)
8283 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8284 ;; we will sort the children of the current headline
8285 (org-back-to-heading)
8286 (setq start (point)
8287 end (progn (org-end-of-subtree t t)
8288 (or (bolp) (insert "\n"))
8289 (org-back-over-empty-lines)
8290 (point))
8291 what "children")
8292 (goto-char start)
8293 (show-subtree)
8294 (outline-next-heading))
8296 ;; we will sort the top-level entries in this file
8297 (goto-char (point-min))
8298 (or (org-at-heading-p) (outline-next-heading))
8299 (setq start (point))
8300 (goto-char (point-max))
8301 (beginning-of-line 1)
8302 (when (looking-at ".*?\\S-")
8303 ;; File ends in a non-white line
8304 (end-of-line 1)
8305 (insert "\n"))
8306 (setq end (point-max))
8307 (setq what "top-level")
8308 (goto-char start)
8309 (show-all)))
8311 (setq beg (point))
8312 (if (>= beg end) (error "Nothing to sort"))
8314 (looking-at "\\(\\*+\\)")
8315 (setq stars (match-string 1)
8316 re (concat "^" (regexp-quote stars) " +")
8317 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8318 txt (buffer-substring beg end))
8319 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8320 (if (and (not (equal stars "*")) (string-match re2 txt))
8321 (error "Region to sort contains a level above the first entry"))
8323 (unless sorting-type
8324 (message
8325 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8326 [t]ime [s]cheduled [d]eadline [c]reated
8327 A/N/P/R/O/F/T/S/D/C means reversed:"
8328 what)
8329 (setq sorting-type (read-char-exclusive))
8331 (unless getkey-func
8332 (and (= (downcase sorting-type) ?f)
8333 (setq getkey-func
8334 (org-icompleting-read "Sort using function: "
8335 obarray 'fboundp t nil nil))
8336 (setq getkey-func (intern getkey-func))))
8338 (and (= (downcase sorting-type) ?r)
8339 (not property)
8340 (setq property
8341 (org-icompleting-read "Property: "
8342 (mapcar 'list (org-buffer-property-keys t))
8343 nil t))))
8345 (message "Sorting entries...")
8347 (save-restriction
8348 (narrow-to-region start end)
8349 (let ((dcst (downcase sorting-type))
8350 (case-fold-search nil)
8351 (now (current-time)))
8352 (sort-subr
8353 (/= dcst sorting-type)
8354 ;; This function moves to the beginning character of the "record" to
8355 ;; be sorted.
8356 (lambda nil
8357 (if (re-search-forward re nil t)
8358 (goto-char (match-beginning 0))
8359 (goto-char (point-max))))
8360 ;; This function moves to the last character of the "record" being
8361 ;; sorted.
8362 (lambda nil
8363 (save-match-data
8364 (condition-case nil
8365 (outline-forward-same-level 1)
8366 (error
8367 (goto-char (point-max))))))
8368 ;; This function returns the value that gets sorted against.
8369 (lambda nil
8370 (cond
8371 ((= dcst ?n)
8372 (if (looking-at org-complex-heading-regexp)
8373 (string-to-number (match-string 4))
8374 nil))
8375 ((= dcst ?a)
8376 (if (looking-at org-complex-heading-regexp)
8377 (funcall case-func (match-string 4))
8378 nil))
8379 ((= dcst ?t)
8380 (let ((end (save-excursion (outline-next-heading) (point))))
8381 (if (or (re-search-forward org-ts-regexp end t)
8382 (re-search-forward org-ts-regexp-both end t))
8383 (org-time-string-to-seconds (match-string 0))
8384 (org-float-time now))))
8385 ((= dcst ?c)
8386 (let ((end (save-excursion (outline-next-heading) (point))))
8387 (if (re-search-forward
8388 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8389 end t)
8390 (org-time-string-to-seconds (match-string 0))
8391 (org-float-time now))))
8392 ((= dcst ?s)
8393 (let ((end (save-excursion (outline-next-heading) (point))))
8394 (if (re-search-forward org-scheduled-time-regexp end t)
8395 (org-time-string-to-seconds (match-string 1))
8396 (org-float-time now))))
8397 ((= dcst ?d)
8398 (let ((end (save-excursion (outline-next-heading) (point))))
8399 (if (re-search-forward org-deadline-time-regexp end t)
8400 (org-time-string-to-seconds (match-string 1))
8401 (org-float-time now))))
8402 ((= dcst ?p)
8403 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8404 (string-to-char (match-string 2))
8405 org-default-priority))
8406 ((= dcst ?r)
8407 (or (org-entry-get nil property) ""))
8408 ((= dcst ?o)
8409 (if (looking-at org-complex-heading-regexp)
8410 (- 9999 (length (member (match-string 2)
8411 org-todo-keywords-1)))))
8412 ((= dcst ?f)
8413 (if getkey-func
8414 (progn
8415 (setq tmp (funcall getkey-func))
8416 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8417 tmp)
8418 (error "Invalid key function `%s'" getkey-func)))
8419 (t (error "Invalid sorting type `%c'" sorting-type))))
8421 (cond
8422 ((= dcst ?a) 'string<)
8423 ((= dcst ?f) compare-func)
8424 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8425 (run-hooks 'org-after-sorting-entries-or-items-hook)
8426 ;; Reset the clock marker if needed
8427 (when cmstr
8428 (save-excursion
8429 (goto-char start)
8430 (search-forward cmstr nil t)
8431 (move-marker org-clock-marker (point))))
8432 (message "Sorting entries...done")))
8434 (defun org-do-sort (table what &optional with-case sorting-type)
8435 "Sort TABLE of WHAT according to SORTING-TYPE.
8436 The user will be prompted for the SORTING-TYPE if the call to this
8437 function does not specify it. WHAT is only for the prompt, to indicate
8438 what is being sorted. The sorting key will be extracted from
8439 the car of the elements of the table.
8440 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8441 (unless sorting-type
8442 (message
8443 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8444 what)
8445 (setq sorting-type (read-char-exclusive)))
8446 (let ((dcst (downcase sorting-type))
8447 extractfun comparefun)
8448 ;; Define the appropriate functions
8449 (cond
8450 ((= dcst ?n)
8451 (setq extractfun 'string-to-number
8452 comparefun (if (= dcst sorting-type) '< '>)))
8453 ((= dcst ?a)
8454 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8455 (lambda(x) (downcase (org-sort-remove-invisible x))))
8456 comparefun (if (= dcst sorting-type)
8457 'string<
8458 (lambda (a b) (and (not (string< a b))
8459 (not (string= a b)))))))
8460 ((= dcst ?t)
8461 (setq extractfun
8462 (lambda (x)
8463 (if (or (string-match org-ts-regexp x)
8464 (string-match org-ts-regexp-both x))
8465 (org-float-time
8466 (org-time-string-to-time (match-string 0 x)))
8468 comparefun (if (= dcst sorting-type) '< '>)))
8469 (t (error "Invalid sorting type `%c'" sorting-type)))
8471 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8472 table)
8473 (lambda (a b) (funcall comparefun (car a) (car b))))))
8476 ;;; The orgstruct minor mode
8478 ;; Define a minor mode which can be used in other modes in order to
8479 ;; integrate the org-mode structure editing commands.
8481 ;; This is really a hack, because the org-mode structure commands use
8482 ;; keys which normally belong to the major mode. Here is how it
8483 ;; works: The minor mode defines all the keys necessary to operate the
8484 ;; structure commands, but wraps the commands into a function which
8485 ;; tests if the cursor is currently at a headline or a plain list
8486 ;; item. If that is the case, the structure command is used,
8487 ;; temporarily setting many Org-mode variables like regular
8488 ;; expressions for filling etc. However, when any of those keys is
8489 ;; used at a different location, function uses `key-binding' to look
8490 ;; up if the key has an associated command in another currently active
8491 ;; keymap (minor modes, major mode, global), and executes that
8492 ;; command. There might be problems if any of the keys is otherwise
8493 ;; used as a prefix key.
8495 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8496 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8497 ;; addresses this by checking explicitly for both bindings.
8499 (defvar orgstruct-mode-map (make-sparse-keymap)
8500 "Keymap for the minor `orgstruct-mode'.")
8502 (defvar org-local-vars nil
8503 "List of local variables, for use by `orgstruct-mode'.")
8505 ;;;###autoload
8506 (define-minor-mode orgstruct-mode
8507 "Toggle the minor mode `orgstruct-mode'.
8508 This mode is for using Org-mode structure commands in other
8509 modes. The following keys behave as if Org-mode were active, if
8510 the cursor is on a headline, or on a plain list item (both as
8511 defined by Org-mode).
8513 M-up Move entry/item up
8514 M-down Move entry/item down
8515 M-left Promote
8516 M-right Demote
8517 M-S-up Move entry/item up
8518 M-S-down Move entry/item down
8519 M-S-left Promote subtree
8520 M-S-right Demote subtree
8521 M-q Fill paragraph and items like in Org-mode
8522 C-c ^ Sort entries
8523 C-c - Cycle list bullet
8524 TAB Cycle item visibility
8525 M-RET Insert new heading/item
8526 S-M-RET Insert new TODO heading / Checkbox item
8527 C-c C-c Set tags / toggle checkbox"
8528 nil " OrgStruct" nil
8529 (org-load-modules-maybe)
8530 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8532 ;;;###autoload
8533 (defun turn-on-orgstruct ()
8534 "Unconditionally turn on `orgstruct-mode'."
8535 (orgstruct-mode 1))
8537 (defvar org-fb-vars nil)
8538 (make-variable-buffer-local 'org-fb-vars)
8539 (defun orgstruct++-mode (&optional arg)
8540 "Toggle `orgstruct-mode', the enhanced version of it.
8541 In addition to setting orgstruct-mode, this also exports all
8542 indentation and autofilling variables from org-mode into the
8543 buffer. It will also recognize item context in multiline items."
8544 (interactive "P")
8545 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8546 (if (< arg 1)
8547 (progn (orgstruct-mode -1)
8548 (mapc (lambda(v)
8549 (org-set-local (car v)
8550 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8551 org-fb-vars))
8552 (orgstruct-mode 1)
8553 (setq org-fb-vars nil)
8554 (let (var val)
8555 (mapc
8556 (lambda (x)
8557 (when (string-match
8558 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8559 (symbol-name (car x)))
8560 (setq var (car x) val (nth 1 x))
8561 (push (list var `(quote ,(eval var))) org-fb-vars)
8562 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8563 org-local-vars)
8564 (org-set-local 'orgstruct-is-++ t))))
8566 (defvar orgstruct-is-++ nil
8567 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8568 (make-variable-buffer-local 'orgstruct-is-++)
8570 ;;;###autoload
8571 (defun turn-on-orgstruct++ ()
8572 "Unconditionally turn on `orgstruct++-mode'."
8573 (orgstruct++-mode 1))
8575 (defun orgstruct-error ()
8576 "Error when there is no default binding for a structure key."
8577 (interactive)
8578 (error "This key has no function outside structure elements"))
8580 (defun orgstruct-setup ()
8581 "Setup orgstruct keymaps."
8582 (let ((nfunc 0)
8583 (bindings
8584 (list
8585 '([(meta up)] org-metaup)
8586 '([(meta down)] org-metadown)
8587 '([(meta left)] org-metaleft)
8588 '([(meta right)] org-metaright)
8589 '([(meta shift up)] org-shiftmetaup)
8590 '([(meta shift down)] org-shiftmetadown)
8591 '([(meta shift left)] org-shiftmetaleft)
8592 '([(meta shift right)] org-shiftmetaright)
8593 '([?\e (up)] org-metaup)
8594 '([?\e (down)] org-metadown)
8595 '([?\e (left)] org-metaleft)
8596 '([?\e (right)] org-metaright)
8597 '([?\e (shift up)] org-shiftmetaup)
8598 '([?\e (shift down)] org-shiftmetadown)
8599 '([?\e (shift left)] org-shiftmetaleft)
8600 '([?\e (shift right)] org-shiftmetaright)
8601 '([(shift up)] org-shiftup)
8602 '([(shift down)] org-shiftdown)
8603 '([(shift left)] org-shiftleft)
8604 '([(shift right)] org-shiftright)
8605 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8606 '("\M-q" fill-paragraph)
8607 '("\C-c^" org-sort)
8608 '("\C-c-" org-cycle-list-bullet)))
8609 elt key fun cmd)
8610 (while (setq elt (pop bindings))
8611 (setq nfunc (1+ nfunc))
8612 (setq key (org-key (car elt))
8613 fun (nth 1 elt)
8614 cmd (orgstruct-make-binding fun nfunc key))
8615 (org-defkey orgstruct-mode-map key cmd))
8617 ;; Prevent an error for users who forgot to make autoloads
8618 (require 'org-element)
8620 ;; Special treatment needed for TAB and RET
8621 (org-defkey orgstruct-mode-map [(tab)]
8622 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8623 (org-defkey orgstruct-mode-map "\C-i"
8624 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8626 (org-defkey orgstruct-mode-map "\M-\C-m"
8627 (orgstruct-make-binding 'org-insert-heading 105
8628 "\M-\C-m" [(meta return)]))
8629 (org-defkey orgstruct-mode-map [(meta return)]
8630 (orgstruct-make-binding 'org-insert-heading 106
8631 [(meta return)] "\M-\C-m"))
8633 (org-defkey orgstruct-mode-map [(shift meta return)]
8634 (orgstruct-make-binding 'org-insert-todo-heading 107
8635 [(meta return)] "\M-\C-m"))
8637 (org-defkey orgstruct-mode-map "\e\C-m"
8638 (orgstruct-make-binding 'org-insert-heading 108
8639 "\e\C-m" [?\e (return)]))
8640 (org-defkey orgstruct-mode-map [?\e (return)]
8641 (orgstruct-make-binding 'org-insert-heading 109
8642 [?\e (return)] "\e\C-m"))
8643 (org-defkey orgstruct-mode-map [?\e (shift return)]
8644 (orgstruct-make-binding 'org-insert-todo-heading 110
8645 [?\e (return)] "\e\C-m"))
8647 (unless org-local-vars
8648 (setq org-local-vars (org-get-local-variables)))
8652 (defun orgstruct-make-binding (fun n &rest keys)
8653 "Create a function for binding in the structure minor mode.
8654 FUN is the command to call inside a table. N is used to create a unique
8655 command name. KEYS are keys that should be checked in for a command
8656 to execute outside of tables."
8657 (eval
8658 (list 'defun
8659 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8660 '(arg)
8661 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8662 "Outside of structure, run the binding of `"
8663 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8664 "'.")
8665 '(interactive "p")
8666 (list 'if
8667 `(org-context-p 'headline 'item
8668 (and orgstruct-is-++
8669 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8670 'item-body))
8671 (list 'org-run-like-in-org-mode (list 'quote fun))
8672 (list 'let '(orgstruct-mode)
8673 (list 'call-interactively
8674 (append '(or)
8675 (mapcar (lambda (k)
8676 (list 'key-binding k))
8677 keys)
8678 '('orgstruct-error))))))))
8680 (defun org-contextualize-keys (alist contexts)
8681 "Return valid elements in ALIST depending on CONTEXTS.
8683 `org-agenda-custom-commands' or `org-capture-templates' are the
8684 values used for ALIST, and `org-agenda-custom-commands-contexts'
8685 or `org-capture-templates-contexts' are the associated contexts
8686 definitions."
8687 (let ((contexts
8688 ;; normalize contexts
8689 (mapcar
8690 (lambda(c) (cond ((listp (cadr c))
8691 (list (car c) (car c) (cadr c)))
8692 ((string= "" (cadr c))
8693 (list (car c) (car c) (caddr c)))
8694 (t c))) contexts))
8695 (a alist) c r s)
8696 ;; loop over all commands or templates
8697 (while (setq c (pop a))
8698 (let (vrules repl)
8699 (cond
8700 ((not (assoc (car c) contexts))
8701 (push c r))
8702 ((and (assoc (car c) contexts)
8703 (setq vrules (org-contextualize-validate-key
8704 (car c) contexts)))
8705 (mapc (lambda (vr)
8706 (when (not (equal (car vr) (cadr vr)))
8707 (setq repl vr))) vrules)
8708 (if (not repl) (push c r)
8709 (push (cadr repl) s)
8710 (push
8711 (cons (car c)
8712 (cdr (or (assoc (cadr repl) alist)
8713 (error "Undefined key `%s' as contextual replacement for `%s'"
8714 (cadr repl) (car c)))))
8715 r))))))
8716 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8717 (delq
8719 (delete-dups
8720 (mapcar (lambda (x)
8721 (let ((tpl (car x)))
8722 (when (not (delq
8724 (mapcar (lambda(y)
8725 (equal y tpl)) s))) x)))
8726 (reverse r))))))
8728 (defun org-contextualize-validate-key (key contexts)
8729 "Check CONTEXTS for agenda or capture KEY."
8730 (let (r rr res)
8731 (while (setq r (pop contexts))
8732 (mapc
8733 (lambda (rr)
8734 (when
8735 (and (equal key (car r))
8736 (if (functionp rr) (funcall rr)
8737 (or (and (eq (car rr) 'in-file)
8738 (buffer-file-name)
8739 (string-match (cdr rr) (buffer-file-name)))
8740 (and (eq (car rr) 'in-mode)
8741 (string-match (cdr rr) (symbol-name major-mode)))
8742 (and (eq (car rr) 'in-buffer)
8743 (string-match (cdr rr) (buffer-name)))
8744 (when (and (eq (car rr) 'not-in-file)
8745 (buffer-file-name))
8746 (not (string-match (cdr rr) (buffer-file-name))))
8747 (when (eq (car rr) 'not-in-mode)
8748 (not (string-match (cdr rr) (symbol-name major-mode))))
8749 (when (eq (car rr) 'not-in-buffer)
8750 (not (string-match (cdr rr) (buffer-name)))))))
8751 (push r res)))
8752 (car (last r))))
8753 (delete-dups (delq nil res))))
8755 (defun org-context-p (&rest contexts)
8756 "Check if local context is any of CONTEXTS.
8757 Possible values in the list of contexts are `table', `headline', and `item'."
8758 (let ((pos (point)))
8759 (goto-char (point-at-bol))
8760 (prog1 (or (and (memq 'table contexts)
8761 (looking-at "[ \t]*|"))
8762 (and (memq 'headline contexts)
8763 (looking-at org-outline-regexp))
8764 (and (memq 'item contexts)
8765 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8766 (and (memq 'item-body contexts)
8767 (org-in-item-p)))
8768 (goto-char pos))))
8770 (defun org-get-local-variables ()
8771 "Return a list of all local variables in an Org mode buffer."
8772 (let (varlist)
8773 (with-current-buffer (get-buffer-create "*Org tmp*")
8774 (erase-buffer)
8775 (org-mode)
8776 (setq varlist (buffer-local-variables)))
8777 (kill-buffer "*Org tmp*")
8778 (delq nil
8779 (mapcar
8780 (lambda (x)
8781 (setq x
8782 (if (symbolp x)
8783 (list x)
8784 (list (car x) (list 'quote (cdr x)))))
8785 (if (string-match
8786 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8787 (symbol-name (car x)))
8788 x nil))
8789 varlist))))
8791 (defun org-clone-local-variables (from-buffer &optional regexp)
8792 "Clone local variables from FROM-BUFFER.
8793 Optional argument REGEXP selects variables to clone."
8794 (mapc
8795 (lambda (pair)
8796 (and (symbolp (car pair))
8797 (or (null regexp)
8798 (string-match regexp (symbol-name (car pair))))
8799 (set (make-local-variable (car pair))
8800 (cdr pair))))
8801 (buffer-local-variables from-buffer)))
8803 ;;;###autoload
8804 (defun org-run-like-in-org-mode (cmd)
8805 "Run a command, pretending that the current buffer is in Org-mode.
8806 This will temporarily bind local variables that are typically bound in
8807 Org-mode to the values they have in Org-mode, and then interactively
8808 call CMD."
8809 (org-load-modules-maybe)
8810 (unless org-local-vars
8811 (setq org-local-vars (org-get-local-variables)))
8812 (eval (list 'let org-local-vars
8813 (list 'call-interactively (list 'quote cmd)))))
8815 ;;;; Archiving
8817 (defun org-get-category (&optional pos force-refresh)
8818 "Get the category applying to position POS."
8819 (save-match-data
8820 (if force-refresh (org-refresh-category-properties))
8821 (let ((pos (or pos (point))))
8822 (or (get-text-property pos 'org-category)
8823 (progn (org-refresh-category-properties)
8824 (get-text-property pos 'org-category))))))
8826 (defun org-refresh-category-properties ()
8827 "Refresh category text properties in the buffer."
8828 (let ((case-fold-search t)
8829 (inhibit-read-only t)
8830 (def-cat (cond
8831 ((null org-category)
8832 (if buffer-file-name
8833 (file-name-sans-extension
8834 (file-name-nondirectory buffer-file-name))
8835 "???"))
8836 ((symbolp org-category) (symbol-name org-category))
8837 (t org-category)))
8838 beg end cat pos optionp)
8839 (org-unmodified
8840 (save-excursion
8841 (save-restriction
8842 (widen)
8843 (goto-char (point-min))
8844 (put-text-property (point) (point-max) 'org-category def-cat)
8845 (while (re-search-forward
8846 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8847 (setq pos (match-end 0)
8848 optionp (equal (char-after (match-beginning 0)) ?#)
8849 cat (org-trim (match-string 2)))
8850 (if optionp
8851 (setq beg (point-at-bol) end (point-max))
8852 (org-back-to-heading t)
8853 (setq beg (point) end (org-end-of-subtree t t)))
8854 (put-text-property beg end 'org-category cat)
8855 (put-text-property beg end 'org-category-position beg)
8856 (goto-char pos)))))))
8858 (defun org-refresh-properties (dprop tprop)
8859 "Refresh buffer text properties.
8860 DPROP is the drawer property and TPROP is the corresponding text
8861 property to set."
8862 (let ((case-fold-search t)
8863 (inhibit-read-only t) p)
8864 (org-unmodified
8865 (save-excursion
8866 (save-restriction
8867 (widen)
8868 (goto-char (point-min))
8869 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8870 (setq p (org-match-string-no-properties 1))
8871 (save-excursion
8872 (org-back-to-heading t)
8873 (put-text-property
8874 (point-at-bol) (point-at-eol) tprop p))))))))
8877 ;;;; Link Stuff
8879 ;;; Link abbreviations
8881 (defun org-link-expand-abbrev (link)
8882 "Apply replacements as defined in `org-link-abbrev-alist'."
8883 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8884 (let* ((key (match-string 1 link))
8885 (as (or (assoc key org-link-abbrev-alist-local)
8886 (assoc key org-link-abbrev-alist)))
8887 (tag (and (match-end 2) (match-string 3 link)))
8888 rpl)
8889 (if (not as)
8890 link
8891 (setq rpl (cdr as))
8892 (cond
8893 ((symbolp rpl) (funcall rpl tag))
8894 ((string-match "%(\\([^)]+\\))" rpl)
8895 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8896 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8897 ((string-match "%h" rpl)
8898 (replace-match (url-hexify-string (or tag "")) t t rpl))
8899 (t (concat rpl tag)))))
8900 link))
8902 ;;; Storing and inserting links
8904 (defvar org-insert-link-history nil
8905 "Minibuffer history for links inserted with `org-insert-link'.")
8907 (defvar org-stored-links nil
8908 "Contains the links stored with `org-store-link'.")
8910 (defvar org-store-link-plist nil
8911 "Plist with info about the most recently link created with `org-store-link'.")
8913 (defvar org-link-protocols nil
8914 "Link protocols added to Org-mode using `org-add-link-type'.")
8916 (defvar org-store-link-functions nil
8917 "List of functions that are called to create and store a link.
8918 Each function will be called in turn until one returns a non-nil
8919 value. Each function should check if it is responsible for creating
8920 this link (for example by looking at the major mode).
8921 If not, it must exit and return nil.
8922 If yes, it should return a non-nil value after a calling
8923 `org-store-link-props' with a list of properties and values.
8924 Special properties are:
8926 :type The link prefix, like \"http\". This must be given.
8927 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8928 This is obligatory as well.
8929 :description Optional default description for the second pair
8930 of brackets in an Org-mode link. The user can still change
8931 this when inserting this link into an Org-mode buffer.
8933 In addition to these, any additional properties can be specified
8934 and then used in capture templates.")
8936 (defun org-add-link-type (type &optional follow export)
8937 "Add TYPE to the list of `org-link-types'.
8938 Re-compute all regular expressions depending on `org-link-types'
8940 FOLLOW and EXPORT are two functions.
8942 FOLLOW should take the link path as the single argument and do whatever
8943 is necessary to follow the link, for example find a file or display
8944 a mail message.
8946 EXPORT should format the link path for export to one of the export formats.
8947 It should be a function accepting three arguments:
8949 path the path of the link, the text after the prefix (like \"http:\")
8950 desc the description of the link, if any, or a description added by
8951 org-export-normalize-links if there is none
8952 format the export format, a symbol like `html' or `latex' or `ascii'..
8954 The function may use the FORMAT information to return different values
8955 depending on the format. The return value will be put literally into
8956 the exported file. If the return value is nil, this means Org should
8957 do what it normally does with links which do not have EXPORT defined.
8959 Org-mode has a built-in default for exporting links. If you are happy with
8960 this default, there is no need to define an export function for the link
8961 type. For a simple example of an export function, see `org-bbdb.el'."
8962 (add-to-list 'org-link-types type t)
8963 (org-make-link-regexps)
8964 (if (assoc type org-link-protocols)
8965 (setcdr (assoc type org-link-protocols) (list follow export))
8966 (push (list type follow export) org-link-protocols)))
8968 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8969 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8971 ;;;###autoload
8972 (defun org-store-link (arg)
8973 "\\<org-mode-map>Store an org-link to the current location.
8974 This link is added to `org-stored-links' and can later be inserted
8975 into an org-buffer with \\[org-insert-link].
8977 For some link types, a prefix arg is interpreted.
8978 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8979 For file links, arg negates `org-context-in-file-links'.
8981 A double prefix arg force skipping storing functions that are not
8982 part of Org's core."
8983 (interactive "P")
8984 (org-load-modules-maybe)
8985 (setq org-store-link-plist nil) ; reset
8986 (org-with-limited-levels
8987 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
8988 (cond
8989 ((and (not (equal arg '(16)))
8990 (setq sfuns
8991 (delq
8992 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
8993 org-store-link-functions))
8994 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
8995 (or (and (cdr sfuns)
8996 (funcall (intern
8997 (completing-read "Which function for creating the link? "
8998 sfunsn t (car sfunsn)))))
8999 (funcall (caar sfuns)))
9000 (setq link (plist-get org-store-link-plist :link)
9001 desc (or (plist-get org-store-link-plist :description) link))))
9002 ((org-src-edit-buffer-p)
9003 (let (label gc)
9004 (while (or (not label)
9005 (save-excursion
9006 (save-restriction
9007 (widen)
9008 (goto-char (point-min))
9009 (re-search-forward
9010 (regexp-quote (format org-coderef-label-format label))
9011 nil t))))
9012 (when label (message "Label exists already") (sit-for 2))
9013 (setq label (read-string "Code line label: " label)))
9014 (end-of-line 1)
9015 (setq link (format org-coderef-label-format label))
9016 (setq gc (- 79 (length link)))
9017 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9018 (insert link)
9019 (setq link (concat "(" label ")") desc nil)))
9021 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9022 ;; We are in the agenda, link to referenced location
9023 (let ((m (or (get-text-property (point) 'org-hd-marker)
9024 (get-text-property (point) 'org-marker))))
9025 (when m
9026 (org-with-point-at m
9027 (setq agenda-link
9028 (if (org-called-interactively-p 'any)
9029 (call-interactively 'org-store-link)
9030 (org-store-link nil)))))))
9032 ((eq major-mode 'calendar-mode)
9033 (let ((cd (calendar-cursor-to-date)))
9034 (setq link
9035 (format-time-string
9036 (car org-time-stamp-formats)
9037 (apply 'encode-time
9038 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9039 nil nil nil))))
9040 (org-store-link-props :type "calendar" :date cd)))
9042 ((eq major-mode 'help-mode)
9043 (setq link (concat "help:" (save-excursion
9044 (goto-char (point-min))
9045 (looking-at "^[^ ]+")
9046 (match-string 0))))
9047 (org-store-link-props :type "help"))
9049 ((eq major-mode 'w3-mode)
9050 (setq cpltxt (if (and (buffer-name)
9051 (not (string-match "Untitled" (buffer-name))))
9052 (buffer-name)
9053 (url-view-url t))
9054 link (url-view-url t))
9055 (org-store-link-props :type "w3" :url (url-view-url t)))
9057 ((setq search (run-hook-with-args-until-success
9058 'org-create-file-search-functions))
9059 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9060 "::" search))
9061 (setq cpltxt (or description link)))
9063 ((eq major-mode 'image-mode)
9064 (setq cpltxt (concat "file:"
9065 (abbreviate-file-name buffer-file-name))
9066 link cpltxt)
9067 (org-store-link-props :type "image" :file buffer-file-name))
9069 ((eq major-mode 'dired-mode)
9070 ;; link to the file in the current line
9071 (let ((file (dired-get-filename nil t)))
9072 (setq file (if file
9073 (abbreviate-file-name
9074 (expand-file-name (dired-get-filename nil t)))
9075 ;; otherwise, no file so use current directory.
9076 default-directory))
9077 (setq cpltxt (concat "file:" file)
9078 link cpltxt)))
9080 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9081 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9082 (cond
9083 ((org-in-regexp "<<\\(.*?\\)>>")
9084 (setq cpltxt
9085 (concat "file:"
9086 (abbreviate-file-name
9087 (buffer-file-name (buffer-base-buffer)))
9088 "::" (match-string 1))
9089 link cpltxt))
9090 ((and (featurep 'org-id)
9091 (or (eq org-id-link-to-org-use-id t)
9092 (and (org-called-interactively-p 'any)
9093 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9094 (and (eq org-id-link-to-org-use-id
9095 'create-if-interactive-and-no-custom-id)
9096 (not custom-id))))
9097 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9098 ;; We can make a link using the ID.
9099 (setq link (condition-case nil
9100 (prog1 (org-id-store-link)
9101 (setq desc (plist-get org-store-link-plist :description)))
9102 (error
9103 ;; probably before first headline, link to file only
9104 (concat "file:"
9105 (abbreviate-file-name
9106 (buffer-file-name (buffer-base-buffer))))))))
9108 ;; Just link to current headline
9109 (setq cpltxt (concat "file:"
9110 (abbreviate-file-name
9111 (buffer-file-name (buffer-base-buffer)))))
9112 ;; Add a context search string
9113 (when (org-xor org-context-in-file-links arg)
9114 (let* ((ee (org-element-at-point))
9115 (et (org-element-type ee))
9116 (ev (plist-get (cadr ee) :value)))
9117 (setq txt (cond
9118 ((org-at-heading-p) nil)
9119 ((eq et 'keyword) ev)
9120 ((org-region-active-p)
9121 (buffer-substring (region-beginning) (region-end)))))
9122 (when (or (null txt) (string-match "\\S-" txt))
9123 (setq cpltxt
9124 (concat cpltxt "::"
9125 (condition-case nil
9126 (org-make-org-heading-search-string txt)
9127 (error "")))
9128 desc (or (and (eq et 'keyword) ev)
9129 (nth 4 (ignore-errors (org-heading-components)))
9130 "NONE")))))
9131 (if (string-match "::\\'" cpltxt)
9132 (setq cpltxt (substring cpltxt 0 -2)))
9133 (setq link cpltxt))))
9135 ((buffer-file-name (buffer-base-buffer))
9136 ;; Just link to this file here.
9137 (setq cpltxt (concat "file:"
9138 (abbreviate-file-name
9139 (buffer-file-name (buffer-base-buffer)))))
9140 ;; Add a context string
9141 (when (org-xor org-context-in-file-links arg)
9142 (setq txt (if (org-region-active-p)
9143 (buffer-substring (region-beginning) (region-end))
9144 (buffer-substring (point-at-bol) (point-at-eol))))
9145 ;; Only use search option if there is some text.
9146 (when (string-match "\\S-" txt)
9147 (setq cpltxt
9148 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9149 desc "NONE")))
9150 (setq link cpltxt))
9152 ((org-called-interactively-p 'interactive)
9153 (user-error "No method for storing a link from this buffer"))
9155 (t (setq link nil)))
9157 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9158 (setq link (or link cpltxt)
9159 desc (or desc cpltxt))
9160 (cond ((equal desc "NONE") (setq desc nil))
9161 ((string-match org-bracket-link-regexp desc)
9162 (setq desc (replace-regexp-in-string
9163 org-bracket-link-regexp
9164 (concat "\\3" (if (equal (length (match-string 0 desc))
9165 (length desc)) "*" "")) desc))))
9167 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9168 (progn
9169 (setq org-stored-links
9170 (cons (list link desc) org-stored-links))
9171 (message "Stored: %s" (or desc link))
9172 (when custom-id
9173 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9174 "::#" custom-id))
9175 (setq org-stored-links
9176 (cons (list link desc) org-stored-links))))
9177 (or agenda-link (and link (org-make-link-string link desc)))))))
9179 (defun org-store-link-props (&rest plist)
9180 "Store link properties, extract names and addresses."
9181 (let (x adr)
9182 (when (setq x (plist-get plist :from))
9183 (setq adr (mail-extract-address-components x))
9184 (setq plist (plist-put plist :fromname (car adr)))
9185 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9186 (when (setq x (plist-get plist :to))
9187 (setq adr (mail-extract-address-components x))
9188 (setq plist (plist-put plist :toname (car adr)))
9189 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9190 (let ((from (plist-get plist :from))
9191 (to (plist-get plist :to)))
9192 (when (and from to org-from-is-user-regexp)
9193 (setq plist
9194 (plist-put plist :fromto
9195 (if (string-match org-from-is-user-regexp from)
9196 (concat "to %t")
9197 (concat "from %f"))))))
9198 (setq org-store-link-plist plist))
9200 (defun org-add-link-props (&rest plist)
9201 "Add these properties to the link property list."
9202 (let (key value)
9203 (while plist
9204 (setq key (pop plist) value (pop plist))
9205 (setq org-store-link-plist
9206 (plist-put org-store-link-plist key value)))))
9208 (defun org-email-link-description (&optional fmt)
9209 "Return the description part of an email link.
9210 This takes information from `org-store-link-plist' and formats it
9211 according to FMT (default from `org-email-link-description-format')."
9212 (setq fmt (or fmt org-email-link-description-format))
9213 (let* ((p org-store-link-plist)
9214 (to (plist-get p :toaddress))
9215 (from (plist-get p :fromaddress))
9216 (table
9217 (list
9218 (cons "%c" (plist-get p :fromto))
9219 (cons "%F" (plist-get p :from))
9220 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9221 (cons "%T" (plist-get p :to))
9222 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9223 (cons "%s" (plist-get p :subject))
9224 (cons "%d" (plist-get p :date))
9225 (cons "%m" (plist-get p :message-id)))))
9226 (when (string-match "%c" fmt)
9227 ;; Check if the user wrote this message
9228 (if (and org-from-is-user-regexp from to
9229 (save-match-data (string-match org-from-is-user-regexp from)))
9230 (setq fmt (replace-match "to %t" t t fmt))
9231 (setq fmt (replace-match "from %f" t t fmt))))
9232 (org-replace-escapes fmt table)))
9234 (defun org-make-org-heading-search-string (&optional string)
9235 "Make search string for the current headline or STRING."
9236 (let ((s (or string
9237 (and (derived-mode-p 'org-mode)
9238 (save-excursion
9239 (org-back-to-heading t)
9240 (plist-get (cadr (org-element-at-point))
9241 :raw-value)))))
9242 (lines org-context-in-file-links))
9243 (or string (setq s (concat "*" s))) ; Add * for headlines
9244 (when (and string (integerp lines) (> lines 0))
9245 (let ((slines (org-split-string s "\n")))
9246 (when (< lines (length slines))
9247 (setq s (mapconcat
9248 'identity
9249 (reverse (nthcdr (- (length slines) lines)
9250 (reverse slines))) "\n")))))
9251 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9253 (defun org-make-link-string (link &optional description)
9254 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9255 (unless (string-match "\\S-" link)
9256 (error "Empty link"))
9257 (when (and description
9258 (stringp description)
9259 (not (string-match "\\S-" description)))
9260 (setq description nil))
9261 (when (stringp description)
9262 ;; Remove brackets from the description, they are fatal.
9263 (while (string-match "\\[" description)
9264 (setq description (replace-match "{" t t description)))
9265 (while (string-match "\\]" description)
9266 (setq description (replace-match "}" t t description))))
9267 (when (equal link description)
9268 ;; No description needed, it is identical
9269 (setq description nil))
9270 (when (and (not description)
9271 (not (string-match (org-image-file-name-regexp) link))
9272 (not (equal link (org-link-escape link))))
9273 (setq description (org-extract-attributes link)))
9274 (setq link
9275 (cond ((string-match (org-image-file-name-regexp) link) link)
9276 ((string-match org-link-types-re link)
9277 (concat (match-string 1 link)
9278 (org-link-escape (substring link (match-end 1)))))
9279 (t (org-link-escape link))))
9280 (concat "[[" link "]"
9281 (if description (concat "[" description "]") "")
9282 "]"))
9284 (defconst org-link-escape-chars
9285 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9286 "List of characters that should be escaped in link.
9287 This is the list that is used for internal purposes.")
9289 (defconst org-link-escape-chars-browser
9290 '(?\ )
9291 "List of escapes for characters that are problematic in links.
9292 This is the list that is used before handing over to the browser.")
9294 (defun org-link-escape (text &optional table merge)
9295 "Return percent escaped representation of TEXT.
9296 TEXT is a string with the text to escape.
9297 Optional argument TABLE is a list with characters that should be
9298 escaped. When nil, `org-link-escape-chars' is used.
9299 If optional argument MERGE is set, merge TABLE into
9300 `org-link-escape-chars'."
9301 (cond
9302 ((and table merge)
9303 (mapc (lambda (defchr)
9304 (unless (member defchr table)
9305 (setq table (cons defchr table)))) org-link-escape-chars))
9306 ((null table)
9307 (setq table org-link-escape-chars)))
9308 (mapconcat
9309 (lambda (char)
9310 (if (or (member char table)
9311 (and (or (< char 32) (= char 37) (> char 126))
9312 org-url-hexify-p))
9313 (mapconcat (lambda (sequence-element)
9314 (format "%%%.2X" sequence-element))
9315 (or (encode-coding-char char 'utf-8)
9316 (error "Unable to percent escape character: %s"
9317 (char-to-string char))) "")
9318 (char-to-string char))) text ""))
9320 (defun org-link-unescape (str)
9321 "Unhex hexified Unicode strings as returned from the JavaScript function
9322 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9323 (unless (and (null str) (string= "" str))
9324 (let ((pos 0) (case-fold-search t) unhexed)
9325 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9326 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9327 (setq str (replace-match unhexed t t str))
9328 (setq pos (+ pos (length unhexed))))))
9329 str)
9331 (defun org-link-unescape-compound (hex)
9332 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9333 Note: this function also decodes single byte encodings like
9334 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9335 (save-match-data
9336 (let* ((bytes (cdr (split-string hex "%")))
9337 (ret "")
9338 (eat 0)
9339 (sum 0))
9340 (while bytes
9341 (let* ((val (string-to-number (pop bytes) 16))
9342 (shift-xor
9343 (if (= 0 eat)
9344 (cond
9345 ((>= val 252) (cons 6 252))
9346 ((>= val 248) (cons 5 248))
9347 ((>= val 240) (cons 4 240))
9348 ((>= val 224) (cons 3 224))
9349 ((>= val 192) (cons 2 192))
9350 (t (cons 0 0)))
9351 (cons 6 128))))
9352 (if (>= val 192) (setq eat (car shift-xor)))
9353 (setq val (logxor val (cdr shift-xor)))
9354 (setq sum (+ (lsh sum (car shift-xor)) val))
9355 (if (> eat 0) (setq eat (- eat 1)))
9356 (cond
9357 ((= 0 eat) ;multi byte
9358 (setq ret (concat ret (org-char-to-string sum)))
9359 (setq sum 0))
9360 ((not bytes) ; single byte(s)
9361 (setq ret (org-link-unescape-single-byte-sequence hex))))
9362 )) ;; end (while bytes
9363 ret )))
9365 (defun org-link-unescape-single-byte-sequence (hex)
9366 "Unhexify hex-encoded single byte character sequences."
9367 (mapconcat (lambda (byte)
9368 (char-to-string (string-to-number byte 16)))
9369 (cdr (split-string hex "%")) ""))
9371 (defun org-xor (a b)
9372 "Exclusive or."
9373 (if a (not b) b))
9375 (defun org-fixup-message-id-for-http (s)
9376 "Replace special characters in a message id, so it can be used in an http query."
9377 (when (string-match "%" s)
9378 (setq s (mapconcat (lambda (c)
9379 (if (eq c ?%)
9380 "%25"
9381 (char-to-string c)))
9382 s "")))
9383 (while (string-match "<" s)
9384 (setq s (replace-match "%3C" t t s)))
9385 (while (string-match ">" s)
9386 (setq s (replace-match "%3E" t t s)))
9387 (while (string-match "@" s)
9388 (setq s (replace-match "%40" t t s)))
9391 (defun org-link-prettify (link)
9392 "Return a human-readable representation of LINK.
9393 The car of LINK must be a raw link the cdr of LINK must be either
9394 a link description or nil."
9395 (let ((desc (or (cadr link) "<no description>")))
9396 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9397 "<" (car link) ">")))
9399 ;;;###autoload
9400 (defun org-insert-link-global ()
9401 "Insert a link like Org-mode does.
9402 This command can be called in any mode to insert a link in Org-mode syntax."
9403 (interactive)
9404 (org-load-modules-maybe)
9405 (org-run-like-in-org-mode 'org-insert-link))
9407 (defun org-insert-all-links (&optional keep)
9408 "Insert all links in `org-stored-links'."
9409 (interactive "P")
9410 (let ((links (copy-sequence org-stored-links)) l)
9411 (while (setq l (if keep (pop links) (pop org-stored-links)))
9412 (insert "- ")
9413 (org-insert-link nil (car l) (cadr l))
9414 (insert "\n"))))
9416 (defun org-link-fontify-links-to-this-file ()
9417 "Fontify links to the current file in `org-stored-links'."
9418 (let ((f (buffer-file-name)) a b)
9419 (setq a (mapcar (lambda(l)
9420 (let ((ll (car l)))
9421 (when (and (string-match "^file:\\(.+\\)::" ll)
9422 (equal f (expand-file-name (match-string 1 ll))))
9423 ll)))
9424 org-stored-links))
9425 (when (featurep 'org-id)
9426 (setq b (mapcar (lambda(l)
9427 (let ((ll (car l)))
9428 (when (and (string-match "^id:\\(.+\\)$" ll)
9429 (equal f (expand-file-name
9430 (or (org-id-find-id-file
9431 (match-string 1 ll)) ""))))
9432 ll)))
9433 org-stored-links)))
9434 (mapcar (lambda(l)
9435 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9436 (delq nil (append a b)))))
9438 (defvar org-link-links-in-this-file nil)
9439 (defun org-insert-link (&optional complete-file link-location default-description)
9440 "Insert a link. At the prompt, enter the link.
9442 Completion can be used to insert any of the link protocol prefixes like
9443 http or ftp in use.
9445 The history can be used to select a link previously stored with
9446 `org-store-link'. When the empty string is entered (i.e. if you just
9447 press RET at the prompt), the link defaults to the most recently
9448 stored link. As SPC triggers completion in the minibuffer, you need to
9449 use M-SPC or C-q SPC to force the insertion of a space character.
9451 You will also be prompted for a description, and if one is given, it will
9452 be displayed in the buffer instead of the link.
9454 If there is already a link at point, this command will allow you to edit link
9455 and description parts.
9457 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9458 be selected using completion. The path to the file will be relative to the
9459 current directory if the file is in the current directory or a subdirectory.
9460 Otherwise, the link will be the absolute path as completed in the minibuffer
9461 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9462 option `org-link-file-path-type'.
9464 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9465 the current directory or below.
9467 With three \\[universal-argument] prefixes, negate the meaning of
9468 `org-keep-stored-link-after-insertion'.
9470 If `org-make-link-description-function' is non-nil, this function will be
9471 called with the link target, and the result will be the default
9472 link description.
9474 If the LINK-LOCATION parameter is non-nil, this value will be
9475 used as the link location instead of reading one interactively.
9477 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9478 be used as the default description."
9479 (interactive "P")
9480 (let* ((wcf (current-window-configuration))
9481 (origbuf (current-buffer))
9482 (region (if (org-region-active-p)
9483 (buffer-substring (region-beginning) (region-end))))
9484 (remove (and region (list (region-beginning) (region-end))))
9485 (desc region)
9486 tmphist ; byte-compile incorrectly complains about this
9487 (link link-location)
9488 (abbrevs org-link-abbrev-alist-local)
9489 entry file all-prefixes auto-desc)
9490 (cond
9491 (link-location) ; specified by arg, just use it.
9492 ((org-in-regexp org-bracket-link-regexp 1)
9493 ;; We do have a link at point, and we are going to edit it.
9494 (setq remove (list (match-beginning 0) (match-end 0)))
9495 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9496 (setq link (read-string "Link: "
9497 (org-link-unescape
9498 (org-match-string-no-properties 1)))))
9499 ((or (org-in-regexp org-angle-link-re)
9500 (org-in-regexp org-plain-link-re))
9501 ;; Convert to bracket link
9502 (setq remove (list (match-beginning 0) (match-end 0))
9503 link (read-string "Link: "
9504 (org-remove-angle-brackets (match-string 0)))))
9505 ((member complete-file '((4) (16)))
9506 ;; Completing read for file names.
9507 (setq link (org-file-complete-link complete-file)))
9509 ;; Read link, with completion for stored links.
9510 (org-link-fontify-links-to-this-file)
9511 (org-switch-to-buffer-other-window "*Org Links*")
9512 (with-current-buffer "*Org Links*"
9513 (erase-buffer)
9514 (insert "Insert a link.
9515 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9516 (when org-stored-links
9517 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9518 (insert (mapconcat 'org-link-prettify
9519 (reverse org-stored-links) "\n")))
9520 (goto-char (point-min)))
9521 (let ((cw (selected-window)))
9522 (select-window (get-buffer-window "*Org Links*" 'visible))
9523 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9524 (unless (pos-visible-in-window-p (point-max))
9525 (org-fit-window-to-buffer))
9526 (and (window-live-p cw) (select-window cw)))
9527 ;; Fake a link history, containing the stored links.
9528 (setq tmphist (append (mapcar 'car org-stored-links)
9529 org-insert-link-history))
9530 (setq all-prefixes (append (mapcar 'car abbrevs)
9531 (mapcar 'car org-link-abbrev-alist)
9532 org-link-types))
9533 (unwind-protect
9534 (progn
9535 (setq link
9536 (org-completing-read
9537 "Link: "
9538 (append
9539 (mapcar (lambda (x) (concat x ":"))
9540 all-prefixes)
9541 (mapcar 'car org-stored-links))
9542 nil nil nil
9543 'tmphist
9544 (caar org-stored-links)))
9545 (if (not (string-match "\\S-" link))
9546 (error "No link selected"))
9547 (mapc (lambda(l)
9548 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9549 org-stored-links)
9550 (if (or (member link all-prefixes)
9551 (and (equal ":" (substring link -1))
9552 (member (substring link 0 -1) all-prefixes)
9553 (setq link (substring link 0 -1))))
9554 (setq link (with-current-buffer origbuf
9555 (org-link-try-special-completion link)))))
9556 (set-window-configuration wcf)
9557 (kill-buffer "*Org Links*"))
9558 (setq entry (assoc link org-stored-links))
9559 (or entry (push link org-insert-link-history))
9560 (setq desc (or desc (nth 1 entry)))))
9562 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9563 (not org-keep-stored-link-after-insertion))
9564 (setq org-stored-links (delq (assoc link org-stored-links)
9565 org-stored-links)))
9567 (if (string-match org-plain-link-re link)
9568 ;; URL-like link, normalize the use of angular brackets.
9569 (setq link (org-remove-angle-brackets link)))
9571 ;; Check if we are linking to the current file with a search
9572 ;; option If yes, simplify the link by using only the search
9573 ;; option.
9574 (when (and buffer-file-name
9575 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9576 (let* ((path (match-string 1 link))
9577 (case-fold-search nil)
9578 (search (match-string 2 link)))
9579 (save-match-data
9580 (if (equal (file-truename buffer-file-name) (file-truename path))
9581 ;; We are linking to this same file, with a search option
9582 (setq link search)))))
9584 ;; Check if we can/should use a relative path. If yes, simplify the link
9585 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9586 (let* ((type (match-string 1 link))
9587 (path (match-string 2 link))
9588 (origpath path)
9589 (case-fold-search nil))
9590 (cond
9591 ((or (eq org-link-file-path-type 'absolute)
9592 (equal complete-file '(16)))
9593 (setq path (abbreviate-file-name (expand-file-name path))))
9594 ((eq org-link-file-path-type 'noabbrev)
9595 (setq path (expand-file-name path)))
9596 ((eq org-link-file-path-type 'relative)
9597 (setq path (file-relative-name path)))
9599 (save-match-data
9600 (if (string-match (concat "^" (regexp-quote
9601 (expand-file-name
9602 (file-name-as-directory
9603 default-directory))))
9604 (expand-file-name path))
9605 ;; We are linking a file with relative path name.
9606 (setq path (substring (expand-file-name path)
9607 (match-end 0)))
9608 (setq path (abbreviate-file-name (expand-file-name path)))))))
9609 (setq link (concat type path))
9610 (if (equal desc origpath)
9611 (setq desc path))))
9613 (if org-make-link-description-function
9614 (setq desc
9615 (or (condition-case nil
9616 (funcall org-make-link-description-function link desc)
9617 (error (progn (message "Can't get link description from `%s'"
9618 (symbol-name org-make-link-description-function))
9619 (sit-for 2) nil)))
9620 (read-string "Description: " default-description)))
9621 (if default-description (setq desc default-description)
9622 (setq desc (or (and auto-desc desc)
9623 (read-string "Description: " desc)))))
9625 (unless (string-match "\\S-" desc) (setq desc nil))
9626 (if remove (apply 'delete-region remove))
9627 (insert (org-make-link-string link desc))))
9629 (defun org-link-try-special-completion (type)
9630 "If there is completion support for link type TYPE, offer it."
9631 (let ((fun (intern (concat "org-" type "-complete-link"))))
9632 (if (functionp fun)
9633 (funcall fun)
9634 (read-string "Link (no completion support): " (concat type ":")))))
9636 (defun org-file-complete-link (&optional arg)
9637 "Create a file link using completion."
9638 (let (file link)
9639 (setq file (org-iread-file-name "File: "))
9640 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9641 (pwd1 (file-name-as-directory (abbreviate-file-name
9642 (expand-file-name ".")))))
9643 (cond
9644 ((equal arg '(16))
9645 (setq link (concat
9646 "file:"
9647 (abbreviate-file-name (expand-file-name file)))))
9648 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9649 (setq link (concat "file:" (match-string 1 file))))
9650 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9651 (expand-file-name file))
9652 (setq link (concat
9653 "file:" (match-string 1 (expand-file-name file)))))
9654 (t (setq link (concat "file:" file)))))
9655 link))
9657 (defun org-iread-file-name (&rest args)
9658 "Read-file-name using `ido-mode' speedup if available.
9659 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9660 See `read-file-name' for a description of parameters."
9661 (org-without-partial-completion
9662 (if (and org-completion-use-ido
9663 (fboundp 'ido-read-file-name)
9664 (boundp 'ido-mode) ido-mode
9665 (listp (second args)))
9666 (let ((ido-enter-matching-directory nil))
9667 (apply 'ido-read-file-name args))
9668 (apply 'read-file-name args))))
9670 (defun org-completing-read (&rest args)
9671 "Completing-read with SPACE being a normal character."
9672 (let ((enable-recursive-minibuffers t)
9673 (minibuffer-local-completion-map
9674 (copy-keymap minibuffer-local-completion-map)))
9675 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9676 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9677 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9678 (apply 'org-icompleting-read args)))
9680 (defun org-completing-read-no-i (&rest args)
9681 (let (org-completion-use-ido org-completion-use-iswitchb)
9682 (apply 'org-completing-read args)))
9684 (defun org-iswitchb-completing-read (prompt choices &rest args)
9685 "Use iswitch as a completing-read replacement to choose from choices.
9686 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9687 from."
9688 (let* ((iswitchb-use-virtual-buffers nil)
9689 (iswitchb-make-buflist-hook
9690 (lambda ()
9691 (setq iswitchb-temp-buflist choices))))
9692 (iswitchb-read-buffer prompt)))
9694 (defun org-icompleting-read (&rest args)
9695 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9696 (org-without-partial-completion
9697 (if (and org-completion-use-ido
9698 (fboundp 'ido-completing-read)
9699 (boundp 'ido-mode) ido-mode
9700 (listp (second args)))
9701 (let ((ido-enter-matching-directory nil))
9702 (apply 'ido-completing-read (concat (car args))
9703 (if (consp (car (nth 1 args)))
9704 (mapcar 'car (nth 1 args))
9705 (nth 1 args))
9706 (cddr args)))
9707 (if (and org-completion-use-iswitchb
9708 (boundp 'iswitchb-mode) iswitchb-mode
9709 (listp (second args)))
9710 (apply 'org-iswitchb-completing-read (concat (car args))
9711 (if (consp (car (nth 1 args)))
9712 (mapcar 'car (nth 1 args))
9713 (nth 1 args))
9714 (cddr args))
9715 (apply 'completing-read args)))))
9717 (defun org-extract-attributes (s)
9718 "Extract the attributes cookie from a string and set as text property."
9719 (let (a attr (start 0) key value)
9720 (save-match-data
9721 (when (string-match "{{\\([^}]+\\)}}$" s)
9722 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9723 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9724 (setq key (match-string 1 a) value (match-string 2 a)
9725 start (match-end 0)
9726 attr (plist-put attr (intern key) value))))
9727 (org-add-props s nil 'org-attr attr))
9730 (defun org-extract-attributes-from-string (tag)
9731 (let (key value attr)
9732 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9733 (setq key (match-string 1 tag) value (match-string 2 tag)
9734 tag (replace-match "" t t tag)
9735 attr (plist-put attr (intern key) value)))
9736 (cons tag attr)))
9738 (defun org-attributes-to-string (plist)
9739 "Format a property list into an HTML attribute list."
9740 (let ((s "") key value)
9741 (while plist
9742 (setq key (pop plist) value (pop plist))
9743 (and value
9744 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9747 ;;; Opening/following a link
9749 (defvar org-link-search-failed nil)
9751 (defvar org-open-link-functions nil
9752 "Hook for functions finding a plain text link.
9753 These functions must take a single argument, the link content.
9754 They will be called for links that look like [[link text][description]]
9755 when LINK TEXT does not have a protocol like \"http:\" and does not look
9756 like a filename (e.g. \"./blue.png\").
9758 These functions will be called *before* Org attempts to resolve the
9759 link by doing text searches in the current buffer - so if you want a
9760 link \"[[target]]\" to still find \"<<target>>\", your function should
9761 handle this as a special case.
9763 When the function does handle the link, it must return a non-nil value.
9764 If it decides that it is not responsible for this link, it must return
9765 nil to indicate that that Org-mode can continue with other options
9766 like exact and fuzzy text search.")
9768 (defun org-next-link ()
9769 "Move forward to the next link.
9770 If the link is in hidden text, expose it."
9771 (interactive)
9772 (when (and org-link-search-failed (eq this-command last-command))
9773 (goto-char (point-min))
9774 (message "Link search wrapped back to beginning of buffer"))
9775 (setq org-link-search-failed nil)
9776 (let* ((pos (point))
9777 (ct (org-context))
9778 (a (assoc :link ct)))
9779 (if a (goto-char (nth 2 a)))
9780 (if (re-search-forward org-any-link-re nil t)
9781 (progn
9782 (goto-char (match-beginning 0))
9783 (if (outline-invisible-p) (org-show-context)))
9784 (goto-char pos)
9785 (setq org-link-search-failed t)
9786 (error "No further link found"))))
9788 (defun org-previous-link ()
9789 "Move backward to the previous link.
9790 If the link is in hidden text, expose it."
9791 (interactive)
9792 (when (and org-link-search-failed (eq this-command last-command))
9793 (goto-char (point-max))
9794 (message "Link search wrapped back to end of buffer"))
9795 (setq org-link-search-failed nil)
9796 (let* ((pos (point))
9797 (ct (org-context))
9798 (a (assoc :link ct)))
9799 (if a (goto-char (nth 1 a)))
9800 (if (re-search-backward org-any-link-re nil t)
9801 (progn
9802 (goto-char (match-beginning 0))
9803 (if (outline-invisible-p) (org-show-context)))
9804 (goto-char pos)
9805 (setq org-link-search-failed t)
9806 (error "No further link found"))))
9808 (defun org-translate-link (s)
9809 "Translate a link string if a translation function has been defined."
9810 (if (and org-link-translation-function
9811 (fboundp org-link-translation-function)
9812 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9813 (progn
9814 (setq s (funcall org-link-translation-function
9815 (match-string 1 s) (match-string 2 s)))
9816 (concat (car s) ":" (cdr s)))
9819 (defun org-translate-link-from-planner (type path)
9820 "Translate a link from Emacs Planner syntax so that Org can follow it.
9821 This is still an experimental function, your mileage may vary."
9822 (cond
9823 ((member type '("http" "https" "news" "ftp"))
9824 ;; standard Internet links are the same.
9825 nil)
9826 ((and (equal type "irc") (string-match "^//" path))
9827 ;; Planner has two / at the beginning of an irc link, we have 1.
9828 ;; We should have zero, actually....
9829 (setq path (substring path 1)))
9830 ((and (equal type "lisp") (string-match "^/" path))
9831 ;; Planner has a slash, we do not.
9832 (setq type "elisp" path (substring path 1)))
9833 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9834 ;; A typical message link. Planner has the id after the final slash,
9835 ;; we separate it with a hash mark
9836 (setq path (concat (match-string 1 path) "#"
9837 (org-remove-angle-brackets (match-string 2 path)))))
9839 (cons type path))
9841 (defun org-find-file-at-mouse (ev)
9842 "Open file link or URL at mouse."
9843 (interactive "e")
9844 (mouse-set-point ev)
9845 (org-open-at-point 'in-emacs))
9847 (defun org-open-at-mouse (ev)
9848 "Open file link or URL at mouse.
9849 See the docstring of `org-open-file' for details."
9850 (interactive "e")
9851 (mouse-set-point ev)
9852 (if (eq major-mode 'org-agenda-mode)
9853 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9854 (org-open-at-point))
9856 (defvar org-window-config-before-follow-link nil
9857 "The window configuration before following a link.
9858 This is saved in case the need arises to restore it.")
9860 (defvar org-open-link-marker (make-marker)
9861 "Marker pointing to the location where `org-open-at-point; was called.")
9863 ;;;###autoload
9864 (defun org-open-at-point-global ()
9865 "Follow a link like Org-mode does.
9866 This command can be called in any mode to follow a link that has
9867 Org-mode syntax."
9868 (interactive)
9869 (org-run-like-in-org-mode 'org-open-at-point))
9871 ;;;###autoload
9872 (defun org-open-link-from-string (s &optional arg reference-buffer)
9873 "Open a link in the string S, as if it was in Org-mode."
9874 (interactive "sLink: \nP")
9875 (let ((reference-buffer (or reference-buffer (current-buffer))))
9876 (with-temp-buffer
9877 (let ((org-inhibit-startup (not reference-buffer)))
9878 (org-mode)
9879 (insert s)
9880 (goto-char (point-min))
9881 (when reference-buffer
9882 (setq org-link-abbrev-alist-local
9883 (with-current-buffer reference-buffer
9884 org-link-abbrev-alist-local)))
9885 (org-open-at-point arg reference-buffer)))))
9887 (defvar org-open-at-point-functions nil
9888 "Hook that is run when following a link at point.
9890 Functions in this hook must return t if they identify and follow
9891 a link at point. If they don't find anything interesting at point,
9892 they must return nil.")
9894 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9895 (defun org-open-at-point (&optional arg reference-buffer)
9896 "Open link at or after point.
9897 If there is no link at point, this function will search forward up to
9898 the end of the current line.
9899 Normally, files will be opened by an appropriate application. If the
9900 optional prefix argument ARG is non-nil, Emacs will visit the file.
9901 With a double prefix argument, try to open outside of Emacs, in the
9902 application the system uses for this file type."
9903 (interactive "P")
9904 ;; if in a code block, then open the block's results
9905 (unless (call-interactively #'org-babel-open-src-block-result)
9906 (org-load-modules-maybe)
9907 (move-marker org-open-link-marker (point))
9908 (setq org-window-config-before-follow-link (current-window-configuration))
9909 (org-remove-occur-highlights nil nil t)
9910 (cond
9911 ((and (org-at-heading-p)
9912 (not (org-at-timestamp-p t))
9913 (not (org-in-regexp
9914 (concat org-plain-link-re "\\|"
9915 org-bracket-link-regexp "\\|"
9916 org-angle-link-re "\\|"
9917 "[ \t]:[^ \t\n]+:[ \t]*$")))
9918 (not (get-text-property (point) 'org-linked-text)))
9919 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9920 (lk0 (car lkall))
9921 (lk (if (stringp lk0) (list lk0) lk0))
9922 (lkend (cdr lkall)))
9923 (mapcar (lambda(l)
9924 (search-forward l nil lkend)
9925 (goto-char (match-beginning 0))
9926 (org-open-at-point))
9927 lk))
9928 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9929 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9930 ((and (org-at-timestamp-p t)
9931 (not (org-in-regexp org-bracket-link-regexp)))
9932 (org-follow-timestamp-link))
9933 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9934 (not (org-in-regexp org-any-link-re)))
9935 (org-footnote-action))
9937 (let (type path link line search (pos (point)))
9938 (catch 'match
9939 (save-excursion
9940 (skip-chars-forward "^]\n\r")
9941 (when (org-in-regexp org-bracket-link-regexp 1)
9942 (setq link (org-extract-attributes
9943 (org-link-unescape (org-match-string-no-properties 1))))
9944 (while (string-match " *\n *" link)
9945 (setq link (replace-match " " t t link)))
9946 (setq link (org-link-expand-abbrev link))
9947 (cond
9948 ((or (file-name-absolute-p link)
9949 (string-match "^\\.\\.?/" link))
9950 (setq type "file" path link))
9951 ((string-match org-link-re-with-space3 link)
9952 (setq type (match-string 1 link) path (match-string 2 link)))
9953 ((string-match "^help:+\\(.+\\)" link)
9954 (setq type "help" path (match-string 1 link)))
9955 (t (setq type "thisfile" path link)))
9956 (throw 'match t)))
9958 (when (get-text-property (point) 'org-linked-text)
9959 (setq type "thisfile"
9960 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9961 (1+ (point)) (point))
9962 path (buffer-substring
9963 (or (previous-single-property-change pos 'org-linked-text)
9964 (point-min))
9965 (or (next-single-property-change pos 'org-linked-text)
9966 (point-max))))
9967 (throw 'match t))
9969 (save-excursion
9970 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9971 (when (or (org-in-regexp org-angle-link-re)
9972 (and plinkpos (goto-char (car plinkpos))
9973 (save-match-data (not (looking-back "\\[\\[")))))
9974 (setq type (match-string 1)
9975 path (org-link-unescape (match-string 2)))
9976 (throw 'match t))))
9977 (save-excursion
9978 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9979 (setq type "tags"
9980 path (match-string 1))
9981 (while (string-match ":" path)
9982 (setq path (replace-match "+" t t path)))
9983 (throw 'match t)))
9984 (when (org-in-regexp "<\\([^><\n]+\\)>")
9985 (setq type "tree-match"
9986 path (match-string 1))
9987 (throw 'match t)))
9988 (unless path
9989 (user-error "No link found"))
9991 ;; switch back to reference buffer
9992 ;; needed when if called in a temporary buffer through
9993 ;; org-open-link-from-string
9994 (with-current-buffer (or reference-buffer (current-buffer))
9996 ;; Remove any trailing spaces in path
9997 (if (string-match " +\\'" path)
9998 (setq path (replace-match "" t t path)))
9999 (if (and org-link-translation-function
10000 (fboundp org-link-translation-function))
10001 ;; Check if we need to translate the link
10002 (let ((tmp (funcall org-link-translation-function type path)))
10003 (setq type (car tmp) path (cdr tmp))))
10005 (cond
10007 ((assoc type org-link-protocols)
10008 (funcall (nth 1 (assoc type org-link-protocols)) path))
10010 ((equal type "help")
10011 (let ((f-or-v (intern path)))
10012 (cond ((fboundp f-or-v)
10013 (describe-function f-or-v))
10014 ((boundp f-or-v)
10015 (describe-variable f-or-v))
10016 (t (error "Not a known function or variable")))))
10018 ((equal type "mailto")
10019 (let ((cmd (car org-link-mailto-program))
10020 (args (cdr org-link-mailto-program)) args1
10021 (address path) (subject "") a)
10022 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10023 (setq address (match-string 1 path)
10024 subject (org-link-escape (match-string 2 path))))
10025 (while args
10026 (cond
10027 ((not (stringp (car args))) (push (pop args) args1))
10028 (t (setq a (pop args))
10029 (if (string-match "%a" a)
10030 (setq a (replace-match address t t a)))
10031 (if (string-match "%s" a)
10032 (setq a (replace-match subject t t a)))
10033 (push a args1))))
10034 (apply cmd (nreverse args1))))
10036 ((member type '("http" "https" "ftp" "news"))
10037 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10038 (org-link-escape
10039 path org-link-escape-chars-browser)
10040 path))))
10042 ((string= type "doi")
10043 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10044 (org-link-escape
10045 path org-link-escape-chars-browser)
10046 path))))
10048 ((member type '("message"))
10049 (browse-url (concat type ":" path)))
10051 ((string= type "tags")
10052 (org-tags-view arg path))
10054 ((string= type "tree-match")
10055 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10057 ((string= type "file")
10058 (if (string-match "::\\([0-9]+\\)\\'" path)
10059 (setq line (string-to-number (match-string 1 path))
10060 path (substring path 0 (match-beginning 0)))
10061 (if (string-match "::\\(.+\\)\\'" path)
10062 (setq search (match-string 1 path)
10063 path (substring path 0 (match-beginning 0)))))
10064 (if (string-match "[*?{]" (file-name-nondirectory path))
10065 (dired path)
10066 (org-open-file path arg line search)))
10068 ((string= type "shell")
10069 (let ((buf (generate-new-buffer "*Org Shell Output"))
10070 (cmd path))
10071 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10072 (string-match org-confirm-shell-link-not-regexp cmd))
10073 (not org-confirm-shell-link-function)
10074 (funcall org-confirm-shell-link-function
10075 (format "Execute \"%s\" in shell? "
10076 (org-add-props cmd nil
10077 'face 'org-warning))))
10078 (progn
10079 (message "Executing %s" cmd)
10080 (shell-command cmd buf)
10081 (if (featurep 'midnight)
10082 (setq clean-buffer-list-kill-buffer-names
10083 (cons buf clean-buffer-list-kill-buffer-names))))
10084 (error "Abort"))))
10086 ((string= type "elisp")
10087 (let ((cmd path))
10088 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10089 (string-match org-confirm-elisp-link-not-regexp cmd))
10090 (not org-confirm-elisp-link-function)
10091 (funcall org-confirm-elisp-link-function
10092 (format "Execute \"%s\" as elisp? "
10093 (org-add-props cmd nil
10094 'face 'org-warning))))
10095 (message "%s => %s" cmd
10096 (if (equal (string-to-char cmd) ?\()
10097 (eval (read cmd))
10098 (call-interactively (read cmd))))
10099 (error "Abort"))))
10101 ((and (string= type "thisfile")
10102 (run-hook-with-args-until-success
10103 'org-open-link-functions path)))
10105 ((string= type "thisfile")
10106 (if arg
10107 (switch-to-buffer-other-window
10108 (org-get-buffer-for-internal-link (current-buffer)))
10109 (org-mark-ring-push))
10110 (let ((cmd `(org-link-search
10111 ,path
10112 ,(cond ((equal arg '(4)) ''occur)
10113 ((equal arg '(16)) ''org-occur))
10114 ,pos)))
10115 (condition-case nil (let ((org-link-search-inhibit-query t))
10116 (eval cmd))
10117 (error (progn (widen) (eval cmd))))))
10119 (t (browse-url-at-point)))))))
10120 (move-marker org-open-link-marker nil)
10121 (run-hook-with-args 'org-follow-link-hook)))
10123 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10124 "Offer links in the current entry and return the selected link.
10125 If there is only one link, return it.
10126 If NTH is an integer, return the NTH link found.
10127 If ZERO is a string, check also this string for a link, and if
10128 there is one, return it."
10129 (with-current-buffer buffer
10130 (save-excursion
10131 (save-restriction
10132 (widen)
10133 (goto-char marker)
10134 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10135 "\\(" org-angle-link-re "\\)\\|"
10136 "\\(" org-plain-link-re "\\)"))
10137 (cnt ?0)
10138 (in-emacs (if (integerp nth) nil nth))
10139 have-zero end links link c)
10140 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10141 (push (match-string 0 zero) links)
10142 (setq cnt (1- cnt) have-zero t))
10143 (save-excursion
10144 (org-back-to-heading t)
10145 (setq end (save-excursion (outline-next-heading) (point)))
10146 (while (re-search-forward re end t)
10147 (push (match-string 0) links))
10148 (setq links (org-uniquify (reverse links))))
10149 (cond
10150 ((null links)
10151 (message "No links"))
10152 ((equal (length links) 1)
10153 (setq link (car links)))
10154 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10155 (setq link (nth (if have-zero nth (1- nth)) links)))
10156 (t ; we have to select a link
10157 (save-excursion
10158 (save-window-excursion
10159 (delete-other-windows)
10160 (with-output-to-temp-buffer "*Select Link*"
10161 (mapc (lambda (l)
10162 (if (not (string-match org-bracket-link-regexp l))
10163 (princ (format "[%c] %s\n" (incf cnt)
10164 (org-remove-angle-brackets l)))
10165 (if (match-end 3)
10166 (princ (format "[%c] %s (%s)\n" (incf cnt)
10167 (match-string 3 l) (match-string 1 l)))
10168 (princ (format "[%c] %s\n" (incf cnt)
10169 (match-string 1 l))))))
10170 links))
10171 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10172 (message "Select link to open, RET to open all:")
10173 (setq c (read-char-exclusive))
10174 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10175 (when (equal c ?q) (error "Abort"))
10176 (if (equal c ?\C-m)
10177 (setq link links)
10178 (setq nth (- c ?0))
10179 (if have-zero (setq nth (1+ nth)))
10180 (unless (and (integerp nth) (>= (length links) nth))
10181 (error "Invalid link selection"))
10182 (setq link (nth (1- nth) links)))))
10183 (cons link end))))))
10185 ;; Add special file links that specify the way of opening
10187 (org-add-link-type "file+sys" 'org-open-file-with-system)
10188 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10189 (defun org-open-file-with-system (path)
10190 "Open file at PATH using the system way of opening it."
10191 (org-open-file path 'system))
10192 (defun org-open-file-with-emacs (path)
10193 "Open file at PATH in Emacs."
10194 (org-open-file path 'emacs))
10197 ;;; File search
10199 (defvar org-create-file-search-functions nil
10200 "List of functions to construct the right search string for a file link.
10201 These functions are called in turn with point at the location to
10202 which the link should point.
10204 A function in the hook should first test if it would like to
10205 handle this file type, for example by checking the `major-mode'
10206 or the file extension. If it decides not to handle this file, it
10207 should just return nil to give other functions a chance. If it
10208 does handle the file, it must return the search string to be used
10209 when following the link. The search string will be part of the
10210 file link, given after a double colon, and `org-open-at-point'
10211 will automatically search for it. If special measures must be
10212 taken to make the search successful, another function should be
10213 added to the companion hook `org-execute-file-search-functions',
10214 which see.
10216 A function in this hook may also use `setq' to set the variable
10217 `description' to provide a suggestion for the descriptive text to
10218 be used for this link when it gets inserted into an Org-mode
10219 buffer with \\[org-insert-link].")
10221 (defvar org-execute-file-search-functions nil
10222 "List of functions to execute a file search triggered by a link.
10224 Functions added to this hook must accept a single argument, the
10225 search string that was part of the file link, the part after the
10226 double colon. The function must first check if it would like to
10227 handle this search, for example by checking the `major-mode' or
10228 the file extension. If it decides not to handle this search, it
10229 should just return nil to give other functions a chance. If it
10230 does handle the search, it must return a non-nil value to keep
10231 other functions from trying.
10233 Each function can access the current prefix argument through the
10234 variable `current-prefix-argument'. Note that a single prefix is
10235 used to force opening a link in Emacs, so it may be good to only
10236 use a numeric or double prefix to guide the search function.
10238 In case this is needed, a function in this hook can also restore
10239 the window configuration before `org-open-at-point' was called using:
10241 (set-window-configuration org-window-config-before-follow-link)")
10243 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10244 (defun org-link-search (s &optional type avoid-pos stealth)
10245 "Search for a link search option.
10246 If S is surrounded by forward slashes, it is interpreted as a
10247 regular expression. In org-mode files, this will create an `org-occur'
10248 sparse tree. In ordinary files, `occur' will be used to list matches.
10249 If the current buffer is in `dired-mode', grep will be used to search
10250 in all files. If AVOID-POS is given, ignore matches near that position.
10252 When optional argument STEALTH is non-nil, do not modify
10253 visibility around point, thus ignoring
10254 `org-show-hierarchy-above', `org-show-following-heading' and
10255 `org-show-siblings' variables."
10256 (let ((case-fold-search t)
10257 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10258 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10259 (append '(("") (" ") ("\t") ("\n"))
10260 org-emphasis-alist)
10261 "\\|") "\\)"))
10262 (pos (point))
10263 (pre nil) (post nil)
10264 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10265 (cond
10266 ;; First check if there are any special search functions
10267 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10268 ;; Now try the builtin stuff
10269 ((and (equal (string-to-char s0) ?#)
10270 (> (length s0) 1)
10271 (save-excursion
10272 (goto-char (point-min))
10273 (and
10274 (re-search-forward
10275 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10276 (setq type 'dedicated
10277 pos (match-beginning 0))))
10278 ;; There is an exact target for this
10279 (goto-char pos)
10280 (org-back-to-heading t)))
10281 ((save-excursion
10282 (goto-char (point-min))
10283 (and
10284 (re-search-forward
10285 (concat "<<" (regexp-quote s0) ">>") nil t)
10286 (setq type 'dedicated
10287 pos (match-beginning 0))))
10288 ;; There is an exact target for this
10289 (goto-char pos))
10290 ((save-excursion
10291 (goto-char (point-min))
10292 (and
10293 (re-search-forward
10294 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10295 (setq type 'dedicated pos (match-beginning 0))))
10296 ;; Found an invisible target.
10297 (goto-char pos))
10298 ((save-excursion
10299 (goto-char (point-min))
10300 (and
10301 (re-search-forward
10302 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10303 (setq type 'dedicated pos (match-beginning 0))))
10304 ;; Found an element with a matching #+name affiliated keyword.
10305 (goto-char pos))
10306 ((and (string-match "^(\\(.*\\))$" s0)
10307 (save-excursion
10308 (goto-char (point-min))
10309 (and
10310 (re-search-forward
10311 (concat "[^[]" (regexp-quote
10312 (format org-coderef-label-format
10313 (match-string 1 s0))))
10314 nil t)
10315 (setq type 'dedicated
10316 pos (1+ (match-beginning 0))))))
10317 ;; There is a coderef target for this
10318 (goto-char pos))
10319 ((string-match "^/\\(.*\\)/$" s)
10320 ;; A regular expression
10321 (cond
10322 ((derived-mode-p 'org-mode)
10323 (org-occur (match-string 1 s)))
10324 ;;((eq major-mode 'dired-mode)
10325 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10326 (t (org-do-occur (match-string 1 s)))))
10327 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10328 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10329 (goto-char (point-min))
10330 (cond
10331 ((let (case-fold-search)
10332 (re-search-forward (format org-complex-heading-regexp-format
10333 (regexp-quote s))
10334 nil t))
10335 ;; OK, found a match
10336 (setq type 'dedicated)
10337 (goto-char (match-beginning 0)))
10338 ((and (not org-link-search-inhibit-query)
10339 (eq org-link-search-must-match-exact-headline 'query-to-create)
10340 (y-or-n-p "No match - create this as a new heading? "))
10341 (goto-char (point-max))
10342 (or (bolp) (newline))
10343 (insert "* " s "\n")
10344 (beginning-of-line 0))
10346 (goto-char pos)
10347 (error "No match"))))
10349 ;; A normal search string
10350 (when (equal (string-to-char s) ?*)
10351 ;; Anchor on headlines, post may include tags.
10352 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10353 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10354 s (substring s 1)))
10355 (remove-text-properties
10356 0 (length s)
10357 '(face nil mouse-face nil keymap nil fontified nil) s)
10358 ;; Make a series of regular expressions to find a match
10359 (setq words (org-split-string s "[ \n\r\t]+")
10361 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10362 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10363 "\\)" markers)
10364 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10365 re2a (concat "[ \t\r\n]" re2a_)
10366 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10367 re4 (concat "[^a-zA-Z_]" re4_)
10369 re1 (concat pre re2 post)
10370 re3 (concat pre (if pre re4_ re4) post)
10371 re5 (concat pre ".*" re4)
10372 re2 (concat pre re2)
10373 re2a (concat pre (if pre re2a_ re2a))
10374 re4 (concat pre (if pre re4_ re4))
10375 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10376 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10377 re5 "\\)"
10379 (cond
10380 ((eq type 'org-occur) (org-occur reall))
10381 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10382 (t (goto-char (point-min))
10383 (setq type 'fuzzy)
10384 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10385 (org-search-not-self 1 re1 nil t)
10386 (org-search-not-self 1 re2 nil t)
10387 (org-search-not-self 1 re2a nil t)
10388 (org-search-not-self 1 re3 nil t)
10389 (org-search-not-self 1 re4 nil t)
10390 (org-search-not-self 1 re5 nil t)
10392 (goto-char (match-beginning 1))
10393 (goto-char pos)
10394 (error "No match"))))))
10395 (and (derived-mode-p 'org-mode)
10396 (not stealth)
10397 (org-show-context 'link-search))
10398 type))
10400 (defun org-search-not-self (group &rest args)
10401 "Execute `re-search-forward', but only accept matches that do not
10402 enclose the position of `org-open-link-marker'."
10403 (let ((m org-open-link-marker))
10404 (catch 'exit
10405 (while (apply 're-search-forward args)
10406 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10407 (goto-char (match-end group))
10408 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10409 (> (match-beginning 0) (marker-position m))
10410 (< (match-end 0) (marker-position m)))
10411 (save-match-data
10412 (or (not (org-in-regexp
10413 org-bracket-link-analytic-regexp 1))
10414 (not (match-end 4)) ; no description
10415 (and (<= (match-beginning 4) (point))
10416 (>= (match-end 4) (point))))))
10417 (throw 'exit (point))))))))
10419 (defun org-get-buffer-for-internal-link (buffer)
10420 "Return a buffer to be used for displaying the link target of internal links."
10421 (cond
10422 ((not org-display-internal-link-with-indirect-buffer)
10423 buffer)
10424 ((string-match "(Clone)$" (buffer-name buffer))
10425 (message "Buffer is already a clone, not making another one")
10426 ;; we also do not modify visibility in this case
10427 buffer)
10428 (t ; make a new indirect buffer for displaying the link
10429 (let* ((bn (buffer-name buffer))
10430 (ibn (concat bn "(Clone)"))
10431 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10432 (with-current-buffer ib (org-overview))
10433 ib))))
10435 (defun org-do-occur (regexp &optional cleanup)
10436 "Call the Emacs command `occur'.
10437 If CLEANUP is non-nil, remove the printout of the regular expression
10438 in the *Occur* buffer. This is useful if the regex is long and not useful
10439 to read."
10440 (occur regexp)
10441 (when cleanup
10442 (let ((cwin (selected-window)) win beg end)
10443 (when (setq win (get-buffer-window "*Occur*"))
10444 (select-window win))
10445 (goto-char (point-min))
10446 (when (re-search-forward "match[a-z]+" nil t)
10447 (setq beg (match-end 0))
10448 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10449 (setq end (1- (match-beginning 0)))))
10450 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10451 (goto-char (point-min))
10452 (select-window cwin))))
10454 ;;; The mark ring for links jumps
10456 (defvar org-mark-ring nil
10457 "Mark ring for positions before jumps in Org-mode.")
10458 (defvar org-mark-ring-last-goto nil
10459 "Last position in the mark ring used to go back.")
10460 ;; Fill and close the ring
10461 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10462 (loop for i from 1 to org-mark-ring-length do
10463 (push (make-marker) org-mark-ring))
10464 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10465 org-mark-ring)
10467 (defun org-mark-ring-push (&optional pos buffer)
10468 "Put the current position or POS into the mark ring and rotate it."
10469 (interactive)
10470 (setq pos (or pos (point)))
10471 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10472 (move-marker (car org-mark-ring)
10473 (or pos (point))
10474 (or buffer (current-buffer)))
10475 (message "%s"
10476 (substitute-command-keys
10477 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10479 (defun org-mark-ring-goto (&optional n)
10480 "Jump to the previous position in the mark ring.
10481 With prefix arg N, jump back that many stored positions. When
10482 called several times in succession, walk through the entire ring.
10483 Org-mode commands jumping to a different position in the current file,
10484 or to another Org-mode file, automatically push the old position
10485 onto the ring."
10486 (interactive "p")
10487 (let (p m)
10488 (if (eq last-command this-command)
10489 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10490 (setq p org-mark-ring))
10491 (setq org-mark-ring-last-goto p)
10492 (setq m (car p))
10493 (org-pop-to-buffer-same-window (marker-buffer m))
10494 (goto-char m)
10495 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10497 (defun org-remove-angle-brackets (s)
10498 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10499 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10501 (defun org-add-angle-brackets (s)
10502 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10503 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10505 (defun org-remove-double-quotes (s)
10506 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10507 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10510 ;;; Following specific links
10512 (defun org-follow-timestamp-link ()
10513 "Open an agenda view for the time-stamp date/range at point."
10514 (cond
10515 ((org-at-date-range-p t)
10516 (let ((org-agenda-start-on-weekday)
10517 (t1 (match-string 1))
10518 (t2 (match-string 2)) tt1 tt2)
10519 (setq tt1 (time-to-days (org-time-string-to-time t1))
10520 tt2 (time-to-days (org-time-string-to-time t2)))
10521 (let ((org-agenda-buffer-tmp-name
10522 (format "*Org Agenda(a:%s)"
10523 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10524 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10525 ((org-at-timestamp-p t)
10526 (let ((org-agenda-buffer-tmp-name
10527 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10528 (org-agenda-list nil (time-to-days (org-time-string-to-time
10529 (substring (match-string 1) 0 10)))
10530 1)))
10531 (t (error "This should not happen"))))
10534 ;;; Following file links
10535 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10536 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10537 (declare-function mailcap-mime-info
10538 "mailcap" (string &optional request no-decode))
10539 (defvar org-wait nil)
10540 (defun org-open-file (path &optional in-emacs line search)
10541 "Open the file at PATH.
10542 First, this expands any special file name abbreviations. Then the
10543 configuration variable `org-file-apps' is checked if it contains an
10544 entry for this file type, and if yes, the corresponding command is launched.
10546 If no application is found, Emacs simply visits the file.
10548 With optional prefix argument IN-EMACS, Emacs will visit the file.
10549 With a double \\[universal-argument] \\[universal-argument] \
10550 prefix arg, Org tries to avoid opening in Emacs
10551 and to use an external application to visit the file.
10553 Optional LINE specifies a line to go to, optional SEARCH a string
10554 to search for. If LINE or SEARCH is given, the file will be
10555 opened in Emacs, unless an entry from org-file-apps that makes
10556 use of groups in a regexp matches.
10558 If you want to change the way frames are used when following a
10559 link, please customize `org-link-frame-setup'.
10561 If the file does not exist, an error is thrown."
10562 (let* ((file (if (equal path "")
10563 buffer-file-name
10564 (substitute-in-file-name (expand-file-name path))))
10565 (file-apps (append org-file-apps (org-default-apps)))
10566 (apps (org-remove-if
10567 'org-file-apps-entry-match-against-dlink-p file-apps))
10568 (apps-dlink (org-remove-if-not
10569 'org-file-apps-entry-match-against-dlink-p file-apps))
10570 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10571 (dirp (if remp nil (file-directory-p file)))
10572 (file (if (and dirp org-open-directory-means-index-dot-org)
10573 (concat (file-name-as-directory file) "index.org")
10574 file))
10575 (a-m-a-p (assq 'auto-mode apps))
10576 (dfile (downcase file))
10577 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10578 (link (cond ((and (eq line nil)
10579 (eq search nil))
10580 file)
10581 (line
10582 (concat file "::" (number-to-string line)))
10583 (search
10584 (concat file "::" search))))
10585 (dlink (downcase link))
10586 (old-buffer (current-buffer))
10587 (old-pos (point))
10588 (old-mode major-mode)
10589 ext cmd link-match-data)
10590 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10591 (setq ext (match-string 1 dfile))
10592 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10593 (setq ext (match-string 1 dfile))))
10594 (cond
10595 ((member in-emacs '((16) system))
10596 (setq cmd (cdr (assoc 'system apps))))
10597 (in-emacs (setq cmd 'emacs))
10599 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10600 (and dirp (cdr (assoc 'directory apps)))
10601 ; first, try matching against apps-dlink
10602 ; if we get a match here, store the match data for later
10603 (let ((match (assoc-default dlink apps-dlink
10604 'string-match)))
10605 (if match
10606 (progn (setq link-match-data (match-data))
10607 match)
10608 (progn (setq in-emacs (or in-emacs line search))
10609 nil))) ; if we have no match in apps-dlink,
10610 ; always open the file in emacs if line or search
10611 ; is given (for backwards compatibility)
10612 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10613 'string-match)
10614 (cdr (assoc ext apps))
10615 (cdr (assoc t apps))))))
10616 (when (eq cmd 'system)
10617 (setq cmd (cdr (assoc 'system apps))))
10618 (when (eq cmd 'default)
10619 (setq cmd (cdr (assoc t apps))))
10620 (when (eq cmd 'mailcap)
10621 (require 'mailcap)
10622 (mailcap-parse-mailcaps)
10623 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10624 (command (mailcap-mime-info mime-type)))
10625 (if (stringp command)
10626 (setq cmd command)
10627 (setq cmd 'emacs))))
10628 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10629 (not (file-exists-p file))
10630 (not org-open-non-existing-files))
10631 (error "No such file: %s" file))
10632 (cond
10633 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10634 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10635 (while (string-match "['\"]%s['\"]" cmd)
10636 (setq cmd (replace-match "%s" t t cmd)))
10637 (while (string-match "%s" cmd)
10638 (setq cmd (replace-match
10639 (save-match-data
10640 (shell-quote-argument
10641 (convert-standard-filename file)))
10642 t t cmd)))
10644 ;; Replace "%1", "%2" etc. in command with group matches from regex
10645 (save-match-data
10646 (let ((match-index 1)
10647 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10648 (set-match-data link-match-data)
10649 (while (<= match-index number-of-groups)
10650 (let ((regex (concat "%" (number-to-string match-index)))
10651 (replace-with (match-string match-index dlink)))
10652 (while (string-match regex cmd)
10653 (setq cmd (replace-match replace-with t t cmd))))
10654 (setq match-index (+ match-index 1)))))
10656 (save-window-excursion
10657 (message "Running %s...done" cmd)
10658 (start-process-shell-command cmd nil cmd)
10659 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10660 ((or (stringp cmd)
10661 (eq cmd 'emacs))
10662 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10663 (widen)
10664 (if line (org-goto-line line)
10665 (if search (org-link-search search))))
10666 ((consp cmd)
10667 (let ((file (convert-standard-filename file)))
10668 (save-match-data
10669 (set-match-data link-match-data)
10670 (eval cmd))))
10671 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10672 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10673 (or (not (equal old-buffer (current-buffer)))
10674 (not (equal old-pos (point))))
10675 (org-mark-ring-push old-pos old-buffer))))
10677 (defun org-file-apps-entry-match-against-dlink-p (entry)
10678 "This function returns non-nil if `entry' uses a regular
10679 expression which should be matched against the whole link by
10680 org-open-file.
10682 It assumes that is the case when the entry uses a regular
10683 expression which has at least one grouping construct and the
10684 action is either a lisp form or a command string containing
10685 '%1', i.e. using at least one subexpression match as a
10686 parameter."
10687 (let ((selector (car entry))
10688 (action (cdr entry)))
10689 (if (stringp selector)
10690 (and (> (regexp-opt-depth selector) 0)
10691 (or (and (stringp action)
10692 (string-match "%[0-9]" action))
10693 (consp action)))
10694 nil)))
10696 (defun org-default-apps ()
10697 "Return the default applications for this operating system."
10698 (cond
10699 ((eq system-type 'darwin)
10700 org-file-apps-defaults-macosx)
10701 ((eq system-type 'windows-nt)
10702 org-file-apps-defaults-windowsnt)
10703 (t org-file-apps-defaults-gnu)))
10705 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10706 "Convert extensions to regular expressions in the cars of LIST.
10707 Also, weed out any non-string entries, because the return value is used
10708 only for regexp matching.
10709 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10710 point to the symbol `emacs', indicating that the file should
10711 be opened in Emacs."
10712 (append
10713 (delq nil
10714 (mapcar (lambda (x)
10715 (if (not (stringp (car x)))
10717 (if (string-match "\\W" (car x))
10719 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10720 list))
10721 (if add-auto-mode
10722 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10724 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10725 (defun org-file-remote-p (file)
10726 "Test whether FILE specifies a location on a remote system.
10727 Return non-nil if the location is indeed remote.
10729 For example, the filename \"/user@host:/foo\" specifies a location
10730 on the system \"/user@host:\"."
10731 (cond ((fboundp 'file-remote-p)
10732 (file-remote-p file))
10733 ((fboundp 'tramp-handle-file-remote-p)
10734 (tramp-handle-file-remote-p file))
10735 ((and (boundp 'ange-ftp-name-format)
10736 (string-match (car ange-ftp-name-format) file))
10737 t)))
10740 ;;;; Refiling
10742 (defun org-get-org-file ()
10743 "Read a filename, with default directory `org-directory'."
10744 (let ((default (or org-default-notes-file remember-data-file)))
10745 (read-file-name (format "File name [%s]: " default)
10746 (file-name-as-directory org-directory)
10747 default)))
10749 (defun org-notes-order-reversed-p ()
10750 "Check if the current file should receive notes in reversed order."
10751 (cond
10752 ((not org-reverse-note-order) nil)
10753 ((eq t org-reverse-note-order) t)
10754 ((not (listp org-reverse-note-order)) nil)
10755 (t (catch 'exit
10756 (let ((all org-reverse-note-order)
10757 entry)
10758 (while (setq entry (pop all))
10759 (if (string-match (car entry) buffer-file-name)
10760 (throw 'exit (cdr entry))))
10761 nil)))))
10763 (defvar org-refile-target-table nil
10764 "The list of refile targets, created by `org-refile'.")
10766 (defvar org-agenda-new-buffers nil
10767 "Buffers created to visit agenda files.")
10769 (defvar org-refile-cache nil
10770 "Cache for refile targets.")
10772 (defvar org-refile-markers nil
10773 "All the markers used for caching refile locations.")
10775 (defun org-refile-marker (pos)
10776 "Get a new refile marker, but only if caching is in use."
10777 (if (not org-refile-use-cache)
10779 (let ((m (make-marker)))
10780 (move-marker m pos)
10781 (push m org-refile-markers)
10782 m)))
10784 (defun org-refile-cache-clear ()
10785 "Clear the refile cache and disable all the markers."
10786 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10787 (setq org-refile-markers nil)
10788 (setq org-refile-cache nil)
10789 (message "Refile cache has been cleared"))
10791 (defun org-refile-cache-check-set (set)
10792 "Check if all the markers in the cache still have live buffers."
10793 (let (marker)
10794 (catch 'exit
10795 (while (and set (setq marker (nth 3 (pop set))))
10796 ;; if org-refile-use-outline-path is 'file, marker may be nil
10797 (when (and marker (null (marker-buffer marker)))
10798 (message "not found") (sit-for 3)
10799 (throw 'exit nil)))
10800 t)))
10802 (defun org-refile-cache-put (set &rest identifiers)
10803 "Push the refile targets SET into the cache, under IDENTIFIERS."
10804 (let* ((key (sha1 (prin1-to-string identifiers)))
10805 (entry (assoc key org-refile-cache)))
10806 (if entry
10807 (setcdr entry set)
10808 (push (cons key set) org-refile-cache))))
10810 (defun org-refile-cache-get (&rest identifiers)
10811 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10812 (cond
10813 ((not org-refile-cache) nil)
10814 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10816 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10817 org-refile-cache))))
10818 (and set (org-refile-cache-check-set set) set)))))
10820 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10821 "Produce a table with refile targets."
10822 (let ((case-fold-search nil)
10823 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10824 (entries (or org-refile-targets '((nil . (:level . 1)))))
10825 targets tgs txt re files f desc descre fast-path-p level pos0)
10826 (message "Getting targets...")
10827 (with-current-buffer (or default-buffer (current-buffer))
10828 (while (setq entry (pop entries))
10829 (setq files (car entry) desc (cdr entry))
10830 (setq fast-path-p nil)
10831 (cond
10832 ((null files) (setq files (list (current-buffer))))
10833 ((eq files 'org-agenda-files)
10834 (setq files (org-agenda-files 'unrestricted)))
10835 ((and (symbolp files) (fboundp files))
10836 (setq files (funcall files)))
10837 ((and (symbolp files) (boundp files))
10838 (setq files (symbol-value files))))
10839 (if (stringp files) (setq files (list files)))
10840 (cond
10841 ((eq (car desc) :tag)
10842 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10843 ((eq (car desc) :todo)
10844 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10845 ((eq (car desc) :regexp)
10846 (setq descre (cdr desc)))
10847 ((eq (car desc) :level)
10848 (setq descre (concat "^\\*\\{" (number-to-string
10849 (if org-odd-levels-only
10850 (1- (* 2 (cdr desc)))
10851 (cdr desc)))
10852 "\\}[ \t]")))
10853 ((eq (car desc) :maxlevel)
10854 (setq fast-path-p t)
10855 (setq descre (concat "^\\*\\{1," (number-to-string
10856 (if org-odd-levels-only
10857 (1- (* 2 (cdr desc)))
10858 (cdr desc)))
10859 "\\}[ \t]")))
10860 (t (error "Bad refiling target description %s" desc)))
10861 (while (setq f (pop files))
10862 (with-current-buffer
10863 (if (bufferp f) f (org-get-agenda-file-buffer f))
10865 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10866 (progn
10867 (if (bufferp f) (setq f (buffer-file-name
10868 (buffer-base-buffer f))))
10869 (setq f (and f (expand-file-name f)))
10870 (if (eq org-refile-use-outline-path 'file)
10871 (push (list (file-name-nondirectory f) f nil nil) tgs))
10872 (save-excursion
10873 (save-restriction
10874 (widen)
10875 (goto-char (point-min))
10876 (while (re-search-forward descre nil t)
10877 (goto-char (setq pos0 (point-at-bol)))
10878 (catch 'next
10879 (when org-refile-target-verify-function
10880 (save-match-data
10881 (or (funcall org-refile-target-verify-function)
10882 (throw 'next t))))
10883 (when (and (looking-at org-complex-heading-regexp)
10884 (not (member (match-string 4) excluded-entries))
10885 (match-string 4))
10886 (setq level (org-reduced-level
10887 (- (match-end 1) (match-beginning 1)))
10888 txt (org-link-display-format (match-string 4))
10889 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10890 re (format org-complex-heading-regexp-format
10891 (regexp-quote (match-string 4))))
10892 (when org-refile-use-outline-path
10893 (setq txt (mapconcat
10894 'org-protect-slash
10895 (append
10896 (if (eq org-refile-use-outline-path
10897 'file)
10898 (list (file-name-nondirectory
10899 (buffer-file-name
10900 (buffer-base-buffer))))
10901 (if (eq org-refile-use-outline-path
10902 'full-file-path)
10903 (list (buffer-file-name
10904 (buffer-base-buffer)))))
10905 (org-get-outline-path fast-path-p
10906 level txt)
10907 (list txt))
10908 "/")))
10909 (push (list txt f re (org-refile-marker (point)))
10910 tgs)))
10911 (when (= (point) pos0)
10912 ;; verification function has not moved point
10913 (goto-char (point-at-eol))))))))
10914 (when org-refile-use-cache
10915 (org-refile-cache-put tgs (buffer-file-name) descre))
10916 (setq targets (append tgs targets))
10917 ))))
10918 (message "Getting targets...done")
10919 (nreverse targets)))
10921 (defun org-protect-slash (s)
10922 (while (string-match "/" s)
10923 (setq s (replace-match "\\" t t s)))
10926 (defvar org-olpa (make-vector 20 nil))
10928 (defun org-get-outline-path (&optional fastp level heading)
10929 "Return the outline path to the current entry, as a list.
10931 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10932 routine which makes outline path derivations for an entire file,
10933 avoiding backtracing. Refile target collection makes use of that."
10934 (if fastp
10935 (progn
10936 (if (> level 19)
10937 (error "Outline path failure, more than 19 levels"))
10938 (loop for i from level upto 19 do
10939 (aset org-olpa i nil))
10940 (prog1
10941 (delq nil (append org-olpa nil))
10942 (aset org-olpa level heading)))
10943 (let (rtn case-fold-search)
10944 (save-excursion
10945 (save-restriction
10946 (widen)
10947 (while (org-up-heading-safe)
10948 (when (looking-at org-complex-heading-regexp)
10949 (push (org-match-string-no-properties 4) rtn)))
10950 rtn)))))
10952 (defun org-format-outline-path (path &optional width prefix separator)
10953 "Format the outline path PATH for display.
10954 WIDTH is the maximum number of characters that is available.
10955 PREFIX is a prefix to be included in the returned string,
10956 such as the file name.
10957 SEPARATOR is inserted between the different parts of the path,
10958 the default is \"/\"."
10959 (setq width (or width 79))
10960 (if prefix (setq width (- width (length prefix))))
10961 (if (not path)
10962 (or prefix "")
10963 (let* ((nsteps (length path))
10964 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10965 (maxwidth (if (<= total-width width)
10966 10000 ;; everything fits
10967 ;; we need to shorten the level headings
10968 (/ (- width nsteps) nsteps)))
10969 (org-odd-levels-only nil)
10970 (n 0)
10971 (total (1+ (length prefix))))
10972 (setq maxwidth (max maxwidth 10))
10973 (concat prefix
10974 (if prefix (or separator "/"))
10975 (mapconcat
10976 (lambda (h)
10977 (setq n (1+ n))
10978 (if (and (= n nsteps) (< maxwidth 10000))
10979 (setq maxwidth (- total-width total)))
10980 (if (< (length h) maxwidth)
10981 (progn (setq total (+ total (length h) 1)) h)
10982 (setq h (substring h 0 (- maxwidth 2))
10983 total (+ total maxwidth 1))
10984 (if (string-match "[ \t]+\\'" h)
10985 (setq h (substring h 0 (match-beginning 0))))
10986 (setq h (concat h "..")))
10987 (org-add-props h nil 'face
10988 (nth (% (1- n) org-n-level-faces)
10989 org-level-faces))
10991 path (or separator "/"))))))
10993 (defun org-display-outline-path (&optional file current separator just-return-string)
10994 "Display the current outline path in the echo area.
10996 If FILE is non-nil, prepend the output with the file name.
10997 If CURRENT is non-nil, append the current heading to the output.
10998 SEPARATOR is passed through to `org-format-outline-path'. It separates
10999 the different parts of the path and defaults to \"/\".
11000 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11001 (interactive "P")
11002 (let* (case-fold-search
11003 message-log-max ; Don't populate the *Messages* buffer
11004 (bfn (buffer-file-name (buffer-base-buffer)))
11005 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11006 res)
11007 (if current (setq path (append path
11008 (save-excursion
11009 (org-back-to-heading t)
11010 (if (looking-at org-complex-heading-regexp)
11011 (list (match-string 4)))))))
11012 (setq res
11013 (org-format-outline-path
11014 path
11015 (1- (frame-width))
11016 (and file bfn (concat (file-name-nondirectory bfn) separator))
11017 separator))
11018 (if just-return-string
11019 (org-no-properties res)
11020 (message "%s" res))))
11022 (defvar org-refile-history nil
11023 "History for refiling operations.")
11025 (defvar org-after-refile-insert-hook nil
11026 "Hook run after `org-refile' has inserted its stuff at the new location.
11027 Note that this is still *before* the stuff will be removed from
11028 the *old* location.")
11030 (defvar org-capture-last-stored-marker)
11031 (defvar org-refile-keep nil
11032 "Non-nil means `org-refile' will copy instead of refile.")
11034 (defun org-copy ()
11035 "Like `org-refile', but copy."
11036 (interactive)
11037 (let ((org-refile-keep t))
11038 (funcall 'org-refile nil nil nil "Copy")))
11040 (defun org-refile (&optional goto default-buffer rfloc msg)
11041 "Move the entry or entries at point to another heading.
11042 The list of target headings is compiled using the information in
11043 `org-refile-targets', which see.
11045 At the target location, the entry is filed as a subitem of the target
11046 heading. Depending on `org-reverse-note-order', the new subitem will
11047 either be the first or the last subitem.
11049 If there is an active region, all entries in that region will be moved.
11050 However, the region must fulfill the requirement that the first heading
11051 is the first one sets the top-level of the moved text - at most siblings
11052 below it are allowed.
11054 With prefix arg GOTO, the command will only visit the target location
11055 and not actually move anything.
11057 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11058 go to the location where the last refiling operation has put the subtree.
11059 With a prefix argument of `2', refile to the running clock.
11061 RFLOC can be a refile location obtained in a different way.
11063 MSG is a string to replace \"Refile\" in the default prompt with
11064 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11066 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11068 If you are using target caching (see `org-refile-use-cache'),
11069 you have to clear the target cache in order to find new targets.
11070 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11071 prefix argument (`C-u C-u C-u C-c C-w')."
11073 (interactive "P")
11074 (if (member goto '(0 (64)))
11075 (org-refile-cache-clear)
11076 (let* ((actionmsg (or msg "Refile"))
11077 (cbuf (current-buffer))
11078 (regionp (org-region-active-p))
11079 (region-start (and regionp (region-beginning)))
11080 (region-end (and regionp (region-end)))
11081 (region-length (and regionp (- region-end region-start)))
11082 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11083 pos it nbuf file re level reversed)
11084 (setq last-command nil)
11085 (when regionp
11086 (goto-char region-start)
11087 (or (bolp) (goto-char (point-at-bol)))
11088 (setq region-start (point))
11089 (unless (or (org-kill-is-subtree-p
11090 (buffer-substring region-start region-end))
11091 (prog1 org-refile-active-region-within-subtree
11092 (org-toggle-heading)))
11093 (error "The region is not a (sequence of) subtree(s)")))
11094 (if (equal goto '(16))
11095 (org-refile-goto-last-stored)
11096 (when (or
11097 (and (equal goto 2)
11098 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11099 (prog1
11100 (setq it (list (or org-clock-heading "running clock")
11101 (buffer-file-name
11102 (marker-buffer org-clock-hd-marker))
11104 (marker-position org-clock-hd-marker)))
11105 (setq goto nil)))
11106 (setq it (or rfloc
11107 (let (heading-text)
11108 (save-excursion
11109 (unless goto
11110 (org-back-to-heading t)
11111 (setq heading-text
11112 (nth 4 (org-heading-components))))
11114 (org-refile-get-location
11115 (cond (goto "Goto")
11116 (regionp (concat actionmsg " region to"))
11117 (t (concat actionmsg " subtree \""
11118 heading-text "\" to")))
11119 default-buffer
11120 (and (not (equal '(4) goto))
11121 org-refile-allow-creating-parent-nodes)
11122 goto))))))
11123 (setq file (nth 1 it)
11124 re (nth 2 it)
11125 pos (nth 3 it))
11126 (if (and (not goto)
11128 (equal (buffer-file-name) file)
11129 (if regionp
11130 (and (>= pos region-start)
11131 (<= pos region-end))
11132 (and (>= pos (point))
11133 (< pos (save-excursion
11134 (org-end-of-subtree t t))))))
11135 (error "Cannot refile to position inside the tree or region"))
11137 (setq nbuf (or (find-buffer-visiting file)
11138 (find-file-noselect file)))
11139 (if goto
11140 (progn
11141 (org-pop-to-buffer-same-window nbuf)
11142 (goto-char pos)
11143 (org-show-context 'org-goto))
11144 (if regionp
11145 (progn
11146 (org-kill-new (buffer-substring region-start region-end))
11147 (org-save-markers-in-region region-start region-end))
11148 (org-copy-subtree 1 nil t))
11149 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11150 (find-file-noselect file)))
11151 (setq reversed (org-notes-order-reversed-p))
11152 (save-excursion
11153 (save-restriction
11154 (widen)
11155 (if pos
11156 (progn
11157 (goto-char pos)
11158 (looking-at org-outline-regexp)
11159 (setq level (org-get-valid-level (funcall outline-level) 1))
11160 (goto-char
11161 (if reversed
11162 (or (outline-next-heading) (point-max))
11163 (or (save-excursion (org-get-next-sibling))
11164 (org-end-of-subtree t t)
11165 (point-max)))))
11166 (setq level 1)
11167 (if (not reversed)
11168 (goto-char (point-max))
11169 (goto-char (point-min))
11170 (or (outline-next-heading) (goto-char (point-max)))))
11171 (if (not (bolp)) (newline))
11172 (org-paste-subtree level)
11173 (when org-log-refile
11174 (org-add-log-setup 'refile nil nil 'findpos
11175 org-log-refile)
11176 (unless (eq org-log-refile 'note)
11177 (save-excursion (org-add-log-note))))
11178 (and org-auto-align-tags
11179 (let ((org-loop-over-headlines-in-active-region nil))
11180 (org-set-tags nil t)))
11181 (with-demoted-errors
11182 (bookmark-set "org-refile-last-stored"))
11183 ;; If we are refiling for capture, make sure that the
11184 ;; last-capture pointers point here
11185 (when (org-bound-and-true-p org-refile-for-capture)
11186 (with-demoted-errors
11187 (bookmark-set "org-capture-last-stored-marker"))
11188 (move-marker org-capture-last-stored-marker (point)))
11189 (if (fboundp 'deactivate-mark) (deactivate-mark))
11190 (run-hooks 'org-after-refile-insert-hook))))
11191 (unless org-refile-keep
11192 (if regionp
11193 (delete-region (point) (+ (point) region-length))
11194 (org-cut-subtree)))
11195 (when (featurep 'org-inlinetask)
11196 (org-inlinetask-remove-END-maybe))
11197 (setq org-markers-to-move nil)
11198 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11200 (defun org-refile-goto-last-stored ()
11201 "Go to the location where the last refile was stored."
11202 (interactive)
11203 (bookmark-jump "org-refile-last-stored")
11204 (message "This is the location of the last refile"))
11206 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11207 no-exclude)
11208 "Prompt the user for a refile location, using PROMPT.
11209 PROMPT should not be suffixed with a colon and a space, because
11210 this function appends the default value from
11211 `org-refile-history' automatically, if that is not empty.
11212 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11213 this is used for the GOTO interface."
11214 (let ((org-refile-targets org-refile-targets)
11215 (org-refile-use-outline-path org-refile-use-outline-path)
11216 excluded-entries)
11217 (when (and (derived-mode-p 'org-mode)
11218 (not org-refile-use-cache)
11219 (not no-exclude))
11220 (org-map-tree
11221 (lambda()
11222 (setq excluded-entries
11223 (append excluded-entries (list (org-get-heading t t)))))))
11224 (setq org-refile-target-table
11225 (org-refile-get-targets default-buffer excluded-entries)))
11226 (unless org-refile-target-table
11227 (error "No refile targets"))
11228 (let* ((cbuf (current-buffer))
11229 (partial-completion-mode nil)
11230 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11231 (cfunc (if (and org-refile-use-outline-path
11232 org-outline-path-complete-in-steps)
11233 'org-olpath-completing-read
11234 'org-icompleting-read))
11235 (extra (if org-refile-use-outline-path "/" ""))
11236 (cbnex (concat (buffer-name) extra))
11237 (filename (and cfn (expand-file-name cfn)))
11238 (tbl (mapcar
11239 (lambda (x)
11240 (if (and (not (member org-refile-use-outline-path
11241 '(file full-file-path)))
11242 (not (equal filename (nth 1 x))))
11243 (cons (concat (car x) extra " ("
11244 (file-name-nondirectory (nth 1 x)) ")")
11245 (cdr x))
11246 (cons (concat (car x) extra) (cdr x))))
11247 org-refile-target-table))
11248 (completion-ignore-case t)
11249 cdef
11250 (prompt (concat prompt
11251 (or (and (car org-refile-history)
11252 (concat " (default " (car org-refile-history) ")"))
11253 (and (assoc cbnex tbl) (setq cdef cbnex)
11254 (concat " (default " cbnex ")"))) ": "))
11255 pa answ parent-target child parent old-hist)
11256 (setq old-hist org-refile-history)
11257 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11258 nil 'org-refile-history (or cdef (car org-refile-history))))
11259 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11260 (org-refile-check-position pa)
11261 (if pa
11262 (progn
11263 (when (or (not org-refile-history)
11264 (not (eq old-hist org-refile-history))
11265 (not (equal (car pa) (car org-refile-history))))
11266 (setq org-refile-history
11267 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11268 org-refile-history
11269 (cdr org-refile-history))))
11270 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11271 (pop org-refile-history)))
11273 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11274 (progn
11275 (setq parent (match-string 1 answ)
11276 child (match-string 2 answ))
11277 (setq parent-target (or (assoc parent tbl)
11278 (assoc (concat parent "/") tbl)))
11279 (when (and parent-target
11280 (or (eq new-nodes t)
11281 (and (eq new-nodes 'confirm)
11282 (y-or-n-p (format "Create new node \"%s\"? "
11283 child)))))
11284 (org-refile-new-child parent-target child)))
11285 (error "Invalid target location")))))
11287 (declare-function org-string-nw-p "org-macs" (s))
11288 (defun org-refile-check-position (refile-pointer)
11289 "Check if the refile pointer matches the headline to which it points."
11290 (let* ((file (nth 1 refile-pointer))
11291 (re (nth 2 refile-pointer))
11292 (pos (nth 3 refile-pointer))
11293 buffer)
11294 (if (and (not (markerp pos)) (not file))
11295 (error "Please save the buffer to a file before refiling")
11296 (when (org-string-nw-p re)
11297 (setq buffer (if (markerp pos)
11298 (marker-buffer pos)
11299 (or (find-buffer-visiting file)
11300 (find-file-noselect file))))
11301 (with-current-buffer buffer
11302 (save-excursion
11303 (save-restriction
11304 (widen)
11305 (goto-char pos)
11306 (beginning-of-line 1)
11307 (unless (org-looking-at-p re)
11308 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11310 (defun org-refile-new-child (parent-target child)
11311 "Use refile target PARENT-TARGET to add new CHILD below it."
11312 (unless parent-target
11313 (error "Cannot find parent for new node"))
11314 (let ((file (nth 1 parent-target))
11315 (pos (nth 3 parent-target))
11316 level)
11317 (with-current-buffer (or (find-buffer-visiting file)
11318 (find-file-noselect file))
11319 (save-excursion
11320 (save-restriction
11321 (widen)
11322 (if pos
11323 (goto-char pos)
11324 (goto-char (point-max))
11325 (if (not (bolp)) (newline)))
11326 (when (looking-at org-outline-regexp)
11327 (setq level (funcall outline-level))
11328 (org-end-of-subtree t t))
11329 (org-back-over-empty-lines)
11330 (insert "\n" (make-string
11331 (if pos (org-get-valid-level level 1) 1) ?*)
11332 " " child "\n")
11333 (beginning-of-line 0)
11334 (list (concat (car parent-target) "/" child) file "" (point)))))))
11336 (defun org-olpath-completing-read (prompt collection &rest args)
11337 "Read an outline path like a file name."
11338 (let ((thetable collection)
11339 (org-completion-use-ido nil) ; does not work with ido.
11340 (org-completion-use-iswitchb nil)) ; or iswitchb
11341 (apply
11342 'org-icompleting-read prompt
11343 (lambda (string predicate &optional flag)
11344 (let (rtn r f (l (length string)))
11345 (cond
11346 ((eq flag nil)
11347 ;; try completion
11348 (try-completion string thetable))
11349 ((eq flag t)
11350 ;; all-completions
11351 (setq rtn (all-completions string thetable predicate))
11352 (mapcar
11353 (lambda (x)
11354 (setq r (substring x l))
11355 (if (string-match " ([^)]*)$" x)
11356 (setq f (match-string 0 x))
11357 (setq f ""))
11358 (if (string-match "/" r)
11359 (concat string (substring r 0 (match-end 0)) f)
11361 rtn))
11362 ((eq flag 'lambda)
11363 ;; exact match?
11364 (assoc string thetable)))))
11365 args)))
11367 ;;;; Dynamic blocks
11369 (defun org-find-dblock (name)
11370 "Find the first dynamic block with name NAME in the buffer.
11371 If not found, stay at current position and return nil."
11372 (let ((case-fold-search t) pos)
11373 (save-excursion
11374 (goto-char (point-min))
11375 (setq pos (and (re-search-forward
11376 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11377 (match-beginning 0))))
11378 (if pos (goto-char pos))
11379 pos))
11381 (defconst org-dblock-start-re
11382 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11383 "Matches the start line of a dynamic block, with parameters.")
11385 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11386 "Matches the end of a dynamic block.")
11388 (defun org-create-dblock (plist)
11389 "Create a dynamic block section, with parameters taken from PLIST.
11390 PLIST must contain a :name entry which is used as name of the block."
11391 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11392 (end-of-line 1)
11393 (newline))
11394 (let ((col (current-column))
11395 (name (plist-get plist :name)))
11396 (insert "#+BEGIN: " name)
11397 (while plist
11398 (if (eq (car plist) :name)
11399 (setq plist (cddr plist))
11400 (insert " " (prin1-to-string (pop plist)))))
11401 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11402 (beginning-of-line -2)))
11404 (defun org-prepare-dblock ()
11405 "Prepare dynamic block for refresh.
11406 This empties the block, puts the cursor at the insert position and returns
11407 the property list including an extra property :name with the block name."
11408 (unless (looking-at org-dblock-start-re)
11409 (error "Not at a dynamic block"))
11410 (let* ((begdel (1+ (match-end 0)))
11411 (name (org-no-properties (match-string 1)))
11412 (params (append (list :name name)
11413 (read (concat "(" (match-string 3) ")")))))
11414 (save-excursion
11415 (beginning-of-line 1)
11416 (skip-chars-forward " \t")
11417 (setq params (plist-put params :indentation-column (current-column))))
11418 (unless (re-search-forward org-dblock-end-re nil t)
11419 (error "Dynamic block not terminated"))
11420 (setq params
11421 (append params
11422 (list :content (buffer-substring
11423 begdel (match-beginning 0)))))
11424 (delete-region begdel (match-beginning 0))
11425 (goto-char begdel)
11426 (open-line 1)
11427 params))
11429 (defun org-map-dblocks (&optional command)
11430 "Apply COMMAND to all dynamic blocks in the current buffer.
11431 If COMMAND is not given, use `org-update-dblock'."
11432 (let ((cmd (or command 'org-update-dblock)))
11433 (save-excursion
11434 (goto-char (point-min))
11435 (while (re-search-forward org-dblock-start-re nil t)
11436 (goto-char (match-beginning 0))
11437 (save-excursion
11438 (condition-case nil
11439 (funcall cmd)
11440 (error (message "Error during update of dynamic block"))))
11441 (unless (re-search-forward org-dblock-end-re nil t)
11442 (error "Dynamic block not terminated"))))))
11444 (defun org-dblock-update (&optional arg)
11445 "User command for updating dynamic blocks.
11446 Update the dynamic block at point. With prefix ARG, update all dynamic
11447 blocks in the buffer."
11448 (interactive "P")
11449 (if arg
11450 (org-update-all-dblocks)
11451 (or (looking-at org-dblock-start-re)
11452 (org-beginning-of-dblock))
11453 (org-update-dblock)))
11455 (defun org-update-dblock ()
11456 "Update the dynamic block at point.
11457 This means to empty the block, parse for parameters and then call
11458 the correct writing function."
11459 (interactive)
11460 (save-window-excursion
11461 (let* ((pos (point))
11462 (line (org-current-line))
11463 (params (org-prepare-dblock))
11464 (name (plist-get params :name))
11465 (indent (plist-get params :indentation-column))
11466 (cmd (intern (concat "org-dblock-write:" name))))
11467 (message "Updating dynamic block `%s' at line %d..." name line)
11468 (funcall cmd params)
11469 (message "Updating dynamic block `%s' at line %d...done" name line)
11470 (goto-char pos)
11471 (when (and indent (> indent 0))
11472 (setq indent (make-string indent ?\ ))
11473 (save-excursion
11474 (org-beginning-of-dblock)
11475 (forward-line 1)
11476 (while (not (looking-at org-dblock-end-re))
11477 (insert indent)
11478 (beginning-of-line 2))
11479 (when (looking-at org-dblock-end-re)
11480 (and (looking-at "[ \t]+")
11481 (replace-match ""))
11482 (insert indent)))))))
11484 (defun org-beginning-of-dblock ()
11485 "Find the beginning of the dynamic block at point.
11486 Error if there is no such block at point."
11487 (let ((pos (point))
11488 beg)
11489 (end-of-line 1)
11490 (if (and (re-search-backward org-dblock-start-re nil t)
11491 (setq beg (match-beginning 0))
11492 (re-search-forward org-dblock-end-re nil t)
11493 (> (match-end 0) pos))
11494 (goto-char beg)
11495 (goto-char pos)
11496 (error "Not in a dynamic block"))))
11498 (defun org-update-all-dblocks ()
11499 "Update all dynamic blocks in the buffer.
11500 This function can be used in a hook."
11501 (interactive)
11502 (when (derived-mode-p 'org-mode)
11503 (org-map-dblocks 'org-update-dblock)))
11506 ;;;; Completion
11508 (defun org-get-export-keywords ()
11509 "Return a list of all currently understood export keywords.
11510 Export keywords include options, block names, attributes and
11511 keywords relative to each registered export back-end."
11512 (delq nil
11513 (let (keywords)
11514 (mapc
11515 (lambda (back-end)
11516 (let ((props (cdr back-end)))
11517 ;; Back-end name (for keywords, like #+LATEX:)
11518 (push (upcase (symbol-name (car back-end))) keywords)
11519 ;; Back-end options.
11520 (mapc (lambda (option) (push (cadr option) keywords))
11521 (plist-get (cdr back-end) :options-alist))))
11522 (org-bound-and-true-p org-export-registered-backends))
11523 keywords)))
11525 (defconst org-options-keywords
11526 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE"
11527 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11528 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY"
11529 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11530 "TITLE:" "TODO:" "TYP_TODO:"))
11532 (defcustom org-structure-template-alist
11533 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11534 "<src lang=\"?\">\n\n</src>")
11535 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11536 "<example>\n?\n</example>")
11537 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11538 "<quote>\n?\n</quote>")
11539 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11540 "<verse>\n?\n</verse>")
11541 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11542 "<verbatim>\n?\n</verbatim>")
11543 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11544 "<center>\n?\n</center>")
11545 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11546 "<literal style=\"latex\">\n?\n</literal>")
11547 ("L" "#+LaTeX: "
11548 "<literal style=\"latex\">?</literal>")
11549 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11550 "<literal style=\"html\">\n?\n</literal>")
11551 ("H" "#+HTML: "
11552 "<literal style=\"html\">?</literal>")
11553 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11554 ("A" "#+ASCII: ")
11555 ("i" "#+INDEX: ?"
11556 "#+INDEX: ?")
11557 ("I" "#+INCLUDE: %file ?"
11558 "<include file=%file markup=\"?\">"))
11559 "Structure completion elements.
11560 This is a list of abbreviation keys and values. The value gets inserted
11561 if you type `<' followed by the key and then press the completion key,
11562 usually `M-TAB'. %file will be replaced by a file name after prompting
11563 for the file using completion. The cursor will be placed at the position
11564 of the `?` in the template.
11565 There are two templates for each key, the first uses the original Org syntax,
11566 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11567 the default when the /org-mtags.el/ module has been loaded. See also the
11568 variable `org-mtags-prefer-muse-templates'."
11569 :group 'org-completion
11570 :type '(repeat
11571 (string :tag "Key")
11572 (string :tag "Template")
11573 (string :tag "Muse Template")))
11575 (defun org-try-structure-completion ()
11576 "Try to complete a structure template before point.
11577 This looks for strings like \"<e\" on an otherwise empty line and
11578 expands them."
11579 (let ((l (buffer-substring (point-at-bol) (point)))
11581 (when (and (looking-at "[ \t]*$")
11582 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11583 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11584 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11585 (match-beginning 1)) a)
11586 t)))
11588 (defun org-complete-expand-structure-template (start cell)
11589 "Expand a structure template."
11590 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11591 (rpl (nth (if musep 2 1) cell))
11592 (ind ""))
11593 (delete-region start (point))
11594 (when (string-match "\\`#\\+" rpl)
11595 (cond
11596 ((bolp))
11597 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11598 (setq ind (buffer-substring (point-at-bol) (point))))
11599 (t (newline))))
11600 (setq start (point))
11601 (if (string-match "%file" rpl)
11602 (setq rpl (replace-match
11603 (concat
11604 "\""
11605 (save-match-data
11606 (abbreviate-file-name (read-file-name "Include file: ")))
11607 "\"")
11608 t t rpl)))
11609 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11610 (concat "\n" ind)))
11611 (insert rpl)
11612 (if (re-search-backward "\\?" start t) (delete-char 1))))
11614 ;;;; TODO, DEADLINE, Comments
11616 (defun org-toggle-comment ()
11617 "Change the COMMENT state of an entry."
11618 (interactive)
11619 (save-excursion
11620 (org-back-to-heading)
11621 (let (case-fold-search)
11622 (cond
11623 ((looking-at (format org-heading-keyword-regexp-format
11624 org-comment-string))
11625 (goto-char (match-end 1))
11626 (looking-at (concat " +" org-comment-string))
11627 (replace-match "" t t)
11628 (when (eolp) (insert " ")))
11629 ((looking-at org-outline-regexp)
11630 (goto-char (match-end 0))
11631 (insert org-comment-string " "))))))
11633 (defvar org-last-todo-state-is-todo nil
11634 "This is non-nil when the last TODO state change led to a TODO state.
11635 If the last change removed the TODO tag or switched to DONE, then
11636 this is nil.")
11638 (defvar org-setting-tags nil) ; dynamically skipped
11640 (defvar org-todo-setup-filter-hook nil
11641 "Hook for functions that pre-filter todo specs.
11642 Each function takes a todo spec and returns either nil or the spec
11643 transformed into canonical form." )
11645 (defvar org-todo-get-default-hook nil
11646 "Hook for functions that get a default item for todo.
11647 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11648 nil or a string to be used for the todo mark." )
11650 (defvar org-agenda-headline-snapshot-before-repeat)
11652 (defun org-current-effective-time ()
11653 "Return current time adjusted for `org-extend-today-until' variable."
11654 (let* ((ct (org-current-time))
11655 (dct (decode-time ct))
11656 (ct1
11657 (cond
11658 (org-use-last-clock-out-time-as-effective-time
11659 (or (org-clock-get-last-clock-out-time) ct))
11660 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11661 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11662 (t ct))))
11663 ct1))
11665 (defun org-todo-yesterday (&optional arg)
11666 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11667 (interactive "P")
11668 (if (eq major-mode 'org-agenda-mode)
11669 (apply 'org-agenda-todo-yesterday arg)
11670 (let* ((hour (third (decode-time
11671 (org-current-time))))
11672 (org-extend-today-until (1+ hour)))
11673 (org-todo arg))))
11675 (defvar org-block-entry-blocking ""
11676 "First entry preventing the TODO state change.")
11678 (defun org-todo (&optional arg)
11679 "Change the TODO state of an item.
11680 The state of an item is given by a keyword at the start of the heading,
11681 like
11682 *** TODO Write paper
11683 *** DONE Call mom
11685 The different keywords are specified in the variable `org-todo-keywords'.
11686 By default the available states are \"TODO\" and \"DONE\".
11687 So for this example: when the item starts with TODO, it is changed to DONE.
11688 When it starts with DONE, the DONE is removed. And when neither TODO nor
11689 DONE are present, add TODO at the beginning of the heading.
11691 With \\[universal-argument] prefix arg, use completion to determine the new \
11692 state.
11693 With numeric prefix arg, switch to that state.
11694 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11695 keywords (nextset).
11696 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11697 With a numeric prefix arg of 0, inhibit note taking for the change.
11699 For calling through lisp, arg is also interpreted in the following way:
11700 'none -> empty state
11701 \"\"(empty string) -> switch to empty state
11702 'done -> switch to DONE
11703 'nextset -> switch to the next set of keywords
11704 'previousset -> switch to the previous set of keywords
11705 \"WAITING\" -> switch to the specified keyword, but only if it
11706 really is a member of `org-todo-keywords'."
11707 (interactive "P")
11708 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11709 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11710 'region-start-level 'region))
11711 org-loop-over-headlines-in-active-region)
11712 (org-map-entries
11713 `(org-todo ,arg)
11714 org-loop-over-headlines-in-active-region
11715 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11716 (if (equal arg '(16)) (setq arg 'nextset))
11717 (let ((org-blocker-hook org-blocker-hook)
11718 commentp
11719 case-fold-search)
11720 (when (equal arg '(64))
11721 (setq arg nil org-blocker-hook nil))
11722 (when (and org-blocker-hook
11723 (or org-inhibit-blocking
11724 (org-entry-get nil "NOBLOCKING")))
11725 (setq org-blocker-hook nil))
11726 (save-excursion
11727 (catch 'exit
11728 (org-back-to-heading t)
11729 (when (looking-at (concat "^\\*+ " org-comment-string))
11730 (org-toggle-comment)
11731 (setq commentp t))
11732 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11733 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11734 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11735 (let* ((match-data (match-data))
11736 (startpos (point-at-bol))
11737 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11738 (org-log-done org-log-done)
11739 (org-log-repeat org-log-repeat)
11740 (org-todo-log-states org-todo-log-states)
11741 (org-inhibit-logging
11742 (if (equal arg 0)
11743 (progn (setq arg nil) 'note) org-inhibit-logging))
11744 (this (match-string 1))
11745 (hl-pos (match-beginning 0))
11746 (head (org-get-todo-sequence-head this))
11747 (ass (assoc head org-todo-kwd-alist))
11748 (interpret (nth 1 ass))
11749 (done-word (nth 3 ass))
11750 (final-done-word (nth 4 ass))
11751 (org-last-state (or this ""))
11752 (completion-ignore-case t)
11753 (member (member this org-todo-keywords-1))
11754 (tail (cdr member))
11755 (org-state (cond
11756 ((and org-todo-key-trigger
11757 (or (and (equal arg '(4))
11758 (eq org-use-fast-todo-selection 'prefix))
11759 (and (not arg) org-use-fast-todo-selection
11760 (not (eq org-use-fast-todo-selection
11761 'prefix)))))
11762 ;; Use fast selection
11763 (org-fast-todo-selection))
11764 ((and (equal arg '(4))
11765 (or (not org-use-fast-todo-selection)
11766 (not org-todo-key-trigger)))
11767 ;; Read a state with completion
11768 (org-icompleting-read
11769 "State: " (mapcar (lambda(x) (list x))
11770 org-todo-keywords-1)
11771 nil t))
11772 ((eq arg 'right)
11773 (if this
11774 (if tail (car tail) nil)
11775 (car org-todo-keywords-1)))
11776 ((eq arg 'left)
11777 (if (equal member org-todo-keywords-1)
11779 (if this
11780 (nth (- (length org-todo-keywords-1)
11781 (length tail) 2)
11782 org-todo-keywords-1)
11783 (org-last org-todo-keywords-1))))
11784 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11785 (setq arg nil))) ; hack to fall back to cycling
11786 (arg
11787 ;; user or caller requests a specific state
11788 (cond
11789 ((equal arg "") nil)
11790 ((eq arg 'none) nil)
11791 ((eq arg 'done) (or done-word (car org-done-keywords)))
11792 ((eq arg 'nextset)
11793 (or (car (cdr (member head org-todo-heads)))
11794 (car org-todo-heads)))
11795 ((eq arg 'previousset)
11796 (let ((org-todo-heads (reverse org-todo-heads)))
11797 (or (car (cdr (member head org-todo-heads)))
11798 (car org-todo-heads))))
11799 ((car (member arg org-todo-keywords-1)))
11800 ((stringp arg)
11801 (error "State `%s' not valid in this file" arg))
11802 ((nth (1- (prefix-numeric-value arg))
11803 org-todo-keywords-1))))
11804 ((null member) (or head (car org-todo-keywords-1)))
11805 ((equal this final-done-word) nil) ;; -> make empty
11806 ((null tail) nil) ;; -> first entry
11807 ((memq interpret '(type priority))
11808 (if (eq this-command last-command)
11809 (car tail)
11810 (if (> (length tail) 0)
11811 (or done-word (car org-done-keywords))
11812 nil)))
11814 (car tail))))
11815 (org-state (or
11816 (run-hook-with-args-until-success
11817 'org-todo-get-default-hook org-state org-last-state)
11818 org-state))
11819 (next (if org-state (concat " " org-state " ") " "))
11820 (change-plist (list :type 'todo-state-change :from this :to org-state
11821 :position startpos))
11822 dolog now-done-p)
11823 (when org-blocker-hook
11824 (setq org-last-todo-state-is-todo
11825 (not (member this org-done-keywords)))
11826 (unless (save-excursion
11827 (save-match-data
11828 (org-with-wide-buffer
11829 (run-hook-with-args-until-failure
11830 'org-blocker-hook change-plist))))
11831 (if (org-called-interactively-p 'interactive)
11832 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11833 this org-state org-block-entry-blocking)
11834 ;; fail silently
11835 (message "TODO state change from %s to %s blocked (by \"%s\")"
11836 this org-state org-block-entry-blocking)
11837 (throw 'exit nil))))
11838 (store-match-data match-data)
11839 (replace-match next t t)
11840 (unless (pos-visible-in-window-p hl-pos)
11841 (message "TODO state changed to %s" (org-trim next)))
11842 (unless head
11843 (setq head (org-get-todo-sequence-head org-state)
11844 ass (assoc head org-todo-kwd-alist)
11845 interpret (nth 1 ass)
11846 done-word (nth 3 ass)
11847 final-done-word (nth 4 ass)))
11848 (when (memq arg '(nextset previousset))
11849 (message "Keyword-Set %d/%d: %s"
11850 (- (length org-todo-sets) -1
11851 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11852 (length org-todo-sets)
11853 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11854 (setq org-last-todo-state-is-todo
11855 (not (member org-state org-done-keywords)))
11856 (setq now-done-p (and (member org-state org-done-keywords)
11857 (not (member this org-done-keywords))))
11858 (and logging (org-local-logging logging))
11859 (when (and (or org-todo-log-states org-log-done)
11860 (not (eq org-inhibit-logging t))
11861 (not (memq arg '(nextset previousset))))
11862 ;; we need to look at recording a time and note
11863 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11864 (nth 2 (assoc this org-todo-log-states))))
11865 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11866 (setq dolog 'time))
11867 (when (and org-state
11868 (member org-state org-not-done-keywords)
11869 (not (member this org-not-done-keywords)))
11870 ;; This is now a todo state and was not one before
11871 ;; If there was a CLOSED time stamp, get rid of it.
11872 (org-add-planning-info nil nil 'closed))
11873 (when (and now-done-p org-log-done)
11874 ;; It is now done, and it was not done before
11875 (org-add-planning-info 'closed (org-current-effective-time))
11876 (if (and (not dolog) (eq 'note org-log-done))
11877 (org-add-log-setup 'done org-state this 'findpos 'note)))
11878 (when (and org-state dolog)
11879 ;; This is a non-nil state, and we need to log it
11880 (org-add-log-setup 'state org-state this 'findpos dolog)))
11881 ;; Fixup tag positioning
11882 (org-todo-trigger-tag-changes org-state)
11883 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11884 (when org-provide-todo-statistics
11885 (org-update-parent-todo-statistics))
11886 (run-hooks 'org-after-todo-state-change-hook)
11887 (if (and arg (not (member org-state org-done-keywords)))
11888 (setq head (org-get-todo-sequence-head org-state)))
11889 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11890 ;; Do we need to trigger a repeat?
11891 (when now-done-p
11892 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11893 ;; This is for the agenda, take a snapshot of the headline.
11894 (save-match-data
11895 (setq org-agenda-headline-snapshot-before-repeat
11896 (org-get-heading))))
11897 (org-auto-repeat-maybe org-state))
11898 ;; Fixup cursor location if close to the keyword
11899 (if (and (outline-on-heading-p)
11900 (not (bolp))
11901 (save-excursion (beginning-of-line 1)
11902 (looking-at org-todo-line-regexp))
11903 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11904 (progn
11905 (goto-char (or (match-end 2) (match-end 1)))
11906 (and (looking-at " ") (just-one-space))))
11907 (when org-trigger-hook
11908 (save-excursion
11909 (run-hook-with-args 'org-trigger-hook change-plist)))
11910 (when commentp (org-toggle-comment))))))))
11912 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11913 "Block turning an entry into a TODO, using the hierarchy.
11914 This checks whether the current task should be blocked from state
11915 changes. Such blocking occurs when:
11917 1. The task has children which are not all in a completed state.
11919 2. A task has a parent with the property :ORDERED:, and there
11920 are siblings prior to the current task with incomplete
11921 status.
11923 3. The parent of the task is blocked because it has siblings that should
11924 be done first, or is child of a block grandparent TODO entry."
11926 (if (not org-enforce-todo-dependencies)
11927 t ; if locally turned off don't block
11928 (catch 'dont-block
11929 ;; If this is not a todo state change, or if this entry is already DONE,
11930 ;; do not block
11931 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11932 (member (plist-get change-plist :from)
11933 (cons 'done org-done-keywords))
11934 (member (plist-get change-plist :to)
11935 (cons 'todo org-not-done-keywords))
11936 (not (plist-get change-plist :to)))
11937 (throw 'dont-block t))
11938 ;; If this task has children, and any are undone, it's blocked
11939 (save-excursion
11940 (org-back-to-heading t)
11941 (let ((this-level (funcall outline-level)))
11942 (outline-next-heading)
11943 (let ((child-level (funcall outline-level)))
11944 (while (and (not (eobp))
11945 (> child-level this-level))
11946 ;; this todo has children, check whether they are all
11947 ;; completed
11948 (if (and (not (org-entry-is-done-p))
11949 (org-entry-is-todo-p))
11950 (progn (setq org-block-entry-blocking (org-get-heading))
11951 (throw 'dont-block nil)))
11952 (outline-next-heading)
11953 (setq child-level (funcall outline-level))))))
11954 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11955 ;; any previous siblings are undone, it's blocked
11956 (save-excursion
11957 (org-back-to-heading t)
11958 (let* ((pos (point))
11959 (parent-pos (and (org-up-heading-safe) (point))))
11960 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11961 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11962 (forward-line 1)
11963 (re-search-forward org-not-done-heading-regexp pos t))
11964 (setq org-block-entry-blocking (match-string 0))
11965 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11966 ;; Search further up the hierarchy, to see if an ancestor is blocked
11967 (while t
11968 (goto-char parent-pos)
11969 (if (not (looking-at org-not-done-heading-regexp))
11970 (throw 'dont-block t)) ; do not block, parent is not a TODO
11971 (setq pos (point))
11972 (setq parent-pos (and (org-up-heading-safe) (point)))
11973 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11974 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11975 (forward-line 1)
11976 (re-search-forward org-not-done-heading-regexp pos t)
11977 (setq org-block-entry-blocking (org-get-heading)))
11978 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11980 (defcustom org-track-ordered-property-with-tag nil
11981 "Should the ORDERED property also be shown as a tag?
11982 The ORDERED property decides if an entry should require subtasks to be
11983 completed in sequence. Since a property is not very visible, setting
11984 this option means that toggling the ORDERED property with the command
11985 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11986 not relevant for the behavior, but it makes things more visible.
11988 Note that toggling the tag with tags commands will not change the property
11989 and therefore not influence behavior!
11991 This can be t, meaning the tag ORDERED should be used, It can also be a
11992 string to select a different tag for this task."
11993 :group 'org-todo
11994 :type '(choice
11995 (const :tag "No tracking" nil)
11996 (const :tag "Track with ORDERED tag" t)
11997 (string :tag "Use other tag")))
11999 (defun org-toggle-ordered-property ()
12000 "Toggle the ORDERED property of the current entry.
12001 For better visibility, you can track the value of this property with a tag.
12002 See variable `org-track-ordered-property-with-tag'."
12003 (interactive)
12004 (let* ((t1 org-track-ordered-property-with-tag)
12005 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12006 (save-excursion
12007 (org-back-to-heading)
12008 (if (org-entry-get nil "ORDERED")
12009 (progn
12010 (org-delete-property "ORDERED")
12011 (and tag (org-toggle-tag tag 'off))
12012 (message "Subtasks can be completed in arbitrary order"))
12013 (org-entry-put nil "ORDERED" "t")
12014 (and tag (org-toggle-tag tag 'on))
12015 (message "Subtasks must be completed in sequence")))))
12017 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12018 (defun org-block-todo-from-checkboxes (change-plist)
12019 "Block turning an entry into a TODO, using checkboxes.
12020 This checks whether the current task should be blocked from state
12021 changes because there are unchecked boxes in this entry."
12022 (if (not org-enforce-todo-checkbox-dependencies)
12023 t ; if locally turned off don't block
12024 (catch 'dont-block
12025 ;; If this is not a todo state change, or if this entry is already DONE,
12026 ;; do not block
12027 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12028 (member (plist-get change-plist :from)
12029 (cons 'done org-done-keywords))
12030 (member (plist-get change-plist :to)
12031 (cons 'todo org-not-done-keywords))
12032 (not (plist-get change-plist :to)))
12033 (throw 'dont-block t))
12034 ;; If this task has checkboxes that are not checked, it's blocked
12035 (save-excursion
12036 (org-back-to-heading t)
12037 (let ((beg (point)) end)
12038 (outline-next-heading)
12039 (setq end (point))
12040 (goto-char beg)
12041 (if (org-list-search-forward
12042 (concat (org-item-beginning-re)
12043 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12044 "\\[[- ]\\]")
12045 end t)
12046 (progn
12047 (if (boundp 'org-blocked-by-checkboxes)
12048 (setq org-blocked-by-checkboxes t))
12049 (throw 'dont-block nil)))))
12050 t))) ; do not block
12052 (defun org-entry-blocked-p ()
12053 "Is the current entry blocked?"
12054 (org-with-buffer-modified-unmodified
12055 (if (org-entry-get nil "NOBLOCKING")
12056 nil ;; Never block this entry
12057 (not
12058 (run-hook-with-args-until-failure
12059 'org-blocker-hook
12060 (list :type 'todo-state-change
12061 :position (point)
12062 :from 'todo
12063 :to 'done))))))
12065 (defun org-update-statistics-cookies (all)
12066 "Update the statistics cookie, either from TODO or from checkboxes.
12067 This should be called with the cursor in a line with a statistics cookie."
12068 (interactive "P")
12069 (if all
12070 (progn
12071 (org-update-checkbox-count 'all)
12072 (org-map-entries 'org-update-parent-todo-statistics))
12073 (if (not (org-at-heading-p))
12074 (org-update-checkbox-count)
12075 (let ((pos (point-marker))
12076 end l1 l2)
12077 (ignore-errors (org-back-to-heading t))
12078 (if (not (org-at-heading-p))
12079 (org-update-checkbox-count)
12080 (setq l1 (org-outline-level))
12081 (setq end (save-excursion
12082 (outline-next-heading)
12083 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12084 (point)))
12085 (if (and (save-excursion
12086 (re-search-forward
12087 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12088 (not (save-excursion (re-search-forward
12089 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12090 (org-update-checkbox-count)
12091 (if (and l2 (> l2 l1))
12092 (progn
12093 (goto-char end)
12094 (org-update-parent-todo-statistics))
12095 (goto-char pos)
12096 (beginning-of-line 1)
12097 (while (re-search-forward
12098 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12099 (point-at-eol) t)
12100 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12101 (goto-char pos)
12102 (move-marker pos nil)))))
12104 (defvar org-entry-property-inherited-from) ;; defined below
12105 (defun org-update-parent-todo-statistics ()
12106 "Update any statistics cookie in the parent of the current headline.
12107 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12108 the entire subtree and this will travel up the hierarchy and update
12109 statistics everywhere."
12110 (let* ((prop (save-excursion (org-up-heading-safe)
12111 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12112 (recursive (or (not org-hierarchical-todo-statistics)
12113 (and prop (string-match "\\<recursive\\>" prop))))
12114 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12116 (first t)
12117 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12118 level ltoggle l1 new ndel
12119 (cnt-all 0) (cnt-done 0) is-percent kwd
12120 checkbox-beg ov ovs ove cookie-present)
12121 (catch 'exit
12122 (save-excursion
12123 (beginning-of-line 1)
12124 (setq ltoggle (funcall outline-level))
12125 ;; Three situations are to consider:
12127 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12128 ;; to the top-level ancestor on the headline;
12130 ;; 2. If parent has "recursive" property, repeat up to the
12131 ;; headline setting that property, taking inheritance into
12132 ;; account;
12134 ;; 3. Else, move up to direct parent and proceed only once.
12135 (while (and (setq level (org-up-heading-safe))
12136 (or recursive first)
12137 (>= (point) lim))
12138 (setq first nil cookie-present nil)
12139 (unless (and level
12140 (not (string-match
12141 "\\<checkbox\\>"
12142 (downcase (or (org-entry-get nil "COOKIE_DATA")
12143 "")))))
12144 (throw 'exit nil))
12145 (while (re-search-forward box-re (point-at-eol) t)
12146 (setq cnt-all 0 cnt-done 0 cookie-present t)
12147 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12148 (save-match-data
12149 (unless (outline-next-heading) (throw 'exit nil))
12150 (while (and (looking-at org-complex-heading-regexp)
12151 (> (setq l1 (length (match-string 1))) level))
12152 (setq kwd (and (or recursive (= l1 ltoggle))
12153 (match-string 2)))
12154 (if (or (eq org-provide-todo-statistics 'all-headlines)
12155 (and (listp org-provide-todo-statistics)
12156 (or (member kwd org-provide-todo-statistics)
12157 (member kwd org-done-keywords))))
12158 (setq cnt-all (1+ cnt-all))
12159 (if (eq org-provide-todo-statistics t)
12160 (and kwd (setq cnt-all (1+ cnt-all)))))
12161 (and (member kwd org-done-keywords)
12162 (setq cnt-done (1+ cnt-done)))
12163 (outline-next-heading)))
12164 (setq new
12165 (if is-percent
12166 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12167 (format "[%d/%d]" cnt-done cnt-all))
12168 ndel (- (match-end 0) checkbox-beg))
12169 ;; handle overlays when updating cookie from column view
12170 (when (setq ov (car (overlays-at checkbox-beg)))
12171 (setq ovs (overlay-start ov) ove (overlay-end ov))
12172 (delete-overlay ov))
12173 (goto-char checkbox-beg)
12174 (insert new)
12175 (delete-region (point) (+ (point) ndel))
12176 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12177 (when ov (move-overlay ov ovs ove)))
12178 (when cookie-present
12179 (run-hook-with-args 'org-after-todo-statistics-hook
12180 cnt-done (- cnt-all cnt-done))))))
12181 (run-hooks 'org-todo-statistics-hook)))
12183 (defvar org-after-todo-statistics-hook nil
12184 "Hook that is called after a TODO statistics cookie has been updated.
12185 Each function is called with two arguments: the number of not-done entries
12186 and the number of done entries.
12188 For example, the following function, when added to this hook, will switch
12189 an entry to DONE when all children are done, and back to TODO when new
12190 entries are set to a TODO status. Note that this hook is only called
12191 when there is a statistics cookie in the headline!
12193 (defun org-summary-todo (n-done n-not-done)
12194 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12195 (let (org-log-done org-log-states) ; turn off logging
12196 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12199 (defvar org-todo-statistics-hook nil
12200 "Hook that is run whenever Org thinks TODO statistics should be updated.
12201 This hook runs even if there is no statistics cookie present, in which case
12202 `org-after-todo-statistics-hook' would not run.")
12204 (defun org-todo-trigger-tag-changes (state)
12205 "Apply the changes defined in `org-todo-state-tags-triggers'."
12206 (let ((l org-todo-state-tags-triggers)
12207 changes)
12208 (when (or (not state) (equal state ""))
12209 (setq changes (append changes (cdr (assoc "" l)))))
12210 (when (and (stringp state) (> (length state) 0))
12211 (setq changes (append changes (cdr (assoc state l)))))
12212 (when (member state org-not-done-keywords)
12213 (setq changes (append changes (cdr (assoc 'todo l)))))
12214 (when (member state org-done-keywords)
12215 (setq changes (append changes (cdr (assoc 'done l)))))
12216 (dolist (c changes)
12217 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12219 (defun org-local-logging (value)
12220 "Get logging settings from a property VALUE."
12221 (let* (words w a)
12222 ;; directly set the variables, they are already local.
12223 (setq org-log-done nil
12224 org-log-repeat nil
12225 org-todo-log-states nil)
12226 (setq words (org-split-string value))
12227 (while (setq w (pop words))
12228 (cond
12229 ((setq a (assoc w org-startup-options))
12230 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12231 (set (nth 1 a) (nth 2 a))))
12232 ((setq a (org-extract-log-state-settings w))
12233 (and (member (car a) org-todo-keywords-1)
12234 (push a org-todo-log-states)))))))
12236 (defun org-get-todo-sequence-head (kwd)
12237 "Return the head of the TODO sequence to which KWD belongs.
12238 If KWD is not set, check if there is a text property remembering the
12239 right sequence."
12240 (let (p)
12241 (cond
12242 ((not kwd)
12243 (or (get-text-property (point-at-bol) 'org-todo-head)
12244 (progn
12245 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12246 nil (point-at-eol)))
12247 (get-text-property p 'org-todo-head))))
12248 ((not (member kwd org-todo-keywords-1))
12249 (car org-todo-keywords-1))
12250 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12252 (defun org-fast-todo-selection ()
12253 "Fast TODO keyword selection with single keys.
12254 Returns the new TODO keyword, or nil if no state change should occur."
12255 (let* ((fulltable org-todo-key-alist)
12256 (done-keywords org-done-keywords) ;; needed for the faces.
12257 (maxlen (apply 'max (mapcar
12258 (lambda (x)
12259 (if (stringp (car x)) (string-width (car x)) 0))
12260 fulltable)))
12261 (expert nil)
12262 (fwidth (+ maxlen 3 1 3))
12263 (ncol (/ (- (window-width) 4) fwidth))
12264 tg cnt e c tbl
12265 groups ingroup)
12266 (save-excursion
12267 (save-window-excursion
12268 (if expert
12269 (set-buffer (get-buffer-create " *Org todo*"))
12270 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12271 (erase-buffer)
12272 (org-set-local 'org-done-keywords done-keywords)
12273 (setq tbl fulltable cnt 0)
12274 (while (setq e (pop tbl))
12275 (cond
12276 ((equal e '(:startgroup))
12277 (push '() groups) (setq ingroup t)
12278 (when (not (= cnt 0))
12279 (setq cnt 0)
12280 (insert "\n"))
12281 (insert "{ "))
12282 ((equal e '(:endgroup))
12283 (setq ingroup nil cnt 0)
12284 (insert "}\n"))
12285 ((equal e '(:newline))
12286 (when (not (= cnt 0))
12287 (setq cnt 0)
12288 (insert "\n")
12289 (setq e (car tbl))
12290 (while (equal (car tbl) '(:newline))
12291 (insert "\n")
12292 (setq tbl (cdr tbl)))))
12294 (setq tg (car e) c (cdr e))
12295 (if ingroup (push tg (car groups)))
12296 (setq tg (org-add-props tg nil 'face
12297 (org-get-todo-face tg)))
12298 (if (and (= cnt 0) (not ingroup)) (insert " "))
12299 (insert "[" c "] " tg (make-string
12300 (- fwidth 4 (length tg)) ?\ ))
12301 (when (= (setq cnt (1+ cnt)) ncol)
12302 (insert "\n")
12303 (if ingroup (insert " "))
12304 (setq cnt 0)))))
12305 (insert "\n")
12306 (goto-char (point-min))
12307 (if (not expert) (org-fit-window-to-buffer))
12308 (message "[a-z..]:Set [SPC]:clear")
12309 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12310 (cond
12311 ((or (= c ?\C-g)
12312 (and (= c ?q) (not (rassoc c fulltable))))
12313 (setq quit-flag t))
12314 ((= c ?\ ) nil)
12315 ((setq e (rassoc c fulltable) tg (car e))
12317 (t (setq quit-flag t)))))))
12319 (defun org-entry-is-todo-p ()
12320 (member (org-get-todo-state) org-not-done-keywords))
12322 (defun org-entry-is-done-p ()
12323 (member (org-get-todo-state) org-done-keywords))
12325 (defun org-get-todo-state ()
12326 (save-excursion
12327 (org-back-to-heading t)
12328 (and (looking-at org-todo-line-regexp)
12329 (match-end 2)
12330 (match-string 2))))
12332 (defun org-at-date-range-p (&optional inactive-ok)
12333 "Is the cursor inside a date range?"
12334 (interactive)
12335 (save-excursion
12336 (catch 'exit
12337 (let ((pos (point)))
12338 (skip-chars-backward "^[<\r\n")
12339 (skip-chars-backward "<[")
12340 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12341 (>= (match-end 0) pos)
12342 (throw 'exit t))
12343 (skip-chars-backward "^<[\r\n")
12344 (skip-chars-backward "<[")
12345 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12346 (>= (match-end 0) pos)
12347 (throw 'exit t)))
12348 nil)))
12350 (defun org-get-repeat (&optional tagline)
12351 "Check if there is a deadline/schedule with repeater in this entry."
12352 (save-match-data
12353 (save-excursion
12354 (org-back-to-heading t)
12355 (and (re-search-forward (if tagline
12356 (concat tagline "\\s-*" org-repeat-re)
12357 org-repeat-re)
12358 (org-entry-end-position) t)
12359 (match-string-no-properties 1)))))
12361 (defvar org-last-changed-timestamp)
12362 (defvar org-last-inserted-timestamp)
12363 (defvar org-log-post-message)
12364 (defvar org-log-note-purpose)
12365 (defvar org-log-note-how)
12366 (defvar org-log-note-extra)
12367 (defun org-auto-repeat-maybe (done-word)
12368 "Check if the current headline contains a repeated deadline/schedule.
12369 If yes, set TODO state back to what it was and change the base date
12370 of repeating deadline/scheduled time stamps to new date.
12371 This function is run automatically after each state change to a DONE state."
12372 ;; last-state is dynamically scoped into this function
12373 (let* ((repeat (org-get-repeat))
12374 (aa (assoc org-last-state org-todo-kwd-alist))
12375 (interpret (nth 1 aa))
12376 (head (nth 2 aa))
12377 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12378 (msg "Entry repeats: ")
12379 (org-log-done nil)
12380 (org-todo-log-states nil)
12381 re type n what ts time to-state)
12382 (when repeat
12383 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12384 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12385 org-todo-repeat-to-state))
12386 (unless (and to-state (member to-state org-todo-keywords-1))
12387 (setq to-state (if (eq interpret 'type) org-last-state head)))
12388 (org-todo to-state)
12389 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12390 (org-entry-put nil "LAST_REPEAT" (format-time-string
12391 (org-time-stamp-format t t))))
12392 (when org-log-repeat
12393 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12394 (memq 'org-add-log-note post-command-hook))
12395 ;; OK, we are already setup for some record
12396 (if (eq org-log-repeat 'note)
12397 ;; make sure we take a note, not only a time stamp
12398 (setq org-log-note-how 'note))
12399 ;; Set up for taking a record
12400 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12401 org-last-state
12402 'findpos org-log-repeat)))
12403 (org-back-to-heading t)
12404 (org-add-planning-info nil nil 'closed)
12405 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12406 org-deadline-time-regexp "\\)\\|\\("
12407 org-ts-regexp "\\)"))
12408 (while (re-search-forward
12409 re (save-excursion (outline-next-heading) (point)) t)
12410 (setq type (if (match-end 1) org-scheduled-string
12411 (if (match-end 3) org-deadline-string "Plain:"))
12412 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12413 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12414 (setq n (string-to-number (match-string 2 ts))
12415 what (match-string 3 ts))
12416 (if (equal what "w") (setq n (* n 7) what "d"))
12417 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12418 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12419 ;; Preparation, see if we need to modify the start date for the change
12420 (when (match-end 1)
12421 (setq time (save-match-data (org-time-string-to-time ts)))
12422 (cond
12423 ((equal (match-string 1 ts) ".")
12424 ;; Shift starting date to today
12425 (org-timestamp-change
12426 (- (org-today) (time-to-days time))
12427 'day))
12428 ((equal (match-string 1 ts) "+")
12429 (let ((nshiftmax 10) (nshift 0))
12430 (while (or (= nshift 0)
12431 (<= (time-to-days time)
12432 (time-to-days (current-time))))
12433 (when (= (incf nshift) nshiftmax)
12434 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12435 (error "Abort")))
12436 (org-timestamp-change n (cdr (assoc what whata)))
12437 (org-at-timestamp-p t)
12438 (setq ts (match-string 1))
12439 (setq time (save-match-data (org-time-string-to-time ts)))))
12440 (org-timestamp-change (- n) (cdr (assoc what whata)))
12441 ;; rematch, so that we have everything in place for the real shift
12442 (org-at-timestamp-p t)
12443 (setq ts (match-string 1))
12444 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12445 (org-timestamp-change n (cdr (assoc what whata)))
12446 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12447 (setq org-log-post-message msg)
12448 (message "%s" msg))))
12450 (defun org-show-todo-tree (arg)
12451 "Make a compact tree which shows all headlines marked with TODO.
12452 The tree will show the lines where the regexp matches, and all higher
12453 headlines above the match.
12454 With a \\[universal-argument] prefix, prompt for a regexp to match.
12455 With a numeric prefix N, construct a sparse tree for the Nth element
12456 of `org-todo-keywords-1'."
12457 (interactive "P")
12458 (let ((case-fold-search nil)
12459 (kwd-re
12460 (cond ((null arg) org-not-done-regexp)
12461 ((equal arg '(4))
12462 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12463 (mapcar 'list org-todo-keywords-1))))
12464 (concat "\\("
12465 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12466 "\\)\\>")))
12467 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12468 (regexp-quote (nth (1- (prefix-numeric-value arg))
12469 org-todo-keywords-1)))
12470 (t (error "Invalid prefix argument: %s" arg)))))
12471 (message "%d TODO entries found"
12472 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12474 (defun org-deadline (&optional arg time)
12475 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12476 With one universal prefix argument, remove any deadline from the item.
12477 With two universal prefix arguments, prompt for a warning delay.
12478 With argument TIME, set the deadline at the corresponding date. TIME
12479 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12480 (interactive "P")
12481 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12482 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12483 'region-start-level 'region))
12484 org-loop-over-headlines-in-active-region)
12485 (org-map-entries
12486 `(org-deadline ',arg ,time)
12487 org-loop-over-headlines-in-active-region
12488 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12489 (let* ((old-date (org-entry-get nil "DEADLINE"))
12490 (repeater (and old-date
12491 (string-match
12492 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12493 old-date)
12494 (match-string 1 old-date))))
12495 (cond
12496 ((equal arg '(4))
12497 (when (and old-date org-log-redeadline)
12498 (org-add-log-setup 'deldeadline nil old-date 'findpos
12499 org-log-redeadline))
12500 (org-remove-timestamp-with-keyword org-deadline-string)
12501 (message "Item no longer has a deadline."))
12502 ((equal arg '(16))
12503 (save-excursion
12504 (if (re-search-forward
12505 org-deadline-time-regexp
12506 (save-excursion (outline-next-heading) (point)) t)
12507 (let* ((rpl0 (match-string 1))
12508 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12509 (replace-match
12510 (concat org-deadline-string
12511 " <" rpl
12512 (format " -%dd" (abs
12513 (- (time-to-days
12514 (save-match-data
12515 (org-read-date nil t nil "Warn starting from")))
12516 (time-to-days nil))))
12517 ">") t t))
12518 (user-error "No deadline information to update"))))
12520 (org-add-planning-info 'deadline time 'closed)
12521 (when (and old-date org-log-redeadline
12522 (not (equal old-date
12523 (substring org-last-inserted-timestamp 1 -1))))
12524 (org-add-log-setup 'redeadline nil old-date 'findpos
12525 org-log-redeadline))
12526 (when repeater
12527 (save-excursion
12528 (org-back-to-heading t)
12529 (when (re-search-forward (concat org-deadline-string " "
12530 org-last-inserted-timestamp)
12531 (save-excursion
12532 (outline-next-heading) (point)) t)
12533 (goto-char (1- (match-end 0)))
12534 (insert " " repeater)
12535 (setq org-last-inserted-timestamp
12536 (concat (substring org-last-inserted-timestamp 0 -1)
12537 " " repeater
12538 (substring org-last-inserted-timestamp -1))))))
12539 (message "Deadline on %s" org-last-inserted-timestamp))))))
12541 (defun org-schedule (&optional arg time)
12542 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12543 With one universal prefix argument, remove any scheduling date from the item.
12544 With two universal prefix arguments, prompt for a delay cookie.
12545 With argument TIME, scheduled at the corresponding date. TIME can
12546 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12547 (interactive "P")
12548 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12549 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12550 'region-start-level 'region))
12551 org-loop-over-headlines-in-active-region)
12552 (org-map-entries
12553 `(org-schedule ',arg ,time)
12554 org-loop-over-headlines-in-active-region
12555 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12556 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12557 (repeater (and old-date
12558 (string-match
12559 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12560 old-date)
12561 (match-string 1 old-date))))
12562 (cond
12563 ((equal arg '(4))
12564 (progn
12565 (when (and old-date org-log-reschedule)
12566 (org-add-log-setup 'delschedule nil old-date 'findpos
12567 org-log-reschedule))
12568 (org-remove-timestamp-with-keyword org-scheduled-string)
12569 (message "Item is no longer scheduled.")))
12570 ((equal arg '(16))
12571 (save-excursion
12572 (if (re-search-forward
12573 org-scheduled-time-regexp
12574 (save-excursion (outline-next-heading) (point)) t)
12575 (let* ((rpl0 (match-string 1))
12576 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12577 (replace-match
12578 (concat org-scheduled-string
12579 " <" rpl
12580 (format " -%dd" (abs
12581 (- (time-to-days
12582 (save-match-data
12583 (org-read-date nil t nil "Delay until")))
12584 (time-to-days nil))))
12585 ">") t t))
12586 (user-error "No scheduled information to update"))))
12588 (org-add-planning-info 'scheduled time 'closed)
12589 (when (and old-date org-log-reschedule
12590 (not (equal old-date
12591 (substring org-last-inserted-timestamp 1 -1))))
12592 (org-add-log-setup 'reschedule nil old-date 'findpos
12593 org-log-reschedule))
12594 (when repeater
12595 (save-excursion
12596 (org-back-to-heading t)
12597 (when (re-search-forward (concat org-scheduled-string " "
12598 org-last-inserted-timestamp)
12599 (save-excursion
12600 (outline-next-heading) (point)) t)
12601 (goto-char (1- (match-end 0)))
12602 (insert " " repeater)
12603 (setq org-last-inserted-timestamp
12604 (concat (substring org-last-inserted-timestamp 0 -1)
12605 " " repeater
12606 (substring org-last-inserted-timestamp -1))))))
12607 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12609 (defun org-get-scheduled-time (pom &optional inherit)
12610 "Get the scheduled time as a time tuple, of a format suitable
12611 for calling org-schedule with, or if there is no scheduling,
12612 returns nil."
12613 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12614 (when time
12615 (apply 'encode-time (org-parse-time-string time)))))
12617 (defun org-get-deadline-time (pom &optional inherit)
12618 "Get the deadline as a time tuple, of a format suitable for
12619 calling org-deadline with, or if there is no scheduling, returns
12620 nil."
12621 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12622 (when time
12623 (apply 'encode-time (org-parse-time-string time)))))
12625 (defun org-remove-timestamp-with-keyword (keyword)
12626 "Remove all time stamps with KEYWORD in the current entry."
12627 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12628 beg)
12629 (save-excursion
12630 (org-back-to-heading t)
12631 (setq beg (point))
12632 (outline-next-heading)
12633 (while (re-search-backward re beg t)
12634 (replace-match "")
12635 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12636 (equal (char-before) ?\ ))
12637 (backward-delete-char 1)
12638 (if (string-match "^[ \t]*$" (buffer-substring
12639 (point-at-bol) (point-at-eol)))
12640 (delete-region (point-at-bol)
12641 (min (point-max) (1+ (point-at-eol))))))))))
12643 (defun org-add-planning-info (what &optional time &rest remove)
12644 "Insert new timestamp with keyword in the line directly after the headline.
12645 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12646 If non is given, the user is prompted for a date.
12647 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12648 be removed."
12649 (interactive)
12650 (let (org-time-was-given org-end-time-was-given ts
12651 end default-time default-input)
12653 (catch 'exit
12654 (when (and (memq what '(scheduled deadline))
12655 (or (not time)
12656 (and (stringp time)
12657 (string-match "^[-+]+[0-9]" time))))
12658 ;; Try to get a default date/time from existing timestamp
12659 (save-excursion
12660 (org-back-to-heading t)
12661 (setq end (save-excursion (outline-next-heading) (point)))
12662 (when (re-search-forward (if (eq what 'scheduled)
12663 org-scheduled-time-regexp
12664 org-deadline-time-regexp)
12665 end t)
12666 (setq ts (match-string 1)
12667 default-time
12668 (apply 'encode-time (org-parse-time-string ts))
12669 default-input (and ts (org-get-compact-tod ts))))))
12670 (when what
12671 (setq time
12672 (if (stringp time)
12673 ;; This is a string (relative or absolute), set proper date
12674 (apply 'encode-time
12675 (org-read-date-analyze
12676 time default-time (decode-time default-time)))
12677 ;; If necessary, get the time from the user
12678 (or time (org-read-date nil 'to-time nil nil
12679 default-time default-input)))))
12681 (when (and org-insert-labeled-timestamps-at-point
12682 (member what '(scheduled deadline)))
12683 (insert
12684 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12685 (org-insert-time-stamp time org-time-was-given
12686 nil nil nil (list org-end-time-was-given))
12687 (setq what nil))
12688 (save-excursion
12689 (save-restriction
12690 (let (col list elt ts buffer-invisibility-spec)
12691 (org-back-to-heading t)
12692 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12693 (goto-char (match-end 1))
12694 (setq col (current-column))
12695 (goto-char (match-end 0))
12696 (if (eobp) (insert "\n") (forward-char 1))
12697 (when (and (not what)
12698 (not (looking-at
12699 (concat "[ \t]*"
12700 org-keyword-time-not-clock-regexp))))
12701 ;; Nothing to add, nothing to remove...... :-)
12702 (throw 'exit nil))
12703 (if (and (not (looking-at org-outline-regexp))
12704 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12705 "[^\r\n]*"))
12706 (not (equal (match-string 1) org-clock-string)))
12707 (narrow-to-region (match-beginning 0) (match-end 0))
12708 (insert-before-markers "\n")
12709 (backward-char 1)
12710 (narrow-to-region (point) (point))
12711 (and org-adapt-indentation (org-indent-to-column col)))
12712 ;; Check if we have to remove something.
12713 (setq list (cons what remove))
12714 (while list
12715 (setq elt (pop list))
12716 (when (or (and (eq elt 'scheduled)
12717 (re-search-forward org-scheduled-time-regexp nil t))
12718 (and (eq elt 'deadline)
12719 (re-search-forward org-deadline-time-regexp nil t))
12720 (and (eq elt 'closed)
12721 (re-search-forward org-closed-time-regexp nil t)))
12722 (replace-match "")
12723 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12724 (and (looking-at "[ \t]+") (replace-match ""))
12725 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12726 (when what
12727 (insert
12728 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12729 (cond ((eq what 'scheduled) org-scheduled-string)
12730 ((eq what 'deadline) org-deadline-string)
12731 ((eq what 'closed) org-closed-string))
12732 " ")
12733 (setq ts (org-insert-time-stamp
12734 time
12735 (or org-time-was-given
12736 (and (eq what 'closed) org-log-done-with-time))
12737 (eq what 'closed)
12738 nil nil (list org-end-time-was-given)))
12739 (insert
12740 (if (not (or (bolp) (eq (char-before) ?\ )
12741 (memq (char-after) '(32 10))
12742 (eobp))) " " ""))
12743 (end-of-line 1))
12744 (goto-char (point-min))
12745 (widen)
12746 (if (and (looking-at "[ \t]*\n")
12747 (equal (char-before) ?\n))
12748 (delete-region (1- (point)) (point-at-eol)))
12749 ts))))))
12751 (defvar org-log-note-marker (make-marker))
12752 (defvar org-log-note-purpose nil)
12753 (defvar org-log-note-state nil)
12754 (defvar org-log-note-previous-state nil)
12755 (defvar org-log-note-how nil)
12756 (defvar org-log-note-extra nil)
12757 (defvar org-log-note-window-configuration nil)
12758 (defvar org-log-note-return-to (make-marker))
12759 (defvar org-log-note-effective-time nil
12760 "Remembered current time so that dynamically scoped
12761 `org-extend-today-until' affects tha timestamps in state change
12762 log")
12764 (defvar org-log-post-message nil
12765 "Message to be displayed after a log note has been stored.
12766 The auto-repeater uses this.")
12768 (defun org-add-note ()
12769 "Add a note to the current entry.
12770 This is done in the same way as adding a state change note."
12771 (interactive)
12772 (org-add-log-setup 'note nil nil 'findpos nil))
12774 (defvar org-property-end-re)
12775 (defun org-add-log-setup (&optional purpose state prev-state
12776 findpos how extra)
12777 "Set up the post command hook to take a note.
12778 If this is about to TODO state change, the new state is expected in STATE.
12779 When FINDPOS is non-nil, find the correct position for the note in
12780 the current entry. If not, assume that it can be inserted at point.
12781 HOW is an indicator what kind of note should be created.
12782 EXTRA is additional text that will be inserted into the notes buffer."
12783 (let* ((org-log-into-drawer (org-log-into-drawer))
12784 (drawer (cond ((stringp org-log-into-drawer)
12785 org-log-into-drawer)
12786 (org-log-into-drawer "LOGBOOK"))))
12787 (save-restriction
12788 (save-excursion
12789 (when findpos
12790 (org-back-to-heading t)
12791 (narrow-to-region (point) (save-excursion
12792 (outline-next-heading) (point)))
12793 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12794 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12795 "[^\r\n]*\\)?"))
12796 (goto-char (match-end 0))
12797 (cond
12798 (drawer
12799 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12800 nil t)
12801 (progn
12802 (goto-char (match-end 0))
12803 (or org-log-states-order-reversed
12804 (and (re-search-forward org-property-end-re nil t)
12805 (goto-char (1- (match-beginning 0))))))
12806 (insert "\n:" drawer ":\n:END:")
12807 (beginning-of-line 0)
12808 (org-indent-line)
12809 (beginning-of-line 2)
12810 (org-indent-line)
12811 (end-of-line 0)))
12812 ((and org-log-state-notes-insert-after-drawers
12813 (save-excursion
12814 (forward-line) (looking-at org-drawer-regexp)))
12815 (forward-line)
12816 (while (looking-at org-drawer-regexp)
12817 (goto-char (match-end 0))
12818 (re-search-forward org-property-end-re (point-max) t)
12819 (forward-line))
12820 (forward-line -1)))
12821 (unless org-log-states-order-reversed
12822 (and (= (char-after) ?\n) (forward-char 1))
12823 (org-skip-over-state-notes)
12824 (skip-chars-backward " \t\n\r")))
12825 (move-marker org-log-note-marker (point))
12826 (setq org-log-note-purpose purpose
12827 org-log-note-state state
12828 org-log-note-previous-state prev-state
12829 org-log-note-how how
12830 org-log-note-extra extra
12831 org-log-note-effective-time (org-current-effective-time))
12832 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12834 (defun org-skip-over-state-notes ()
12835 "Skip past the list of State notes in an entry."
12836 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12837 (when (ignore-errors (goto-char (org-in-item-p)))
12838 (let* ((struct (org-list-struct))
12839 (prevs (org-list-prevs-alist struct)))
12840 (while (looking-at "[ \t]*- State")
12841 (goto-char (or (org-list-get-next-item (point) struct prevs)
12842 (org-list-get-item-end (point) struct)))))))
12844 (defun org-add-log-note (&optional purpose)
12845 "Pop up a window for taking a note, and add this note later at point."
12846 (remove-hook 'post-command-hook 'org-add-log-note)
12847 (setq org-log-note-window-configuration (current-window-configuration))
12848 (delete-other-windows)
12849 (move-marker org-log-note-return-to (point))
12850 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12851 (goto-char org-log-note-marker)
12852 (org-switch-to-buffer-other-window "*Org Note*")
12853 (erase-buffer)
12854 (if (memq org-log-note-how '(time state))
12855 (let (current-prefix-arg) (org-store-log-note))
12856 (let ((org-inhibit-startup t)) (org-mode))
12857 (insert (format "# Insert note for %s.
12858 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12859 (cond
12860 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12861 ((eq org-log-note-purpose 'done) "closed todo item")
12862 ((eq org-log-note-purpose 'state)
12863 (format "state change from \"%s\" to \"%s\""
12864 (or org-log-note-previous-state "")
12865 (or org-log-note-state "")))
12866 ((eq org-log-note-purpose 'reschedule)
12867 "rescheduling")
12868 ((eq org-log-note-purpose 'delschedule)
12869 "no longer scheduled")
12870 ((eq org-log-note-purpose 'redeadline)
12871 "changing deadline")
12872 ((eq org-log-note-purpose 'deldeadline)
12873 "removing deadline")
12874 ((eq org-log-note-purpose 'refile)
12875 "refiling")
12876 ((eq org-log-note-purpose 'note)
12877 "this entry")
12878 (t (error "This should not happen")))))
12879 (if org-log-note-extra (insert org-log-note-extra))
12880 (org-set-local 'org-finish-function 'org-store-log-note)
12881 (run-hooks 'org-log-buffer-setup-hook)))
12883 (defvar org-note-abort nil) ; dynamically scoped
12884 (defun org-store-log-note ()
12885 "Finish taking a log note, and insert it to where it belongs."
12886 (let ((txt (buffer-string)))
12887 (kill-buffer (current-buffer))
12888 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12889 lines ind bul)
12890 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12891 (setq txt (replace-match "" t t txt)))
12892 (if (string-match "\\s-+\\'" txt)
12893 (setq txt (replace-match "" t t txt)))
12894 (setq lines (org-split-string txt "\n"))
12895 (when (and note (string-match "\\S-" note))
12896 (setq note
12897 (org-replace-escapes
12898 note
12899 (list (cons "%u" (user-login-name))
12900 (cons "%U" user-full-name)
12901 (cons "%t" (format-time-string
12902 (org-time-stamp-format 'long 'inactive)
12903 org-log-note-effective-time))
12904 (cons "%T" (format-time-string
12905 (org-time-stamp-format 'long nil)
12906 org-log-note-effective-time))
12907 (cons "%d" (format-time-string
12908 (org-time-stamp-format nil 'inactive)
12909 org-log-note-effective-time))
12910 (cons "%D" (format-time-string
12911 (org-time-stamp-format nil nil)
12912 org-log-note-effective-time))
12913 (cons "%s" (if org-log-note-state
12914 (concat "\"" org-log-note-state "\"")
12915 ""))
12916 (cons "%S" (if org-log-note-previous-state
12917 (concat "\"" org-log-note-previous-state "\"")
12918 "\"\"")))))
12919 (if lines (setq note (concat note " \\\\")))
12920 (push note lines))
12921 (when (or current-prefix-arg org-note-abort)
12922 (when org-log-into-drawer
12923 (org-remove-empty-drawer-at
12924 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12925 org-log-note-marker))
12926 (setq lines nil))
12927 (when lines
12928 (with-current-buffer (marker-buffer org-log-note-marker)
12929 (save-excursion
12930 (goto-char org-log-note-marker)
12931 (move-marker org-log-note-marker nil)
12932 (end-of-line 1)
12933 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12934 (setq ind (save-excursion
12935 (if (ignore-errors (goto-char (org-in-item-p)))
12936 (let ((struct (org-list-struct)))
12937 (org-list-get-ind
12938 (org-list-get-top-point struct) struct))
12939 (skip-chars-backward " \r\t\n")
12940 (cond
12941 ((and (org-at-heading-p)
12942 org-adapt-indentation)
12943 (1+ (org-current-level)))
12944 ((org-at-heading-p) 0)
12945 (t (org-get-indentation))))))
12946 (setq bul (org-list-bullet-string "-"))
12947 (org-indent-line-to ind)
12948 (insert bul (pop lines))
12949 (let ((ind-body (+ (length bul) ind)))
12950 (while lines
12951 (insert "\n")
12952 (org-indent-line-to ind-body)
12953 (insert (pop lines))))
12954 (message "Note stored")
12955 (org-back-to-heading t)
12956 (org-cycle-hide-drawers 'children))))))
12957 (set-window-configuration org-log-note-window-configuration)
12958 (with-current-buffer (marker-buffer org-log-note-return-to)
12959 (goto-char org-log-note-return-to))
12960 (move-marker org-log-note-return-to nil)
12961 (and org-log-post-message (message "%s" org-log-post-message)))
12963 (defun org-remove-empty-drawer-at (drawer pos)
12964 "Remove an empty drawer DRAWER at position POS.
12965 POS may also be a marker."
12966 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12967 (save-excursion
12968 (save-restriction
12969 (widen)
12970 (goto-char pos)
12971 (if (org-in-regexp
12972 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12973 (replace-match ""))))))
12975 (defvar org-ts-type nil)
12976 (defun org-sparse-tree (&optional arg type)
12977 "Create a sparse tree, prompt for the details.
12978 This command can create sparse trees. You first need to select the type
12979 of match used to create the tree:
12981 t Show all TODO entries.
12982 T Show entries with a specific TODO keyword.
12983 m Show entries selected by a tags/property match.
12984 p Enter a property name and its value (both with completion on existing
12985 names/values) and show entries with that property.
12986 r Show entries matching a regular expression (`/' can be used as well).
12987 b Show deadlines and scheduled items before a date.
12988 a Show deadlines and scheduled items after a date.
12989 d Show deadlines due within `org-deadline-warning-days'.
12990 D Show deadlines and scheduled items between a date range."
12991 (interactive "P")
12992 (let (ans kwd value ts-type)
12993 (setq type (or type org-sparse-tree-default-date-type))
12994 (setq org-ts-type type)
12995 (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"
12996 (cond ((eq type 'all) "all timestamps")
12997 ((eq type 'scheduled) "only scheduled")
12998 ((eq type 'deadline) "only deadline")
12999 ((eq type 'active) "only active timestamps")
13000 ((eq type 'inactive) "only inactive timestamps")
13001 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13002 (t "scheduled/deadline")))
13003 (setq ans (read-char-exclusive))
13004 (cond
13005 ((equal ans ?c)
13006 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13007 ((equal ans ?d)
13008 (call-interactively 'org-check-deadlines))
13009 ((equal ans ?b)
13010 (call-interactively 'org-check-before-date))
13011 ((equal ans ?a)
13012 (call-interactively 'org-check-after-date))
13013 ((equal ans ?D)
13014 (call-interactively 'org-check-dates-range))
13015 ((equal ans ?t)
13016 (call-interactively 'org-show-todo-tree))
13017 ((equal ans ?T)
13018 (org-show-todo-tree '(4)))
13019 ((member ans '(?T ?m))
13020 (call-interactively 'org-match-sparse-tree))
13021 ((member ans '(?p ?P))
13022 (setq kwd (org-icompleting-read "Property: "
13023 (mapcar 'list (org-buffer-property-keys))))
13024 (setq value (org-icompleting-read "Value: "
13025 (mapcar 'list (org-property-values kwd))))
13026 (unless (string-match "\\`{.*}\\'" value)
13027 (setq value (concat "\"" value "\"")))
13028 (org-match-sparse-tree arg (concat kwd "=" value)))
13029 ((member ans '(?r ?R ?/))
13030 (call-interactively 'org-occur))
13031 (t (error "No such sparse tree command \"%c\"" ans)))))
13033 (defvar org-occur-highlights nil
13034 "List of overlays used for occur matches.")
13035 (make-variable-buffer-local 'org-occur-highlights)
13036 (defvar org-occur-parameters nil
13037 "Parameters of the active org-occur calls.
13038 This is a list, each call to org-occur pushes as cons cell,
13039 containing the regular expression and the callback, onto the list.
13040 The list can contain several entries if `org-occur' has been called
13041 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13042 will only contain one set of parameters. When the highlights are
13043 removed (for example with `C-c C-c', or with the next edit (depending
13044 on `org-remove-highlights-with-change'), this variable is emptied
13045 as well.")
13046 (make-variable-buffer-local 'org-occur-parameters)
13048 (defun org-occur (regexp &optional keep-previous callback)
13049 "Make a compact tree which shows all matches of REGEXP.
13050 The tree will show the lines where the regexp matches, and all higher
13051 headlines above the match. It will also show the heading after the match,
13052 to make sure editing the matching entry is easy.
13053 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13054 call to `org-occur' will be kept, to allow stacking of calls to this
13055 command.
13056 If CALLBACK is non-nil, it is a function which is called to confirm
13057 that the match should indeed be shown."
13058 (interactive "sRegexp: \nP")
13059 (when (equal regexp "")
13060 (error "Regexp cannot be empty"))
13061 (unless keep-previous
13062 (org-remove-occur-highlights nil nil t))
13063 (push (cons regexp callback) org-occur-parameters)
13064 (let ((cnt 0))
13065 (save-excursion
13066 (goto-char (point-min))
13067 (if (or (not keep-previous) ; do not want to keep
13068 (not org-occur-highlights)) ; no previous matches
13069 ;; hide everything
13070 (org-overview))
13071 (while (re-search-forward regexp nil t)
13072 (when (or (not callback)
13073 (save-match-data (funcall callback)))
13074 (setq cnt (1+ cnt))
13075 (when org-highlight-sparse-tree-matches
13076 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13077 (org-show-context 'occur-tree))))
13078 (when org-remove-highlights-with-change
13079 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13080 nil 'local))
13081 (unless org-sparse-tree-open-archived-trees
13082 (org-hide-archived-subtrees (point-min) (point-max)))
13083 (run-hooks 'org-occur-hook)
13084 (if (org-called-interactively-p 'interactive)
13085 (message "%d match(es) for regexp %s" cnt regexp))
13086 cnt))
13088 (defun org-occur-next-match (&optional n reset)
13089 "Function for `next-error-function' to find sparse tree matches.
13090 N is the number of matches to move, when negative move backwards.
13091 RESET is entirely ignored - this function always goes back to the
13092 starting point when no match is found."
13093 (let* ((limit (if (< n 0) (point-min) (point-max)))
13094 (search-func (if (< n 0)
13095 'previous-single-char-property-change
13096 'next-single-char-property-change))
13097 (n (abs n))
13098 (pos (point))
13100 (catch 'exit
13101 (while (setq p1 (funcall search-func (point) 'org-type))
13102 (when (equal p1 limit)
13103 (goto-char pos)
13104 (error "No more matches"))
13105 (when (equal (get-char-property p1 'org-type) 'org-occur)
13106 (setq n (1- n))
13107 (when (= n 0)
13108 (goto-char p1)
13109 (throw 'exit (point))))
13110 (goto-char p1))
13111 (goto-char p1)
13112 (error "No more matches"))))
13114 (defun org-show-context (&optional key)
13115 "Make sure point and context are visible.
13116 How much context is shown depends upon the variables
13117 `org-show-hierarchy-above', `org-show-following-heading',
13118 `org-show-entry-below' and `org-show-siblings'."
13119 (let ((heading-p (org-at-heading-p t))
13120 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13121 (following-p (org-get-alist-option org-show-following-heading key))
13122 (entry-p (org-get-alist-option org-show-entry-below key))
13123 (siblings-p (org-get-alist-option org-show-siblings key)))
13124 (catch 'exit
13125 ;; Show heading or entry text
13126 (if (and heading-p (not entry-p))
13127 (org-flag-heading nil) ; only show the heading
13128 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13129 (org-show-hidden-entry))) ; show entire entry
13130 (when following-p
13131 ;; Show next sibling, or heading below text
13132 (save-excursion
13133 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13134 (org-flag-heading nil))))
13135 (when siblings-p (org-show-siblings))
13136 (when hierarchy-p
13137 ;; show all higher headings, possibly with siblings
13138 (save-excursion
13139 (while (and (condition-case nil
13140 (progn (org-up-heading-all 1) t)
13141 (error nil))
13142 (not (bobp)))
13143 (org-flag-heading nil)
13144 (when siblings-p (org-show-siblings))))))))
13146 (defvar org-reveal-start-hook nil
13147 "Hook run before revealing a location.")
13149 (defun org-reveal (&optional siblings)
13150 "Show current entry, hierarchy above it, and the following headline.
13151 This can be used to show a consistent set of context around locations
13152 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13153 not t for the search context.
13155 With optional argument SIBLINGS, on each level of the hierarchy all
13156 siblings are shown. This repairs the tree structure to what it would
13157 look like when opened with hierarchical calls to `org-cycle'.
13158 With double optional argument \\[universal-argument] \\[universal-argument], \
13159 go to the parent and show the
13160 entire tree."
13161 (interactive "P")
13162 (run-hooks 'org-reveal-start-hook)
13163 (let ((org-show-hierarchy-above t)
13164 (org-show-following-heading t)
13165 (org-show-siblings (if siblings t org-show-siblings)))
13166 (org-show-context nil))
13167 (when (equal siblings '(16))
13168 (save-excursion
13169 (when (org-up-heading-safe)
13170 (org-show-subtree)
13171 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13173 (defun org-highlight-new-match (beg end)
13174 "Highlight from BEG to END and mark the highlight is an occur headline."
13175 (let ((ov (make-overlay beg end)))
13176 (overlay-put ov 'face 'secondary-selection)
13177 (overlay-put ov 'org-type 'org-occur)
13178 (push ov org-occur-highlights)))
13180 (defun org-remove-occur-highlights (&optional beg end noremove)
13181 "Remove the occur highlights from the buffer.
13182 BEG and END are ignored. If NOREMOVE is nil, remove this function
13183 from the `before-change-functions' in the current buffer."
13184 (interactive)
13185 (unless org-inhibit-highlight-removal
13186 (mapc 'delete-overlay org-occur-highlights)
13187 (setq org-occur-highlights nil)
13188 (setq org-occur-parameters nil)
13189 (unless noremove
13190 (remove-hook 'before-change-functions
13191 'org-remove-occur-highlights 'local))))
13193 ;;;; Priorities
13195 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13196 "Regular expression matching the priority indicator.")
13198 (defvar org-remove-priority-next-time nil)
13200 (defun org-priority-up ()
13201 "Increase the priority of the current item."
13202 (interactive)
13203 (org-priority 'up))
13205 (defun org-priority-down ()
13206 "Decrease the priority of the current item."
13207 (interactive)
13208 (org-priority 'down))
13210 (defun org-priority (&optional action show)
13211 "Change the priority of an item.
13212 ACTION can be `set', `up', `down', or a character."
13213 (interactive "P")
13214 (if (equal action '(4))
13215 (org-show-priority)
13216 (unless org-enable-priority-commands
13217 (error "Priority commands are disabled"))
13218 (setq action (or action 'set))
13219 (let (current new news have remove)
13220 (save-excursion
13221 (org-back-to-heading t)
13222 (if (looking-at org-priority-regexp)
13223 (setq current (string-to-char (match-string 2))
13224 have t))
13225 (cond
13226 ((eq action 'remove)
13227 (setq remove t new ?\ ))
13228 ((or (eq action 'set)
13229 (if (featurep 'xemacs) (characterp action) (integerp action)))
13230 (if (not (eq action 'set))
13231 (setq new action)
13232 (message "Priority %c-%c, SPC to remove: "
13233 org-highest-priority org-lowest-priority)
13234 (save-match-data
13235 (setq new (read-char-exclusive))))
13236 (if (and (= (upcase org-highest-priority) org-highest-priority)
13237 (= (upcase org-lowest-priority) org-lowest-priority))
13238 (setq new (upcase new)))
13239 (cond ((equal new ?\ ) (setq remove t))
13240 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13241 (error "Priority must be between `%c' and `%c'"
13242 org-highest-priority org-lowest-priority))))
13243 ((eq action 'up)
13244 (setq new (if have
13245 (1- current) ; normal cycling
13246 ;; last priority was empty
13247 (if (eq last-command this-command)
13248 org-lowest-priority ; wrap around empty to lowest
13249 ;; default
13250 (if org-priority-start-cycle-with-default
13251 org-default-priority
13252 (1- org-default-priority))))))
13253 ((eq action 'down)
13254 (setq new (if have
13255 (1+ current) ; normal cycling
13256 ;; last priority was empty
13257 (if (eq last-command this-command)
13258 org-highest-priority ; wrap around empty to highest
13259 ;; default
13260 (if org-priority-start-cycle-with-default
13261 org-default-priority
13262 (1+ org-default-priority))))))
13263 (t (error "Invalid action")))
13264 (if (or (< (upcase new) org-highest-priority)
13265 (> (upcase new) org-lowest-priority))
13266 (if (and (memq action '(up down))
13267 (not have) (not (eq last-command this-command)))
13268 ;; `new' is from default priority
13269 (error
13270 "The default can not be set, see `org-default-priority' why")
13271 ;; normal cycling: `new' is beyond highest/lowest priority
13272 ;; and is wrapped around to the empty priority
13273 (setq remove t)))
13274 (setq news (format "%c" new))
13275 (if have
13276 (if remove
13277 (replace-match "" t t nil 1)
13278 (replace-match news t t nil 2))
13279 (if remove
13280 (error "No priority cookie found in line")
13281 (let ((case-fold-search nil))
13282 (looking-at org-todo-line-regexp))
13283 (if (match-end 2)
13284 (progn
13285 (goto-char (match-end 2))
13286 (insert " [#" news "]"))
13287 (goto-char (match-beginning 3))
13288 (insert "[#" news "] "))))
13289 (org-preserve-lc (org-set-tags nil 'align)))
13290 (if remove
13291 (message "Priority removed")
13292 (message "Priority of current item set to %s" news)))))
13294 (defun org-show-priority ()
13295 "Show the priority of the current item.
13296 This priority is composed of the main priority given with the [#A] cookies,
13297 and by additional input from the age of a schedules or deadline entry."
13298 (interactive)
13299 (let ((pri (if (eq major-mode 'org-agenda-mode)
13300 (org-get-at-bol 'priority)
13301 (save-excursion
13302 (save-match-data
13303 (beginning-of-line)
13304 (and (looking-at org-heading-regexp)
13305 (org-get-priority (match-string 0))))))))
13306 (message "Priority is %d" (if pri pri -1000))))
13308 (defun org-get-priority (s)
13309 "Find priority cookie and return priority."
13310 (save-match-data
13311 (if (functionp org-get-priority-function)
13312 (funcall org-get-priority-function)
13313 (if (not (string-match org-priority-regexp s))
13314 (* 1000 (- org-lowest-priority org-default-priority))
13315 (* 1000 (- org-lowest-priority
13316 (string-to-char (match-string 2 s))))))))
13318 ;;;; Tags
13320 (defvar org-agenda-archives-mode)
13321 (defvar org-map-continue-from nil
13322 "Position from where mapping should continue.
13323 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13325 (defvar org-scanner-tags nil
13326 "The current tag list while the tags scanner is running.")
13327 (defvar org-trust-scanner-tags nil
13328 "Should `org-get-tags-at' use the tags for the scanner.
13329 This is for internal dynamical scoping only.
13330 When this is non-nil, the function `org-get-tags-at' will return the value
13331 of `org-scanner-tags' instead of building the list by itself. This
13332 can lead to large speed-ups when the tags scanner is used in a file with
13333 many entries, and when the list of tags is retrieved, for example to
13334 obtain a list of properties. Building the tags list for each entry in such
13335 a file becomes an N^2 operation - but with this variable set, it scales
13336 as N.")
13338 (defun org-scan-tags (action matcher todo-only &optional start-level)
13339 "Scan headline tags with inheritance and produce output ACTION.
13341 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13342 or `agenda' to produce an entry list for an agenda view. It can also be
13343 a Lisp form or a function that should be called at each matched headline, in
13344 this case the return value is a list of all return values from these calls.
13346 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13347 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13348 only lines with a not-done TODO keyword are included in the output.
13349 This should be the same variable that was scoped into
13350 and set by `org-make-tags-matcher' when it constructed MATCHER.
13352 START-LEVEL can be a string with asterisks, reducing the scope to
13353 headlines matching this string."
13354 (require 'org-agenda)
13355 (let* ((re (concat "^"
13356 (if start-level
13357 ;; Get the correct level to match
13358 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13359 org-outline-regexp)
13360 " *\\(\\<\\("
13361 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13362 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13363 (props (list 'face 'default
13364 'done-face 'org-agenda-done
13365 'undone-face 'default
13366 'mouse-face 'highlight
13367 'org-not-done-regexp org-not-done-regexp
13368 'org-todo-regexp org-todo-regexp
13369 'org-complex-heading-regexp org-complex-heading-regexp
13370 'help-echo
13371 (format "mouse-2 or RET jump to org file %s"
13372 (abbreviate-file-name
13373 (or (buffer-file-name (buffer-base-buffer))
13374 (buffer-name (buffer-base-buffer)))))))
13375 (case-fold-search nil)
13376 (org-map-continue-from nil)
13377 lspos tags tags-list
13378 (tags-alist (list (cons 0 org-file-tags)))
13379 (llast 0) rtn rtn1 level category i txt
13380 todo marker entry priority)
13381 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13382 (setq action (list 'lambda nil action)))
13383 (save-excursion
13384 (goto-char (point-min))
13385 (when (eq action 'sparse-tree)
13386 (org-overview)
13387 (org-remove-occur-highlights))
13388 (while (re-search-forward re nil t)
13389 (setq org-map-continue-from nil)
13390 (catch :skip
13391 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13392 tags (if (match-end 4) (org-match-string-no-properties 4)))
13393 (goto-char (setq lspos (match-beginning 0)))
13394 (setq level (org-reduced-level (org-outline-level))
13395 category (org-get-category))
13396 (setq i llast llast level)
13397 ;; remove tag lists from same and sublevels
13398 (while (>= i level)
13399 (when (setq entry (assoc i tags-alist))
13400 (setq tags-alist (delete entry tags-alist)))
13401 (setq i (1- i)))
13402 ;; add the next tags
13403 (when tags
13404 (setq tags (org-split-string tags ":")
13405 tags-alist
13406 (cons (cons level tags) tags-alist)))
13407 ;; compile tags for current headline
13408 (setq tags-list
13409 (if org-use-tag-inheritance
13410 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13411 tags)
13412 org-scanner-tags tags-list)
13413 (when org-use-tag-inheritance
13414 (setcdr (car tags-alist)
13415 (mapcar (lambda (x)
13416 (setq x (copy-sequence x))
13417 (org-add-prop-inherited x))
13418 (cdar tags-alist))))
13419 (when (and tags org-use-tag-inheritance
13420 (or (not (eq t org-use-tag-inheritance))
13421 org-tags-exclude-from-inheritance))
13422 ;; selective inheritance, remove uninherited ones
13423 (setcdr (car tags-alist)
13424 (org-remove-uninherited-tags (cdar tags-alist))))
13425 (when (and
13427 ;; eval matcher only when the todo condition is OK
13428 (and (or (not todo-only) (member todo org-not-done-keywords))
13429 (let ((case-fold-search t) (org-trust-scanner-tags t))
13430 (eval matcher)))
13432 ;; Call the skipper, but return t if it does not skip,
13433 ;; so that the `and' form continues evaluating
13434 (progn
13435 (unless (eq action 'sparse-tree) (org-agenda-skip))
13438 ;; Check if timestamps are deselecting this entry
13439 (or (not todo-only)
13440 (and (member todo org-not-done-keywords)
13441 (or (not org-agenda-tags-todo-honor-ignore-options)
13442 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13444 ;; select this headline
13445 (cond
13446 ((eq action 'sparse-tree)
13447 (and org-highlight-sparse-tree-matches
13448 (org-get-heading) (match-end 0)
13449 (org-highlight-new-match
13450 (match-beginning 1) (match-end 1)))
13451 (org-show-context 'tags-tree))
13452 ((eq action 'agenda)
13453 (setq txt (org-agenda-format-item
13455 (concat
13456 (if (eq org-tags-match-list-sublevels 'indented)
13457 (make-string (1- level) ?.) "")
13458 (org-get-heading))
13459 level category
13460 tags-list)
13461 priority (org-get-priority txt))
13462 (goto-char lspos)
13463 (setq marker (org-agenda-new-marker))
13464 (org-add-props txt props
13465 'org-marker marker 'org-hd-marker marker 'org-category category
13466 'todo-state todo
13467 'priority priority 'type "tagsmatch")
13468 (push txt rtn))
13469 ((functionp action)
13470 (setq org-map-continue-from nil)
13471 (save-excursion
13472 (setq rtn1 (funcall action))
13473 (push rtn1 rtn)))
13474 (t (error "Invalid action")))
13476 ;; if we are to skip sublevels, jump to end of subtree
13477 (unless org-tags-match-list-sublevels
13478 (org-end-of-subtree t)
13479 (backward-char 1))))
13480 ;; Get the correct position from where to continue
13481 (if org-map-continue-from
13482 (goto-char org-map-continue-from)
13483 (and (= (point) lspos) (end-of-line 1)))))
13484 (when (and (eq action 'sparse-tree)
13485 (not org-sparse-tree-open-archived-trees))
13486 (org-hide-archived-subtrees (point-min) (point-max)))
13487 (nreverse rtn)))
13489 (defun org-remove-uninherited-tags (tags)
13490 "Remove all tags that are not inherited from the list TAGS."
13491 (cond
13492 ((eq org-use-tag-inheritance t)
13493 (if org-tags-exclude-from-inheritance
13494 (org-delete-all org-tags-exclude-from-inheritance tags)
13495 tags))
13496 ((not org-use-tag-inheritance) nil)
13497 ((stringp org-use-tag-inheritance)
13498 (delq nil (mapcar
13499 (lambda (x)
13500 (if (and (string-match org-use-tag-inheritance x)
13501 (not (member x org-tags-exclude-from-inheritance)))
13502 x nil))
13503 tags)))
13504 ((listp org-use-tag-inheritance)
13505 (delq nil (mapcar
13506 (lambda (x)
13507 (if (member x org-use-tag-inheritance) x nil))
13508 tags)))))
13510 (defun org-match-sparse-tree (&optional todo-only match)
13511 "Create a sparse tree according to tags string MATCH.
13512 MATCH can contain positive and negative selection of tags, like
13513 \"+WORK+URGENT-WITHBOSS\".
13514 If optional argument TODO-ONLY is non-nil, only select lines that are
13515 also TODO lines."
13516 (interactive "P")
13517 (org-agenda-prepare-buffers (list (current-buffer)))
13518 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13520 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13522 (defvar org-cached-props nil)
13523 (defun org-cached-entry-get (pom property)
13524 (if (or (eq t org-use-property-inheritance)
13525 (and (stringp org-use-property-inheritance)
13526 (string-match org-use-property-inheritance property))
13527 (and (listp org-use-property-inheritance)
13528 (member property org-use-property-inheritance)))
13529 ;; Caching is not possible, check it directly
13530 (org-entry-get pom property 'inherit)
13531 ;; Get all properties, so that we can do complicated checks easily
13532 (cdr (assoc property (or org-cached-props
13533 (setq org-cached-props
13534 (org-entry-properties pom)))))))
13536 (defun org-global-tags-completion-table (&optional files)
13537 "Return the list of all tags in all agenda buffer/files.
13538 Optional FILES argument is a list of files which can be used
13539 instead of the agenda files."
13540 (save-excursion
13541 (org-uniquify
13542 (delq nil
13543 (apply 'append
13544 (mapcar
13545 (lambda (file)
13546 (set-buffer (find-file-noselect file))
13547 (append (org-get-buffer-tags)
13548 (mapcar (lambda (x) (if (stringp (car-safe x))
13549 (list (car-safe x)) nil))
13550 org-tag-alist)))
13551 (if (and files (car files))
13552 files
13553 (org-agenda-files))))))))
13555 (defun org-make-tags-matcher (match)
13556 "Create the TAGS/TODO matcher form for the selection string MATCH.
13558 The variable `todo-only' is scoped dynamically into this function.
13559 It will be set to t if the matcher restricts matching to TODO entries,
13560 otherwise will not be touched.
13562 Returns a cons of the selection string MATCH and the constructed
13563 lisp form implementing the matcher. The matcher is to be evaluated
13564 at an Org entry, with point on the headline, and returns t if the
13565 entry matches the selection string MATCH. The returned lisp form
13566 references two variables with information about the entry, which
13567 must be bound around the form's evaluation: todo, the TODO keyword
13568 at the entry (or nil of none); and tags-list, the list of all tags
13569 at the entry including inherited ones. Additionally, the category
13570 of the entry (if any) must be specified as the text property
13571 'org-category on the headline.
13573 See also `org-scan-tags'.
13575 (declare (special todo-only))
13576 (unless (boundp 'todo-only)
13577 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13578 (unless match
13579 ;; Get a new match request, with completion
13580 (let ((org-last-tags-completion-table
13581 (org-global-tags-completion-table)))
13582 (setq match (org-completing-read-no-i
13583 "Match: " 'org-tags-completion-function nil nil nil
13584 'org-tags-history))))
13586 ;; Parse the string and create a lisp form
13587 (let ((match0 match)
13588 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13589 minus tag mm
13590 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13591 orterms term orlist re-p str-p level-p level-op time-p
13592 prop-p pn pv po gv rest)
13593 (if (string-match "/+" match)
13594 ;; match contains also a todo-matching request
13595 (progn
13596 (setq tagsmatch (substring match 0 (match-beginning 0))
13597 todomatch (substring match (match-end 0)))
13598 (if (string-match "^!" todomatch)
13599 (setq todo-only t todomatch (substring todomatch 1)))
13600 (if (string-match "^\\s-*$" todomatch)
13601 (setq todomatch nil)))
13602 ;; only matching tags
13603 (setq tagsmatch match todomatch nil))
13605 ;; Make the tags matcher
13606 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13607 (setq tagsmatcher t)
13608 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13609 (while (setq term (pop orterms))
13610 (while (and (equal (substring term -1) "\\") orterms)
13611 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13612 (while (string-match re term)
13613 (setq rest (substring term (match-end 0))
13614 minus (and (match-end 1)
13615 (equal (match-string 1 term) "-"))
13616 tag (save-match-data (replace-regexp-in-string
13617 "\\\\-" "-"
13618 (match-string 2 term)))
13619 re-p (equal (string-to-char tag) ?{)
13620 level-p (match-end 4)
13621 prop-p (match-end 5)
13622 mm (cond
13623 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13624 (level-p
13625 (setq level-op (org-op-to-function (match-string 3 term)))
13626 `(,level-op level ,(string-to-number
13627 (match-string 4 term))))
13628 (prop-p
13629 (setq pn (match-string 5 term)
13630 po (match-string 6 term)
13631 pv (match-string 7 term)
13632 re-p (equal (string-to-char pv) ?{)
13633 str-p (equal (string-to-char pv) ?\")
13634 time-p (save-match-data
13635 (string-match "^\"[[<].*[]>]\"$" pv))
13636 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13637 (if time-p (setq pv (org-matcher-time pv)))
13638 (setq po (org-op-to-function po (if time-p 'time str-p)))
13639 (cond
13640 ((equal pn "CATEGORY")
13641 (setq gv '(get-text-property (point) 'org-category)))
13642 ((equal pn "TODO")
13643 (setq gv 'todo))
13645 (setq gv `(org-cached-entry-get nil ,pn))))
13646 (if re-p
13647 (if (eq po 'org<>)
13648 `(not (string-match ,pv (or ,gv "")))
13649 `(string-match ,pv (or ,gv "")))
13650 (if str-p
13651 `(,po (or ,gv "") ,pv)
13652 `(,po (string-to-number (or ,gv ""))
13653 ,(string-to-number pv) ))))
13654 (t `(member ,tag tags-list)))
13655 mm (if minus (list 'not mm) mm)
13656 term rest)
13657 (push mm tagsmatcher))
13658 (push (if (> (length tagsmatcher) 1)
13659 (cons 'and tagsmatcher)
13660 (car tagsmatcher))
13661 orlist)
13662 (setq tagsmatcher nil))
13663 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13664 (setq tagsmatcher
13665 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13666 ;; Make the todo matcher
13667 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13668 (setq todomatcher t)
13669 (setq orterms (org-split-string todomatch "|") orlist nil)
13670 (while (setq term (pop orterms))
13671 (while (string-match re term)
13672 (setq minus (and (match-end 1)
13673 (equal (match-string 1 term) "-"))
13674 kwd (match-string 2 term)
13675 re-p (equal (string-to-char kwd) ?{)
13676 term (substring term (match-end 0))
13677 mm (if re-p
13678 `(string-match ,(substring kwd 1 -1) todo)
13679 (list 'equal 'todo kwd))
13680 mm (if minus (list 'not mm) mm))
13681 (push mm todomatcher))
13682 (push (if (> (length todomatcher) 1)
13683 (cons 'and todomatcher)
13684 (car todomatcher))
13685 orlist)
13686 (setq todomatcher nil))
13687 (setq todomatcher (if (> (length orlist) 1)
13688 (cons 'or orlist) (car orlist))))
13690 ;; Return the string and lisp forms of the matcher
13691 (setq matcher (if todomatcher
13692 (list 'and tagsmatcher todomatcher)
13693 tagsmatcher))
13694 (when todo-only
13695 (setq matcher (list 'and '(member todo org-not-done-keywords)
13696 matcher)))
13697 (cons match0 matcher)))
13699 (defun org-op-to-function (op &optional stringp)
13700 "Turn an operator into the appropriate function."
13701 (setq op
13702 (cond
13703 ((equal op "<" ) '(< string< org-time<))
13704 ((equal op ">" ) '(> org-string> org-time>))
13705 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13706 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13707 ((member op '("=" "==")) '(= string= org-time=))
13708 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13709 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13711 (defun org<> (a b) (not (= a b)))
13712 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13713 (defun org-string>= (a b) (not (string< a b)))
13714 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13715 (defun org-string<> (a b) (not (string= a b)))
13716 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13717 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13718 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13719 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13720 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13721 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13722 (defun org-2ft (s)
13723 "Convert S to a floating point time.
13724 If S is already a number, just return it. If it is a string, parse
13725 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13726 (cond
13727 ((numberp s) s)
13728 ((stringp s)
13729 (condition-case nil
13730 (float-time (apply 'encode-time (org-parse-time-string s)))
13731 (error 0.)))
13732 (t 0.)))
13734 (defun org-time-today ()
13735 "Time in seconds today at 0:00.
13736 Returns the float number of seconds since the beginning of the
13737 epoch to the beginning of today (00:00)."
13738 (float-time (apply 'encode-time
13739 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13741 (defun org-matcher-time (s)
13742 "Interpret a time comparison value."
13743 (save-match-data
13744 (cond
13745 ((string= s "<now>") (float-time))
13746 ((string= s "<today>") (org-time-today))
13747 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13748 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13749 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13750 (+ (org-time-today)
13751 (* (string-to-number (match-string 1 s))
13752 (cdr (assoc (match-string 2 s)
13753 '(("d" . 86400.0) ("w" . 604800.0)
13754 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13755 (t (org-2ft s)))))
13757 (defun org-match-any-p (re list)
13758 "Does re match any element of list?"
13759 (setq list (mapcar (lambda (x) (string-match re x)) list))
13760 (delq nil list))
13762 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13763 (defvar org-tags-overlay (make-overlay 1 1))
13764 (org-detach-overlay org-tags-overlay)
13766 (defun org-get-local-tags-at (&optional pos)
13767 "Get a list of tags defined in the current headline."
13768 (org-get-tags-at pos 'local))
13770 (defun org-get-local-tags ()
13771 "Get a list of tags defined in the current headline."
13772 (org-get-tags-at nil 'local))
13774 (defun org-get-tags-at (&optional pos local)
13775 "Get a list of all headline tags applicable at POS.
13776 POS defaults to point. If tags are inherited, the list contains
13777 the targets in the same sequence as the headlines appear, i.e.
13778 the tags of the current headline come last.
13779 When LOCAL is non-nil, only return tags from the current headline,
13780 ignore inherited ones."
13781 (interactive)
13782 (if (and org-trust-scanner-tags
13783 (or (not pos) (equal pos (point)))
13784 (not local))
13785 org-scanner-tags
13786 (let (tags ltags lastpos parent)
13787 (save-excursion
13788 (save-restriction
13789 (widen)
13790 (goto-char (or pos (point)))
13791 (save-match-data
13792 (catch 'done
13793 (condition-case nil
13794 (progn
13795 (org-back-to-heading t)
13796 (while (not (equal lastpos (point)))
13797 (setq lastpos (point))
13798 (when (looking-at
13799 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13800 (setq ltags (org-split-string
13801 (org-match-string-no-properties 1) ":"))
13802 (when parent
13803 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13804 (setq tags (append
13805 (if parent
13806 (org-remove-uninherited-tags ltags)
13807 ltags)
13808 tags)))
13809 (or org-use-tag-inheritance (throw 'done t))
13810 (if local (throw 'done t))
13811 (or (org-up-heading-safe) (error nil))
13812 (setq parent t)))
13813 (error nil)))))
13814 (if local
13815 tags
13816 (reverse (delete-dups
13817 (reverse (append
13818 (org-remove-uninherited-tags
13819 org-file-tags) tags)))))))))
13821 (defun org-add-prop-inherited (s)
13822 (add-text-properties 0 (length s) '(inherited t) s)
13825 (defun org-toggle-tag (tag &optional onoff)
13826 "Toggle the tag TAG for the current line.
13827 If ONOFF is `on' or `off', don't toggle but set to this state."
13828 (let (res current)
13829 (save-excursion
13830 (org-back-to-heading t)
13831 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13832 (point-at-eol) t)
13833 (progn
13834 (setq current (match-string 1))
13835 (replace-match ""))
13836 (setq current ""))
13837 (setq current (nreverse (org-split-string current ":")))
13838 (cond
13839 ((eq onoff 'on)
13840 (setq res t)
13841 (or (member tag current) (push tag current)))
13842 ((eq onoff 'off)
13843 (or (not (member tag current)) (setq current (delete tag current))))
13844 (t (if (member tag current)
13845 (setq current (delete tag current))
13846 (setq res t)
13847 (push tag current))))
13848 (end-of-line 1)
13849 (if current
13850 (progn
13851 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13852 (org-set-tags nil t))
13853 (delete-horizontal-space))
13854 (run-hooks 'org-after-tags-change-hook))
13855 res))
13857 (defun org-align-tags-here (to-col)
13858 ;; Assumes that this is a headline
13859 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13860 (beginning-of-line 1)
13861 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13862 (< pos (match-beginning 2)))
13863 (progn
13864 (setq tags-l (- (match-end 2) (match-beginning 2)))
13865 (goto-char (match-beginning 1))
13866 (insert " ")
13867 (delete-region (point) (1+ (match-beginning 2)))
13868 (setq ncol (max (current-column)
13869 (1+ col)
13870 (if (> to-col 0)
13871 to-col
13872 (- (abs to-col) tags-l))))
13873 (setq p (point))
13874 (insert (make-string (- ncol (current-column)) ?\ ))
13875 (setq ncol (current-column))
13876 (when indent-tabs-mode (tabify p (point-at-eol)))
13877 (org-move-to-column (min ncol col) t))
13878 (goto-char pos))))
13880 (defun org-set-tags-command (&optional arg just-align)
13881 "Call the set-tags command for the current entry."
13882 (interactive "P")
13883 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13884 (org-set-tags arg just-align)
13885 (save-excursion
13886 (org-back-to-heading t)
13887 (org-set-tags arg just-align))))
13889 (defun org-set-tags-to (data)
13890 "Set the tags of the current entry to DATA, replacing the current tags.
13891 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13892 If DATA is nil or the empty string, any tags will be removed."
13893 (interactive "sTags: ")
13894 (setq data
13895 (cond
13896 ((eq data nil) "")
13897 ((equal data "") "")
13898 ((stringp data)
13899 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13900 ":"))
13901 ((listp data)
13902 (concat ":" (mapconcat 'identity data ":") ":"))))
13903 (when data
13904 (save-excursion
13905 (org-back-to-heading t)
13906 (when (looking-at org-complex-heading-regexp)
13907 (if (match-end 5)
13908 (progn
13909 (goto-char (match-beginning 5))
13910 (insert data)
13911 (delete-region (point) (point-at-eol))
13912 (org-set-tags nil 'align))
13913 (goto-char (point-at-eol))
13914 (insert " " data)
13915 (org-set-tags nil 'align)))
13916 (beginning-of-line 1)
13917 (if (looking-at ".*?\\([ \t]+\\)$")
13918 (delete-region (match-beginning 1) (match-end 1))))))
13920 (defun org-align-all-tags ()
13921 "Align the tags i all headings."
13922 (interactive)
13923 (save-excursion
13924 (or (ignore-errors (org-back-to-heading t))
13925 (outline-next-heading))
13926 (if (org-at-heading-p)
13927 (org-set-tags t)
13928 (message "No headings"))))
13930 (defvar org-indent-indentation-per-level)
13931 (defun org-set-tags (&optional arg just-align)
13932 "Set the tags for the current headline.
13933 With prefix ARG, realign all tags in headings in the current buffer."
13934 (interactive "P")
13935 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13936 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13937 'region-start-level 'region))
13938 org-loop-over-headlines-in-active-region)
13939 (org-map-entries
13940 ;; We don't use ARG and JUST-ALIGN here these args are not
13941 ;; useful when looping over headlines
13942 `(org-set-tags)
13943 org-loop-over-headlines-in-active-region
13944 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13945 (let* ((re org-outline-regexp-bol)
13946 (current (unless arg (org-get-tags-string)))
13947 (col (current-column))
13948 (org-setting-tags t)
13949 table current-tags inherited-tags ; computed below when needed
13950 tags p0 c0 c1 rpl di tc level)
13951 (if arg
13952 (save-excursion
13953 (goto-char (point-min))
13954 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13955 (while (re-search-forward re nil t)
13956 (org-set-tags nil t)
13957 (end-of-line 1)))
13958 (message "All tags realigned to column %d" org-tags-column))
13959 (if just-align
13960 (setq tags current)
13961 ;; Get a new set of tags from the user
13962 (save-excursion
13963 (setq table (append org-tag-persistent-alist
13964 (or org-tag-alist (org-get-buffer-tags))
13965 (and
13966 org-complete-tags-always-offer-all-agenda-tags
13967 (org-global-tags-completion-table
13968 (org-agenda-files))))
13969 org-last-tags-completion-table table
13970 current-tags (org-split-string current ":")
13971 inherited-tags (nreverse
13972 (nthcdr (length current-tags)
13973 (nreverse (org-get-tags-at))))
13974 tags
13975 (if (or (eq t org-use-fast-tag-selection)
13976 (and org-use-fast-tag-selection
13977 (delq nil (mapcar 'cdr table))))
13978 (org-fast-tag-selection
13979 current-tags inherited-tags table
13980 (if org-fast-tag-selection-include-todo
13981 org-todo-key-alist))
13982 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13983 (org-trim
13984 (org-icompleting-read "Tags: "
13985 'org-tags-completion-function
13986 nil nil current 'org-tags-history))))))
13987 (while (string-match "[-+&]+" tags)
13988 ;; No boolean logic, just a list
13989 (setq tags (replace-match ":" t t tags))))
13991 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13993 (if org-tags-sort-function
13994 (setq tags (mapconcat 'identity
13995 (sort (org-split-string
13996 tags (org-re "[^[:alnum:]_@#%]+"))
13997 org-tags-sort-function) ":")))
13999 (if (string-match "\\`[\t ]*\\'" tags)
14000 (setq tags "")
14001 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14002 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14004 ;; Insert new tags at the correct column
14005 (beginning-of-line 1)
14006 (setq level (or (and (looking-at org-outline-regexp)
14007 (- (match-end 0) (point) 1))
14009 (cond
14010 ((and (equal current "") (equal tags "")))
14011 ((re-search-forward
14012 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14013 (point-at-eol) t)
14014 (if (equal tags "")
14015 (setq rpl "")
14016 (goto-char (match-beginning 0))
14017 (setq c0 (current-column)
14018 ;; compute offset for the case of org-indent-mode active
14019 di (if org-indent-mode
14020 (* (1- org-indent-indentation-per-level) (1- level))
14022 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14023 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14024 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14025 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14026 (replace-match rpl t t)
14027 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14028 tags)
14029 (t (error "Tags alignment failed")))
14030 (org-move-to-column col)
14031 (unless just-align
14032 (run-hooks 'org-after-tags-change-hook))))))
14034 (defun org-change-tag-in-region (beg end tag off)
14035 "Add or remove TAG for each entry in the region.
14036 This works in the agenda, and also in an org-mode buffer."
14037 (interactive
14038 (list (region-beginning) (region-end)
14039 (let ((org-last-tags-completion-table
14040 (if (derived-mode-p 'org-mode)
14041 (org-get-buffer-tags)
14042 (org-global-tags-completion-table))))
14043 (org-icompleting-read
14044 "Tag: " 'org-tags-completion-function nil nil nil
14045 'org-tags-history))
14046 (progn
14047 (message "[s]et or [r]emove? ")
14048 (equal (read-char-exclusive) ?r))))
14049 (if (fboundp 'deactivate-mark) (deactivate-mark))
14050 (let ((agendap (equal major-mode 'org-agenda-mode))
14051 l1 l2 m buf pos newhead (cnt 0))
14052 (goto-char end)
14053 (setq l2 (1- (org-current-line)))
14054 (goto-char beg)
14055 (setq l1 (org-current-line))
14056 (loop for l from l1 to l2 do
14057 (org-goto-line l)
14058 (setq m (get-text-property (point) 'org-hd-marker))
14059 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14060 (and agendap m))
14061 (setq buf (if agendap (marker-buffer m) (current-buffer))
14062 pos (if agendap m (point)))
14063 (with-current-buffer buf
14064 (save-excursion
14065 (save-restriction
14066 (goto-char pos)
14067 (setq cnt (1+ cnt))
14068 (org-toggle-tag tag (if off 'off 'on))
14069 (setq newhead (org-get-heading)))))
14070 (and agendap (org-agenda-change-all-lines newhead m))))
14071 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14073 (defun org-tags-completion-function (string predicate &optional flag)
14074 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14075 (confirm (lambda (x) (stringp (car x)))))
14076 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14077 (setq s1 (match-string 1 string)
14078 s2 (match-string 2 string))
14079 (setq s1 "" s2 string))
14080 (cond
14081 ((eq flag nil)
14082 ;; try completion
14083 (setq rtn (try-completion s2 ctable confirm))
14084 (if (stringp rtn)
14085 (setq rtn
14086 (concat s1 s2 (substring rtn (length s2))
14087 (if (and org-add-colon-after-tag-completion
14088 (assoc rtn ctable))
14089 ":" ""))))
14090 rtn)
14091 ((eq flag t)
14092 ;; all-completions
14093 (all-completions s2 ctable confirm)
14095 ((eq flag 'lambda)
14096 ;; exact match?
14097 (assoc s2 ctable)))
14100 (defun org-fast-tag-insert (kwd tags face &optional end)
14101 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14102 (insert (format "%-12s" (concat kwd ":"))
14103 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14104 (or end "")))
14106 (defun org-fast-tag-show-exit (flag)
14107 (save-excursion
14108 (org-goto-line 3)
14109 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14110 (replace-match ""))
14111 (when flag
14112 (end-of-line 1)
14113 (org-move-to-column (- (window-width) 19) t)
14114 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14116 (defun org-set-current-tags-overlay (current prefix)
14117 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14118 (if (featurep 'xemacs)
14119 (org-overlay-display org-tags-overlay (concat prefix s)
14120 'secondary-selection)
14121 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14122 (org-overlay-display org-tags-overlay (concat prefix s)))))
14124 (defvar org-last-tag-selection-key nil)
14125 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14126 "Fast tag selection with single keys.
14127 CURRENT is the current list of tags in the headline, INHERITED is the
14128 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14129 possibly with grouping information. TODO-TABLE is a similar table with
14130 TODO keywords, should these have keys assigned to them.
14131 If the keys are nil, a-z are automatically assigned.
14132 Returns the new tags string, or nil to not change the current settings."
14133 (let* ((fulltable (append table todo-table))
14134 (maxlen (apply 'max (mapcar
14135 (lambda (x)
14136 (if (stringp (car x)) (string-width (car x)) 0))
14137 fulltable)))
14138 (buf (current-buffer))
14139 (expert (eq org-fast-tag-selection-single-key 'expert))
14140 (buffer-tags nil)
14141 (fwidth (+ maxlen 3 1 3))
14142 (ncol (/ (- (window-width) 4) fwidth))
14143 (i-face 'org-done)
14144 (c-face 'org-todo)
14145 tg cnt e c char c1 c2 ntable tbl rtn
14146 ov-start ov-end ov-prefix
14147 (exit-after-next org-fast-tag-selection-single-key)
14148 (done-keywords org-done-keywords)
14149 groups ingroup)
14150 (save-excursion
14151 (beginning-of-line 1)
14152 (if (looking-at
14153 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14154 (setq ov-start (match-beginning 1)
14155 ov-end (match-end 1)
14156 ov-prefix "")
14157 (setq ov-start (1- (point-at-eol))
14158 ov-end (1+ ov-start))
14159 (skip-chars-forward "^\n\r")
14160 (setq ov-prefix
14161 (concat
14162 (buffer-substring (1- (point)) (point))
14163 (if (> (current-column) org-tags-column)
14165 (make-string (- org-tags-column (current-column)) ?\ ))))))
14166 (move-overlay org-tags-overlay ov-start ov-end)
14167 (save-window-excursion
14168 (if expert
14169 (set-buffer (get-buffer-create " *Org tags*"))
14170 (delete-other-windows)
14171 (split-window-vertically)
14172 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14173 (erase-buffer)
14174 (org-set-local 'org-done-keywords done-keywords)
14175 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14176 (org-fast-tag-insert "Current" current c-face "\n\n")
14177 (org-fast-tag-show-exit exit-after-next)
14178 (org-set-current-tags-overlay current ov-prefix)
14179 (setq tbl fulltable char ?a cnt 0)
14180 (while (setq e (pop tbl))
14181 (cond
14182 ((equal (car e) :startgroup)
14183 (push '() groups) (setq ingroup t)
14184 (when (not (= cnt 0))
14185 (setq cnt 0)
14186 (insert "\n"))
14187 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14188 ((equal (car e) :endgroup)
14189 (setq ingroup nil cnt 0)
14190 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14191 ((equal e '(:newline))
14192 (when (not (= cnt 0))
14193 (setq cnt 0)
14194 (insert "\n")
14195 (setq e (car tbl))
14196 (while (equal (car tbl) '(:newline))
14197 (insert "\n")
14198 (setq tbl (cdr tbl)))))
14200 (setq tg (copy-sequence (car e)) c2 nil)
14201 (if (cdr e)
14202 (setq c (cdr e))
14203 ;; automatically assign a character.
14204 (setq c1 (string-to-char
14205 (downcase (substring
14206 tg (if (= (string-to-char tg) ?@) 1 0)))))
14207 (if (or (rassoc c1 ntable) (rassoc c1 table))
14208 (while (or (rassoc char ntable) (rassoc char table))
14209 (setq char (1+ char)))
14210 (setq c2 c1))
14211 (setq c (or c2 char)))
14212 (if ingroup (push tg (car groups)))
14213 (setq tg (org-add-props tg nil 'face
14214 (cond
14215 ((not (assoc tg table))
14216 (org-get-todo-face tg))
14217 ((member tg current) c-face)
14218 ((member tg inherited) i-face))))
14219 (if (and (= cnt 0) (not ingroup)) (insert " "))
14220 (insert "[" c "] " tg (make-string
14221 (- fwidth 4 (length tg)) ?\ ))
14222 (push (cons tg c) ntable)
14223 (when (= (setq cnt (1+ cnt)) ncol)
14224 (insert "\n")
14225 (if ingroup (insert " "))
14226 (setq cnt 0)))))
14227 (setq ntable (nreverse ntable))
14228 (insert "\n")
14229 (goto-char (point-min))
14230 (if (not expert) (org-fit-window-to-buffer))
14231 (setq rtn
14232 (catch 'exit
14233 (while t
14234 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14235 (if (not groups) "no " "")
14236 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14237 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14238 (setq org-last-tag-selection-key c)
14239 (cond
14240 ((= c ?\r) (throw 'exit t))
14241 ((= c ?!)
14242 (setq groups (not groups))
14243 (goto-char (point-min))
14244 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14245 ((= c ?\C-c)
14246 (if (not expert)
14247 (org-fast-tag-show-exit
14248 (setq exit-after-next (not exit-after-next)))
14249 (setq expert nil)
14250 (delete-other-windows)
14251 (set-window-buffer (split-window-vertically) " *Org tags*")
14252 (org-switch-to-buffer-other-window " *Org tags*")
14253 (org-fit-window-to-buffer)))
14254 ((or (= c ?\C-g)
14255 (and (= c ?q) (not (rassoc c ntable))))
14256 (org-detach-overlay org-tags-overlay)
14257 (setq quit-flag t))
14258 ((= c ?\ )
14259 (setq current nil)
14260 (if exit-after-next (setq exit-after-next 'now)))
14261 ((= c ?\t)
14262 (condition-case nil
14263 (setq tg (org-icompleting-read
14264 "Tag: "
14265 (or buffer-tags
14266 (with-current-buffer buf
14267 (org-get-buffer-tags)))))
14268 (quit (setq tg "")))
14269 (when (string-match "\\S-" tg)
14270 (add-to-list 'buffer-tags (list tg))
14271 (if (member tg current)
14272 (setq current (delete tg current))
14273 (push tg current)))
14274 (if exit-after-next (setq exit-after-next 'now)))
14275 ((setq e (rassoc c todo-table) tg (car e))
14276 (with-current-buffer buf
14277 (save-excursion (org-todo tg)))
14278 (if exit-after-next (setq exit-after-next 'now)))
14279 ((setq e (rassoc c ntable) tg (car e))
14280 (if (member tg current)
14281 (setq current (delete tg current))
14282 (loop for g in groups do
14283 (if (member tg g)
14284 (mapc (lambda (x)
14285 (setq current (delete x current)))
14286 g)))
14287 (push tg current))
14288 (if exit-after-next (setq exit-after-next 'now))))
14290 ;; Create a sorted list
14291 (setq current
14292 (sort current
14293 (lambda (a b)
14294 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14295 (if (eq exit-after-next 'now) (throw 'exit t))
14296 (goto-char (point-min))
14297 (beginning-of-line 2)
14298 (delete-region (point) (point-at-eol))
14299 (org-fast-tag-insert "Current" current c-face)
14300 (org-set-current-tags-overlay current ov-prefix)
14301 (while (re-search-forward
14302 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14303 (setq tg (match-string 1))
14304 (add-text-properties
14305 (match-beginning 1) (match-end 1)
14306 (list 'face
14307 (cond
14308 ((member tg current) c-face)
14309 ((member tg inherited) i-face)
14310 (t (get-text-property (match-beginning 1) 'face))))))
14311 (goto-char (point-min)))))
14312 (org-detach-overlay org-tags-overlay)
14313 (if rtn
14314 (mapconcat 'identity current ":")
14315 nil))))
14317 (defun org-get-tags-string ()
14318 "Get the TAGS string in the current headline."
14319 (unless (org-at-heading-p t)
14320 (error "Not on a heading"))
14321 (save-excursion
14322 (beginning-of-line 1)
14323 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14324 (org-match-string-no-properties 1)
14325 "")))
14327 (defun org-get-tags ()
14328 "Get the list of tags specified in the current headline."
14329 (org-split-string (org-get-tags-string) ":"))
14331 (defun org-get-buffer-tags ()
14332 "Get a table of all tags used in the buffer, for completion."
14333 (let (tags)
14334 (save-excursion
14335 (goto-char (point-min))
14336 (while (re-search-forward
14337 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14338 (when (equal (char-after (point-at-bol 0)) ?*)
14339 (mapc (lambda (x) (add-to-list 'tags x))
14340 (org-split-string (org-match-string-no-properties 1) ":")))))
14341 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14342 (mapcar 'list tags)))
14344 ;;;; The mapping API
14346 (defun org-map-entries (func &optional match scope &rest skip)
14347 "Call FUNC at each headline selected by MATCH in SCOPE.
14349 FUNC is a function or a lisp form. The function will be called without
14350 arguments, with the cursor positioned at the beginning of the headline.
14351 The return values of all calls to the function will be collected and
14352 returned as a list.
14354 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14355 does not need to preserve point. After evaluation, the cursor will be
14356 moved to the end of the line (presumably of the headline of the
14357 processed entry) and search continues from there. Under some
14358 circumstances, this may not produce the wanted results. For example,
14359 if you have removed (e.g. archived) the current (sub)tree it could
14360 mean that the next entry will be skipped entirely. In such cases, you
14361 can specify the position from where search should continue by making
14362 FUNC set the variable `org-map-continue-from' to the desired buffer
14363 position.
14365 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14366 Only headlines that are matched by this query will be considered during
14367 the iteration. When MATCH is nil or t, all headlines will be
14368 visited by the iteration.
14370 SCOPE determines the scope of this command. It can be any of:
14372 nil The current buffer, respecting the restriction if any
14373 tree The subtree started with the entry at point
14374 region The entries within the active region, if any
14375 region-start-level
14376 The entries within the active region, but only those at
14377 the same level than the first one.
14378 file The current buffer, without restriction
14379 file-with-archives
14380 The current buffer, and any archives associated with it
14381 agenda All agenda files
14382 agenda-with-archives
14383 All agenda files with any archive files associated with them
14384 \(file1 file2 ...)
14385 If this is a list, all files in the list will be scanned
14387 The remaining args are treated as settings for the skipping facilities of
14388 the scanner. The following items can be given here:
14390 archive skip trees with the archive tag.
14391 comment skip trees with the COMMENT keyword
14392 function or Emacs Lisp form:
14393 will be used as value for `org-agenda-skip-function', so whenever
14394 the function returns t, FUNC will not be called for that
14395 entry and search will continue from the point where the
14396 function leaves it.
14398 If your function needs to retrieve the tags including inherited tags
14399 at the *current* entry, you can use the value of the variable
14400 `org-scanner-tags' which will be much faster than getting the value
14401 with `org-get-tags-at'. If your function gets properties with
14402 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14403 to t around the call to `org-entry-properties' to get the same speedup.
14404 Note that if your function moves around to retrieve tags and properties at
14405 a *different* entry, you cannot use these techniques."
14406 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14407 (not (org-region-active-p)))
14408 (let* ((org-agenda-archives-mode nil) ; just to make sure
14409 (org-agenda-skip-archived-trees (memq 'archive skip))
14410 (org-agenda-skip-comment-trees (memq 'comment skip))
14411 (org-agenda-skip-function
14412 (car (org-delete-all '(comment archive) skip)))
14413 (org-tags-match-list-sublevels t)
14414 (start-level (eq scope 'region-start-level))
14415 matcher file res
14416 org-todo-keywords-for-agenda
14417 org-done-keywords-for-agenda
14418 org-todo-keyword-alist-for-agenda
14419 org-drawers-for-agenda
14420 org-tag-alist-for-agenda
14421 todo-only)
14423 (cond
14424 ((eq match t) (setq matcher t))
14425 ((eq match nil) (setq matcher t))
14426 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14428 (save-excursion
14429 (save-restriction
14430 (cond ((eq scope 'tree)
14431 (org-back-to-heading t)
14432 (org-narrow-to-subtree)
14433 (setq scope nil))
14434 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14435 (org-region-active-p))
14436 ;; If needed, set start-level to a string like "2"
14437 (when start-level
14438 (save-excursion
14439 (goto-char (region-beginning))
14440 (unless (org-at-heading-p) (outline-next-heading))
14441 (setq start-level (org-current-level))))
14442 (narrow-to-region (region-beginning)
14443 (save-excursion
14444 (goto-char (region-end))
14445 (unless (and (bolp) (org-at-heading-p))
14446 (outline-next-heading))
14447 (point)))
14448 (setq scope nil)))
14450 (if (not scope)
14451 (progn
14452 (org-agenda-prepare-buffers
14453 (list (buffer-file-name (current-buffer))))
14454 (setq res (org-scan-tags func matcher todo-only start-level)))
14455 ;; Get the right scope
14456 (cond
14457 ((and scope (listp scope) (symbolp (car scope)))
14458 (setq scope (eval scope)))
14459 ((eq scope 'agenda)
14460 (setq scope (org-agenda-files t)))
14461 ((eq scope 'agenda-with-archives)
14462 (setq scope (org-agenda-files t))
14463 (setq scope (org-add-archive-files scope)))
14464 ((eq scope 'file)
14465 (setq scope (list (buffer-file-name))))
14466 ((eq scope 'file-with-archives)
14467 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14468 (org-agenda-prepare-buffers scope)
14469 (while (setq file (pop scope))
14470 (with-current-buffer (org-find-base-buffer-visiting file)
14471 (save-excursion
14472 (save-restriction
14473 (widen)
14474 (goto-char (point-min))
14475 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14476 res)))
14478 ;;;; Properties
14480 ;;; Setting and retrieving properties
14482 (defconst org-special-properties
14483 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14484 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14485 "The special properties valid in Org-mode.
14487 These are properties that are not defined in the property drawer,
14488 but in some other way.")
14490 (defconst org-default-properties
14491 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14492 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14493 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14494 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14495 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14496 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14497 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14498 "Some properties that are used by Org-mode for various purposes.
14499 Being in this list makes sure that they are offered for completion.")
14501 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14502 "Regular expression matching the first line of a property drawer.")
14504 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14505 "Regular expression matching the last line of a property drawer.")
14507 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14508 "Regular expression matching the first line of a property drawer.")
14510 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14511 "Regular expression matching the first line of a property drawer.")
14513 (defconst org-property-drawer-re
14514 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14515 org-property-end-re "\\)\n?")
14516 "Matches an entire property drawer.")
14518 (defconst org-clock-drawer-re
14519 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14520 org-property-end-re "\\)\n?")
14521 "Matches an entire clock drawer.")
14523 (defsubst org-re-property (property)
14524 "Return a regexp matching a PROPERTY line.
14525 Match group 1 will be set to the value."
14526 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14528 (defsubst org-re-property-keyword (property)
14529 "Return a regexp matching a PROPERTY line, possibly with no
14530 value for the property."
14531 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14533 (defun org-property-action ()
14534 "Do an action on properties."
14535 (interactive)
14536 (let (c)
14537 (org-at-property-p)
14538 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14539 (setq c (read-char-exclusive))
14540 (cond
14541 ((equal c ?s)
14542 (call-interactively 'org-set-property))
14543 ((equal c ?d)
14544 (call-interactively 'org-delete-property))
14545 ((equal c ?D)
14546 (call-interactively 'org-delete-property-globally))
14547 ((equal c ?c)
14548 (call-interactively 'org-compute-property-at-point))
14549 (t (error "No such property action %c" c)))))
14551 (defun org-inc-effort ()
14552 "Increment the value of the effort property in the current entry."
14553 (interactive)
14554 (org-set-effort nil t))
14556 (defun org-set-effort (&optional value increment)
14557 "Set the effort property of the current entry.
14558 With numerical prefix arg, use the nth allowed value, 0 stands for the
14559 10th allowed value.
14561 When INCREMENT is non-nil, set the property to the next allowed value."
14562 (interactive "P")
14563 (if (equal value 0) (setq value 10))
14564 (let* ((completion-ignore-case t)
14565 (prop org-effort-property)
14566 (cur (org-entry-get nil prop))
14567 (allowed (org-property-get-allowed-values nil prop 'table))
14568 (existing (mapcar 'list (org-property-values prop)))
14570 (val (cond
14571 ((stringp value) value)
14572 ((and allowed (integerp value))
14573 (or (car (nth (1- value) allowed))
14574 (car (org-last allowed))))
14575 ((and allowed increment)
14576 (or (caadr (member (list cur) allowed))
14577 (error "Allowed effort values are not set")))
14578 (allowed
14579 (message "Select 1-9,0, [RET%s]: %s"
14580 (if cur (concat "=" cur) "")
14581 (mapconcat 'car allowed " "))
14582 (setq rpl (read-char-exclusive))
14583 (if (equal rpl ?\r)
14585 (setq rpl (- rpl ?0))
14586 (if (equal rpl 0) (setq rpl 10))
14587 (if (and (> rpl 0) (<= rpl (length allowed)))
14588 (car (nth (1- rpl) allowed))
14589 (org-completing-read "Effort: " allowed nil))))
14591 (let (org-completion-use-ido org-completion-use-iswitchb)
14592 (org-completing-read
14593 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14594 (concat "[" cur "]") "")
14595 ": ")
14596 existing nil nil "" nil cur))))))
14597 (unless (equal (org-entry-get nil prop) val)
14598 (org-entry-put nil prop val))
14599 (save-excursion
14600 (org-back-to-heading t)
14601 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14602 (message "%s is now %s" prop val)))
14604 (defun org-at-property-p ()
14605 "Is cursor inside a property drawer?"
14606 (save-excursion
14607 (beginning-of-line 1)
14608 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14609 (save-match-data ;; Used by calling procedures
14610 (let ((p (point))
14611 (range (unless (org-before-first-heading-p)
14612 (org-get-property-block))))
14613 (and range (<= (car range) p) (< p (cdr range))))))))
14615 (defun org-get-property-block (&optional beg end force)
14616 "Return the (beg . end) range of the body of the property drawer.
14617 BEG and END are the beginning and end of the current subtree, or of
14618 the part before the first headline. If they are not given, they will
14619 be found. If the drawer does not exist and FORCE is non-nil, create
14620 the drawer."
14621 (catch 'exit
14622 (save-excursion
14623 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14624 (progn (org-back-to-heading t) (point))))
14625 (end (or end (and (not (outline-next-heading)) (point-max))
14626 (point))))
14627 (goto-char beg)
14628 (if (re-search-forward org-property-start-re end t)
14629 (setq beg (1+ (match-end 0)))
14630 (if force
14631 (save-excursion
14632 (org-insert-property-drawer)
14633 (setq end (progn (outline-next-heading) (point))))
14634 (throw 'exit nil))
14635 (goto-char beg)
14636 (if (re-search-forward org-property-start-re end t)
14637 (setq beg (1+ (match-end 0)))))
14638 (if (re-search-forward org-property-end-re end t)
14639 (setq end (match-beginning 0))
14640 (or force (throw 'exit nil))
14641 (goto-char beg)
14642 (setq end beg)
14643 (org-indent-line)
14644 (insert ":END:\n"))
14645 (cons beg end)))))
14647 (defun org-entry-properties (&optional pom which specific)
14648 "Get all properties of the entry at point-or-marker POM.
14649 This includes the TODO keyword, the tags, time strings for deadline,
14650 scheduled, and clocking, and any additional properties defined in the
14651 entry. The return value is an alist, keys may occur multiple times
14652 if the property key was used several times.
14653 POM may also be nil, in which case the current entry is used.
14654 If WHICH is nil or `all', get all properties. If WHICH is
14655 `special' or `standard', only get that subclass. If WHICH
14656 is a string only get exactly this property. SPECIFIC can be a string, the
14657 specific property we are interested in. Specifying it can speed
14658 things up because then unnecessary parsing is avoided."
14659 (setq which (or which 'all))
14660 (org-with-point-at pom
14661 (let ((clockstr (substring org-clock-string 0 -1))
14662 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14663 (case-fold-search nil)
14664 beg end range props sum-props key key1 value string clocksum clocksumt)
14665 (save-excursion
14666 (when (condition-case nil
14667 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14668 (error nil))
14669 (setq beg (point))
14670 (setq sum-props (get-text-property (point) 'org-summaries))
14671 (setq clocksum (get-text-property (point) :org-clock-minutes)
14672 clocksumt (get-text-property (point) :org-clock-minutes-today))
14673 (outline-next-heading)
14674 (setq end (point))
14675 (when (memq which '(all special))
14676 ;; Get the special properties, like TODO and tags
14677 (goto-char beg)
14678 (when (and (or (not specific) (string= specific "TODO"))
14679 (looking-at org-todo-line-regexp) (match-end 2))
14680 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14681 (when (and (or (not specific) (string= specific "PRIORITY"))
14682 (looking-at org-priority-regexp))
14683 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14684 (when (or (not specific) (string= specific "FILE"))
14685 (push (cons "FILE" buffer-file-name) props))
14686 (when (and (or (not specific) (string= specific "TAGS"))
14687 (setq value (org-get-tags-string))
14688 (string-match "\\S-" value))
14689 (push (cons "TAGS" value) props))
14690 (when (and (or (not specific) (string= specific "ALLTAGS"))
14691 (setq value (org-get-tags-at)))
14692 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14693 ":"))
14694 props))
14695 (when (or (not specific) (string= specific "BLOCKED"))
14696 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14697 (when (or (not specific)
14698 (member specific
14699 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14700 "TIMESTAMP" "TIMESTAMP_IA")))
14701 (catch 'match
14702 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14703 (setq key (if (match-end 1)
14704 (substring (org-match-string-no-properties 1)
14705 0 -1))
14706 string (if (equal key clockstr)
14707 (org-trim
14708 (buffer-substring-no-properties
14709 (match-beginning 3) (goto-char
14710 (point-at-eol))))
14711 (substring (org-match-string-no-properties 3)
14712 1 -1)))
14713 ;; Get the correct property name from the key. This is
14714 ;; necessary if the user has configured time keywords.
14715 (setq key1 (concat key ":"))
14716 (cond
14717 ((not key)
14718 (setq key
14719 (if (= (char-after (match-beginning 3)) ?\[)
14720 "TIMESTAMP_IA" "TIMESTAMP")))
14721 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14722 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14723 ((equal key1 org-closed-string) (setq key "CLOSED"))
14724 ((equal key1 org-clock-string) (setq key "CLOCK")))
14725 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14726 (progn
14727 (push (cons key string) props)
14728 ;; no need to search further if match is found
14729 (throw 'match t))
14730 (when (or (equal key "CLOCK") (not (assoc key props)))
14731 (push (cons key string) props)))))))
14733 (when (memq which '(all standard))
14734 ;; Get the standard properties, like :PROP: ...
14735 (setq range (org-get-property-block beg end))
14736 (when range
14737 (goto-char (car range))
14738 (while (re-search-forward
14739 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14740 (cdr range) t)
14741 (setq key (org-match-string-no-properties 1)
14742 value (org-trim (or (org-match-string-no-properties 2) "")))
14743 (unless (member key excluded)
14744 (push (cons key (or value "")) props)))))
14745 (if clocksum
14746 (push (cons "CLOCKSUM"
14747 (org-columns-number-to-string (/ (float clocksum) 60.)
14748 'add_times))
14749 props))
14750 (if clocksumt
14751 (push (cons "CLOCKSUM_T"
14752 (org-columns-number-to-string (/ (float clocksumt) 60.)
14753 'add_times))
14754 props))
14755 (unless (assoc "CATEGORY" props)
14756 (push (cons "CATEGORY" (org-get-category)) props))
14757 (append sum-props (nreverse props)))))))
14759 (defun org-entry-get (pom property &optional inherit literal-nil)
14760 "Get value of PROPERTY for entry or content at point-or-marker POM.
14761 If INHERIT is non-nil and the entry does not have the property,
14762 then also check higher levels of the hierarchy.
14763 If INHERIT is the symbol `selective', use inheritance only if the setting
14764 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14765 If the property is present but empty, the return value is the empty string.
14766 If the property is not present at all, nil is returned.
14768 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14769 do not interpret it as the list atom nil. This is used for inheritance
14770 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14771 (org-with-point-at pom
14772 (if (and inherit (if (eq inherit 'selective)
14773 (org-property-inherit-p property)
14775 (org-entry-get-with-inheritance property literal-nil)
14776 (if (member property org-special-properties)
14777 ;; We need a special property. Use `org-entry-properties' to
14778 ;; retrieve it, but specify the wanted property
14779 (cdr (assoc property (org-entry-properties nil 'special property)))
14780 (let ((range (org-get-property-block)))
14781 (when (and range (not (eq (car range) (cdr range))))
14782 (let* ((props (list (or (assoc property org-file-properties)
14783 (assoc property org-global-properties)
14784 (assoc property org-global-properties-fixed))))
14785 (ap (lambda (key)
14786 (when (re-search-forward
14787 (org-re-property key) (cdr range) t)
14788 (setq props
14789 (org-update-property-plist
14791 (if (match-end 1)
14792 (org-match-string-no-properties 1) "")
14793 props)))))
14794 val)
14795 (goto-char (car range))
14796 (funcall ap property)
14797 (goto-char (car range))
14798 (while (funcall ap (concat property "+")))
14799 (setq val (cdr (assoc property props)))
14800 (when val (if literal-nil val (org-not-nil val))))))))))
14802 (defun org-property-or-variable-value (var &optional inherit)
14803 "Check if there is a property fixing the value of VAR.
14804 If yes, return this value. If not, return the current value of the variable."
14805 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14806 (if (and prop (stringp prop) (string-match "\\S-" prop))
14807 (read prop)
14808 (symbol-value var))))
14810 (defun org-entry-delete (pom property)
14811 "Delete the property PROPERTY from entry at point-or-marker POM."
14812 (org-with-point-at pom
14813 (if (member property org-special-properties)
14814 nil ; cannot delete these properties.
14815 (let ((range (org-get-property-block)))
14816 (if (and range
14817 (goto-char (car range))
14818 (re-search-forward
14819 (org-re-property property)
14820 (cdr range) t))
14821 (progn
14822 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14824 nil)))))
14826 ;; Multi-values properties are properties that contain multiple values
14827 ;; These values are assumed to be single words, separated by whitespace.
14828 (defun org-entry-add-to-multivalued-property (pom property value)
14829 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14830 (let* ((old (org-entry-get pom property))
14831 (values (and old (org-split-string old "[ \t]"))))
14832 (setq value (org-entry-protect-space value))
14833 (unless (member value values)
14834 (setq values (cons value values))
14835 (org-entry-put pom property
14836 (mapconcat 'identity values " ")))))
14838 (defun org-entry-remove-from-multivalued-property (pom property value)
14839 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14840 (let* ((old (org-entry-get pom property))
14841 (values (and old (org-split-string old "[ \t]"))))
14842 (setq value (org-entry-protect-space value))
14843 (when (member value values)
14844 (setq values (delete value values))
14845 (org-entry-put pom property
14846 (mapconcat 'identity values " ")))))
14848 (defun org-entry-member-in-multivalued-property (pom property value)
14849 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14850 (let* ((old (org-entry-get pom property))
14851 (values (and old (org-split-string old "[ \t]"))))
14852 (setq value (org-entry-protect-space value))
14853 (member value values)))
14855 (defun org-entry-get-multivalued-property (pom property)
14856 "Return a list of values in a multivalued property."
14857 (let* ((value (org-entry-get pom property))
14858 (values (and value (org-split-string value "[ \t]"))))
14859 (mapcar 'org-entry-restore-space values)))
14861 (defun org-entry-put-multivalued-property (pom property &rest values)
14862 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14863 VALUES should be a list of strings. Spaces will be protected."
14864 (org-entry-put pom property
14865 (mapconcat 'org-entry-protect-space values " "))
14866 (let* ((value (org-entry-get pom property))
14867 (values (and value (org-split-string value "[ \t]"))))
14868 (mapcar 'org-entry-restore-space values)))
14870 (defun org-entry-protect-space (s)
14871 "Protect spaces and newline in string S."
14872 (while (string-match " " s)
14873 (setq s (replace-match "%20" t t s)))
14874 (while (string-match "\n" s)
14875 (setq s (replace-match "%0A" t t s)))
14878 (defun org-entry-restore-space (s)
14879 "Restore spaces and newline in string S."
14880 (while (string-match "%20" s)
14881 (setq s (replace-match " " t t s)))
14882 (while (string-match "%0A" s)
14883 (setq s (replace-match "\n" t t s)))
14886 (defvar org-entry-property-inherited-from (make-marker)
14887 "Marker pointing to the entry from where a property was inherited.
14888 Each call to `org-entry-get-with-inheritance' will set this marker to the
14889 location of the entry where the inheritance search matched. If there was
14890 no match, the marker will point nowhere.
14891 Note that also `org-entry-get' calls this function, if the INHERIT flag
14892 is set.")
14894 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14895 "Get PROPERTY of entry or content at point, search higher levels if needed.
14896 The search will stop at the first ancestor which has the property defined.
14897 If the value found is \"nil\", return nil to show that the property
14898 should be considered as undefined (this is the meaning of nil here).
14899 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14900 (move-marker org-entry-property-inherited-from nil)
14901 (let (tmp)
14902 (save-excursion
14903 (save-restriction
14904 (widen)
14905 (catch 'ex
14906 (while t
14907 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14908 (or (ignore-errors (org-back-to-heading t))
14909 (goto-char (point-min)))
14910 (move-marker org-entry-property-inherited-from (point))
14911 (throw 'ex tmp))
14912 (or (ignore-errors (org-up-heading-safe))
14913 (throw 'ex nil))))))
14914 (setq tmp (or tmp
14915 (cdr (assoc property org-file-properties))
14916 (cdr (assoc property org-global-properties))
14917 (cdr (assoc property org-global-properties-fixed))))
14918 (if literal-nil tmp (org-not-nil tmp))))
14920 (defvar org-property-changed-functions nil
14921 "Hook called when the value of a property has changed.
14922 Each hook function should accept two arguments, the name of the property
14923 and the new value.")
14925 (defun org-entry-put (pom property value)
14926 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14927 (org-with-point-at pom
14928 (org-back-to-heading t)
14929 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14930 range)
14931 (cond
14932 ((equal property "TODO")
14933 (when (and (stringp value) (string-match "\\S-" value)
14934 (not (member value org-todo-keywords-1)))
14935 (error "\"%s\" is not a valid TODO state" value))
14936 (if (or (not value)
14937 (not (string-match "\\S-" value)))
14938 (setq value 'none))
14939 (org-todo value)
14940 (org-set-tags nil 'align))
14941 ((equal property "PRIORITY")
14942 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14943 (string-to-char value) ?\ ))
14944 (org-set-tags nil 'align))
14945 ((equal property "CLOCKSUM")
14946 (if (not (re-search-forward
14947 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14948 (error "Cannot find a clock log")
14949 (goto-char (- (match-end 1) 2))
14950 (cond
14951 ((eq value 'earlier) (org-timestamp-down))
14952 ((eq value 'later) (org-timestamp-up)))
14953 (org-clock-sum-current-item)))
14954 ((equal property "SCHEDULED")
14955 (if (re-search-forward org-scheduled-time-regexp end t)
14956 (cond
14957 ((eq value 'earlier) (org-timestamp-change -1 'day))
14958 ((eq value 'later) (org-timestamp-change 1 'day))
14959 (t (call-interactively 'org-schedule)))
14960 (call-interactively 'org-schedule)))
14961 ((equal property "DEADLINE")
14962 (if (re-search-forward org-deadline-time-regexp end t)
14963 (cond
14964 ((eq value 'earlier) (org-timestamp-change -1 'day))
14965 ((eq value 'later) (org-timestamp-change 1 'day))
14966 (t (call-interactively 'org-deadline)))
14967 (call-interactively 'org-deadline)))
14968 ((member property org-special-properties)
14969 (error "The %s property can not yet be set with `org-entry-put'"
14970 property))
14971 (t ; a non-special property
14972 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14973 (setq range (org-get-property-block beg end 'force))
14974 (goto-char (car range))
14975 (if (re-search-forward
14976 (org-re-property-keyword property) (cdr range) t)
14977 (progn
14978 (delete-region (match-beginning 0) (match-end 0))
14979 (goto-char (match-beginning 0)))
14980 (goto-char (cdr range))
14981 (insert "\n")
14982 (backward-char 1)
14983 (org-indent-line))
14984 (insert ":" property ":")
14985 (and value (insert " " value))
14986 (org-indent-line)))))
14987 (run-hook-with-args 'org-property-changed-functions property value)))
14989 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14990 "Get all property keys in the current buffer.
14991 With INCLUDE-SPECIALS, also list the special properties that reflect things
14992 like tags and TODO state.
14993 With INCLUDE-DEFAULTS, also include properties that has special meaning
14994 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14995 and others.
14996 With INCLUDE-COLUMNS, also include property names given in COLUMN
14997 formats in the current buffer."
14998 (let (rtn range cfmt s p)
14999 (save-excursion
15000 (save-restriction
15001 (widen)
15002 (goto-char (point-min))
15003 (while (re-search-forward org-property-start-re nil t)
15004 (setq range (org-get-property-block))
15005 (goto-char (car range))
15006 (while (re-search-forward
15007 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15008 (cdr range) t)
15009 (add-to-list 'rtn (org-match-string-no-properties 1)))
15010 (outline-next-heading))))
15012 (when include-specials
15013 (setq rtn (append org-special-properties rtn)))
15015 (when include-defaults
15016 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15017 (add-to-list 'rtn org-effort-property))
15019 (when include-columns
15020 (save-excursion
15021 (save-restriction
15022 (widen)
15023 (goto-char (point-min))
15024 (while (re-search-forward
15025 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15026 nil t)
15027 (setq cfmt (match-string 2) s 0)
15028 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15029 cfmt s)
15030 (setq s (match-end 0)
15031 p (match-string 1 cfmt))
15032 (unless (or (equal p "ITEM")
15033 (member p org-special-properties))
15034 (add-to-list 'rtn (match-string 1 cfmt))))))))
15036 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15038 (defun org-property-values (key)
15039 "Return a list of all values of property KEY in the current buffer."
15040 (save-excursion
15041 (save-restriction
15042 (widen)
15043 (goto-char (point-min))
15044 (let ((re (org-re-property key))
15045 values)
15046 (while (re-search-forward re nil t)
15047 (add-to-list 'values (org-trim (match-string 1))))
15048 (delete "" values)))))
15050 (defun org-insert-property-drawer ()
15051 "Insert a property drawer into the current entry."
15052 (org-back-to-heading t)
15053 (looking-at org-outline-regexp)
15054 (let ((indent (if org-adapt-indentation
15055 (- (match-end 0) (match-beginning 0))
15057 (beg (point))
15058 (re (concat "^[ \t]*" org-keyword-time-regexp))
15059 end hiddenp)
15060 (outline-next-heading)
15061 (setq end (point))
15062 (goto-char beg)
15063 (while (re-search-forward re end t))
15064 (setq hiddenp (outline-invisible-p))
15065 (end-of-line 1)
15066 (and (equal (char-after) ?\n) (forward-char 1))
15067 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15068 (if (member (match-string 1) '("CLOCK:" ":END:"))
15069 ;; just skip this line
15070 (beginning-of-line 2)
15071 ;; Drawer start, find the end
15072 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15073 (beginning-of-line 1)))
15074 (org-skip-over-state-notes)
15075 (skip-chars-backward " \t\n\r")
15076 (if (eq (char-before) ?*) (forward-char 1))
15077 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15078 (beginning-of-line 0)
15079 (org-indent-to-column indent)
15080 (beginning-of-line 2)
15081 (org-indent-to-column indent)
15082 (beginning-of-line 0)
15083 (if hiddenp
15084 (save-excursion
15085 (org-back-to-heading t)
15086 (hide-entry))
15087 (org-flag-drawer t))))
15089 (defun org-insert-drawer (&optional arg drawer)
15090 "Insert a drawer at point.
15092 Optional argument DRAWER, when non-nil, is a string representing
15093 drawer's name. Otherwise, the user is prompted for a name.
15095 If a region is active, insert the drawer around that region
15096 instead.
15098 Point is left between drawer's boundaries."
15099 (interactive "P")
15100 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15101 "LOGBOOK"))
15102 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15103 ;; internally by Org. They are meant to be inserted
15104 ;; automatically.
15105 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15106 ;; Remove system drawers from list. Note: For some reason,
15107 ;; `org-completing-read' ignores the predicate while
15108 ;; `completing-read' handles it fine.
15109 (drawer (if arg "PROPERTIES"
15110 (or drawer
15111 (completing-read
15112 "Drawer: " org-drawers
15113 (lambda (d) (not (member d system-drawers))))))))
15114 (cond
15115 ;; With C-u, fall back on `org-insert-property-drawer'
15116 (arg (org-insert-property-drawer))
15117 ;; With an active region, insert a drawer at point.
15118 ((not (org-region-active-p))
15119 (progn
15120 (unless (bolp) (insert "\n"))
15121 (insert (format ":%s:\n\n:END:\n" drawer))
15122 (forward-line -2)))
15123 ;; Otherwise, insert the drawer at point
15125 (let ((rbeg (region-beginning))
15126 (rend (copy-marker (region-end))))
15127 (unwind-protect
15128 (progn
15129 (goto-char rbeg)
15130 (beginning-of-line)
15131 (when (save-excursion
15132 (re-search-forward org-outline-regexp-bol rend t))
15133 (error "Drawers cannot contain headlines"))
15134 ;; Position point at the beginning of the first
15135 ;; non-blank line in region. Insert drawer's opening
15136 ;; there, then indent it.
15137 (org-skip-whitespace)
15138 (beginning-of-line)
15139 (insert ":" drawer ":\n")
15140 (forward-line -1)
15141 (indent-for-tab-command)
15142 ;; Move point to the beginning of the first blank line
15143 ;; after the last non-blank line in region. Insert
15144 ;; drawer's closing, then indent it.
15145 (goto-char rend)
15146 (skip-chars-backward " \r\t\n")
15147 (insert "\n:END:")
15148 (deactivate-mark t)
15149 (indent-for-tab-command)
15150 (unless (eolp) (insert "\n")))
15151 ;; Clear marker, whatever the outcome of insertion is.
15152 (set-marker rend nil)))))))
15154 (defvar org-property-set-functions-alist nil
15155 "Property set function alist.
15156 Each entry should have the following format:
15158 (PROPERTY . READ-FUNCTION)
15160 The read function will be called with the same argument as
15161 `org-completing-read'.")
15163 (defun org-set-property-function (property)
15164 "Get the function that should be used to set PROPERTY.
15165 This is computed according to `org-property-set-functions-alist'."
15166 (or (cdr (assoc property org-property-set-functions-alist))
15167 'org-completing-read))
15169 (defun org-read-property-value (property)
15170 "Read PROPERTY value from user."
15171 (let* ((completion-ignore-case t)
15172 (allowed (org-property-get-allowed-values nil property 'table))
15173 (cur (org-entry-get nil property))
15174 (prompt (concat property " value"
15175 (if (and cur (string-match "\\S-" cur))
15176 (concat " [" cur "]") "") ": "))
15177 (set-function (org-set-property-function property))
15178 (val (if allowed
15179 (funcall set-function prompt allowed nil
15180 (not (get-text-property 0 'org-unrestricted
15181 (caar allowed))))
15182 (let (org-completion-use-ido org-completion-use-iswitchb)
15183 (funcall set-function prompt
15184 (mapcar 'list (org-property-values property))
15185 nil nil "" nil cur)))))
15186 (if (equal val "")
15188 val)))
15190 (defvar org-last-set-property nil)
15191 (defvar org-last-set-property-value nil)
15192 (defun org-read-property-name ()
15193 "Read a property name."
15194 (let* ((completion-ignore-case t)
15195 (keys (org-buffer-property-keys nil t t))
15196 (default-prop (or (save-excursion
15197 (save-match-data
15198 (beginning-of-line)
15199 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15200 (null (string= (match-string 1) "END"))
15201 (match-string 1))))
15202 org-last-set-property))
15203 (property (org-icompleting-read
15204 (concat "Property"
15205 (if default-prop (concat " [" default-prop "]") "")
15206 ": ")
15207 (mapcar 'list keys)
15208 nil nil nil nil
15209 default-prop)))
15210 (if (member property keys)
15211 property
15212 (or (cdr (assoc (downcase property)
15213 (mapcar (lambda (x) (cons (downcase x) x))
15214 keys)))
15215 property))))
15217 (defun org-set-property-and-value (use-last)
15218 "Allow to set [PROPERTY]: [value] direction from prompt.
15219 When use-default, don't even ask, just use the last
15220 \"[PROPERTY]: [value]\" string from the history."
15221 (interactive "P")
15222 (let* ((completion-ignore-case t)
15223 (pv (or (and use-last org-last-set-property-value)
15224 (org-completing-read
15225 "Enter a \"[Property]: [value]\" pair: "
15226 nil nil nil nil nil
15227 org-last-set-property-value)))
15228 prop val)
15229 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15230 (setq prop (match-string 1 pv)
15231 val (match-string 2 pv))
15232 (org-set-property prop val))))
15234 (defun org-set-property (property value)
15235 "In the current entry, set PROPERTY to VALUE.
15236 When called interactively, this will prompt for a property name, offering
15237 completion on existing and default properties. And then it will prompt
15238 for a value, offering completion either on allowed values (via an inherited
15239 xxx_ALL property) or on existing values in other instances of this property
15240 in the current file."
15241 (interactive (list nil nil))
15242 (let* ((property (or property (org-read-property-name)))
15243 (value (or value (org-read-property-value property)))
15244 (fn (cdr (assoc property org-properties-postprocess-alist))))
15245 (setq org-last-set-property property)
15246 (setq org-last-set-property-value (concat property ": " value))
15247 ;; Possibly postprocess the inserted value:
15248 (when fn (setq value (funcall fn value)))
15249 (unless (equal (org-entry-get nil property) value)
15250 (org-entry-put nil property value))))
15252 (defun org-delete-property (property)
15253 "In the current entry, delete PROPERTY."
15254 (interactive
15255 (let* ((completion-ignore-case t)
15256 (prop (org-icompleting-read "Property: "
15257 (org-entry-properties nil 'standard))))
15258 (list prop)))
15259 (message "Property %s %s" property
15260 (if (org-entry-delete nil property)
15261 "deleted"
15262 "was not present in the entry")))
15264 (defun org-delete-property-globally (property)
15265 "Remove PROPERTY globally, from all entries."
15266 (interactive
15267 (let* ((completion-ignore-case t)
15268 (prop (org-icompleting-read
15269 "Globally remove property: "
15270 (mapcar 'list (org-buffer-property-keys)))))
15271 (list prop)))
15272 (save-excursion
15273 (save-restriction
15274 (widen)
15275 (goto-char (point-min))
15276 (let ((cnt 0))
15277 (while (re-search-forward
15278 (org-re-property property)
15279 nil t)
15280 (setq cnt (1+ cnt))
15281 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15282 (message "Property \"%s\" removed from %d entries" property cnt)))))
15284 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15286 (defun org-compute-property-at-point ()
15287 "Compute the property at point.
15288 This looks for an enclosing column format, extracts the operator and
15289 then applies it to the property in the column format's scope."
15290 (interactive)
15291 (unless (org-at-property-p)
15292 (error "Not at a property"))
15293 (let ((prop (org-match-string-no-properties 2)))
15294 (org-columns-get-format-and-top-level)
15295 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15296 (error "No operator defined for property %s" prop))
15297 (org-columns-compute prop)))
15299 (defvar org-property-allowed-value-functions nil
15300 "Hook for functions supplying allowed values for a specific property.
15301 The functions must take a single argument, the name of the property, and
15302 return a flat list of allowed values. If \":ETC\" is one of
15303 the values, this means that these values are intended as defaults for
15304 completion, but that other values should be allowed too.
15305 The functions must return nil if they are not responsible for this
15306 property.")
15308 (defun org-property-get-allowed-values (pom property &optional table)
15309 "Get allowed values for the property PROPERTY.
15310 When TABLE is non-nil, return an alist that can directly be used for
15311 completion."
15312 (let (vals)
15313 (cond
15314 ((equal property "TODO")
15315 (setq vals (org-with-point-at pom
15316 (append org-todo-keywords-1 '("")))))
15317 ((equal property "PRIORITY")
15318 (let ((n org-lowest-priority))
15319 (while (>= n org-highest-priority)
15320 (push (char-to-string n) vals)
15321 (setq n (1- n)))))
15322 ((member property org-special-properties))
15323 ((setq vals (run-hook-with-args-until-success
15324 'org-property-allowed-value-functions property)))
15326 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15327 (when (and vals (string-match "\\S-" vals))
15328 (setq vals (car (read-from-string (concat "(" vals ")"))))
15329 (setq vals (mapcar (lambda (x)
15330 (cond ((stringp x) x)
15331 ((numberp x) (number-to-string x))
15332 ((symbolp x) (symbol-name x))
15333 (t "???")))
15334 vals)))))
15335 (when (member ":ETC" vals)
15336 (setq vals (remove ":ETC" vals))
15337 (org-add-props (car vals) '(org-unrestricted t)))
15338 (if table (mapcar 'list vals) vals)))
15340 (defun org-property-previous-allowed-value (&optional previous)
15341 "Switch to the next allowed value for this property."
15342 (interactive)
15343 (org-property-next-allowed-value t))
15345 (defun org-property-next-allowed-value (&optional previous)
15346 "Switch to the next allowed value for this property."
15347 (interactive)
15348 (unless (org-at-property-p)
15349 (error "Not at a property"))
15350 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15351 (key (match-string 2))
15352 (value (match-string 3))
15353 (allowed (or (org-property-get-allowed-values (point) key)
15354 (and (member value '("[ ]" "[-]" "[X]"))
15355 '("[ ]" "[X]"))))
15356 nval)
15357 (unless allowed
15358 (error "Allowed values for this property have not been defined"))
15359 (if previous (setq allowed (reverse allowed)))
15360 (if (member value allowed)
15361 (setq nval (car (cdr (member value allowed)))))
15362 (setq nval (or nval (car allowed)))
15363 (if (equal nval value)
15364 (error "Only one allowed value for this property"))
15365 (org-at-property-p)
15366 (replace-match (concat " :" key ": " nval) t t)
15367 (org-indent-line)
15368 (beginning-of-line 1)
15369 (skip-chars-forward " \t")
15370 (when (equal prop org-effort-property)
15371 (save-excursion
15372 (org-back-to-heading t)
15373 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15374 (run-hook-with-args 'org-property-changed-functions key nval)))
15376 (defun org-find-olp (path &optional this-buffer)
15377 "Return a marker pointing to the entry at outline path OLP.
15378 If anything goes wrong, throw an error.
15379 You can wrap this call to catch the error like this:
15381 (condition-case msg
15382 (org-mobile-locate-entry (match-string 4))
15383 (error (nth 1 msg)))
15385 The return value will then be either a string with the error message,
15386 or a marker if everything is OK.
15388 If THIS-BUFFER is set, the outline path does not contain a file,
15389 only headings."
15390 (let* ((file (if this-buffer buffer-file-name (pop path)))
15391 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15392 (level 1)
15393 (lmin 1)
15394 (lmax 1)
15395 limit re end found pos heading cnt flevel)
15396 (unless buffer (error "File not found :%s" file))
15397 (with-current-buffer buffer
15398 (save-excursion
15399 (save-restriction
15400 (widen)
15401 (setq limit (point-max))
15402 (goto-char (point-min))
15403 (while (setq heading (pop path))
15404 (setq re (format org-complex-heading-regexp-format
15405 (regexp-quote heading)))
15406 (setq cnt 0 pos (point))
15407 (while (re-search-forward re end t)
15408 (setq level (- (match-end 1) (match-beginning 1)))
15409 (if (and (>= level lmin) (<= level lmax))
15410 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15411 (when (= cnt 0) (error "Heading not found on level %d: %s"
15412 lmax heading))
15413 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15414 lmax heading))
15415 (goto-char found)
15416 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15417 (setq end (save-excursion (org-end-of-subtree t t))))
15418 (when (org-at-heading-p)
15419 (point-marker)))))))
15421 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15422 "Find node HEADING in BUFFER.
15423 Return a marker to the heading if it was found, or nil if not.
15424 If POS-ONLY is set, return just the position instead of a marker.
15426 The heading text must match exact, but it may have a TODO keyword,
15427 a priority cookie and tags in the standard locations."
15428 (with-current-buffer (or buffer (current-buffer))
15429 (save-excursion
15430 (save-restriction
15431 (widen)
15432 (goto-char (point-min))
15433 (let (case-fold-search)
15434 (if (re-search-forward
15435 (format org-complex-heading-regexp-format
15436 (regexp-quote heading)) nil t)
15437 (if pos-only
15438 (match-beginning 0)
15439 (move-marker (make-marker) (match-beginning 0)))))))))
15441 (defun org-find-exact-heading-in-directory (heading &optional dir)
15442 "Find Org node headline HEADING in all .org files in directory DIR.
15443 When the target headline is found, return a marker to this location."
15444 (let ((files (directory-files (or dir default-directory)
15445 nil "\\`[^.#].*\\.org\\'"))
15446 file visiting m buffer)
15447 (catch 'found
15448 (while (setq file (pop files))
15449 (message "trying %s" file)
15450 (setq visiting (org-find-base-buffer-visiting file))
15451 (setq buffer (or visiting (find-file-noselect file)))
15452 (setq m (org-find-exact-headline-in-buffer
15453 heading buffer))
15454 (when (and (not m) (not visiting)) (kill-buffer buffer))
15455 (and m (throw 'found m))))))
15457 (defun org-find-entry-with-id (ident)
15458 "Locate the entry that contains the ID property with exact value IDENT.
15459 IDENT can be a string, a symbol or a number, this function will search for
15460 the string representation of it.
15461 Return the position where this entry starts, or nil if there is no such entry."
15462 (interactive "sID: ")
15463 (let ((id (cond
15464 ((stringp ident) ident)
15465 ((symbol-name ident) (symbol-name ident))
15466 ((numberp ident) (number-to-string ident))
15467 (t (error "IDENT %s must be a string, symbol or number" ident))))
15468 (case-fold-search nil))
15469 (save-excursion
15470 (save-restriction
15471 (widen)
15472 (goto-char (point-min))
15473 (when (re-search-forward
15474 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15475 nil t)
15476 (org-back-to-heading t)
15477 (point))))))
15479 ;;;; Timestamps
15481 (defvar org-last-changed-timestamp nil)
15482 (defvar org-last-inserted-timestamp nil
15483 "The last time stamp inserted with `org-insert-time-stamp'.")
15484 (defvar org-time-was-given) ; dynamically scoped parameter
15485 (defvar org-end-time-was-given) ; dynamically scoped parameter
15486 (defvar org-ts-what) ; dynamically scoped parameter
15488 (defun org-time-stamp (arg &optional inactive)
15489 "Prompt for a date/time and insert a time stamp.
15490 If the user specifies a time like HH:MM or if this command is
15491 called with at least one prefix argument, the time stamp contains
15492 the date and the time. Otherwise, only the date is be included.
15494 All parts of a date not specified by the user is filled in from
15495 the current date/time. So if you just press return without
15496 typing anything, the time stamp will represent the current
15497 date/time.
15499 If there is already a timestamp at the cursor, it will be
15500 modified.
15502 With two universal prefix arguments, insert an active timestamp
15503 with the current time without prompting the user."
15504 (interactive "P")
15505 (let* ((ts nil)
15506 (default-time
15507 ;; Default time is either today, or, when entering a range,
15508 ;; the range start.
15509 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15510 (save-excursion
15511 (re-search-backward
15512 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15513 (- (point) 20) t)))
15514 (apply 'encode-time (org-parse-time-string (match-string 1)))
15515 (current-time)))
15516 (default-input (and ts (org-get-compact-tod ts)))
15517 (repeater (save-excursion
15518 (save-match-data
15519 (beginning-of-line)
15520 (when (re-search-forward
15521 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15522 (save-excursion (progn (end-of-line) (point))) t)
15523 (match-string 0)))))
15524 org-time-was-given org-end-time-was-given time)
15525 (cond
15526 ((and (org-at-timestamp-p t)
15527 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15528 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15529 (insert "--")
15530 (setq time (let ((this-command this-command))
15531 (org-read-date arg 'totime nil nil
15532 default-time default-input inactive)))
15533 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15534 ((org-at-timestamp-p t)
15535 (setq time (let ((this-command this-command))
15536 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15537 (when (org-at-timestamp-p t) ; just to get the match data
15538 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15539 (replace-match "")
15540 (setq org-last-changed-timestamp
15541 (org-insert-time-stamp
15542 time (or org-time-was-given arg)
15543 inactive nil nil (list org-end-time-was-given)))
15544 (when repeater (goto-char (1- (point))) (insert " " repeater)
15545 (setq org-last-changed-timestamp
15546 (concat (substring org-last-inserted-timestamp 0 -1)
15547 " " repeater ">"))))
15548 (message "Timestamp updated"))
15549 ((equal arg '(16))
15550 (org-insert-time-stamp (current-time) t))
15552 (setq time (let ((this-command this-command))
15553 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15554 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15555 nil nil (list org-end-time-was-given))))))
15557 ;; FIXME: can we use this for something else, like computing time differences?
15558 (defun org-get-compact-tod (s)
15559 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15560 (let* ((t1 (match-string 1 s))
15561 (h1 (string-to-number (match-string 2 s)))
15562 (m1 (string-to-number (match-string 3 s)))
15563 (t2 (and (match-end 4) (match-string 5 s)))
15564 (h2 (and t2 (string-to-number (match-string 6 s))))
15565 (m2 (and t2 (string-to-number (match-string 7 s))))
15566 dh dm)
15567 (if (not t2)
15569 (setq dh (- h2 h1) dm (- m2 m1))
15570 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15571 (concat t1 "+" (number-to-string dh)
15572 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15574 (defun org-time-stamp-inactive (&optional arg)
15575 "Insert an inactive time stamp.
15576 An inactive time stamp is enclosed in square brackets instead of angle
15577 brackets. It is inactive in the sense that it does not trigger agenda entries,
15578 does not link to the calendar and cannot be changed with the S-cursor keys.
15579 So these are more for recording a certain time/date."
15580 (interactive "P")
15581 (org-time-stamp arg 'inactive))
15583 (defvar org-date-ovl (make-overlay 1 1))
15584 (overlay-put org-date-ovl 'face 'org-date-selected)
15585 (org-detach-overlay org-date-ovl)
15587 (defvar org-ans1) ; dynamically scoped parameter
15588 (defvar org-ans2) ; dynamically scoped parameter
15590 (defvar org-plain-time-of-day-regexp) ; defined below
15592 (defvar org-overriding-default-time nil) ; dynamically scoped
15593 (defvar org-read-date-overlay nil)
15594 (defvar org-dcst nil) ; dynamically scoped
15595 (defvar org-read-date-history nil)
15596 (defvar org-read-date-final-answer nil)
15597 (defvar org-read-date-analyze-futurep nil)
15598 (defvar org-read-date-analyze-forced-year nil)
15599 (defvar org-read-date-inactive)
15601 (defvar org-read-date-minibuffer-local-map
15602 (let ((map (make-sparse-keymap)))
15603 (set-keymap-parent map minibuffer-local-map)
15604 (org-defkey map [(meta shift left)]
15605 (lambda () (interactive)
15606 (org-eval-in-calendar '(calendar-backward-month 1))))
15607 (org-defkey map [(meta shift right)]
15608 (lambda () (interactive)
15609 (org-eval-in-calendar '(calendar-forward-month 1))))
15610 (org-defkey map [(meta shift up)]
15611 (lambda () (interactive)
15612 (org-eval-in-calendar '(calendar-backward-year 1))))
15613 (org-defkey map [(meta shift down)]
15614 (lambda () (interactive)
15615 (org-eval-in-calendar '(calendar-forward-year 1))))
15616 (org-defkey map [?\e (shift left)]
15617 (lambda () (interactive)
15618 (org-eval-in-calendar '(calendar-backward-month 1))))
15619 (org-defkey map [?\e (shift right)]
15620 (lambda () (interactive)
15621 (org-eval-in-calendar '(calendar-forward-month 1))))
15622 (org-defkey map [?\e (shift up)]
15623 (lambda () (interactive)
15624 (org-eval-in-calendar '(calendar-backward-year 1))))
15625 (org-defkey map [?\e (shift down)]
15626 (lambda () (interactive)
15627 (org-eval-in-calendar '(calendar-forward-year 1))))
15628 (org-defkey map [(shift up)]
15629 (lambda () (interactive)
15630 (org-eval-in-calendar '(calendar-backward-week 1))))
15631 (org-defkey map [(shift down)]
15632 (lambda () (interactive)
15633 (org-eval-in-calendar '(calendar-forward-week 1))))
15634 (org-defkey map [(shift left)]
15635 (lambda () (interactive)
15636 (org-eval-in-calendar '(calendar-backward-day 1))))
15637 (org-defkey map [(shift right)]
15638 (lambda () (interactive)
15639 (org-eval-in-calendar '(calendar-forward-day 1))))
15640 (org-defkey map "?"
15641 (lambda () (interactive)
15642 (org-eval-in-calendar '(diary-view-entries))
15643 (message "")))
15644 (org-defkey map ">"
15645 (lambda () (interactive)
15646 (org-eval-in-calendar '(scroll-calendar-left 1))))
15647 (org-defkey map "<"
15648 (lambda () (interactive)
15649 (org-eval-in-calendar '(scroll-calendar-right 1))))
15650 (org-defkey map "\C-v"
15651 (lambda () (interactive)
15652 (org-eval-in-calendar
15653 '(calendar-scroll-left-three-months 1))))
15654 (org-defkey map "\M-v"
15655 (lambda () (interactive)
15656 (org-eval-in-calendar
15657 '(calendar-scroll-right-three-months 1))))
15658 map)
15659 "Keymap for minibuffer commands when using `org-read-date'.")
15661 (defun org-read-date (&optional org-with-time to-time from-string prompt
15662 default-time default-input inactive)
15663 "Read a date, possibly a time, and make things smooth for the user.
15664 The prompt will suggest to enter an ISO date, but you can also enter anything
15665 which will at least partially be understood by `parse-time-string'.
15666 Unrecognized parts of the date will default to the current day, month, year,
15667 hour and minute. If this command is called to replace a timestamp at point,
15668 or to enter the second timestamp of a range, the default time is taken
15669 from the existing stamp. Furthermore, the command prefers the future,
15670 so if you are giving a date where the year is not given, and the day-month
15671 combination is already past in the current year, it will assume you
15672 mean next year. For details, see the manual. A few examples:
15674 3-2-5 --> 2003-02-05
15675 feb 15 --> currentyear-02-15
15676 2/15 --> currentyear-02-15
15677 sep 12 9 --> 2009-09-12
15678 12:45 --> today 12:45
15679 22 sept 0:34 --> currentyear-09-22 0:34
15680 12 --> currentyear-currentmonth-12
15681 Fri --> nearest Friday (today or later)
15682 etc.
15684 Furthermore you can specify a relative date by giving, as the *first* thing
15685 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15686 change in days weeks, months, years.
15687 With a single plus or minus, the date is relative to today. With a double
15688 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15689 +4d --> four days from today
15690 +4 --> same as above
15691 +2w --> two weeks from today
15692 ++5 --> five days from default date
15694 The function understands only English month and weekday abbreviations.
15696 While prompting, a calendar is popped up - you can also select the
15697 date with the mouse (button 1). The calendar shows a period of three
15698 months. To scroll it to other months, use the keys `>' and `<'.
15699 If you don't like the calendar, turn it off with
15700 \(setq org-read-date-popup-calendar nil)
15702 With optional argument TO-TIME, the date will immediately be converted
15703 to an internal time.
15704 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15705 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15706 still enter a time, and this function will inform the calling routine
15707 about this change. The calling routine may then choose to change the
15708 format used to insert the time stamp into the buffer to include the time.
15709 With optional argument FROM-STRING, read from this string instead from
15710 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15711 the time/date that is used for everything that is not specified by the
15712 user."
15713 (require 'parse-time)
15714 (let* ((org-time-stamp-rounding-minutes
15715 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15716 (org-dcst org-display-custom-times)
15717 (ct (org-current-time))
15718 (org-def (or org-overriding-default-time default-time ct))
15719 (org-defdecode (decode-time org-def))
15720 (dummy (progn
15721 (when (< (nth 2 org-defdecode) org-extend-today-until)
15722 (setcar (nthcdr 2 org-defdecode) -1)
15723 (setcar (nthcdr 1 org-defdecode) 59)
15724 (setq org-def (apply 'encode-time org-defdecode)
15725 org-defdecode (decode-time org-def)))))
15726 (mouse-autoselect-window nil) ; Don't let the mouse jump
15727 (calendar-frame-setup nil)
15728 (calendar-setup nil)
15729 (calendar-move-hook nil)
15730 (calendar-view-diary-initially-flag nil)
15731 (calendar-view-holidays-initially-flag nil)
15732 (timestr (format-time-string
15733 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15734 (prompt (concat (if prompt (concat prompt " ") "")
15735 (format "Date+time [%s]: " timestr)))
15736 ans (org-ans0 "") org-ans1 org-ans2 final)
15738 (cond
15739 (from-string (setq ans from-string))
15740 (org-read-date-popup-calendar
15741 (save-excursion
15742 (save-window-excursion
15743 (calendar)
15744 (org-eval-in-calendar '(setq cursor-type nil) t)
15745 (unwind-protect
15746 (progn
15747 (calendar-forward-day (- (time-to-days org-def)
15748 (calendar-absolute-from-gregorian
15749 (calendar-current-date))))
15750 (org-eval-in-calendar nil t)
15751 (let* ((old-map (current-local-map))
15752 (map (copy-keymap calendar-mode-map))
15753 (minibuffer-local-map
15754 (copy-keymap org-read-date-minibuffer-local-map)))
15755 (org-defkey map (kbd "RET") 'org-calendar-select)
15756 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15757 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15758 (unwind-protect
15759 (progn
15760 (use-local-map map)
15761 (setq org-read-date-inactive inactive)
15762 (add-hook 'post-command-hook 'org-read-date-display)
15763 (setq org-ans0 (read-string prompt default-input
15764 'org-read-date-history nil))
15765 ;; org-ans0: from prompt
15766 ;; org-ans1: from mouse click
15767 ;; org-ans2: from calendar motion
15768 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15769 (remove-hook 'post-command-hook 'org-read-date-display)
15770 (use-local-map old-map)
15771 (when org-read-date-overlay
15772 (delete-overlay org-read-date-overlay)
15773 (setq org-read-date-overlay nil)))))
15774 (bury-buffer "*Calendar*")))))
15776 (t ; Naked prompt only
15777 (unwind-protect
15778 (setq ans (read-string prompt default-input
15779 'org-read-date-history timestr))
15780 (when org-read-date-overlay
15781 (delete-overlay org-read-date-overlay)
15782 (setq org-read-date-overlay nil)))))
15784 (setq final (org-read-date-analyze ans org-def org-defdecode))
15786 (when org-read-date-analyze-forced-year
15787 (message "Year was forced into %s"
15788 (if org-read-date-force-compatible-dates
15789 "compatible range (1970-2037)"
15790 "range representable on this machine"))
15791 (ding))
15793 ;; One round trip to get rid of 34th of August and stuff like that....
15794 (setq final (decode-time (apply 'encode-time final)))
15796 (setq org-read-date-final-answer ans)
15798 (if to-time
15799 (apply 'encode-time final)
15800 (if (and (boundp 'org-time-was-given) org-time-was-given)
15801 (format "%04d-%02d-%02d %02d:%02d"
15802 (nth 5 final) (nth 4 final) (nth 3 final)
15803 (nth 2 final) (nth 1 final))
15804 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15806 (defvar org-def)
15807 (defvar org-defdecode)
15808 (defvar org-with-time)
15809 (defun org-read-date-display ()
15810 "Display the current date prompt interpretation in the minibuffer."
15811 (when org-read-date-display-live
15812 (when org-read-date-overlay
15813 (delete-overlay org-read-date-overlay))
15814 (when (minibufferp (current-buffer))
15815 (save-excursion
15816 (end-of-line 1)
15817 (while (not (equal (buffer-substring
15818 (max (point-min) (- (point) 4)) (point))
15819 " "))
15820 (insert " ")))
15821 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15822 " " (or org-ans1 org-ans2)))
15823 (org-end-time-was-given nil)
15824 (f (org-read-date-analyze ans org-def org-defdecode))
15825 (fmts (if org-dcst
15826 org-time-stamp-custom-formats
15827 org-time-stamp-formats))
15828 (fmt (if (or org-with-time
15829 (and (boundp 'org-time-was-given) org-time-was-given))
15830 (cdr fmts)
15831 (car fmts)))
15832 (txt (format-time-string fmt (apply 'encode-time f)))
15833 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15834 (txt (concat "=> " txt)))
15835 (when (and org-end-time-was-given
15836 (string-match org-plain-time-of-day-regexp txt))
15837 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15838 org-end-time-was-given
15839 (substring txt (match-end 0)))))
15840 (when org-read-date-analyze-futurep
15841 (setq txt (concat txt " (=>F)")))
15842 (setq org-read-date-overlay
15843 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15844 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15846 (defun org-read-date-analyze (ans org-def org-defdecode)
15847 "Analyze the combined answer of the date prompt."
15848 ;; FIXME: cleanup and comment
15849 (let ((nowdecode (decode-time (current-time)))
15850 delta deltan deltaw deltadef year month day
15851 hour minute second wday pm h2 m2 tl wday1
15852 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15853 (setq org-read-date-analyze-futurep nil
15854 org-read-date-analyze-forced-year nil)
15855 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15856 (setq ans "+0"))
15858 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15859 (setq ans (replace-match "" t t ans)
15860 deltan (car delta)
15861 deltaw (nth 1 delta)
15862 deltadef (nth 2 delta)))
15864 ;; Check if there is an iso week date in there. If yes, store the
15865 ;; info and postpone interpreting it until the rest of the parsing
15866 ;; is done.
15867 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15868 (setq iso-year (if (match-end 1)
15869 (org-small-year-to-year
15870 (string-to-number (match-string 1 ans))))
15871 iso-weekday (if (match-end 3)
15872 (string-to-number (match-string 3 ans)))
15873 iso-week (string-to-number (match-string 2 ans)))
15874 (setq ans (replace-match "" t t ans)))
15876 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15877 (when (string-match
15878 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15879 (setq year (if (match-end 2)
15880 (string-to-number (match-string 2 ans))
15881 (progn (setq kill-year t)
15882 (string-to-number (format-time-string "%Y"))))
15883 month (string-to-number (match-string 3 ans))
15884 day (string-to-number (match-string 4 ans)))
15885 (if (< year 100) (setq year (+ 2000 year)))
15886 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15887 t nil ans)))
15889 ;; Help matching dotted european dates
15890 (when (string-match
15891 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15892 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15893 (setq kill-year t)
15894 (string-to-number (format-time-string "%Y")))
15895 day (string-to-number (match-string 1 ans))
15896 month (string-to-number (match-string 2 ans))
15897 ans (replace-match (format "%04d-%02d-%02d" year month day)
15898 t nil ans)))
15900 ;; Help matching american dates, like 5/30 or 5/30/7
15901 (when (string-match
15902 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15903 (setq year (if (match-end 4)
15904 (string-to-number (match-string 4 ans))
15905 (progn (setq kill-year t)
15906 (string-to-number (format-time-string "%Y"))))
15907 month (string-to-number (match-string 1 ans))
15908 day (string-to-number (match-string 2 ans)))
15909 (if (< year 100) (setq year (+ 2000 year)))
15910 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15911 t nil ans)))
15912 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15913 ;; If there is a time with am/pm, and *no* time without it, we convert
15914 ;; so that matching will be successful.
15915 (loop for i from 1 to 2 do ; twice, for end time as well
15916 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15917 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15918 (setq hour (string-to-number (match-string 1 ans))
15919 minute (if (match-end 3)
15920 (string-to-number (match-string 3 ans))
15922 pm (equal ?p
15923 (string-to-char (downcase (match-string 4 ans)))))
15924 (if (and (= hour 12) (not pm))
15925 (setq hour 0)
15926 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15927 (setq ans (replace-match (format "%02d:%02d" hour minute)
15928 t t ans))))
15930 ;; Check if a time range is given as a duration
15931 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15932 (setq hour (string-to-number (match-string 1 ans))
15933 h2 (+ hour (string-to-number (match-string 3 ans)))
15934 minute (string-to-number (match-string 2 ans))
15935 m2 (+ minute (if (match-end 5) (string-to-number
15936 (match-string 5 ans))0)))
15937 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15938 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15939 t t ans)))
15941 ;; Check if there is a time range
15942 (when (boundp 'org-end-time-was-given)
15943 (setq org-time-was-given nil)
15944 (when (and (string-match org-plain-time-of-day-regexp ans)
15945 (match-end 8))
15946 (setq org-end-time-was-given (match-string 8 ans))
15947 (setq ans (concat (substring ans 0 (match-beginning 7))
15948 (substring ans (match-end 7))))))
15950 (setq tl (parse-time-string ans)
15951 day (or (nth 3 tl) (nth 3 org-defdecode))
15952 month (or (nth 4 tl)
15953 (if (and org-read-date-prefer-future
15954 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15955 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15956 (nth 4 org-defdecode)))
15957 year (or (and (not kill-year) (nth 5 tl))
15958 (if (and org-read-date-prefer-future
15959 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15960 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15961 (nth 5 org-defdecode)))
15962 hour (or (nth 2 tl) (nth 2 org-defdecode))
15963 minute (or (nth 1 tl) (nth 1 org-defdecode))
15964 second (or (nth 0 tl) 0)
15965 wday (nth 6 tl))
15967 (when (and (eq org-read-date-prefer-future 'time)
15968 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15969 (equal day (nth 3 nowdecode))
15970 (equal month (nth 4 nowdecode))
15971 (equal year (nth 5 nowdecode))
15972 (nth 2 tl)
15973 (or (< (nth 2 tl) (nth 2 nowdecode))
15974 (and (= (nth 2 tl) (nth 2 nowdecode))
15975 (nth 1 tl)
15976 (< (nth 1 tl) (nth 1 nowdecode)))))
15977 (setq day (1+ day)
15978 futurep t))
15980 ;; Special date definitions below
15981 (cond
15982 (iso-week
15983 ;; There was an iso week
15984 (require 'cal-iso)
15985 (setq futurep nil)
15986 (setq year (or iso-year year)
15987 day (or iso-weekday wday 1)
15988 wday nil ; to make sure that the trigger below does not match
15989 iso-date (calendar-gregorian-from-absolute
15990 (calendar-absolute-from-iso
15991 (list iso-week day year))))
15992 ; FIXME: Should we also push ISO weeks into the future?
15993 ; (when (and org-read-date-prefer-future
15994 ; (not iso-year)
15995 ; (< (calendar-absolute-from-gregorian iso-date)
15996 ; (time-to-days (current-time))))
15997 ; (setq year (1+ year)
15998 ; iso-date (calendar-gregorian-from-absolute
15999 ; (calendar-absolute-from-iso
16000 ; (list iso-week day year)))))
16001 (setq month (car iso-date)
16002 year (nth 2 iso-date)
16003 day (nth 1 iso-date)))
16004 (deltan
16005 (setq futurep nil)
16006 (unless deltadef
16007 (let ((now (decode-time (current-time))))
16008 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16009 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16010 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16011 ((equal deltaw "m") (setq month (+ month deltan)))
16012 ((equal deltaw "y") (setq year (+ year deltan)))))
16013 ((and wday (not (nth 3 tl)))
16014 ;; Weekday was given, but no day, so pick that day in the week
16015 ;; on or after the derived date.
16016 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16017 (unless (equal wday wday1)
16018 (setq day (+ day (% (- wday wday1 -7) 7))))))
16019 (if (and (boundp 'org-time-was-given)
16020 (nth 2 tl))
16021 (setq org-time-was-given t))
16022 (if (< year 100) (setq year (+ 2000 year)))
16023 ;; Check of the date is representable
16024 (if org-read-date-force-compatible-dates
16025 (progn
16026 (if (< year 1970)
16027 (setq year 1970 org-read-date-analyze-forced-year t))
16028 (if (> year 2037)
16029 (setq year 2037 org-read-date-analyze-forced-year t)))
16030 (condition-case nil
16031 (ignore (encode-time second minute hour day month year))
16032 (error
16033 (setq year (nth 5 org-defdecode))
16034 (setq org-read-date-analyze-forced-year t))))
16035 (setq org-read-date-analyze-futurep futurep)
16036 (list second minute hour day month year)))
16038 (defvar parse-time-weekdays)
16039 (defun org-read-date-get-relative (s today default)
16040 "Check string S for special relative date string.
16041 TODAY and DEFAULT are internal times, for today and for a default.
16042 Return shift list (N what def-flag)
16043 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16044 N is the number of WHATs to shift.
16045 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16046 the DEFAULT date rather than TODAY."
16047 (require 'parse-time)
16048 (when (and
16049 (string-match
16050 (concat
16051 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16052 "\\([0-9]+\\)?"
16053 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16054 "\\([ \t]\\|$\\)") s)
16055 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16056 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16057 (string-to-char (substring (match-string 1 s) -1))
16058 ?+))
16059 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16060 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16061 (what (if (match-end 3) (match-string 3 s) "d"))
16062 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16063 (date (if rel default today))
16064 (wday (nth 6 (decode-time date)))
16065 delta)
16066 (if wday1
16067 (progn
16068 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16069 (if (= dir ?-) (setq delta (- delta 7)))
16070 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16071 (list delta "d" rel))
16072 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16074 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16075 "Turn a user-specified date into the internal representation.
16076 The internal representation needed by the calendar is (month day year).
16077 This is a wrapper to handle the brain-dead convention in calendar that
16078 user function argument order change dependent on argument order."
16079 (if (boundp 'calendar-date-style)
16080 (cond
16081 ((eq calendar-date-style 'american)
16082 (list arg1 arg2 arg3))
16083 ((eq calendar-date-style 'european)
16084 (list arg2 arg1 arg3))
16085 ((eq calendar-date-style 'iso)
16086 (list arg2 arg3 arg1)))
16087 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16088 (if (org-bound-and-true-p european-calendar-style)
16089 (list arg2 arg1 arg3)
16090 (list arg1 arg2 arg3)))))
16092 (defun org-eval-in-calendar (form &optional keepdate)
16093 "Eval FORM in the calendar window and return to current window.
16094 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16095 otherwise stick to the current value of `org-ans2'."
16096 (let ((sf (selected-frame))
16097 (sw (selected-window)))
16098 (select-window (get-buffer-window "*Calendar*" t))
16099 (eval form)
16100 (when (and (not keepdate) (calendar-cursor-to-date))
16101 (let* ((date (calendar-cursor-to-date))
16102 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16103 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16104 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16105 (select-window sw)
16106 (org-select-frame-set-input-focus sf)))
16108 (defun org-calendar-select ()
16109 "Return to `org-read-date' with the date currently selected.
16110 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16111 (interactive)
16112 (when (calendar-cursor-to-date)
16113 (let* ((date (calendar-cursor-to-date))
16114 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16115 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16116 (if (active-minibuffer-window) (exit-minibuffer))))
16118 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16119 "Insert a date stamp for the date given by the internal TIME.
16120 WITH-HM means use the stamp format that includes the time of the day.
16121 INACTIVE means use square brackets instead of angular ones, so that the
16122 stamp will not contribute to the agenda.
16123 PRE and POST are optional strings to be inserted before and after the
16124 stamp.
16125 The command returns the inserted time stamp."
16126 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16127 stamp)
16128 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16129 (insert-before-markers (or pre ""))
16130 (when (listp extra)
16131 (setq extra (car extra))
16132 (if (and (stringp extra)
16133 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16134 (setq extra (format "-%02d:%02d"
16135 (string-to-number (match-string 1 extra))
16136 (string-to-number (match-string 2 extra))))
16137 (setq extra nil)))
16138 (when extra
16139 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16140 (insert-before-markers (setq stamp (format-time-string fmt time)))
16141 (insert-before-markers (or post ""))
16142 (setq org-last-inserted-timestamp stamp)))
16144 (defun org-toggle-time-stamp-overlays ()
16145 "Toggle the use of custom time stamp formats."
16146 (interactive)
16147 (setq org-display-custom-times (not org-display-custom-times))
16148 (unless org-display-custom-times
16149 (let ((p (point-min)) (bmp (buffer-modified-p)))
16150 (while (setq p (next-single-property-change p 'display))
16151 (if (and (get-text-property p 'display)
16152 (eq (get-text-property p 'face) 'org-date))
16153 (remove-text-properties
16154 p (setq p (next-single-property-change p 'display))
16155 '(display t))))
16156 (set-buffer-modified-p bmp)))
16157 (if (featurep 'xemacs)
16158 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16159 (org-restart-font-lock)
16160 (setq org-table-may-need-update t)
16161 (if org-display-custom-times
16162 (message "Time stamps are overlaid with custom format")
16163 (message "Time stamp overlays removed")))
16165 (defun org-display-custom-time (beg end)
16166 "Overlay modified time stamp format over timestamp between BEG and END."
16167 (let* ((ts (buffer-substring beg end))
16168 t1 w1 with-hm tf time str w2 (off 0))
16169 (save-match-data
16170 (setq t1 (org-parse-time-string ts t))
16171 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16172 (setq off (- (match-end 0) (match-beginning 0)))))
16173 (setq end (- end off))
16174 (setq w1 (- end beg)
16175 with-hm (and (nth 1 t1) (nth 2 t1))
16176 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16177 time (org-fix-decoded-time t1)
16178 str (org-add-props
16179 (format-time-string
16180 (substring tf 1 -1) (apply 'encode-time time))
16181 nil 'mouse-face 'highlight)
16182 w2 (length str))
16183 (if (not (= w2 w1))
16184 (add-text-properties (1+ beg) (+ 2 beg)
16185 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16186 (if (featurep 'xemacs)
16187 (progn
16188 (put-text-property beg end 'invisible t)
16189 (put-text-property beg end 'end-glyph (make-glyph str)))
16190 (put-text-property beg end 'display str))))
16192 (defun org-translate-time (string)
16193 "Translate all timestamps in STRING to custom format.
16194 But do this only if the variable `org-display-custom-times' is set."
16195 (when org-display-custom-times
16196 (save-match-data
16197 (let* ((start 0)
16198 (re org-ts-regexp-both)
16199 t1 with-hm inactive tf time str beg end)
16200 (while (setq start (string-match re string start))
16201 (setq beg (match-beginning 0)
16202 end (match-end 0)
16203 t1 (save-match-data
16204 (org-parse-time-string (substring string beg end) t))
16205 with-hm (and (nth 1 t1) (nth 2 t1))
16206 inactive (equal (substring string beg (1+ beg)) "[")
16207 tf (funcall (if with-hm 'cdr 'car)
16208 org-time-stamp-custom-formats)
16209 time (org-fix-decoded-time t1)
16210 str (format-time-string
16211 (concat
16212 (if inactive "[" "<") (substring tf 1 -1)
16213 (if inactive "]" ">"))
16214 (apply 'encode-time time))
16215 string (replace-match str t t string)
16216 start (+ start (length str)))))))
16217 string)
16219 (defun org-fix-decoded-time (time)
16220 "Set 0 instead of nil for the first 6 elements of time.
16221 Don't touch the rest."
16222 (let ((n 0))
16223 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16225 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16227 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16228 "Difference between TIMESTAMP-STRING and now in days.
16229 If SECONDS is non-nil, return the difference in seconds."
16230 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16231 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16232 (funcall fdiff (current-time)))))
16234 (defun org-deadline-close (timestamp-string &optional ndays)
16235 "Is the time in TIMESTAMP-STRING close to the current date?"
16236 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16237 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16238 (not (org-entry-is-done-p))))
16240 (defun org-get-wdays (ts &optional delay zero-delay)
16241 "Get the deadline lead time appropriate for timestring TS.
16242 When DELAY is non-nil, get the delay time for scheduled items
16243 instead of the deadline lead time. When ZERO-DELAY is non-nil
16244 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16245 don't try to find the delay cookie in the scheduled timestamp."
16246 (let ((tv (if delay org-scheduled-delay-days
16247 org-deadline-warning-days)))
16248 (cond
16249 ((or (and delay (< tv 0))
16250 (and delay zero-delay (<= tv 0))
16251 (and (not delay) (<= tv 0)))
16252 ;; Enforce this value no matter what
16253 (- tv))
16254 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16255 ;; lead time is specified.
16256 (floor (* (string-to-number (match-string 1 ts))
16257 (cdr (assoc (match-string 2 ts)
16258 '(("d" . 1) ("w" . 7)
16259 ("m" . 30.4) ("y" . 365.25)
16260 ("h" . 0.041667)))))))
16261 ;; go for the default.
16262 (t tv))))
16264 (defun org-calendar-select-mouse (ev)
16265 "Return to `org-read-date' with the date currently selected.
16266 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16267 (interactive "e")
16268 (mouse-set-point ev)
16269 (when (calendar-cursor-to-date)
16270 (let* ((date (calendar-cursor-to-date))
16271 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16272 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16273 (if (active-minibuffer-window) (exit-minibuffer))))
16275 (defun org-check-deadlines (ndays)
16276 "Check if there are any deadlines due or past due.
16277 A deadline is considered due if it happens within `org-deadline-warning-days'
16278 days from today's date. If the deadline appears in an entry marked DONE,
16279 it is not shown. The prefix arg NDAYS can be used to test that many
16280 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16281 (interactive "P")
16282 (let* ((org-warn-days
16283 (cond
16284 ((equal ndays '(4)) 100000)
16285 (ndays (prefix-numeric-value ndays))
16286 (t (abs org-deadline-warning-days))))
16287 (case-fold-search nil)
16288 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16289 (callback
16290 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16292 (message "%d deadlines past-due or due within %d days"
16293 (org-occur regexp nil callback)
16294 org-warn-days)))
16296 (defsubst org-re-timestamp (type)
16297 "Return a regexp for timestamp TYPE.
16298 Allowed values for TYPE are:
16300 all: all timestamps
16301 active: only active timestamps (<...>)
16302 inactive: only inactive timestamps ([...])
16303 scheduled: only scheduled timestamps
16304 deadline: only deadline timestamps
16306 When TYPE is nil, fall back on returning a regexp that matches
16307 both scheduled and deadline timestamps."
16308 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16309 ((eq type 'active) org-ts-regexp)
16310 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16311 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16312 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16313 ((eq type 'scheduled-or-deadline)
16314 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16316 (defun org-check-before-date (date)
16317 "Check if there are deadlines or scheduled entries before DATE."
16318 (interactive (list (org-read-date)))
16319 (let ((case-fold-search nil)
16320 (regexp (org-re-timestamp org-ts-type))
16321 (callback
16322 (lambda () (time-less-p
16323 (org-time-string-to-time (match-string 1))
16324 (org-time-string-to-time date)))))
16325 (message "%d entries before %s"
16326 (org-occur regexp nil callback) date)))
16328 (defun org-check-after-date (date)
16329 "Check if there are deadlines or scheduled entries after DATE."
16330 (interactive (list (org-read-date)))
16331 (let ((case-fold-search nil)
16332 (regexp (org-re-timestamp org-ts-type))
16333 (callback
16334 (lambda () (not
16335 (time-less-p
16336 (org-time-string-to-time (match-string 1))
16337 (org-time-string-to-time date))))))
16338 (message "%d entries after %s"
16339 (org-occur regexp nil callback) date)))
16341 (defun org-check-dates-range (start-date end-date)
16342 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16343 (interactive (list (org-read-date nil nil nil "Range starts")
16344 (org-read-date nil nil nil "Range end")))
16345 (let ((case-fold-search nil)
16346 (regexp (org-re-timestamp org-ts-type))
16347 (callback
16348 (lambda ()
16349 (let ((match (match-string 1)))
16350 (and
16351 (not (time-less-p
16352 (org-time-string-to-time match)
16353 (org-time-string-to-time start-date)))
16354 (time-less-p
16355 (org-time-string-to-time match)
16356 (org-time-string-to-time end-date)))))))
16357 (message "%d entries between %s and %s"
16358 (org-occur regexp nil callback) start-date end-date)))
16360 (defun org-evaluate-time-range (&optional to-buffer)
16361 "Evaluate a time range by computing the difference between start and end.
16362 Normally the result is just printed in the echo area, but with prefix arg
16363 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16364 If the time range is actually in a table, the result is inserted into the
16365 next column.
16366 For time difference computation, a year is assumed to be exactly 365
16367 days in order to avoid rounding problems."
16368 (interactive "P")
16370 (org-clock-update-time-maybe)
16371 (save-excursion
16372 (unless (org-at-date-range-p t)
16373 (goto-char (point-at-bol))
16374 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16375 (if (not (org-at-date-range-p t))
16376 (error "Not at a time-stamp range, and none found in current line")))
16377 (let* ((ts1 (match-string 1))
16378 (ts2 (match-string 2))
16379 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16380 (match-end (match-end 0))
16381 (time1 (org-time-string-to-time ts1))
16382 (time2 (org-time-string-to-time ts2))
16383 (t1 (org-float-time time1))
16384 (t2 (org-float-time time2))
16385 (diff (abs (- t2 t1)))
16386 (negative (< (- t2 t1) 0))
16387 ;; (ys (floor (* 365 24 60 60)))
16388 (ds (* 24 60 60))
16389 (hs (* 60 60))
16390 (fy "%dy %dd %02d:%02d")
16391 (fy1 "%dy %dd")
16392 (fd "%dd %02d:%02d")
16393 (fd1 "%dd")
16394 (fh "%02d:%02d")
16395 y d h m align)
16396 (if havetime
16397 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16399 d (floor (/ diff ds)) diff (mod diff ds)
16400 h (floor (/ diff hs)) diff (mod diff hs)
16401 m (floor (/ diff 60)))
16402 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16404 d (floor (+ (/ diff ds) 0.5))
16405 h 0 m 0))
16406 (if (not to-buffer)
16407 (message "%s" (org-make-tdiff-string y d h m))
16408 (if (org-at-table-p)
16409 (progn
16410 (goto-char match-end)
16411 (setq align t)
16412 (and (looking-at " *|") (goto-char (match-end 0))))
16413 (goto-char match-end))
16414 (if (looking-at
16415 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16416 (replace-match ""))
16417 (if negative (insert " -"))
16418 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16419 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16420 (insert " " (format fh h m))))
16421 (if align (org-table-align))
16422 (message "Time difference inserted")))))
16424 (defun org-make-tdiff-string (y d h m)
16425 (let ((fmt "")
16426 (l nil))
16427 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16428 l (push y l)))
16429 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16430 l (push d l)))
16431 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16432 l (push h l)))
16433 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16434 l (push m l)))
16435 (apply 'format fmt (nreverse l))))
16437 (defun org-time-string-to-time (s &optional buffer pos)
16438 "Convert a timestamp string into internal time."
16439 (condition-case errdata
16440 (apply 'encode-time (org-parse-time-string s))
16441 (error (error "Bad timestamp `%s'%s\nError was: %s"
16442 s (if (not (and buffer pos))
16444 (format " at %d in buffer `%s'" pos buffer))
16445 (cdr errdata)))))
16447 (defun org-time-string-to-seconds (s)
16448 "Convert a timestamp string to a number of seconds."
16449 (org-float-time (org-time-string-to-time s)))
16451 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16452 "Convert a time stamp to an absolute day number.
16453 If there is a specifier for a cyclic time stamp, get the closest date to
16454 DAYNR.
16455 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16456 The variable date is bound by the calendar when this is called."
16457 (cond
16458 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16459 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16460 daynr
16461 (+ daynr 1000)))
16462 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16463 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16464 (time-to-days (current-time))) (match-string 0 s)
16465 prefer show-all))
16466 (t (time-to-days
16467 (condition-case errdata
16468 (apply 'encode-time (org-parse-time-string s))
16469 (error (error "Bad timestamp `%s'%s\nError was: %s"
16470 s (if (not (and buffer pos))
16472 (format " at %d in buffer `%s'" pos buffer))
16473 (cdr errdata))))))))
16475 (defun org-days-to-iso-week (days)
16476 "Return the iso week number."
16477 (require 'cal-iso)
16478 (car (calendar-iso-from-absolute days)))
16480 (defun org-small-year-to-year (year)
16481 "Convert 2-digit years into 4-digit years.
16482 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16483 The year 2000 cannot be abbreviated. Any year larger than 99
16484 is returned unchanged."
16485 (if (< year 38)
16486 (setq year (+ 2000 year))
16487 (if (< year 100)
16488 (setq year (+ 1900 year))))
16489 year)
16491 (defun org-time-from-absolute (d)
16492 "Return the time corresponding to date D.
16493 D may be an absolute day number, or a calendar-type list (month day year)."
16494 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16495 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16497 (defun org-calendar-holiday ()
16498 "List of holidays, for Diary display in Org-mode."
16499 (require 'holidays)
16500 (let ((hl (funcall
16501 (if (fboundp 'calendar-check-holidays)
16502 'calendar-check-holidays 'check-calendar-holidays) date)))
16503 (if hl (mapconcat 'identity hl "; "))))
16505 (defun org-diary-sexp-entry (sexp entry date)
16506 "Process a SEXP diary ENTRY for DATE."
16507 (require 'diary-lib)
16508 (let ((result (if calendar-debug-sexp
16509 (let ((stack-trace-on-error t))
16510 (eval (car (read-from-string sexp))))
16511 (condition-case nil
16512 (eval (car (read-from-string sexp)))
16513 (error
16514 (beep)
16515 (message "Bad sexp at line %d in %s: %s"
16516 (org-current-line)
16517 (buffer-file-name) sexp)
16518 (sleep-for 2))))))
16519 (cond ((stringp result) (split-string result "; "))
16520 ((and (consp result)
16521 (not (consp (cdr result)))
16522 (stringp (cdr result))) (cdr result))
16523 ((and (consp result)
16524 (stringp (car result))) result)
16525 (result entry))))
16527 (defun org-diary-to-ical-string (frombuf)
16528 "Get iCalendar entries from diary entries in buffer FROMBUF.
16529 This uses the icalendar.el library."
16530 (let* ((tmpdir (if (featurep 'xemacs)
16531 (temp-directory)
16532 temporary-file-directory))
16533 (tmpfile (make-temp-name
16534 (expand-file-name "orgics" tmpdir)))
16535 buf rtn b e)
16536 (with-current-buffer frombuf
16537 (icalendar-export-region (point-min) (point-max) tmpfile)
16538 (setq buf (find-buffer-visiting tmpfile))
16539 (set-buffer buf)
16540 (goto-char (point-min))
16541 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16542 (setq b (match-beginning 0)))
16543 (goto-char (point-max))
16544 (if (re-search-backward "^END:VEVENT" nil t)
16545 (setq e (match-end 0)))
16546 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16547 (kill-buffer buf)
16548 (delete-file tmpfile)
16549 rtn))
16551 (defun org-closest-date (start current change prefer show-all)
16552 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16553 When PREFER is `past', return a date that is either CURRENT or past.
16554 When PREFER is `future', return a date that is either CURRENT or future.
16555 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16556 ;; Make the proper lists from the dates
16557 (catch 'exit
16558 (let ((a1 '(("h" . hour)
16559 ("d" . day)
16560 ("w" . week)
16561 ("m" . month)
16562 ("y" . year)))
16563 (shour (nth 2 (org-parse-time-string start)))
16564 dn dw sday cday n1 n2 n0
16565 d m y y1 y2 date1 date2 nmonths nm ny m2)
16567 (setq start (org-date-to-gregorian start)
16568 current (org-date-to-gregorian
16569 (if show-all
16570 current
16571 (time-to-days (current-time))))
16572 sday (calendar-absolute-from-gregorian start)
16573 cday (calendar-absolute-from-gregorian current))
16575 (if (<= cday sday) (throw 'exit sday))
16577 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16578 (setq dn (string-to-number (match-string 1 change))
16579 dw (cdr (assoc (match-string 2 change) a1)))
16580 (error "Invalid change specifier: %s" change))
16581 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16582 (cond
16583 ((eq dw 'hour)
16584 (let ((missing-hours
16585 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16586 dn)))
16587 (setq n1 (if (zerop missing-hours) cday
16588 (- cday (1+ (floor (/ missing-hours 24)))))
16589 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16590 ((eq dw 'day)
16591 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16592 n2 (+ n1 dn)))
16593 ((eq dw 'year)
16594 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16595 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16596 (setq date1 (list m d y1)
16597 n1 (calendar-absolute-from-gregorian date1)
16598 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16599 n2 (calendar-absolute-from-gregorian date2)))
16600 ((eq dw 'month)
16601 ;; approx number of month between the two dates
16602 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16603 ;; How often does dn fit in there?
16604 (setq d (nth 1 start) m (car start) y (nth 2 start)
16605 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16606 m (+ m nm)
16607 ny (floor (/ m 12))
16608 y (+ y ny)
16609 m (- m (* ny 12)))
16610 (while (> m 12) (setq m (- m 12) y (1+ y)))
16611 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16612 (setq m2 (+ m dn) y2 y)
16613 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16614 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16615 (while (<= n2 cday)
16616 (setq n1 n2 m m2 y y2)
16617 (setq m2 (+ m dn) y2 y)
16618 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16619 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16620 ;; Make sure n1 is the earlier date
16621 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16622 (if show-all
16623 (cond
16624 ((eq prefer 'past) (if (= cday n2) n2 n1))
16625 ((eq prefer 'future) (if (= cday n1) n1 n2))
16626 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16627 (cond
16628 ((eq prefer 'past) (if (= cday n2) n2 n1))
16629 ((eq prefer 'future) (if (= cday n1) n1 n2))
16630 (t (if (= cday n1) n1 n2)))))))
16632 (defun org-date-to-gregorian (date)
16633 "Turn any specification of DATE into a Gregorian date for the calendar."
16634 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16635 ((and (listp date) (= (length date) 3)) date)
16636 ((stringp date)
16637 (setq date (org-parse-time-string date))
16638 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16639 ((listp date)
16640 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16642 (defun org-parse-time-string (s &optional nodefault)
16643 "Parse the standard Org-mode time string.
16644 This should be a lot faster than the normal `parse-time-string'.
16645 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16646 hour and minute fields will be nil if not given."
16647 (cond ((string-match org-ts-regexp0 s)
16648 (list 0
16649 (if (or (match-beginning 8) (not nodefault))
16650 (string-to-number (or (match-string 8 s) "0")))
16651 (if (or (match-beginning 7) (not nodefault))
16652 (string-to-number (or (match-string 7 s) "0")))
16653 (string-to-number (match-string 4 s))
16654 (string-to-number (match-string 3 s))
16655 (string-to-number (match-string 2 s))
16656 nil nil nil))
16657 ((string-match "^<[^>]+>$" s)
16658 (decode-time (seconds-to-time (org-matcher-time s))))
16659 (t (error "Not a standard Org-mode time string: %s" s))))
16661 (defun org-timestamp-up (&optional arg)
16662 "Increase the date item at the cursor by one.
16663 If the cursor is on the year, change the year. If it is on the month,
16664 the day or the time, change that.
16665 With prefix ARG, change by that many units."
16666 (interactive "p")
16667 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16669 (defun org-timestamp-down (&optional arg)
16670 "Decrease the date item at the cursor by one.
16671 If the cursor is on the year, change the year. If it is on the month,
16672 the day or the time, change that.
16673 With prefix ARG, change by that many units."
16674 (interactive "p")
16675 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16677 (defun org-timestamp-up-day (&optional arg)
16678 "Increase the date in the time stamp by one day.
16679 With prefix ARG, change that many days."
16680 (interactive "p")
16681 (if (and (not (org-at-timestamp-p t))
16682 (org-at-heading-p))
16683 (org-todo 'up)
16684 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16686 (defun org-timestamp-down-day (&optional arg)
16687 "Decrease the date in the time stamp by one day.
16688 With prefix ARG, change that many days."
16689 (interactive "p")
16690 (if (and (not (org-at-timestamp-p t))
16691 (org-at-heading-p))
16692 (org-todo 'down)
16693 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16695 (defun org-at-timestamp-p (&optional inactive-ok)
16696 "Determine if the cursor is in or at a timestamp."
16697 (interactive)
16698 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16699 (pos (point))
16700 (ans (or (looking-at tsr)
16701 (save-excursion
16702 (skip-chars-backward "^[<\n\r\t")
16703 (if (> (point) (point-min)) (backward-char 1))
16704 (and (looking-at tsr)
16705 (> (- (match-end 0) pos) -1))))))
16706 (and ans
16707 (boundp 'org-ts-what)
16708 (setq org-ts-what
16709 (cond
16710 ((= pos (match-beginning 0)) 'bracket)
16711 ;; Point is considered to be "on the bracket" whether
16712 ;; it's really on it or right after it.
16713 ((= pos (1- (match-end 0))) 'bracket)
16714 ((= pos (match-end 0)) 'after)
16715 ((org-pos-in-match-range pos 2) 'year)
16716 ((org-pos-in-match-range pos 3) 'month)
16717 ((org-pos-in-match-range pos 7) 'hour)
16718 ((org-pos-in-match-range pos 8) 'minute)
16719 ((or (org-pos-in-match-range pos 4)
16720 (org-pos-in-match-range pos 5)) 'day)
16721 ((and (> pos (or (match-end 8) (match-end 5)))
16722 (< pos (match-end 0)))
16723 (- pos (or (match-end 8) (match-end 5))))
16724 (t 'day))))
16725 ans))
16727 (defun org-toggle-timestamp-type ()
16728 "Toggle the type (<active> or [inactive]) of a time stamp."
16729 (interactive)
16730 (when (org-at-timestamp-p t)
16731 (let ((beg (match-beginning 0)) (end (match-end 0))
16732 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16733 (save-excursion
16734 (goto-char beg)
16735 (while (re-search-forward "[][<>]" end t)
16736 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16737 t t)))
16738 (message "Timestamp is now %sactive"
16739 (if (equal (char-after beg) ?<) "" "in")))))
16741 (defvar org-clock-history) ; defined in org-clock.el
16742 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16743 (defun org-timestamp-change (n &optional what updown)
16744 "Change the date in the time stamp at point.
16745 The date will be changed by N times WHAT. WHAT can be `day', `month',
16746 `year', `minute', `second'. If WHAT is not given, the cursor position
16747 in the timestamp determines what will be changed."
16748 (let ((origin (point)) origin-cat
16749 with-hm inactive
16750 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16751 org-ts-what
16752 extra rem
16753 ts time time0 fixnext clrgx)
16754 (if (not (org-at-timestamp-p t))
16755 (error "Not at a timestamp"))
16756 (if (and (not what) (eq org-ts-what 'bracket))
16757 (org-toggle-timestamp-type)
16758 ;; Point isn't on brackets. Remember the part of the time-stamp
16759 ;; the point was in. Indeed, size of time-stamps may change,
16760 ;; but point must be kept in the same category nonetheless.
16761 (setq origin-cat org-ts-what)
16762 (if (and (not what) (not (eq org-ts-what 'day))
16763 org-display-custom-times
16764 (get-text-property (point) 'display)
16765 (not (get-text-property (1- (point)) 'display)))
16766 (setq org-ts-what 'day))
16767 (setq org-ts-what (or what org-ts-what)
16768 inactive (= (char-after (match-beginning 0)) ?\[)
16769 ts (match-string 0))
16770 (replace-match "")
16771 (if (string-match
16772 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16774 (setq extra (match-string 1 ts)))
16775 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16776 (setq with-hm t))
16777 (setq time0 (org-parse-time-string ts))
16778 (when (and updown
16779 (eq org-ts-what 'minute)
16780 (not current-prefix-arg))
16781 ;; This looks like s-up and s-down. Change by one rounding step.
16782 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16783 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16784 (setcar (cdr time0) (+ (nth 1 time0)
16785 (if (> n 0) (- rem) (- dm rem))))))
16786 (setq time
16787 (encode-time (or (car time0) 0)
16788 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16789 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16790 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16791 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16792 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16793 (nthcdr 6 time0)))
16794 (when (and (member org-ts-what '(hour minute))
16795 extra
16796 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16797 (setq extra (org-modify-ts-extra
16798 extra
16799 (if (eq org-ts-what 'hour) 2 5)
16800 n dm)))
16801 (when (integerp org-ts-what)
16802 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16803 (if (eq what 'calendar)
16804 (let ((cal-date (org-get-date-from-calendar)))
16805 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16806 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16807 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16808 (setcar time0 (or (car time0) 0))
16809 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16810 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16811 (setq time (apply 'encode-time time0))))
16812 ;; Insert the new time-stamp, and ensure point stays in the same
16813 ;; category as before (i.e. not after the last position in that
16814 ;; category).
16815 (let ((pos (point)))
16816 ;; Stay before inserted string. `save-excursion' is of no use.
16817 (setq org-last-changed-timestamp
16818 (org-insert-time-stamp time with-hm inactive nil nil extra))
16819 (goto-char pos))
16820 (save-match-data
16821 (looking-at org-ts-regexp3)
16822 (goto-char (cond
16823 ;; `day' category ends before `hour' if any, or at
16824 ;; the end of the day name.
16825 ((eq origin-cat 'day)
16826 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16827 ((eq origin-cat 'hour) (min (match-end 7) origin))
16828 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16829 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16830 ;; `year' and `month' have both fixed size: point
16831 ;; couldn't have moved into another part.
16832 (t origin))))
16833 ;; Update clock if on a CLOCK line.
16834 (org-clock-update-time-maybe)
16835 ;; Maybe adjust the closest clock in `org-clock-history'
16836 (when org-clock-adjust-closest
16837 (if (not (and (org-at-clock-log-p)
16838 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16839 org-clock-history))))))
16840 (message "No clock to adjust")
16841 (cond ((save-excursion ; fix previous clock?
16842 (re-search-backward org-ts-regexp0 nil t)
16843 (org-looking-back (concat org-clock-string " \\[")))
16844 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16845 ((save-excursion ; fix next clock?
16846 (re-search-backward org-ts-regexp0 nil t)
16847 (looking-at (concat org-ts-regexp0 "\\] =>")))
16848 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16849 (save-window-excursion
16850 ;; Find closest clock to point, adjust the previous/next one in history
16851 (let* ((p (save-excursion (org-back-to-heading t)))
16852 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16853 (clfixnth
16854 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16855 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16856 (if (not clfixpos)
16857 (message "No clock to adjust")
16858 (save-excursion
16859 (org-goto-marker-or-bmk clfixpos)
16860 (org-show-subtree)
16861 (when (re-search-forward clrgx nil t)
16862 (goto-char (match-beginning 1))
16863 (let (org-clock-adjust-closest)
16864 (org-timestamp-change n org-ts-what updown))
16865 (message "Clock adjusted in %s for heading: %s"
16866 (file-name-nondirectory (buffer-file-name))
16867 (org-get-heading t t)))))))))
16868 ;; Try to recenter the calendar window, if any.
16869 (if (and org-calendar-follow-timestamp-change
16870 (get-buffer-window "*Calendar*" t)
16871 (memq org-ts-what '(day month year)))
16872 (org-recenter-calendar (time-to-days time))))))
16874 (defun org-modify-ts-extra (s pos n dm)
16875 "Change the different parts of the lead-time and repeat fields in timestamp."
16876 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16877 ng h m new rem)
16878 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16879 (cond
16880 ((or (org-pos-in-match-range pos 2)
16881 (org-pos-in-match-range pos 3))
16882 (setq m (string-to-number (match-string 3 s))
16883 h (string-to-number (match-string 2 s)))
16884 (if (org-pos-in-match-range pos 2)
16885 (setq h (+ h n))
16886 (setq n (* dm (org-no-warnings (signum n))))
16887 (when (not (= 0 (setq rem (% m dm))))
16888 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16889 (setq m (+ m n)))
16890 (if (< m 0) (setq m (+ m 60) h (1- h)))
16891 (if (> m 59) (setq m (- m 60) h (1+ h)))
16892 (setq h (min 24 (max 0 h)))
16893 (setq ng 1 new (format "-%02d:%02d" h m)))
16894 ((org-pos-in-match-range pos 6)
16895 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16896 ((org-pos-in-match-range pos 5)
16897 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16899 ((org-pos-in-match-range pos 9)
16900 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16901 ((org-pos-in-match-range pos 8)
16902 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16904 (when ng
16905 (setq s (concat
16906 (substring s 0 (match-beginning ng))
16908 (substring s (match-end ng))))))
16911 (defun org-recenter-calendar (date)
16912 "If the calendar is visible, recenter it to DATE."
16913 (let ((cwin (get-buffer-window "*Calendar*" t)))
16914 (when cwin
16915 (let ((calendar-move-hook nil))
16916 (with-selected-window cwin
16917 (calendar-goto-date (if (listp date) date
16918 (calendar-gregorian-from-absolute date))))))))
16920 (defun org-goto-calendar (&optional arg)
16921 "Go to the Emacs calendar at the current date.
16922 If there is a time stamp in the current line, go to that date.
16923 A prefix ARG can be used to force the current date."
16924 (interactive "P")
16925 (let ((tsr org-ts-regexp) diff
16926 (calendar-move-hook nil)
16927 (calendar-view-holidays-initially-flag nil)
16928 (calendar-view-diary-initially-flag nil))
16929 (if (or (org-at-timestamp-p)
16930 (save-excursion
16931 (beginning-of-line 1)
16932 (looking-at (concat ".*" tsr))))
16933 (let ((d1 (time-to-days (current-time)))
16934 (d2 (time-to-days
16935 (org-time-string-to-time (match-string 1)))))
16936 (setq diff (- d2 d1))))
16937 (calendar)
16938 (calendar-goto-today)
16939 (if (and diff (not arg)) (calendar-forward-day diff))))
16941 (defun org-get-date-from-calendar ()
16942 "Return a list (month day year) of date at point in calendar."
16943 (with-current-buffer "*Calendar*"
16944 (save-match-data
16945 (calendar-cursor-to-date))))
16947 (defun org-date-from-calendar ()
16948 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16949 If there is already a time stamp at the cursor position, update it."
16950 (interactive)
16951 (if (org-at-timestamp-p t)
16952 (org-timestamp-change 0 'calendar)
16953 (let ((cal-date (org-get-date-from-calendar)))
16954 (org-insert-time-stamp
16955 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16957 (defcustom org-effort-durations
16958 `(("h" . 60)
16959 ("d" . ,(* 60 8))
16960 ("w" . ,(* 60 8 5))
16961 ("m" . ,(* 60 8 5 4))
16962 ("y" . ,(* 60 8 5 40)))
16963 "Conversion factor to minutes for an effort modifier.
16965 Each entry has the form (MODIFIER . MINUTES).
16967 In an effort string, a number followed by MODIFIER is multiplied
16968 by the specified number of MINUTES to obtain an effort in
16969 minutes.
16971 For example, if the value of this variable is ((\"hours\" . 60)), then an
16972 effort string \"2hours\" is equivalent to 120 minutes."
16973 :group 'org-agenda
16974 :version "24.1"
16975 :type '(alist :key-type (string :tag "Modifier")
16976 :value-type (number :tag "Minutes")))
16978 (defun org-minutes-to-clocksum-string (m)
16979 "Format number of minutes as a clocksum string.
16980 The format is determined by `org-time-clocksum-format',
16981 `org-time-clocksum-use-fractional' and
16982 `org-time-clocksum-fractional-format' and
16983 `org-time-clocksum-use-effort-durations'."
16984 (let ((clocksum "") h d w mo y fmt n)
16985 (setq h (if org-time-clocksum-use-effort-durations
16986 (cdr (assoc "h" org-effort-durations)) 60)
16987 d (if org-time-clocksum-use-effort-durations
16988 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
16989 w (if org-time-clocksum-use-effort-durations
16990 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
16991 mo (if org-time-clocksum-use-effort-durations
16992 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
16993 y (if org-time-clocksum-use-effort-durations
16994 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
16995 ;; fractional format
16996 (if org-time-clocksum-use-fractional
16997 (cond
16998 ;; single format string
16999 ((stringp org-time-clocksum-fractional-format)
17000 (format org-time-clocksum-fractional-format (/ m (float h))))
17001 ;; choice of fractional formats for different time units
17002 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17003 (> (/ (truncate m) (* y d h)) 0))
17004 (format fmt (/ m (* y d (float h)))))
17005 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17006 (> (/ (truncate m) (* mo d h)) 0))
17007 (format fmt (/ m (* mo d (float h)))))
17008 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17009 (> (/ (truncate m) (* w d h)) 0))
17010 (format fmt (/ m (* w d (float h)))))
17011 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17012 (> (/ (truncate m) (* d h)) 0))
17013 (format fmt (/ m (* d (float h)))))
17014 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17015 (> (/ (truncate m) h) 0))
17016 (format fmt (/ m (float h))))
17017 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17018 (format fmt m))
17019 ;; fall back to smallest time unit with a format
17020 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17021 (format fmt (/ m (float h))))
17022 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17023 (format fmt (/ m (* d (float h)))))
17024 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17025 (format fmt (/ m (* w d (float h)))))
17026 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17027 (format fmt (/ m (* mo d (float h)))))
17028 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17029 (format fmt (/ m (* y d (float h))))))
17030 ;; standard (non-fractional) format, with single format string
17031 (if (stringp org-time-clocksum-format)
17032 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17033 ;; separate formats components
17034 (and (setq fmt (plist-get org-time-clocksum-format :years))
17035 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17036 (plist-get org-time-clocksum-format :require-years))
17037 (setq clocksum (concat clocksum (format fmt n))
17038 m (- m (* n y d h))))
17039 (and (setq fmt (plist-get org-time-clocksum-format :months))
17040 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17041 (plist-get org-time-clocksum-format :require-months))
17042 (setq clocksum (concat clocksum (format fmt n))
17043 m (- m (* n mo d h))))
17044 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17045 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17046 (plist-get org-time-clocksum-format :require-weeks))
17047 (setq clocksum (concat clocksum (format fmt n))
17048 m (- m (* n w d h))))
17049 (and (setq fmt (plist-get org-time-clocksum-format :days))
17050 (or (> (setq n (/ (truncate m) (* d h))) 0)
17051 (plist-get org-time-clocksum-format :require-days))
17052 (setq clocksum (concat clocksum (format fmt n))
17053 m (- m (* n d h))))
17054 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17055 (or (> (setq n (/ (truncate m) h)) 0)
17056 (plist-get org-time-clocksum-format :require-hours))
17057 (setq clocksum (concat clocksum (format fmt n))
17058 m (- m (* n h))))
17059 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17060 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17061 (setq clocksum (concat clocksum (format fmt m))))
17062 ;; return formatted time duration
17063 clocksum))))
17065 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17066 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17067 "Org mode version 8.0")
17069 (defun org-hours-to-clocksum-string (n)
17070 (org-minutes-to-clocksum-string (* n 60)))
17072 (defun org-hh:mm-string-to-minutes (s)
17073 "Convert a string H:MM to a number of minutes.
17074 If the string is just a number, interpret it as minutes.
17075 In fact, the first hh:mm or number in the string will be taken,
17076 there can be extra stuff in the string.
17077 If no number is found, the return value is 0."
17078 (cond
17079 ((integerp s) s)
17080 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17081 (+ (* (string-to-number (match-string 1 s)) 60)
17082 (string-to-number (match-string 2 s))))
17083 ((string-match "\\([0-9]+\\)" s)
17084 (string-to-number (match-string 1 s)))
17085 (t 0)))
17087 (defcustom org-image-actual-width t
17088 "Should we use the actual width of images when inlining them?
17090 When set to `t', always use the image width.
17092 When set to a number, use imagemagick (when available) to set
17093 the image's width to this value.
17095 When set to a number in a list, try to get the width from the
17096 #+ATTR.* keyword if it matches a width specification like
17097 width=\"[0-9]+\", and fall back on that number if none is found.
17099 When set to nil, try to get the width from an #+ATTR.* keyword
17100 and fall back on the original width if none is found.
17102 This requires Emacs >= 24.1, build with imagemagick support."
17103 :group 'org-appearance
17104 :version "24.3"
17105 :type '(choice
17106 (const :tag "Use the image width" t)
17107 (integer :tag "Use a number of pixels")
17108 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17109 (const :tag "Use #+ATTR* or don't resize" nil)))
17111 (defcustom org-agenda-inhibit-startup t
17112 "Inhibit startup when preparing agenda buffers.
17113 When this variable is `t' (the default), the initialization of
17114 the Org agenda buffers is inhibited: e.g. the visibility state
17115 is not set, the tables are not re-aligned, etc."
17116 :type 'boolean
17117 :version "24.3"
17118 :group 'org-agenda)
17120 (defun org-duration-string-to-minutes (s &optional output-to-string)
17121 "Convert a duration string S to minutes.
17123 A bare number is interpreted as minutes, modifiers can be set by
17124 customizing `org-effort-durations' (which see).
17126 Entries containing a colon are interpreted as H:MM by
17127 `org-hh:mm-string-to-minutes'."
17128 (let ((result 0)
17129 (re (concat "\\([0-9.]+\\) *\\("
17130 (regexp-opt (mapcar 'car org-effort-durations))
17131 "\\)")))
17132 (while (string-match re s)
17133 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17134 (string-to-number (match-string 1 s))))
17135 (setq s (replace-match "" nil t s)))
17136 (setq result (floor result))
17137 (incf result (org-hh:mm-string-to-minutes s))
17138 (if output-to-string (number-to-string result) result)))
17140 ;;;; Files
17142 (defun org-save-all-org-buffers ()
17143 "Save all Org-mode buffers without user confirmation."
17144 (interactive)
17145 (message "Saving all Org-mode buffers...")
17146 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17147 (when (featurep 'org-id) (org-id-locations-save))
17148 (message "Saving all Org-mode buffers... done"))
17150 (defun org-revert-all-org-buffers ()
17151 "Revert all Org-mode buffers.
17152 Prompt for confirmation when there are unsaved changes.
17153 Be sure you know what you are doing before letting this function
17154 overwrite your changes.
17156 This function is useful in a setup where one tracks org files
17157 with a version control system, to revert on one machine after pulling
17158 changes from another. I believe the procedure must be like this:
17160 1. M-x org-save-all-org-buffers
17161 2. Pull changes from the other machine, resolve conflicts
17162 3. M-x org-revert-all-org-buffers"
17163 (interactive)
17164 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17165 (error "Abort"))
17166 (save-excursion
17167 (save-window-excursion
17168 (mapc
17169 (lambda (b)
17170 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17171 (with-current-buffer b buffer-file-name))
17172 (org-pop-to-buffer-same-window b)
17173 (revert-buffer t 'no-confirm)))
17174 (buffer-list))
17175 (when (and (featurep 'org-id) org-id-track-globally)
17176 (org-id-locations-load)))))
17178 ;;;; Agenda files
17180 ;;;###autoload
17181 (defun org-switchb (&optional arg)
17182 "Switch between Org buffers.
17183 With one prefix argument, restrict available buffers to files.
17184 With two prefix arguments, restrict available buffers to agenda files.
17186 Defaults to `iswitchb' for buffer name completion.
17187 Set `org-completion-use-ido' to make it use ido instead."
17188 (interactive "P")
17189 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17190 ((equal arg '(16)) (org-buffer-list 'agenda))
17191 (t (org-buffer-list))))
17192 (org-completion-use-iswitchb org-completion-use-iswitchb)
17193 (org-completion-use-ido org-completion-use-ido))
17194 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17195 (setq org-completion-use-iswitchb t))
17196 (org-pop-to-buffer-same-window
17197 (org-icompleting-read "Org buffer: "
17198 (mapcar 'list (mapcar 'buffer-name blist))
17199 nil t))))
17201 ;;; Define some older names previously used for this functionality
17202 ;;;###autoload
17203 (defalias 'org-ido-switchb 'org-switchb)
17204 ;;;###autoload
17205 (defalias 'org-iswitchb 'org-switchb)
17207 (defun org-buffer-list (&optional predicate exclude-tmp)
17208 "Return a list of Org buffers.
17209 PREDICATE can be `export', `files' or `agenda'.
17211 export restrict the list to Export buffers.
17212 files restrict the list to buffers visiting Org files.
17213 agenda restrict the list to buffers visiting agenda files.
17215 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17216 (let* ((bfn nil)
17217 (agenda-files (and (eq predicate 'agenda)
17218 (mapcar 'file-truename (org-agenda-files t))))
17219 (filter
17220 (cond
17221 ((eq predicate 'files)
17222 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17223 ((eq predicate 'export)
17224 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17225 ((eq predicate 'agenda)
17226 (lambda (b)
17227 (with-current-buffer b
17228 (and (derived-mode-p 'org-mode)
17229 (setq bfn (buffer-file-name b))
17230 (member (file-truename bfn) agenda-files)))))
17231 (t (lambda (b) (with-current-buffer b
17232 (or (derived-mode-p 'org-mode)
17233 (string-match "\*Org .*Export"
17234 (buffer-name b)))))))))
17235 (delq nil
17236 (mapcar
17237 (lambda(b)
17238 (if (and (funcall filter b)
17239 (or (not exclude-tmp)
17240 (not (string-match "tmp" (buffer-name b)))))
17242 nil))
17243 (buffer-list)))))
17245 (defun org-agenda-files (&optional unrestricted archives)
17246 "Get the list of agenda files.
17247 Optional UNRESTRICTED means return the full list even if a restriction
17248 is currently in place.
17249 When ARCHIVES is t, include all archive files that are really being
17250 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17251 `org-agenda-archives-mode' is t."
17252 (let ((files
17253 (cond
17254 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17255 ((stringp org-agenda-files) (org-read-agenda-file-list))
17256 ((listp org-agenda-files) org-agenda-files)
17257 (t (error "Invalid value of `org-agenda-files'")))))
17258 (setq files (apply 'append
17259 (mapcar (lambda (f)
17260 (if (file-directory-p f)
17261 (directory-files
17262 f t org-agenda-file-regexp)
17263 (list f)))
17264 files)))
17265 (when org-agenda-skip-unavailable-files
17266 (setq files (delq nil
17267 (mapcar (function
17268 (lambda (file)
17269 (and (file-readable-p file) file)))
17270 files))))
17271 (when (or (eq archives t)
17272 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17273 (setq files (org-add-archive-files files)))
17274 files))
17276 (defun org-agenda-file-p (&optional file)
17277 "Return non-nil, if FILE is an agenda file.
17278 If FILE is omitted, use the file associated with the current
17279 buffer."
17280 (member (or file (buffer-file-name))
17281 (org-agenda-files t)))
17283 (defun org-edit-agenda-file-list ()
17284 "Edit the list of agenda files.
17285 Depending on setup, this either uses customize to edit the variable
17286 `org-agenda-files', or it visits the file that is holding the list. In the
17287 latter case, the buffer is set up in a way that saving it automatically kills
17288 the buffer and restores the previous window configuration."
17289 (interactive)
17290 (if (stringp org-agenda-files)
17291 (let ((cw (current-window-configuration)))
17292 (find-file org-agenda-files)
17293 (org-set-local 'org-window-configuration cw)
17294 (org-add-hook 'after-save-hook
17295 (lambda ()
17296 (set-window-configuration
17297 (prog1 org-window-configuration
17298 (kill-buffer (current-buffer))))
17299 (org-install-agenda-files-menu)
17300 (message "New agenda file list installed"))
17301 nil 'local)
17302 (message "%s" (substitute-command-keys
17303 "Edit list and finish with \\[save-buffer]")))
17304 (customize-variable 'org-agenda-files)))
17306 (defun org-store-new-agenda-file-list (list)
17307 "Set new value for the agenda file list and save it correctly."
17308 (if (stringp org-agenda-files)
17309 (let ((fe (org-read-agenda-file-list t)) b u)
17310 (while (setq b (find-buffer-visiting org-agenda-files))
17311 (kill-buffer b))
17312 (with-temp-file org-agenda-files
17313 (insert
17314 (mapconcat
17315 (lambda (f) ;; Keep un-expanded entries.
17316 (if (setq u (assoc f fe))
17317 (cdr u)
17319 list "\n")
17320 "\n")))
17321 (let ((org-mode-hook nil) (org-inhibit-startup t)
17322 (org-insert-mode-line-in-empty-file nil))
17323 (setq org-agenda-files list)
17324 (customize-save-variable 'org-agenda-files org-agenda-files))))
17326 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17327 "Read the list of agenda files from a file.
17328 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17329 filenames, used by `org-store-new-agenda-file-list' to write back
17330 un-expanded file names."
17331 (when (file-directory-p org-agenda-files)
17332 (error "`org-agenda-files' cannot be a single directory"))
17333 (when (stringp org-agenda-files)
17334 (with-temp-buffer
17335 (insert-file-contents org-agenda-files)
17336 (mapcar
17337 (lambda (f)
17338 (let ((e (expand-file-name (substitute-in-file-name f)
17339 org-directory)))
17340 (if pair-with-expansion
17341 (cons e f)
17342 e)))
17343 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17345 ;;;###autoload
17346 (defun org-cycle-agenda-files ()
17347 "Cycle through the files in `org-agenda-files'.
17348 If the current buffer visits an agenda file, find the next one in the list.
17349 If the current buffer does not, find the first agenda file."
17350 (interactive)
17351 (let* ((fs (org-agenda-files t))
17352 (files (append fs (list (car fs))))
17353 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17354 file)
17355 (unless files (error "No agenda files"))
17356 (catch 'exit
17357 (while (setq file (pop files))
17358 (if (equal (file-truename file) tcf)
17359 (when (car files)
17360 (find-file (car files))
17361 (throw 'exit t))))
17362 (find-file (car fs)))
17363 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17365 (defun org-agenda-file-to-front (&optional to-end)
17366 "Move/add the current file to the top of the agenda file list.
17367 If the file is not present in the list, it is added to the front. If it is
17368 present, it is moved there. With optional argument TO-END, add/move to the
17369 end of the list."
17370 (interactive "P")
17371 (let ((org-agenda-skip-unavailable-files nil)
17372 (file-alist (mapcar (lambda (x)
17373 (cons (file-truename x) x))
17374 (org-agenda-files t)))
17375 (ctf (file-truename
17376 (or buffer-file-name
17377 (error "Please save the current buffer to a file"))))
17378 x had)
17379 (setq x (assoc ctf file-alist) had x)
17381 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17382 (if to-end
17383 (setq file-alist (append (delq x file-alist) (list x)))
17384 (setq file-alist (cons x (delq x file-alist))))
17385 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17386 (org-install-agenda-files-menu)
17387 (message "File %s to %s of agenda file list"
17388 (if had "moved" "added") (if to-end "end" "front"))))
17390 (defun org-remove-file (&optional file)
17391 "Remove current file from the list of files in variable `org-agenda-files'.
17392 These are the files which are being checked for agenda entries.
17393 Optional argument FILE means use this file instead of the current."
17394 (interactive)
17395 (let* ((org-agenda-skip-unavailable-files nil)
17396 (file (or file buffer-file-name
17397 (error "Current buffer does not visit a file")))
17398 (true-file (file-truename file))
17399 (afile (abbreviate-file-name file))
17400 (files (delq nil (mapcar
17401 (lambda (x)
17402 (if (equal true-file
17403 (file-truename x))
17404 nil x))
17405 (org-agenda-files t)))))
17406 (if (not (= (length files) (length (org-agenda-files t))))
17407 (progn
17408 (org-store-new-agenda-file-list files)
17409 (org-install-agenda-files-menu)
17410 (message "Removed file: %s" afile))
17411 (message "File was not in list: %s (not removed)" afile))))
17413 (defun org-file-menu-entry (file)
17414 (vector file (list 'find-file file) t))
17416 (defun org-check-agenda-file (file)
17417 "Make sure FILE exists. If not, ask user what to do."
17418 (when (not (file-exists-p file))
17419 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17420 (abbreviate-file-name file))
17421 (let ((r (downcase (read-char-exclusive))))
17422 (cond
17423 ((equal r ?r)
17424 (org-remove-file file)
17425 (throw 'nextfile t))
17426 (t (error "Abort"))))))
17428 (defun org-get-agenda-file-buffer (file)
17429 "Get a buffer visiting FILE. If the buffer needs to be created, add
17430 it to the list of buffers which might be released later."
17431 (let ((buf (org-find-base-buffer-visiting file)))
17432 (if buf
17433 buf ; just return it
17434 ;; Make a new buffer and remember it
17435 (setq buf (find-file-noselect file))
17436 (if buf (push buf org-agenda-new-buffers))
17437 buf)))
17439 (defun org-release-buffers (blist)
17440 "Release all buffers in list, asking the user for confirmation when needed.
17441 When a buffer is unmodified, it is just killed. When modified, it is saved
17442 \(if the user agrees) and then killed."
17443 (let (buf file)
17444 (while (setq buf (pop blist))
17445 (setq file (buffer-file-name buf))
17446 (when (and (buffer-modified-p buf)
17447 file
17448 (y-or-n-p (format "Save file %s? " file)))
17449 (with-current-buffer buf (save-buffer)))
17450 (kill-buffer buf))))
17452 (defun org-agenda-prepare-buffers (files)
17453 "Create buffers for all agenda files, protect archived trees and comments."
17454 (interactive)
17455 (let ((pa '(:org-archived t))
17456 (pc '(:org-comment t))
17457 (pall '(:org-archived t :org-comment t))
17458 (inhibit-read-only t)
17459 (org-inhibit-startup org-agenda-inhibit-startup)
17460 (rea (concat ":" org-archive-tag ":"))
17461 bmp file re)
17462 (save-excursion
17463 (save-restriction
17464 (while (setq file (pop files))
17465 (catch 'nextfile
17466 (if (bufferp file)
17467 (set-buffer file)
17468 (org-check-agenda-file file)
17469 (set-buffer (org-get-agenda-file-buffer file)))
17470 (widen)
17471 (setq bmp (buffer-modified-p))
17472 (org-refresh-category-properties)
17473 (org-refresh-properties org-effort-property 'org-effort)
17474 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17475 (setq org-todo-keywords-for-agenda
17476 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17477 (setq org-done-keywords-for-agenda
17478 (append org-done-keywords-for-agenda org-done-keywords))
17479 (setq org-todo-keyword-alist-for-agenda
17480 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17481 (setq org-drawers-for-agenda
17482 (append org-drawers-for-agenda org-drawers))
17483 (setq org-tag-alist-for-agenda
17484 (append org-tag-alist-for-agenda org-tag-alist))
17486 (save-excursion
17487 (remove-text-properties (point-min) (point-max) pall)
17488 (when org-agenda-skip-archived-trees
17489 (goto-char (point-min))
17490 (while (re-search-forward rea nil t)
17491 (if (org-at-heading-p t)
17492 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17493 (goto-char (point-min))
17494 (setq re (format org-heading-keyword-regexp-format
17495 org-comment-string))
17496 (while (re-search-forward re nil t)
17497 (add-text-properties
17498 (match-beginning 0) (org-end-of-subtree t) pc)))
17499 (set-buffer-modified-p bmp)))))
17500 (setq org-todo-keywords-for-agenda
17501 (org-uniquify org-todo-keywords-for-agenda))
17502 (setq org-todo-keyword-alist-for-agenda
17503 (org-uniquify org-todo-keyword-alist-for-agenda)
17504 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17508 ;;;; CDLaTeX minor mode
17510 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17511 "Keymap for the minor `org-cdlatex-mode'.")
17513 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17514 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17515 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17516 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17517 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17519 (defvar org-cdlatex-texmathp-advice-is-done nil
17520 "Flag remembering if we have applied the advice to texmathp already.")
17522 (define-minor-mode org-cdlatex-mode
17523 "Toggle the minor `org-cdlatex-mode'.
17524 This mode supports entering LaTeX environment and math in LaTeX fragments
17525 in Org-mode.
17526 \\{org-cdlatex-mode-map}"
17527 nil " OCDL" nil
17528 (when org-cdlatex-mode
17529 (require 'cdlatex)
17530 (run-hooks 'cdlatex-mode-hook)
17531 (cdlatex-compute-tables))
17532 (unless org-cdlatex-texmathp-advice-is-done
17533 (setq org-cdlatex-texmathp-advice-is-done t)
17534 (defadvice texmathp (around org-math-always-on activate)
17535 "Always return t in org-mode buffers.
17536 This is because we want to insert math symbols without dollars even outside
17537 the LaTeX math segments. If Orgmode thinks that point is actually inside
17538 an embedded LaTeX fragment, let texmathp do its job.
17539 \\[org-cdlatex-mode-map]"
17540 (interactive)
17541 (let (p)
17542 (cond
17543 ((not (derived-mode-p 'org-mode)) ad-do-it)
17544 ((eq this-command 'cdlatex-math-symbol)
17545 (setq ad-return-value t
17546 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17548 (let ((p (org-inside-LaTeX-fragment-p)))
17549 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17550 (setq ad-return-value t
17551 texmathp-why '("Org-mode embedded math" . 0))
17552 (if p ad-do-it)))))))))
17554 (defun turn-on-org-cdlatex ()
17555 "Unconditionally turn on `org-cdlatex-mode'."
17556 (org-cdlatex-mode 1))
17558 (defun org-try-cdlatex-tab ()
17559 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17560 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17561 - inside a LaTeX fragment, or
17562 - after the first word in a line, where an abbreviation expansion could
17563 insert a LaTeX environment."
17564 (when org-cdlatex-mode
17565 (cond
17566 ;; Before any word on the line: No expansion possible.
17567 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17568 ;; Just after first word on the line: Expand it. Make sure it
17569 ;; cannot happen on headlines, though.
17570 ((save-excursion
17571 (skip-chars-backward "a-zA-Z0-9*")
17572 (skip-chars-backward " \t")
17573 (and (bolp) (not (org-at-heading-p))))
17574 (cdlatex-tab) t)
17575 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17577 (defun org-cdlatex-underscore-caret (&optional arg)
17578 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17579 Revert to the normal definition outside of these fragments."
17580 (interactive "P")
17581 (if (org-inside-LaTeX-fragment-p)
17582 (call-interactively 'cdlatex-sub-superscript)
17583 (let (org-cdlatex-mode)
17584 (call-interactively (key-binding (vector last-input-event))))))
17586 (defun org-cdlatex-math-modify (&optional arg)
17587 "Execute `cdlatex-math-modify' in LaTeX fragments.
17588 Revert to the normal definition outside of these fragments."
17589 (interactive "P")
17590 (if (org-inside-LaTeX-fragment-p)
17591 (call-interactively 'cdlatex-math-modify)
17592 (let (org-cdlatex-mode)
17593 (call-interactively (key-binding (vector last-input-event))))))
17597 ;;;; LaTeX fragments
17599 (defvar org-latex-regexps
17600 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17601 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17602 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17603 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17604 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17605 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17606 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17607 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17608 "Regular expressions for matching embedded LaTeX.")
17610 (defun org-inside-LaTeX-fragment-p ()
17611 "Test if point is inside a LaTeX fragment.
17612 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17613 sequence appearing also before point.
17614 Even though the matchers for math are configurable, this function assumes
17615 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17616 delimiters are skipped when they have been removed by customization.
17617 The return value is nil, or a cons cell with the delimiter and the
17618 position of this delimiter.
17620 This function does a reasonably good job, but can locally be fooled by
17621 for example currency specifications. For example it will assume being in
17622 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17623 fragments that are properly closed, but during editing, we have to live
17624 with the uncertainty caused by missing closing delimiters. This function
17625 looks only before point, not after."
17626 (catch 'exit
17627 (let ((pos (point))
17628 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17629 (lim (progn
17630 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17631 (point)))
17632 dd-on str (start 0) m re)
17633 (goto-char pos)
17634 (when dodollar
17635 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17636 re (nth 1 (assoc "$" org-latex-regexps)))
17637 (while (string-match re str start)
17638 (cond
17639 ((= (match-end 0) (length str))
17640 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17641 ((= (match-end 0) (- (length str) 5))
17642 (throw 'exit nil))
17643 (t (setq start (match-end 0))))))
17644 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17645 (goto-char pos)
17646 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17647 (and (match-beginning 2) (throw 'exit nil))
17648 ;; count $$
17649 (while (re-search-backward "\\$\\$" lim t)
17650 (setq dd-on (not dd-on)))
17651 (goto-char pos)
17652 (if dd-on (cons "$$" m))))))
17654 (defun org-inside-latex-macro-p ()
17655 "Is point inside a LaTeX macro or its arguments?"
17656 (save-match-data
17657 (org-in-regexp
17658 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17660 (defvar org-latex-fragment-image-overlays nil
17661 "List of overlays carrying the images of latex fragments.")
17662 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17664 (defun org-remove-latex-fragment-image-overlays ()
17665 "Remove all overlays with LaTeX fragment images in current buffer."
17666 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17667 (setq org-latex-fragment-image-overlays nil))
17669 (defun org-preview-latex-fragment (&optional subtree)
17670 "Preview the LaTeX fragment at point, or all locally or globally.
17671 If the cursor is in a LaTeX fragment, create the image and overlay
17672 it over the source code. If there is no fragment at point, display
17673 all fragments in the current text, from one headline to the next. With
17674 prefix SUBTREE, display all fragments in the current subtree. With a
17675 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17676 the cursor is before the first headline,
17677 display all fragments in the buffer.
17678 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17679 (interactive "P")
17680 (unless buffer-file-name
17681 (error "Can't preview LaTeX fragment in a non-file buffer"))
17682 (org-remove-latex-fragment-image-overlays)
17683 (save-excursion
17684 (save-restriction
17685 (let (beg end at msg)
17686 (cond
17687 ((or (equal subtree '(16))
17688 (not (save-excursion
17689 (re-search-backward org-outline-regexp-bol nil t))))
17690 (setq beg (point-min) end (point-max)
17691 msg "Creating images for buffer...%s"))
17692 ((equal subtree '(4))
17693 (org-back-to-heading)
17694 (setq beg (point) end (org-end-of-subtree t)
17695 msg "Creating images for subtree...%s"))
17697 (if (setq at (org-inside-LaTeX-fragment-p))
17698 (goto-char (max (point-min) (- (cdr at) 2)))
17699 (org-back-to-heading))
17700 (setq beg (point) end (progn (outline-next-heading) (point))
17701 msg (if at "Creating image...%s"
17702 "Creating images for entry...%s"))))
17703 (message msg "")
17704 (narrow-to-region beg end)
17705 (goto-char beg)
17706 (org-format-latex
17707 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17708 (file-name-nondirectory
17709 buffer-file-name)))
17710 default-directory 'overlays msg at 'forbuffer
17711 org-latex-create-formula-image-program)
17712 (message msg "done. Use `C-c C-c' to remove images.")))))
17714 (defun org-format-latex (prefix &optional dir overlays msg at
17715 forbuffer processing-type)
17716 "Replace LaTeX fragments with links to an image, and produce images.
17717 Some of the options can be changed using the variable
17718 `org-format-latex-options'."
17719 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17720 (let* ((prefixnodir (file-name-nondirectory prefix))
17721 (absprefix (expand-file-name prefix dir))
17722 (todir (file-name-directory absprefix))
17723 (opt org-format-latex-options)
17724 (optnew org-format-latex-options)
17725 (matchers (plist-get opt :matchers))
17726 (re-list org-latex-regexps)
17727 (cnt 0) txt hash link beg end re e checkdir
17728 string
17729 m n block-type block linkfile movefile ov)
17730 ;; Check the different regular expressions
17731 (while (setq e (pop re-list))
17732 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17733 block (if block-type "\n\n" ""))
17734 (when (member m matchers)
17735 (goto-char (point-min))
17736 (while (re-search-forward re nil t)
17737 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17738 (or (not overlays)
17739 (not (eq (get-char-property (match-beginning n)
17740 'org-overlay-type)
17741 'org-latex-overlay))))
17742 (cond
17743 ((eq processing-type 'verbatim))
17744 ((eq processing-type 'mathjax)
17745 ;; Prepare for MathJax processing.
17746 (setq string (match-string n))
17747 (when (member m '("$" "$1"))
17748 (save-excursion
17749 (delete-region (match-beginning n) (match-end n))
17750 (goto-char (match-beginning n))
17751 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17752 ((or (eq processing-type 'dvipng)
17753 (eq processing-type 'imagemagick))
17754 ;; Process to an image.
17755 (setq txt (match-string n)
17756 beg (match-beginning n) end (match-end n)
17757 cnt (1+ cnt))
17758 (let ((face (face-at-point))
17759 (fg (plist-get opt :foreground))
17760 (bg (plist-get opt :background))
17761 ;; Ensure full list is printed.
17762 print-length print-level)
17763 (when forbuffer
17764 ;; Get the colors from the face at point.
17765 (goto-char beg)
17766 (when (eq fg 'auto)
17767 (setq fg (face-attribute face :foreground nil 'default)))
17768 (when (eq bg 'auto)
17769 (setq bg (face-attribute face :background nil 'default)))
17770 (setq optnew (copy-sequence opt))
17771 (plist-put optnew :foreground fg)
17772 (plist-put optnew :background bg))
17773 (setq hash (sha1 (prin1-to-string
17774 (list org-format-latex-header
17775 org-latex-default-packages-alist
17776 org-latex-packages-alist
17777 org-format-latex-options
17778 forbuffer txt fg bg)))
17779 linkfile (format "%s_%s.png" prefix hash)
17780 movefile (format "%s_%s.png" absprefix hash)))
17781 (setq link (concat block "[[file:" linkfile "]]" block))
17782 (if msg (message msg cnt))
17783 (goto-char beg)
17784 (unless checkdir ; Ensure the directory exists.
17785 (setq checkdir t)
17786 (or (file-directory-p todir) (make-directory todir t)))
17787 (unless (file-exists-p movefile)
17788 (org-create-formula-image
17789 txt movefile optnew forbuffer processing-type))
17790 (if overlays
17791 (progn
17792 (mapc (lambda (o)
17793 (if (eq (overlay-get o 'org-overlay-type)
17794 'org-latex-overlay)
17795 (delete-overlay o)))
17796 (overlays-in beg end))
17797 (setq ov (make-overlay beg end))
17798 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17799 (if (featurep 'xemacs)
17800 (progn
17801 (overlay-put ov 'invisible t)
17802 (overlay-put
17803 ov 'end-glyph
17804 (make-glyph (vector 'png :file movefile))))
17805 (overlay-put
17806 ov 'display
17807 (list 'image :type 'png :file movefile :ascent 'center)))
17808 (push ov org-latex-fragment-image-overlays)
17809 (goto-char end))
17810 (delete-region beg end)
17811 (insert (org-add-props link
17812 (list 'org-latex-src
17813 (replace-regexp-in-string
17814 "\"" "" txt)
17815 'org-latex-src-embed-type
17816 (if block-type 'paragraph 'character))))))
17817 ((eq processing-type 'mathml)
17818 ;; Process to MathML
17819 (unless (save-match-data (org-format-latex-mathml-available-p))
17820 (error "LaTeX to MathML converter not configured"))
17821 (setq txt (match-string n)
17822 beg (match-beginning n) end (match-end n)
17823 cnt (1+ cnt))
17824 (if msg (message msg cnt))
17825 (goto-char beg)
17826 (delete-region beg end)
17827 (insert (org-format-latex-as-mathml
17828 txt block-type prefix dir)))
17830 (error "Unknown conversion type %s for latex fragments"
17831 processing-type)))))))))
17833 (defun org-create-math-formula (latex-frag &optional mathml-file)
17834 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17835 Use `org-latex-to-mathml-convert-command'. If the conversion is
17836 sucessful, return the portion between \"<math...> </math>\"
17837 elements otherwise return nil. When MATHML-FILE is specified,
17838 write the results in to that file. When invoked as an
17839 interactive command, prompt for LATEX-FRAG, with initial value
17840 set to the current active region and echo the results for user
17841 inspection."
17842 (interactive (list (let ((frag (when (org-region-active-p)
17843 (buffer-substring-no-properties
17844 (region-beginning) (region-end)))))
17845 (read-string "LaTeX Fragment: " frag nil frag))))
17846 (unless latex-frag (error "Invalid latex-frag"))
17847 (let* ((tmp-in-file (file-relative-name
17848 (make-temp-name (expand-file-name "ltxmathml-in"))))
17849 (ignore (write-region latex-frag nil tmp-in-file))
17850 (tmp-out-file (file-relative-name
17851 (make-temp-name (expand-file-name "ltxmathml-out"))))
17852 (cmd (format-spec
17853 org-latex-to-mathml-convert-command
17854 `((?j . ,(shell-quote-argument
17855 (expand-file-name org-latex-to-mathml-jar-file)))
17856 (?I . ,(shell-quote-argument tmp-in-file))
17857 (?o . ,(shell-quote-argument tmp-out-file)))))
17858 mathml shell-command-output)
17859 (when (org-called-interactively-p 'any)
17860 (unless (org-format-latex-mathml-available-p)
17861 (error "LaTeX to MathML converter not configured")))
17862 (message "Running %s" cmd)
17863 (setq shell-command-output (shell-command-to-string cmd))
17864 (setq mathml
17865 (when (file-readable-p tmp-out-file)
17866 (with-current-buffer (find-file-noselect tmp-out-file t)
17867 (goto-char (point-min))
17868 (when (re-search-forward
17869 (concat
17870 (regexp-quote
17871 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17872 "\\(.\\|\n\\)*"
17873 (regexp-quote "</math>")) nil t)
17874 (prog1 (match-string 0) (kill-buffer))))))
17875 (cond
17876 (mathml
17877 (setq mathml
17878 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17879 (when mathml-file
17880 (write-region mathml nil mathml-file))
17881 (when (org-called-interactively-p 'any)
17882 (message mathml)))
17883 ((message "LaTeX to MathML conversion failed")
17884 (message shell-command-output)))
17885 (delete-file tmp-in-file)
17886 (when (file-exists-p tmp-out-file)
17887 (delete-file tmp-out-file))
17888 mathml))
17890 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17891 prefix &optional dir)
17892 "Use `org-create-math-formula' but check local cache first."
17893 (let* ((absprefix (expand-file-name prefix dir))
17894 (print-length nil) (print-level nil)
17895 (formula-id (concat
17896 "formula-"
17897 (sha1
17898 (prin1-to-string
17899 (list latex-frag
17900 org-latex-to-mathml-convert-command)))))
17901 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17902 (formula-cache-dir (file-name-directory formula-cache)))
17904 (unless (file-directory-p formula-cache-dir)
17905 (make-directory formula-cache-dir t))
17907 (unless (file-exists-p formula-cache)
17908 (org-create-math-formula latex-frag formula-cache))
17910 (if (file-exists-p formula-cache)
17911 ;; Successful conversion. Return the link to MathML file.
17912 (org-add-props
17913 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17914 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17915 'org-latex-src-embed-type (if latex-frag-type
17916 'paragraph 'character)))
17917 ;; Failed conversion. Return the LaTeX fragment verbatim
17918 latex-frag)))
17920 (defun org-create-formula-image (string tofile options buffer &optional type)
17921 "Create an image from LaTeX source using dvipng or convert.
17922 This function calls either `org-create-formula-image-with-dvipng'
17923 or `org-create-formula-image-with-imagemagick' depending on the
17924 value of `org-latex-create-formula-image-program' or on the value
17925 of the optional TYPE variable.
17927 Note: ultimately these two function should be combined as they
17928 share a good deal of logic."
17929 (org-check-external-command
17930 "latex" "needed to convert LaTeX fragments to images")
17931 (funcall
17932 (case (or type org-latex-create-formula-image-program)
17933 ('dvipng
17934 (org-check-external-command
17935 "dvipng" "needed to convert LaTeX fragments to images")
17936 #'org-create-formula-image-with-dvipng)
17937 ('imagemagick
17938 (org-check-external-command
17939 "convert" "you need to install imagemagick")
17940 #'org-create-formula-image-with-imagemagick)
17941 (t (error
17942 "invalid value of `org-latex-create-formula-image-program'")))
17943 string tofile options buffer))
17945 ;; This function borrows from Ganesh Swami's latex2png.el
17946 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17947 "This calls dvipng."
17948 (let* ((tmpdir (if (featurep 'xemacs)
17949 (temp-directory)
17950 temporary-file-directory))
17951 (texfilebase (make-temp-name
17952 (expand-file-name "orgtex" tmpdir)))
17953 (texfile (concat texfilebase ".tex"))
17954 (dvifile (concat texfilebase ".dvi"))
17955 (pngfile (concat texfilebase ".png"))
17956 (fnh (if (featurep 'xemacs)
17957 (font-height (face-font 'default))
17958 (face-attribute 'default :height nil)))
17959 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17960 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17961 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17962 "Black"))
17963 (bg (or (plist-get options (if buffer :background :html-background))
17964 "Transparent")))
17965 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17966 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17967 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17968 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17969 (with-temp-file texfile
17970 (require 'ox-latex)
17971 (insert (org-latex-guess-inputenc
17972 (org-splice-latex-header
17973 org-format-latex-header
17974 org-latex-default-packages-alist
17975 org-latex-packages-alist t)))
17976 (insert "\n\\begin{document}\n" string "\n\\end{document}\n"))
17977 (let ((dir default-directory))
17978 (condition-case nil
17979 (progn
17980 (cd tmpdir)
17981 (call-process "latex" nil nil nil texfile))
17982 (error nil))
17983 (cd dir))
17984 (if (not (file-exists-p dvifile))
17985 (progn (message "Failed to create dvi file from %s" texfile) nil)
17986 (condition-case nil
17987 (if (featurep 'xemacs)
17988 (call-process "dvipng" nil nil nil
17989 "-fg" fg "-bg" bg
17990 "-T" "tight"
17991 "-o" pngfile
17992 dvifile)
17993 (call-process "dvipng" nil nil nil
17994 "-fg" fg "-bg" bg
17995 "-D" dpi
17996 ;;"-x" scale "-y" scale
17997 "-T" "tight"
17998 "-o" pngfile
17999 dvifile))
18000 (error nil))
18001 (if (not (file-exists-p pngfile))
18002 (if org-format-latex-signal-error
18003 (error "Failed to create png file from %s" texfile)
18004 (message "Failed to create png file from %s" texfile)
18005 nil)
18006 ;; Use the requested file name and clean up
18007 (copy-file pngfile tofile 'replace)
18008 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18009 (if (file-exists-p (concat texfilebase e))
18010 (delete-file (concat texfilebase e))))
18011 pngfile))))
18013 (defvar org-latex-pdf-process) ; From ox-latex.el
18014 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18015 "This calls convert, which is included into imagemagick."
18016 (let* ((tmpdir (if (featurep 'xemacs)
18017 (temp-directory)
18018 temporary-file-directory))
18019 (texfilebase (make-temp-name
18020 (expand-file-name "orgtex" tmpdir)))
18021 (texfile (concat texfilebase ".tex"))
18022 (pdffile (concat texfilebase ".pdf"))
18023 (pngfile (concat texfilebase ".png"))
18024 (fnh (if (featurep 'xemacs)
18025 (font-height (face-font 'default))
18026 (face-attribute 'default :height nil)))
18027 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18028 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18029 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18030 "black"))
18031 (bg (or (plist-get options (if buffer :background :html-background))
18032 "white")))
18033 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18034 (setq fg (org-latex-color-format fg)))
18035 (if (eq bg 'default) (setq bg (org-latex-color :background))
18036 (setq bg (org-latex-color-format
18037 (if (string= bg "Transparent") "white" bg))))
18038 (with-temp-file texfile
18039 (require 'ox-latex)
18040 (insert (org-latex-guess-inputenc
18041 (org-splice-latex-header
18042 org-format-latex-header
18043 org-latex-default-packages-alist
18044 org-latex-packages-alist t)))
18045 (insert "\n\\begin{document}\n"
18046 "\\definecolor{fg}{rgb}{" fg "}\n"
18047 "\\definecolor{bg}{rgb}{" bg "}\n"
18048 "\n\\pagecolor{bg}\n"
18049 "\n{\\color{fg}\n"
18050 string
18051 "\n}\n"
18052 "\n\\end{document}\n"))
18053 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18054 (condition-case nil
18055 (progn
18056 (cd tmpdir)
18057 (setq cmds org-latex-pdf-process)
18058 (while cmds
18059 (setq latex-frags-cmds (pop cmds))
18060 (if (listp latex-frags-cmds)
18061 (setq cmds nil)
18062 (setq latex-frags-cmds (list (car org-latex-pdf-process)))))
18063 (while latex-frags-cmds
18064 (setq cmd (pop latex-frags-cmds))
18065 (while (string-match "%b" cmd)
18066 (setq cmd (replace-match
18067 (save-match-data
18068 (shell-quote-argument texfile))
18069 t t cmd)))
18070 (while (string-match "%f" cmd)
18071 (setq cmd (replace-match
18072 (save-match-data
18073 (shell-quote-argument
18074 (file-name-nondirectory texfile)))
18075 t t cmd)))
18076 (while (string-match "%o" cmd)
18077 (setq cmd (replace-match
18078 (save-match-data
18079 (shell-quote-argument
18080 (file-name-directory texfile)))
18081 t t cmd)))
18082 (setq cmd (split-string cmd))
18083 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18084 (error nil))
18085 (cd dir))
18086 (if (not (file-exists-p pdffile))
18087 (progn (message "Failed to create pdf file from %s" texfile) nil)
18088 (condition-case nil
18089 (if (featurep 'xemacs)
18090 (call-process "convert" nil nil nil
18091 "-density" "96"
18092 "-trim"
18093 "-antialias"
18094 pdffile
18095 "-quality" "100"
18096 ;; "-sharpen" "0x1.0"
18097 pngfile)
18098 (call-process "convert" nil nil nil
18099 "-density" dpi
18100 "-trim"
18101 "-antialias"
18102 pdffile
18103 "-quality" "100"
18104 ;; "-sharpen" "0x1.0"
18105 pngfile))
18106 (error nil))
18107 (if (not (file-exists-p pngfile))
18108 (if org-format-latex-signal-error
18109 (error "Failed to create png file from %s" texfile)
18110 (message "Failed to create png file from %s" texfile)
18111 nil)
18112 ;; Use the requested file name and clean up
18113 (copy-file pngfile tofile 'replace)
18114 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18115 (if (file-exists-p (concat texfilebase e))
18116 (delete-file (concat texfilebase e))))
18117 pngfile))))
18119 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18120 "Fill a LaTeX header template TPL.
18121 In the template, the following place holders will be recognized:
18123 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18124 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18125 [PACKAGES] \\usepackage statements for PKG
18126 [NO-PACKAGES] do not include PKG
18127 [EXTRA] the string EXTRA
18128 [NO-EXTRA] do not include EXTRA
18130 For backward compatibility, if both the positive and the negative place
18131 holder is missing, the positive one (without the \"NO-\") will be
18132 assumed to be present at the end of the template.
18133 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18134 EXTRA is a string.
18135 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18136 (let (rpl (end ""))
18137 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18138 (setq rpl (if (or (match-end 1) (not def-pkg))
18139 "" (org-latex-packages-to-string def-pkg snippets-p t))
18140 tpl (replace-match rpl t t tpl))
18141 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18143 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18144 (setq rpl (if (or (match-end 1) (not pkg))
18145 "" (org-latex-packages-to-string pkg snippets-p t))
18146 tpl (replace-match rpl t t tpl))
18147 (if pkg (setq end
18148 (concat end "\n"
18149 (org-latex-packages-to-string pkg snippets-p)))))
18151 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18152 (setq rpl (if (or (match-end 1) (not extra))
18153 "" (concat extra "\n"))
18154 tpl (replace-match rpl t t tpl))
18155 (if (and extra (string-match "\\S-" extra))
18156 (setq end (concat end "\n" extra))))
18158 (if (string-match "\\S-" end)
18159 (concat tpl "\n" end)
18160 tpl)))
18162 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18163 "Turn an alist of packages into a string with the \\usepackage macros."
18164 (setq pkg (mapconcat (lambda(p)
18165 (cond
18166 ((stringp p) p)
18167 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18168 (format "%% Package %s omitted" (cadr p)))
18169 ((equal "" (car p))
18170 (format "\\usepackage{%s}" (cadr p)))
18172 (format "\\usepackage[%s]{%s}"
18173 (car p) (cadr p)))))
18175 "\n"))
18176 (if newline (concat pkg "\n") pkg))
18178 (defun org-dvipng-color (attr)
18179 "Return a RGB color specification for dvipng."
18180 (apply 'format "rgb %s %s %s"
18181 (mapcar 'org-normalize-color
18182 (if (featurep 'xemacs)
18183 (color-rgb-components
18184 (face-property 'default
18185 (cond ((eq attr :foreground) 'foreground)
18186 ((eq attr :background) 'background))))
18187 (color-values (face-attribute 'default attr nil))))))
18189 (defun org-dvipng-color-format (color-name)
18190 "Convert COLOR-NAME to a RGB color value for dvipng."
18191 (apply 'format "rgb %s %s %s"
18192 (mapcar 'org-normalize-color
18193 (color-values color-name))))
18195 (defun org-latex-color (attr)
18196 "Return a RGB color for the LaTeX color package."
18197 (apply 'format "%s,%s,%s"
18198 (mapcar 'org-normalize-color
18199 (if (featurep 'xemacs)
18200 (color-rgb-components
18201 (face-property 'default
18202 (cond ((eq attr :foreground) 'foreground)
18203 ((eq attr :background) 'background))))
18204 (color-values (face-attribute 'default attr nil))))))
18206 (defun org-latex-color-format (color-name)
18207 "Convert COLOR-NAME to a RGB color value."
18208 (apply 'format "%s,%s,%s"
18209 (mapcar 'org-normalize-color
18210 (color-values color-name))))
18212 (defun org-normalize-color (value)
18213 "Return string to be used as color value for an RGB component."
18214 (format "%g" (/ value 65535.0)))
18218 ;; Image display
18220 (defvar org-inline-image-overlays nil)
18221 (make-variable-buffer-local 'org-inline-image-overlays)
18223 (defun org-toggle-inline-images (&optional include-linked)
18224 "Toggle the display of inline images.
18225 INCLUDE-LINKED is passed to `org-display-inline-images'."
18226 (interactive "P")
18227 (if org-inline-image-overlays
18228 (progn
18229 (org-remove-inline-images)
18230 (message "Inline image display turned off"))
18231 (org-display-inline-images include-linked)
18232 (if (and (org-called-interactively-p)
18233 org-inline-image-overlays)
18234 (message "%d images displayed inline"
18235 (length org-inline-image-overlays))
18236 (message "No images to display inline"))))
18238 (defun org-redisplay-inline-images ()
18239 "Refresh the display of inline images."
18240 (interactive)
18241 (if (not org-inline-image-overlays)
18242 (org-toggle-inline-images)
18243 (org-toggle-inline-images)
18244 (org-toggle-inline-images)))
18246 (defun org-display-inline-images (&optional include-linked refresh beg end)
18247 "Display inline images.
18248 Normally only links without a description part are inlined, because this
18249 is how it will work for export. When INCLUDE-LINKED is set, also links
18250 with a description part will be inlined. This can be nice for a quick
18251 look at those images, but it does not reflect what exported files will look
18252 like.
18253 When REFRESH is set, refresh existing images between BEG and END.
18254 This will create new image displays only if necessary.
18255 BEG and END default to the buffer boundaries."
18256 (interactive "P")
18257 (unless refresh
18258 (org-remove-inline-images)
18259 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18260 (save-excursion
18261 (save-restriction
18262 (widen)
18263 (setq beg (or beg (point-min)) end (or end (point-max)))
18264 (goto-char beg)
18265 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18266 (substring (org-image-file-name-regexp) 0 -2)
18267 "\\)\\]" (if include-linked "" "\\]")))
18268 old file ov img type attrwidth width)
18269 (while (re-search-forward re end t)
18270 (setq old (get-char-property-and-overlay (match-beginning 1)
18271 'org-image-overlay)
18272 file (expand-file-name
18273 (concat (or (match-string 3) "") (match-string 4))))
18274 (when (image-type-available-p 'imagemagick)
18275 (setq attrwidth (if (or (listp org-image-actual-width)
18276 (null org-image-actual-width))
18277 (save-excursion
18278 (save-match-data
18279 (when (re-search-backward
18280 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18281 (save-excursion
18282 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18283 (string-to-number (match-string 1))))))
18284 width (cond ((eq org-image-actual-width t) nil)
18285 ((null org-image-actual-width) attrwidth)
18286 ((numberp org-image-actual-width)
18287 org-image-actual-width)
18288 ((listp org-image-actual-width)
18289 (or attrwidth (car org-image-actual-width))))
18290 type (if width 'imagemagick)))
18291 (when (file-exists-p file)
18292 (if (and (car-safe old) refresh)
18293 (image-refresh (overlay-get (cdr old) 'display))
18294 (setq img (save-match-data (create-image file type nil :width width)))
18295 (when img
18296 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18297 (overlay-put ov 'display img)
18298 (overlay-put ov 'face 'default)
18299 (overlay-put ov 'org-image-overlay t)
18300 (overlay-put ov 'modification-hooks
18301 (list 'org-display-inline-remove-overlay))
18302 (push ov org-inline-image-overlays)))))))))
18304 (define-obsolete-function-alias
18305 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18307 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18308 "Remove inline-display overlay if a corresponding region is modified."
18309 (let ((inhibit-modification-hooks t))
18310 (when (and ov after)
18311 (delete ov org-inline-image-overlays)
18312 (delete-overlay ov))))
18314 (defun org-remove-inline-images ()
18315 "Remove inline display of images."
18316 (interactive)
18317 (mapc 'delete-overlay org-inline-image-overlays)
18318 (setq org-inline-image-overlays nil))
18320 ;;;; Key bindings
18322 ;; Outline functions from `outline-mode-prefix-map'
18323 ;; that can be remapped in Org:
18324 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18325 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18326 (define-key org-mode-map [remap outline-forward-same-level]
18327 'org-forward-heading-same-level)
18328 (define-key org-mode-map [remap outline-backward-same-level]
18329 'org-backward-heading-same-level)
18330 (define-key org-mode-map [remap show-branches]
18331 'org-kill-note-or-show-branches)
18332 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18333 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18334 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18336 ;; Outline functions from `outline-mode-prefix-map' that can not
18337 ;; be remapped in Org:
18339 ;; - the column "key binding" shows whether the Outline function is still
18340 ;; available in Org mode on the same key that it has been bound to in
18341 ;; Outline mode:
18342 ;; - "overridden": key used for a different functionality in Org mode
18343 ;; - else: key still bound to the same Outline function in Org mode
18345 ;; | Outline function | key binding | Org replacement |
18346 ;; |------------------------------------+-------------+-----------------------|
18347 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18348 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18349 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18350 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18351 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18352 ;; | `show-entry' | overridden | no replacement |
18353 ;; | `show-children' | `C-c C-i' | visibility cycling |
18354 ;; | `show-branches' | `C-c C-k' | still same function |
18355 ;; | `show-subtree' | overridden | visibility cycling |
18356 ;; | `show-all' | overridden | no replacement |
18357 ;; | `hide-subtree' | overridden | visibility cycling |
18358 ;; | `hide-body' | overridden | no replacement |
18359 ;; | `hide-entry' | overridden | visibility cycling |
18360 ;; | `hide-leaves' | overridden | no replacement |
18361 ;; | `hide-sublevels' | overridden | no replacement |
18362 ;; | `hide-other' | overridden | no replacement |
18364 ;; Make `C-c C-x' a prefix key
18365 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18367 ;; TAB key with modifiers
18368 (org-defkey org-mode-map "\C-i" 'org-cycle)
18369 (org-defkey org-mode-map [(tab)] 'org-cycle)
18370 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18371 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18372 ;; The following line is necessary under Suse GNU/Linux
18373 (unless (featurep 'xemacs)
18374 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18375 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18376 (define-key org-mode-map [backtab] 'org-shifttab)
18378 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18379 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18380 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18382 ;; Cursor keys with modifiers
18383 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18384 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18385 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18386 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18388 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18389 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18390 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18391 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18393 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18394 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18395 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18396 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18398 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18399 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18400 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18401 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18403 ;; Babel keys
18404 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18405 (mapc (lambda (pair)
18406 (define-key org-babel-map (car pair) (cdr pair)))
18407 org-babel-key-bindings)
18409 ;;; Extra keys for tty access.
18410 ;; We only set them when really needed because otherwise the
18411 ;; menus don't show the simple keys
18413 (when (or org-use-extra-keys
18414 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18415 (not window-system))
18416 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18417 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18418 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18419 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18420 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18421 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18422 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18423 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18424 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18425 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18426 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18427 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18428 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18429 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18430 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18431 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18432 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18433 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18434 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18435 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18436 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18437 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18438 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18439 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18440 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18441 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18442 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18443 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18445 ;; All the other keys
18447 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18448 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18449 (if (boundp 'narrow-map)
18450 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18451 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18452 (if (boundp 'narrow-map)
18453 (org-defkey narrow-map "b" 'org-narrow-to-block)
18454 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18455 (if (boundp 'narrow-map)
18456 (org-defkey narrow-map "e" 'org-narrow-to-element)
18457 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18458 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18459 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18460 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18461 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18462 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18463 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18464 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18465 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18466 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18467 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18468 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18469 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18470 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18471 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18472 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18473 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18474 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18475 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18476 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18477 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18478 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18479 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18480 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18481 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18482 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18483 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18484 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18485 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18486 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18487 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18488 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18489 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18490 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18491 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18492 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18493 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18494 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18495 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18496 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18497 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18498 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18499 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18500 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18501 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18502 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18503 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18504 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18505 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18506 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18507 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18508 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18509 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18510 (org-defkey org-mode-map "\C-c^" 'org-sort)
18511 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18512 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18513 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18514 (org-defkey org-mode-map "\C-m" 'org-return)
18515 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18516 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18517 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18518 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18519 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18520 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18521 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18522 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18523 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18524 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18525 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18526 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18527 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18528 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18529 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18530 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18531 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18532 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18533 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18534 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18535 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18536 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18537 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18539 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18540 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18541 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18543 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18544 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18545 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18546 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18547 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18548 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18549 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18550 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18551 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18552 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18553 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18554 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18555 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18556 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18557 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18558 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18559 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18560 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18561 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18562 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18563 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18564 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18565 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18567 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18568 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18569 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18570 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18571 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18573 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18575 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18577 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18578 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18580 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18583 (when (featurep 'xemacs)
18584 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18587 (defconst org-speed-commands-default
18589 ("Outline Navigation")
18590 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18591 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18592 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18593 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18594 ("u" . (org-speed-move-safe 'outline-up-heading))
18595 ("j" . org-goto)
18596 ("g" . (org-refile t))
18597 ("Outline Visibility")
18598 ("c" . org-cycle)
18599 ("C" . org-shifttab)
18600 (" " . org-display-outline-path)
18601 ("=" . org-columns)
18602 ("Outline Structure Editing")
18603 ("U" . org-shiftmetaup)
18604 ("D" . org-shiftmetadown)
18605 ("r" . org-metaright)
18606 ("l" . org-metaleft)
18607 ("R" . org-shiftmetaright)
18608 ("L" . org-shiftmetaleft)
18609 ("i" . (progn (forward-char 1) (call-interactively
18610 'org-insert-heading-respect-content)))
18611 ("^" . org-sort)
18612 ("w" . org-refile)
18613 ("a" . org-archive-subtree-default-with-confirmation)
18614 ("." . org-mark-subtree)
18615 ("#" . org-toggle-comment)
18616 ("Clock Commands")
18617 ("I" . org-clock-in)
18618 ("O" . org-clock-out)
18619 ("Meta Data Editing")
18620 ("t" . org-todo)
18621 ("," . (org-priority))
18622 ("0" . (org-priority ?\ ))
18623 ("1" . (org-priority ?A))
18624 ("2" . (org-priority ?B))
18625 ("3" . (org-priority ?C))
18626 (":" . org-set-tags-command)
18627 ("e" . org-set-effort)
18628 ("E" . org-inc-effort)
18629 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18630 (org-entry-put (point) "APPT_WARNTIME" m)))
18631 ("Agenda Views etc")
18632 ("v" . org-agenda)
18633 ("/" . org-sparse-tree)
18634 ("Misc")
18635 ("o" . org-open-at-point)
18636 ("?" . org-speed-command-help)
18637 ("<" . (org-agenda-set-restriction-lock 'subtree))
18638 (">" . (org-agenda-remove-restriction-lock))
18640 "The default speed commands.")
18642 (defun org-print-speed-command (e)
18643 (if (> (length (car e)) 1)
18644 (progn
18645 (princ "\n")
18646 (princ (car e))
18647 (princ "\n")
18648 (princ (make-string (length (car e)) ?-))
18649 (princ "\n"))
18650 (princ (car e))
18651 (princ " ")
18652 (if (symbolp (cdr e))
18653 (princ (symbol-name (cdr e)))
18654 (prin1 (cdr e)))
18655 (princ "\n")))
18657 (defun org-speed-command-help ()
18658 "Show the available speed commands."
18659 (interactive)
18660 (if (not org-use-speed-commands)
18661 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18662 (with-output-to-temp-buffer "*Help*"
18663 (princ "User-defined Speed commands\n===========================\n")
18664 (mapc 'org-print-speed-command org-speed-commands-user)
18665 (princ "\n")
18666 (princ "Built-in Speed commands\n=======================\n")
18667 (mapc 'org-print-speed-command org-speed-commands-default))
18668 (with-current-buffer "*Help*"
18669 (setq truncate-lines t))))
18671 (defun org-speed-move-safe (cmd)
18672 "Execute CMD, but make sure that the cursor always ends up in a headline.
18673 If not, return to the original position and throw an error."
18674 (interactive)
18675 (let ((pos (point)))
18676 (call-interactively cmd)
18677 (unless (and (bolp) (org-at-heading-p))
18678 (goto-char pos)
18679 (error "Boundary reached while executing %s" cmd))))
18681 (defvar org-self-insert-command-undo-counter 0)
18683 (defvar org-table-auto-blank-field) ; defined in org-table.el
18684 (defvar org-speed-command nil)
18686 (define-obsolete-function-alias
18687 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18689 (defun org-speed-command-activate (keys)
18690 "Hook for activating single-letter speed commands.
18691 `org-speed-commands-default' specifies a minimal command set.
18692 Use `org-speed-commands-user' for further customization."
18693 (when (or (and (bolp) (looking-at org-outline-regexp))
18694 (and (functionp org-use-speed-commands)
18695 (funcall org-use-speed-commands)))
18696 (cdr (assoc keys (append org-speed-commands-user
18697 org-speed-commands-default)))))
18699 (define-obsolete-function-alias
18700 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18702 (defun org-babel-speed-command-activate (keys)
18703 "Hook for activating single-letter code block commands."
18704 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18705 (cdr (assoc keys org-babel-key-bindings))))
18707 (defcustom org-speed-command-hook
18708 '(org-speed-command-default-hook org-babel-speed-command-hook)
18709 "Hook for activating speed commands at strategic locations.
18710 Hook functions are called in sequence until a valid handler is
18711 found.
18713 Each hook takes a single argument, a user-pressed command key
18714 which is also a `self-insert-command' from the global map.
18716 Within the hook, examine the cursor position and the command key
18717 and return nil or a valid handler as appropriate. Handler could
18718 be one of an interactive command, a function, or a form.
18720 Set `org-use-speed-commands' to non-nil value to enable this
18721 hook. The default setting is `org-speed-command-activate'."
18722 :group 'org-structure
18723 :version "24.1"
18724 :type 'hook)
18726 (defun org-self-insert-command (N)
18727 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18728 If the cursor is in a table looking at whitespace, the whitespace is
18729 overwritten, and the table is not marked as requiring realignment."
18730 (interactive "p")
18731 (org-check-before-invisible-edit 'insert)
18732 (cond
18733 ((and org-use-speed-commands
18734 (setq org-speed-command
18735 (run-hook-with-args-until-success
18736 'org-speed-command-hook (this-command-keys))))
18737 (cond
18738 ((commandp org-speed-command)
18739 (setq this-command org-speed-command)
18740 (call-interactively org-speed-command))
18741 ((functionp org-speed-command)
18742 (funcall org-speed-command))
18743 ((and org-speed-command (listp org-speed-command))
18744 (eval org-speed-command))
18745 (t (let (org-use-speed-commands)
18746 (call-interactively 'org-self-insert-command)))))
18747 ((and
18748 (org-table-p)
18749 (progn
18750 ;; check if we blank the field, and if that triggers align
18751 (and (featurep 'org-table) org-table-auto-blank-field
18752 (member last-command
18753 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18754 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18755 ;; got extra space, this field does not determine column width
18756 (let (org-table-may-need-update) (org-table-blank-field))
18757 ;; no extra space, this field may determine column width
18758 (org-table-blank-field)))
18760 (eq N 1)
18761 (looking-at "[^|\n]* |"))
18762 (let (org-table-may-need-update)
18763 (goto-char (1- (match-end 0)))
18764 (backward-delete-char 1)
18765 (goto-char (match-beginning 0))
18766 (self-insert-command N)))
18768 (setq org-table-may-need-update t)
18769 (self-insert-command N)
18770 (org-fix-tags-on-the-fly)
18771 (if org-self-insert-cluster-for-undo
18772 (if (not (eq last-command 'org-self-insert-command))
18773 (setq org-self-insert-command-undo-counter 1)
18774 (if (>= org-self-insert-command-undo-counter 20)
18775 (setq org-self-insert-command-undo-counter 1)
18776 (and (> org-self-insert-command-undo-counter 0)
18777 buffer-undo-list (listp buffer-undo-list)
18778 (not (cadr buffer-undo-list)) ; remove nil entry
18779 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18780 (setq org-self-insert-command-undo-counter
18781 (1+ org-self-insert-command-undo-counter))))))))
18783 (defun org-check-before-invisible-edit (kind)
18784 "Check is editing if kind KIND would be dangerous with invisible text around.
18785 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18786 ;; First, try to get out of here as quickly as possible, to reduce overhead
18787 (if (and org-catch-invisible-edits
18788 (or (not (boundp 'visible-mode)) (not visible-mode))
18789 (or (get-char-property (point) 'invisible)
18790 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18791 ;; OK, we need to take a closer look
18792 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18793 (invisible-before-point (if (bobp) nil (get-char-property
18794 (1- (point)) 'invisible)))
18795 (border-and-ok-direction
18797 ;; Check if we are acting predictably before invisible text
18798 (and invisible-at-point (not invisible-before-point)
18799 (memq kind '(insert delete-backward)))
18800 ;; Check if we are acting predictably after invisible text
18801 ;; This works not well, and I have turned it off. It seems
18802 ;; better to always show and stop after invisible text.
18803 ;; (and (not invisible-at-point) invisible-before-point
18804 ;; (memq kind '(insert delete)))
18806 (when (or (memq invisible-at-point '(outline org-hide-block t))
18807 (memq invisible-before-point '(outline org-hide-block t)))
18808 (if (eq org-catch-invisible-edits 'error)
18809 (error "Editing in invisible areas is prohibited - make visible first"))
18810 (if (and org-custom-properties-overlays
18811 (y-or-n-p "Display invisible properties in this buffer? "))
18812 (org-toggle-custom-properties-visibility)
18813 ;; Make the area visible
18814 (save-excursion
18815 (if invisible-before-point
18816 (goto-char (previous-single-char-property-change
18817 (point) 'invisible)))
18818 (org-cycle))
18819 (cond
18820 ((eq org-catch-invisible-edits 'show)
18821 ;; That's it, we do the edit after showing
18822 (message
18823 "Unfolding invisible region around point before editing")
18824 (sit-for 1))
18825 ((and (eq org-catch-invisible-edits 'smart)
18826 border-and-ok-direction)
18827 (message "Unfolding invisible region around point before editing"))
18829 ;; Don't do the edit, make the user repeat it in full visibility
18830 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18832 (defun org-fix-tags-on-the-fly ()
18833 (when (and (equal (char-after (point-at-bol)) ?*)
18834 (org-at-heading-p))
18835 (org-align-tags-here org-tags-column)))
18837 (defun org-delete-backward-char (N)
18838 "Like `delete-backward-char', insert whitespace at field end in tables.
18839 When deleting backwards, in tables this function will insert whitespace in
18840 front of the next \"|\" separator, to keep the table aligned. The table will
18841 still be marked for re-alignment if the field did fill the entire column,
18842 because, in this case the deletion might narrow the column."
18843 (interactive "p")
18844 (save-match-data
18845 (org-check-before-invisible-edit 'delete-backward)
18846 (if (and (org-table-p)
18847 (eq N 1)
18848 (string-match "|" (buffer-substring (point-at-bol) (point)))
18849 (looking-at ".*?|"))
18850 (let ((pos (point))
18851 (noalign (looking-at "[^|\n\r]* |"))
18852 (c org-table-may-need-update))
18853 (backward-delete-char N)
18854 (if (not overwrite-mode)
18855 (progn
18856 (skip-chars-forward "^|")
18857 (insert " ")
18858 (goto-char (1- pos))))
18859 ;; noalign: if there were two spaces at the end, this field
18860 ;; does not determine the width of the column.
18861 (if noalign (setq org-table-may-need-update c)))
18862 (backward-delete-char N)
18863 (org-fix-tags-on-the-fly))))
18865 (defun org-delete-char (N)
18866 "Like `delete-char', but insert whitespace at field end in tables.
18867 When deleting characters, in tables this function will insert whitespace in
18868 front of the next \"|\" separator, to keep the table aligned. The table will
18869 still be marked for re-alignment if the field did fill the entire column,
18870 because, in this case the deletion might narrow the column."
18871 (interactive "p")
18872 (save-match-data
18873 (org-check-before-invisible-edit 'delete)
18874 (if (and (org-table-p)
18875 (not (bolp))
18876 (not (= (char-after) ?|))
18877 (eq N 1))
18878 (if (looking-at ".*?|")
18879 (let ((pos (point))
18880 (noalign (looking-at "[^|\n\r]* |"))
18881 (c org-table-may-need-update))
18882 (replace-match (concat
18883 (substring (match-string 0) 1 -1)
18884 " |"))
18885 (goto-char pos)
18886 ;; noalign: if there were two spaces at the end, this field
18887 ;; does not determine the width of the column.
18888 (if noalign (setq org-table-may-need-update c)))
18889 (delete-char N))
18890 (delete-char N)
18891 (org-fix-tags-on-the-fly))))
18893 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18894 (put 'org-self-insert-command 'delete-selection t)
18895 (put 'orgtbl-self-insert-command 'delete-selection t)
18896 (put 'org-delete-char 'delete-selection 'supersede)
18897 (put 'org-delete-backward-char 'delete-selection 'supersede)
18898 (put 'org-yank 'delete-selection 'yank)
18900 ;; Make `flyspell-mode' delay after some commands
18901 (put 'org-self-insert-command 'flyspell-delayed t)
18902 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18903 (put 'org-delete-char 'flyspell-delayed t)
18904 (put 'org-delete-backward-char 'flyspell-delayed t)
18906 ;; Make pabbrev-mode expand after org-mode commands
18907 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18908 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18910 ;; How to do this: Measure non-white length of current string
18911 ;; If equal to column width, we should realign.
18913 (defun org-remap (map &rest commands)
18914 "In MAP, remap the functions given in COMMANDS.
18915 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18916 (let (new old)
18917 (while commands
18918 (setq old (pop commands) new (pop commands))
18919 (if (fboundp 'command-remapping)
18920 (org-defkey map (vector 'remap old) new)
18921 (substitute-key-definition old new map global-map)))))
18923 (when (eq org-enable-table-editor 'optimized)
18924 ;; If the user wants maximum table support, we need to hijack
18925 ;; some standard editing functions
18926 (org-remap org-mode-map
18927 'self-insert-command 'org-self-insert-command
18928 'delete-char 'org-delete-char
18929 'delete-backward-char 'org-delete-backward-char)
18930 (org-defkey org-mode-map "|" 'org-force-self-insert))
18932 (defvar org-ctrl-c-ctrl-c-hook nil
18933 "Hook for functions attaching themselves to `C-c C-c'.
18935 This can be used to add additional functionality to the C-c C-c
18936 key which executes context-dependent commands. This hook is run
18937 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18938 run after the last test.
18940 Each function will be called with no arguments. The function
18941 must check if the context is appropriate for it to act. If yes,
18942 it should do its thing and then return a non-nil value. If the
18943 context is wrong, just do nothing and return nil.")
18945 (defvar org-ctrl-c-ctrl-c-final-hook nil
18946 "Hook for functions attaching themselves to `C-c C-c'.
18948 This can be used to add additional functionality to the C-c C-c
18949 key which executes context-dependent commands. This hook is run
18950 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18951 before the first test.
18953 Each function will be called with no arguments. The function
18954 must check if the context is appropriate for it to act. If yes,
18955 it should do its thing and then return a non-nil value. If the
18956 context is wrong, just do nothing and return nil.")
18958 (defvar org-tab-first-hook nil
18959 "Hook for functions to attach themselves to TAB.
18960 See `org-ctrl-c-ctrl-c-hook' for more information.
18961 This hook runs as the first action when TAB is pressed, even before
18962 `org-cycle' messes around with the `outline-regexp' to cater for
18963 inline tasks and plain list item folding.
18964 If any function in this hook returns t, any other actions that
18965 would have been caused by TAB (such as table field motion or visibility
18966 cycling) will not occur.")
18968 (defvar org-tab-after-check-for-table-hook nil
18969 "Hook for functions to attach themselves to TAB.
18970 See `org-ctrl-c-ctrl-c-hook' for more information.
18971 This hook runs after it has been established that the cursor is not in a
18972 table, but before checking if the cursor is in a headline or if global cycling
18973 should be done.
18974 If any function in this hook returns t, not other actions like visibility
18975 cycling will be done.")
18977 (defvar org-tab-after-check-for-cycling-hook nil
18978 "Hook for functions to attach themselves to TAB.
18979 See `org-ctrl-c-ctrl-c-hook' for more information.
18980 This hook runs after it has been established that not table field motion and
18981 not visibility should be done because of current context. This is probably
18982 the place where a package like yasnippets can hook in.")
18984 (defvar org-tab-before-tab-emulation-hook nil
18985 "Hook for functions to attach themselves to TAB.
18986 See `org-ctrl-c-ctrl-c-hook' for more information.
18987 This hook runs after every other options for TAB have been exhausted, but
18988 before indentation and \t insertion takes place.")
18990 (defvar org-metaleft-hook nil
18991 "Hook for functions attaching themselves to `M-left'.
18992 See `org-ctrl-c-ctrl-c-hook' for more information.")
18993 (defvar org-metaright-hook nil
18994 "Hook for functions attaching themselves to `M-right'.
18995 See `org-ctrl-c-ctrl-c-hook' for more information.")
18996 (defvar org-metaup-hook nil
18997 "Hook for functions attaching themselves to `M-up'.
18998 See `org-ctrl-c-ctrl-c-hook' for more information.")
18999 (defvar org-metadown-hook nil
19000 "Hook for functions attaching themselves to `M-down'.
19001 See `org-ctrl-c-ctrl-c-hook' for more information.")
19002 (defvar org-shiftmetaleft-hook nil
19003 "Hook for functions attaching themselves to `M-S-left'.
19004 See `org-ctrl-c-ctrl-c-hook' for more information.")
19005 (defvar org-shiftmetaright-hook nil
19006 "Hook for functions attaching themselves to `M-S-right'.
19007 See `org-ctrl-c-ctrl-c-hook' for more information.")
19008 (defvar org-shiftmetaup-hook nil
19009 "Hook for functions attaching themselves to `M-S-up'.
19010 See `org-ctrl-c-ctrl-c-hook' for more information.")
19011 (defvar org-shiftmetadown-hook nil
19012 "Hook for functions attaching themselves to `M-S-down'.
19013 See `org-ctrl-c-ctrl-c-hook' for more information.")
19014 (defvar org-metareturn-hook nil
19015 "Hook for functions attaching themselves to `M-RET'.
19016 See `org-ctrl-c-ctrl-c-hook' for more information.")
19017 (defvar org-shiftup-hook nil
19018 "Hook for functions attaching themselves to `S-up'.
19019 See `org-ctrl-c-ctrl-c-hook' for more information.")
19020 (defvar org-shiftup-final-hook nil
19021 "Hook for functions attaching themselves to `S-up'.
19022 This one runs after all other options except shift-select have been excluded.
19023 See `org-ctrl-c-ctrl-c-hook' for more information.")
19024 (defvar org-shiftdown-hook nil
19025 "Hook for functions attaching themselves to `S-down'.
19026 See `org-ctrl-c-ctrl-c-hook' for more information.")
19027 (defvar org-shiftdown-final-hook nil
19028 "Hook for functions attaching themselves to `S-down'.
19029 This one runs after all other options except shift-select have been excluded.
19030 See `org-ctrl-c-ctrl-c-hook' for more information.")
19031 (defvar org-shiftleft-hook nil
19032 "Hook for functions attaching themselves to `S-left'.
19033 See `org-ctrl-c-ctrl-c-hook' for more information.")
19034 (defvar org-shiftleft-final-hook nil
19035 "Hook for functions attaching themselves to `S-left'.
19036 This one runs after all other options except shift-select have been excluded.
19037 See `org-ctrl-c-ctrl-c-hook' for more information.")
19038 (defvar org-shiftright-hook nil
19039 "Hook for functions attaching themselves to `S-right'.
19040 See `org-ctrl-c-ctrl-c-hook' for more information.")
19041 (defvar org-shiftright-final-hook nil
19042 "Hook for functions attaching themselves to `S-right'.
19043 This one runs after all other options except shift-select have been excluded.
19044 See `org-ctrl-c-ctrl-c-hook' for more information.")
19046 (defun org-modifier-cursor-error ()
19047 "Throw an error, a modified cursor command was applied in wrong context."
19048 (error "This command is active in special context like tables, headlines or items"))
19050 (defun org-shiftselect-error ()
19051 "Throw an error because Shift-Cursor command was applied in wrong context."
19052 (if (and (boundp 'shift-select-mode) shift-select-mode)
19053 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19054 (error "This command works only in special context like headlines or timestamps")))
19056 (defun org-call-for-shift-select (cmd)
19057 (let ((this-command-keys-shift-translated t))
19058 (call-interactively cmd)))
19060 (defun org-shifttab (&optional arg)
19061 "Global visibility cycling or move to previous table field.
19062 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19063 on context.
19064 See the individual commands for more information."
19065 (interactive "P")
19066 (cond
19067 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19068 ((integerp arg)
19069 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19070 (message "Content view to level: %d" arg)
19071 (org-content (prefix-numeric-value arg2))
19072 (setq org-cycle-global-status 'overview)))
19073 (t (call-interactively 'org-global-cycle))))
19075 (defun org-shiftmetaleft ()
19076 "Promote subtree or delete table column.
19077 Calls `org-promote-subtree', `org-outdent-item-tree', or
19078 `org-table-delete-column', depending on context. See the
19079 individual commands for more information."
19080 (interactive)
19081 (cond
19082 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19083 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19084 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19085 ((if (not (org-region-active-p)) (org-at-item-p)
19086 (save-excursion (goto-char (region-beginning))
19087 (org-at-item-p)))
19088 (call-interactively 'org-outdent-item-tree))
19089 (t (org-modifier-cursor-error))))
19091 (defun org-shiftmetaright ()
19092 "Demote subtree or insert table column.
19093 Calls `org-demote-subtree', `org-indent-item-tree', or
19094 `org-table-insert-column', depending on context. See the
19095 individual commands for more information."
19096 (interactive)
19097 (cond
19098 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19099 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19100 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19101 ((if (not (org-region-active-p)) (org-at-item-p)
19102 (save-excursion (goto-char (region-beginning))
19103 (org-at-item-p)))
19104 (call-interactively 'org-indent-item-tree))
19105 (t (org-modifier-cursor-error))))
19107 (defun org-shiftmetaup (&optional arg)
19108 "Move subtree up or kill table row.
19109 Calls `org-move-subtree-up' or `org-table-kill-row' or
19110 `org-move-item-up' or `org-timestamp-up', depending on context.
19111 See the individual commands for more information."
19112 (interactive "P")
19113 (cond
19114 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19115 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19116 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19117 ((org-at-item-p) (call-interactively 'org-move-item-up))
19118 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19119 (call-interactively 'org-timestamp-up)))
19120 (t (org-modifier-cursor-error))))
19122 (defun org-shiftmetadown (&optional arg)
19123 "Move subtree down or insert table row.
19124 Calls `org-move-subtree-down' or `org-table-insert-row' or
19125 `org-move-item-down' or `org-timestamp-up', depending on context.
19126 See the individual commands for more information."
19127 (interactive "P")
19128 (cond
19129 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19130 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19131 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19132 ((org-at-item-p) (call-interactively 'org-move-item-down))
19133 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19134 (call-interactively 'org-timestamp-down)))
19135 (t (org-modifier-cursor-error))))
19137 (defsubst org-hidden-tree-error ()
19138 (error
19139 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19141 (defun org-metaleft (&optional arg)
19142 "Promote heading or move table column to left.
19143 Calls `org-do-promote' or `org-table-move-column', depending on context.
19144 With no specific context, calls the Emacs default `backward-word'.
19145 See the individual commands for more information."
19146 (interactive "P")
19147 (cond
19148 ((run-hook-with-args-until-success 'org-metaleft-hook))
19149 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19150 ((org-with-limited-levels
19151 (or (org-at-heading-p)
19152 (and (org-region-active-p)
19153 (save-excursion
19154 (goto-char (region-beginning))
19155 (org-at-heading-p)))))
19156 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19157 (call-interactively 'org-do-promote))
19158 ;; At an inline task.
19159 ((org-at-heading-p)
19160 (call-interactively 'org-inlinetask-promote))
19161 ((or (org-at-item-p)
19162 (and (org-region-active-p)
19163 (save-excursion
19164 (goto-char (region-beginning))
19165 (org-at-item-p))))
19166 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19167 (call-interactively 'org-outdent-item))
19168 (t (call-interactively 'backward-word))))
19170 (defun org-metaright (&optional arg)
19171 "Demote a subtree, a list item or move table column to right.
19172 In front of a drawer or a block keyword, indent it correctly.
19173 With no specific context, calls the Emacs default `forward-word'.
19174 See the individual commands for more information."
19175 (interactive "P")
19176 (cond
19177 ((run-hook-with-args-until-success 'org-metaright-hook))
19178 ((org-at-table-p) (call-interactively 'org-table-move-column))
19179 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19180 ((org-at-block-p) (call-interactively 'org-indent-block))
19181 ((org-with-limited-levels
19182 (or (org-at-heading-p)
19183 (and (org-region-active-p)
19184 (save-excursion
19185 (goto-char (region-beginning))
19186 (org-at-heading-p)))))
19187 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19188 (call-interactively 'org-do-demote))
19189 ;; At an inline task.
19190 ((org-at-heading-p)
19191 (call-interactively 'org-inlinetask-demote))
19192 ((or (org-at-item-p)
19193 (and (org-region-active-p)
19194 (save-excursion
19195 (goto-char (region-beginning))
19196 (org-at-item-p))))
19197 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19198 (call-interactively 'org-indent-item))
19199 (t (call-interactively 'forward-word))))
19201 (defun org-check-for-hidden (what)
19202 "Check if there are hidden headlines/items in the current visual line.
19203 WHAT can be either `headlines' or `items'. If the current line is
19204 an outline or item heading and it has a folded subtree below it,
19205 this function returns t, nil otherwise."
19206 (let ((re (cond
19207 ((eq what 'headlines) org-outline-regexp-bol)
19208 ((eq what 'items) (org-item-beginning-re))
19209 (t (error "This should not happen"))))
19210 beg end)
19211 (save-excursion
19212 (catch 'exit
19213 (unless (org-region-active-p)
19214 (setq beg (point-at-bol))
19215 (beginning-of-line 2)
19216 (while (and (not (eobp)) ;; this is like `next-line'
19217 (get-char-property (1- (point)) 'invisible))
19218 (beginning-of-line 2))
19219 (setq end (point))
19220 (goto-char beg)
19221 (goto-char (point-at-eol))
19222 (setq end (max end (point)))
19223 (while (re-search-forward re end t)
19224 (if (get-char-property (match-beginning 0) 'invisible)
19225 (throw 'exit t))))
19226 nil))))
19228 (defun org-metaup (&optional arg)
19229 "Move subtree up or move table row up.
19230 Calls `org-move-subtree-up' or `org-table-move-row' or
19231 `org-move-item-up', depending on context. See the individual commands
19232 for more information."
19233 (interactive "P")
19234 (cond
19235 ((run-hook-with-args-until-success 'org-metaup-hook))
19236 ((org-region-active-p)
19237 (let* ((a (min (region-beginning) (region-end)))
19238 (b (1- (max (region-beginning) (region-end))))
19239 (c (save-excursion (goto-char a)
19240 (move-beginning-of-line 0)))
19241 (d (save-excursion (goto-char a)
19242 (move-end-of-line 0) (point))))
19243 (transpose-regions a b c d)
19244 (goto-char c)))
19245 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19246 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19247 ((org-at-item-p) (call-interactively 'org-move-item-up))
19248 (t (org-drag-element-backward))))
19250 (defun org-metadown (&optional arg)
19251 "Move subtree down or move table row down.
19252 Calls `org-move-subtree-down' or `org-table-move-row' or
19253 `org-move-item-down', depending on context. See the individual
19254 commands for more information."
19255 (interactive "P")
19256 (cond
19257 ((run-hook-with-args-until-success 'org-metadown-hook))
19258 ((org-region-active-p)
19259 (let* ((a (min (region-beginning) (region-end)))
19260 (b (max (region-beginning) (region-end)))
19261 (c (save-excursion (goto-char b)
19262 (move-beginning-of-line 1)))
19263 (d (save-excursion (goto-char b)
19264 (move-end-of-line 1) (1+ (point)))))
19265 (transpose-regions a b c d)
19266 (goto-char d)))
19267 ((org-at-table-p) (call-interactively 'org-table-move-row))
19268 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19269 ((org-at-item-p) (call-interactively 'org-move-item-down))
19270 (t (org-drag-element-forward))))
19272 (defun org-shiftup (&optional arg)
19273 "Increase item in timestamp or increase priority of current headline.
19274 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19275 depending on context. See the individual commands for more information."
19276 (interactive "P")
19277 (cond
19278 ((run-hook-with-args-until-success 'org-shiftup-hook))
19279 ((and org-support-shift-select (org-region-active-p))
19280 (org-call-for-shift-select 'previous-line))
19281 ((org-at-timestamp-p t)
19282 (call-interactively (if org-edit-timestamp-down-means-later
19283 'org-timestamp-down 'org-timestamp-up)))
19284 ((and (not (eq org-support-shift-select 'always))
19285 org-enable-priority-commands
19286 (org-at-heading-p))
19287 (call-interactively 'org-priority-up))
19288 ((and (not org-support-shift-select) (org-at-item-p))
19289 (call-interactively 'org-previous-item))
19290 ((org-clocktable-try-shift 'up arg))
19291 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19292 (org-support-shift-select
19293 (org-call-for-shift-select 'previous-line))
19294 (t (org-shiftselect-error))))
19296 (defun org-shiftdown (&optional arg)
19297 "Decrease item in timestamp or decrease priority of current headline.
19298 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19299 depending on context. See the individual commands for more information."
19300 (interactive "P")
19301 (cond
19302 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19303 ((and org-support-shift-select (org-region-active-p))
19304 (org-call-for-shift-select 'next-line))
19305 ((org-at-timestamp-p t)
19306 (call-interactively (if org-edit-timestamp-down-means-later
19307 'org-timestamp-up 'org-timestamp-down)))
19308 ((and (not (eq org-support-shift-select 'always))
19309 org-enable-priority-commands
19310 (org-at-heading-p))
19311 (call-interactively 'org-priority-down))
19312 ((and (not org-support-shift-select) (org-at-item-p))
19313 (call-interactively 'org-next-item))
19314 ((org-clocktable-try-shift 'down arg))
19315 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19316 (org-support-shift-select
19317 (org-call-for-shift-select 'next-line))
19318 (t (org-shiftselect-error))))
19320 (defun org-shiftright (&optional arg)
19321 "Cycle the thing at point or in the current line, depending on context.
19322 Depending on context, this does one of the following:
19324 - switch a timestamp at point one day into the future
19325 - on a headline, switch to the next TODO keyword.
19326 - on an item, switch entire list to the next bullet type
19327 - on a property line, switch to the next allowed value
19328 - on a clocktable definition line, move time block into the future"
19329 (interactive "P")
19330 (cond
19331 ((run-hook-with-args-until-success 'org-shiftright-hook))
19332 ((and org-support-shift-select (org-region-active-p))
19333 (org-call-for-shift-select 'forward-char))
19334 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19335 ((and (not (eq org-support-shift-select 'always))
19336 (org-at-heading-p))
19337 (let ((org-inhibit-logging
19338 (not org-treat-S-cursor-todo-selection-as-state-change))
19339 (org-inhibit-blocking
19340 (not org-treat-S-cursor-todo-selection-as-state-change)))
19341 (org-call-with-arg 'org-todo 'right)))
19342 ((or (and org-support-shift-select
19343 (not (eq org-support-shift-select 'always))
19344 (org-at-item-bullet-p))
19345 (and (not org-support-shift-select) (org-at-item-p)))
19346 (org-call-with-arg 'org-cycle-list-bullet nil))
19347 ((and (not (eq org-support-shift-select 'always))
19348 (org-at-property-p))
19349 (call-interactively 'org-property-next-allowed-value))
19350 ((org-clocktable-try-shift 'right arg))
19351 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19352 (org-support-shift-select
19353 (org-call-for-shift-select 'forward-char))
19354 (t (org-shiftselect-error))))
19356 (defun org-shiftleft (&optional arg)
19357 "Cycle the thing at point or in the current line, depending on context.
19358 Depending on context, this does one of the following:
19360 - switch a timestamp at point one day into the past
19361 - on a headline, switch to the previous TODO keyword.
19362 - on an item, switch entire list to the previous bullet type
19363 - on a property line, switch to the previous allowed value
19364 - on a clocktable definition line, move time block into the past"
19365 (interactive "P")
19366 (cond
19367 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19368 ((and org-support-shift-select (org-region-active-p))
19369 (org-call-for-shift-select 'backward-char))
19370 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19371 ((and (not (eq org-support-shift-select 'always))
19372 (org-at-heading-p))
19373 (let ((org-inhibit-logging
19374 (not org-treat-S-cursor-todo-selection-as-state-change))
19375 (org-inhibit-blocking
19376 (not org-treat-S-cursor-todo-selection-as-state-change)))
19377 (org-call-with-arg 'org-todo 'left)))
19378 ((or (and org-support-shift-select
19379 (not (eq org-support-shift-select 'always))
19380 (org-at-item-bullet-p))
19381 (and (not org-support-shift-select) (org-at-item-p)))
19382 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19383 ((and (not (eq org-support-shift-select 'always))
19384 (org-at-property-p))
19385 (call-interactively 'org-property-previous-allowed-value))
19386 ((org-clocktable-try-shift 'left arg))
19387 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19388 (org-support-shift-select
19389 (org-call-for-shift-select 'backward-char))
19390 (t (org-shiftselect-error))))
19392 (defun org-shiftcontrolright ()
19393 "Switch to next TODO set."
19394 (interactive)
19395 (cond
19396 ((and org-support-shift-select (org-region-active-p))
19397 (org-call-for-shift-select 'forward-word))
19398 ((and (not (eq org-support-shift-select 'always))
19399 (org-at-heading-p))
19400 (org-call-with-arg 'org-todo 'nextset))
19401 (org-support-shift-select
19402 (org-call-for-shift-select 'forward-word))
19403 (t (org-shiftselect-error))))
19405 (defun org-shiftcontrolleft ()
19406 "Switch to previous TODO set."
19407 (interactive)
19408 (cond
19409 ((and org-support-shift-select (org-region-active-p))
19410 (org-call-for-shift-select 'backward-word))
19411 ((and (not (eq org-support-shift-select 'always))
19412 (org-at-heading-p))
19413 (org-call-with-arg 'org-todo 'previousset))
19414 (org-support-shift-select
19415 (org-call-for-shift-select 'backward-word))
19416 (t (org-shiftselect-error))))
19418 (defun org-shiftcontrolup (&optional n)
19419 "Change timestamps synchronously up in CLOCK log lines.
19420 Optional argument N tells to change by that many units."
19421 (interactive "P")
19422 (cond ((and (not org-support-shift-select)
19423 (org-at-clock-log-p)
19424 (org-at-timestamp-p t))
19425 (org-clock-timestamps-up n))
19426 (t (org-shiftselect-error))))
19428 (defun org-shiftcontroldown (&optional n)
19429 "Change timestamps synchronously down in CLOCK log lines.
19430 Optional argument N tells to change by that many units."
19431 (interactive "P")
19432 (cond ((and (not org-support-shift-select)
19433 (org-at-clock-log-p)
19434 (org-at-timestamp-p t))
19435 (org-clock-timestamps-down n))
19436 (t (org-shiftselect-error))))
19438 (defun org-ctrl-c-ret ()
19439 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19440 (interactive)
19441 (cond
19442 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19443 (t (call-interactively 'org-insert-heading))))
19445 (defun org-find-visible ()
19446 (let ((s (point)))
19447 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19448 (get-char-property s 'invisible)))
19450 (defun org-find-invisible ()
19451 (let ((s (point)))
19452 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19453 (not (get-char-property s 'invisible))))
19456 (defun org-copy-visible (beg end)
19457 "Copy the visible parts of the region."
19458 (interactive "r")
19459 (let (snippets s)
19460 (save-excursion
19461 (save-restriction
19462 (narrow-to-region beg end)
19463 (setq s (goto-char (point-min)))
19464 (while (not (= (point) (point-max)))
19465 (goto-char (org-find-invisible))
19466 (push (buffer-substring s (point)) snippets)
19467 (setq s (goto-char (org-find-visible))))))
19468 (kill-new (apply 'concat (nreverse snippets)))))
19470 (defun org-copy-special ()
19471 "Copy region in table or copy current subtree.
19472 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19473 See the individual commands for more information."
19474 (interactive)
19475 (call-interactively
19476 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19478 (defun org-cut-special ()
19479 "Cut region in table or cut current subtree.
19480 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19481 See the individual commands for more information."
19482 (interactive)
19483 (call-interactively
19484 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19486 (defun org-paste-special (arg)
19487 "Paste rectangular region into table, or past subtree relative to level.
19488 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19489 See the individual commands for more information."
19490 (interactive "P")
19491 (if (org-at-table-p)
19492 (org-table-paste-rectangle)
19493 (org-paste-subtree arg)))
19495 (defsubst org-in-fixed-width-region-p ()
19496 "Is point in a fixed-width region?"
19497 (save-match-data
19498 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19500 (defun org-edit-special (&optional arg)
19501 "Call a special editor for the element at point.
19502 When at a table, call the formula editor with `org-table-edit-formulas'.
19503 When in a source code block, call `org-edit-src-code'.
19504 When in a fixed-width region, call `org-edit-fixed-width-region'.
19505 When at an #+INCLUDE keyword, visit the included file.
19506 On a link, call `ffap' to visit the link at point.
19507 Otherwise, return a user error."
19508 (interactive)
19509 (let ((element (org-element-at-point)))
19510 (case (org-element-type element)
19511 (src-block
19512 (if (not arg) (org-edit-src-code)
19513 (let* ((info (org-babel-get-src-block-info))
19514 (lang (nth 0 info))
19515 (params (nth 2 info))
19516 (session (cdr (assq :session params))))
19517 (if (not session) (org-edit-src-code)
19518 ;; At a src-block with a session and function called with
19519 ;; an ARG: switch to the buffer related to the inferior
19520 ;; process.
19521 (funcall (intern (concat "org-babel-prep-session:" lang))
19522 session params)))))
19523 (keyword
19524 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19525 (find-file
19526 (org-remove-double-quotes
19527 (car (org-split-string (org-element-property :value element)))))
19528 (user-error "No special environment to edit here")))
19529 (table
19530 (if (eq (org-element-property :type element) 'table.el)
19531 (org-edit-src-code)
19532 (call-interactively 'org-table-edit-formulas)))
19533 ;; Only Org tables contain `table-row' type elements.
19534 (table-row (call-interactively 'org-table-edit-formulas))
19535 ((example-block export-block) (org-edit-src-code))
19536 (fixed-width (org-edit-fixed-width-region))
19537 (otherwise
19538 ;; No notable element at point. Though, we may be at a link,
19539 ;; which is an object. Thus, scan deeper.
19540 (if (eq (org-element-type (org-element-context element)) 'link)
19541 (call-interactively 'ffap)
19542 (user-error "No special environment to edit here"))))))
19544 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19545 (defun org-ctrl-c-ctrl-c (&optional arg)
19546 "Set tags in headline, or update according to changed information at point.
19548 This command does many different things, depending on context:
19550 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19551 this is what we do.
19553 - If the cursor is on a statistics cookie, update it.
19555 - If the cursor is in a headline, prompt for tags and insert them
19556 into the current line, aligned to `org-tags-column'. When called
19557 with prefix arg, realign all tags in the current buffer.
19559 - If the cursor is in one of the special #+KEYWORD lines, this
19560 triggers scanning the buffer for these lines and updating the
19561 information.
19563 - If the cursor is inside a table, realign the table. This command
19564 works even if the automatic table editor has been turned off.
19566 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19567 the entire table.
19569 - If the cursor is at a footnote reference or definition, jump to
19570 the corresponding definition or references, respectively.
19572 - If the cursor is a the beginning of a dynamic block, update it.
19574 - If the current buffer is a capture buffer, close note and file it.
19576 - If the cursor is on a <<<target>>>, update radio targets and
19577 corresponding links in this buffer.
19579 - If the cursor is on a numbered item in a plain list, renumber the
19580 ordered list.
19582 - If the cursor is on a checkbox, toggle it.
19584 - If the cursor is on a code block, evaluate it. The variable
19585 `org-confirm-babel-evaluate' can be used to control prompting
19586 before code block evaluation, by default every code block
19587 evaluation requires confirmation. Code block evaluation can be
19588 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19589 (interactive "P")
19590 (cond
19591 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19592 org-occur-highlights
19593 org-latex-fragment-image-overlays)
19594 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19595 (org-remove-occur-highlights)
19596 (org-remove-latex-fragment-image-overlays)
19597 (message "Temporary highlights/overlays removed from current buffer"))
19598 ((and (local-variable-p 'org-finish-function (current-buffer))
19599 (fboundp org-finish-function))
19600 (funcall org-finish-function))
19601 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19603 (let* ((context (org-element-context)) (type (org-element-type context)))
19604 ;; Test if point is within blanks at the end of an element.
19605 (if (save-excursion
19606 (or (not context)
19607 (beginning-of-line)
19608 (and (looking-at "[ \t]*$")
19609 (skip-chars-forward " \r\t\n")
19610 (>= (point) (org-element-property :end context)))))
19611 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19612 (user-error "C-c C-c can do nothing useful at this location"))
19613 ;; For convenience: at the first line of a paragraph on the
19614 ;; same line as an item, apply function on that item instead.
19615 (when (eq type 'paragraph)
19616 (let ((parent (org-element-property :parent context)))
19617 (when (and (eq (org-element-type parent) 'item)
19618 (= (point-at-bol) (org-element-property :begin parent)))
19619 (setq context parent type 'item))))
19620 ;; Act according to type of element or object at point.
19621 (case type
19622 (clock (org-clock-update-time-maybe))
19623 (dynamic-block
19624 (save-excursion
19625 (goto-char (org-element-property :post-affiliated context))
19626 (org-update-dblock)))
19627 (footnote-definition
19628 (goto-char (org-element-property :post-affiliated context))
19629 (call-interactively 'org-footnote-action))
19630 (footnote-reference (call-interactively 'org-footnote-action))
19631 ((headline inlinetask)
19632 (save-excursion (goto-char (org-element-property :begin context))
19633 (call-interactively 'org-set-tags)))
19634 (item
19635 ;; At an item: a double C-u set checkbox to "[-]"
19636 ;; unconditionally, whereas a single one will toggle its
19637 ;; presence. Without an universal argument, if the item
19638 ;; has a checkbox, toggle it. Otherwise repair the list.
19639 (let* ((box (org-element-property :checkbox context))
19640 (struct (org-element-property :structure context))
19641 (old-struct (copy-tree struct))
19642 (parents (org-list-parents-alist struct))
19643 (prevs (org-list-prevs-alist struct))
19644 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19645 (org-list-set-checkbox
19646 (org-element-property :begin context) struct
19647 (cond ((equal arg '(16)) "[-]")
19648 ((and (not box) (equal arg '(4))) "[ ]")
19649 ((or (not box) (equal arg '(4))) nil)
19650 ((eq box 'on) "[ ]")
19651 (t "[X]")))
19652 ;; Mimic `org-list-write-struct' but with grabbing
19653 ;; a return value from `org-list-struct-fix-box'.
19654 (org-list-struct-fix-ind struct parents 2)
19655 (org-list-struct-fix-item-end struct)
19656 (org-list-struct-fix-bul struct prevs)
19657 (org-list-struct-fix-ind struct parents)
19658 (let ((block-item
19659 (org-list-struct-fix-box struct parents prevs orderedp)))
19660 (if (and box (equal struct old-struct))
19661 (if (equal arg '(16))
19662 (message "Checkboxes already reset")
19663 (user-error "Cannot toggle this checkbox: %s"
19664 (if (eq box 'on)
19665 "all subitems checked"
19666 "unchecked subitems")))
19667 (org-list-struct-apply-struct struct old-struct)
19668 (org-update-checkbox-count-maybe))
19669 (when block-item
19670 (message "Checkboxes were removed due to empty box at line %d"
19671 (org-current-line block-item))))))
19672 (keyword
19673 (let ((org-inhibit-startup-visibility-stuff t)
19674 (org-startup-align-all-tables nil))
19675 (when (boundp 'org-table-coordinate-overlays)
19676 (mapc 'delete-overlay org-table-coordinate-overlays)
19677 (setq org-table-coordinate-overlays nil))
19678 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19679 (message "Local setup has been refreshed"))
19680 (plain-list
19681 ;; At a plain list, with a double C-u argument, set
19682 ;; checkboxes of each item to "[-]", whereas a single one
19683 ;; will toggle their presence according to the state of the
19684 ;; first item in the list. Without an argument, repair the
19685 ;; list.
19686 (let* ((begin (org-element-property :contents-begin context))
19687 (struct (org-element-property :structure context))
19688 (old-struct (copy-tree struct))
19689 (first-box (save-excursion
19690 (goto-char begin)
19691 (looking-at org-list-full-item-re)
19692 (match-string-no-properties 3)))
19693 (new-box (cond ((equal arg '(16)) "[-]")
19694 ((equal arg '(4)) (unless first-box "[ ]"))
19695 ((equal first-box "[X]") "[ ]")
19696 (t "[X]"))))
19697 (cond
19698 (arg
19699 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19700 (org-list-get-all-items
19701 begin struct (org-list-prevs-alist struct))))
19702 ((and first-box (eq (point) begin))
19703 ;; For convenience, when point is at bol on the first
19704 ;; item of the list and no argument is provided, simply
19705 ;; toggle checkbox of that item, if any.
19706 (org-list-set-checkbox begin struct new-box)))
19707 (org-list-write-struct
19708 struct (org-list-parents-alist struct) old-struct)
19709 (org-update-checkbox-count-maybe)
19710 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19711 ((property-drawer node-property)
19712 (call-interactively 'org-property-action))
19713 ((radio-target target)
19714 (call-interactively 'org-update-radio-target-regexp))
19715 (statistics-cookie
19716 (call-interactively 'org-update-statistics-cookies))
19717 ((table table-cell table-row)
19718 ;; At a table, recalculate every field and align it. Also
19719 ;; send the table if necessary. If the table has
19720 ;; a `table.el' type, just give up. At a table row or
19721 ;; cell, maybe recalculate line but always align table.
19722 (if (eq (org-element-property :type context) 'table.el)
19723 (message "Use C-c ' to edit table.el tables")
19724 (let ((org-enable-table-editor t))
19725 (if (or (eq type 'table)
19726 ;; Check if point is at a TBLFM line.
19727 (and (eq type 'table-row)
19728 (= (point) (org-element-property :end context))))
19729 (save-excursion
19730 (goto-char (org-element-property :contents-begin context))
19731 (org-call-with-arg 'org-table-recalculate (or arg t))
19732 (orgtbl-send-table 'maybe))
19733 (org-table-maybe-eval-formula)
19734 (cond (arg (call-interactively 'org-table-recalculate))
19735 ((org-table-maybe-recalculate-line))
19736 (t (org-table-align)))))))
19737 (timestamp (org-timestamp-change 0 'day))
19738 (otherwise
19739 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19740 (user-error
19741 "C-c C-c can do nothing useful at this location")))))))))
19743 (defun org-mode-restart ()
19744 "Restart Org-mode, to scan again for special lines.
19745 Also updates the keyword regular expressions."
19746 (interactive)
19747 (org-mode)
19748 (message "Org-mode restarted"))
19750 (defun org-kill-note-or-show-branches ()
19751 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19752 (interactive)
19753 (if (not org-finish-function)
19754 (progn
19755 (hide-subtree)
19756 (call-interactively 'show-branches))
19757 (let ((org-note-abort t))
19758 (funcall org-finish-function))))
19760 (defun org-return (&optional indent)
19761 "Goto next table row or insert a newline.
19762 Calls `org-table-next-row' or `newline', depending on context.
19763 See the individual commands for more information."
19764 (interactive)
19765 (let (org-ts-what)
19766 (cond
19767 ((or (bobp) (org-in-src-block-p))
19768 (if indent (newline-and-indent) (newline)))
19769 ((org-at-table-p)
19770 (org-table-justify-field-maybe)
19771 (call-interactively 'org-table-next-row))
19772 ;; when `newline-and-indent' is called within a list, make sure
19773 ;; text moved stays inside the item.
19774 ((and (org-in-item-p) indent)
19775 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19776 (progn
19777 (save-match-data (newline))
19778 (org-indent-line-to (length (match-string 0))))
19779 (let ((ind (org-get-indentation)))
19780 (newline)
19781 (if (org-looking-back org-list-end-re)
19782 (org-indent-line)
19783 (org-indent-line-to ind)))))
19784 ((and org-return-follows-link
19785 (org-at-timestamp-p t)
19786 (not (eq org-ts-what 'after)))
19787 (org-follow-timestamp-link))
19788 ((and org-return-follows-link
19789 (let ((tprop (get-text-property (point) 'face)))
19790 (or (eq tprop 'org-link)
19791 (and (listp tprop) (memq 'org-link tprop)))))
19792 (call-interactively 'org-open-at-point))
19793 ((and (org-at-heading-p)
19794 (looking-at
19795 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19796 (org-show-entry)
19797 (end-of-line 1)
19798 (newline))
19799 (t (if indent (newline-and-indent) (newline))))))
19801 (defun org-return-indent ()
19802 "Goto next table row or insert a newline and indent.
19803 Calls `org-table-next-row' or `newline-and-indent', depending on
19804 context. See the individual commands for more information."
19805 (interactive)
19806 (org-return t))
19808 (defun org-ctrl-c-star ()
19809 "Compute table, or change heading status of lines.
19810 Calls `org-table-recalculate' or `org-toggle-heading',
19811 depending on context."
19812 (interactive)
19813 (cond
19814 ((org-at-table-p)
19815 (call-interactively 'org-table-recalculate))
19817 ;; Convert all lines in region to list items
19818 (call-interactively 'org-toggle-heading))))
19820 (defun org-ctrl-c-minus ()
19821 "Insert separator line in table or modify bullet status of line.
19822 Also turns a plain line or a region of lines into list items.
19823 Calls `org-table-insert-hline', `org-toggle-item', or
19824 `org-cycle-list-bullet', depending on context."
19825 (interactive)
19826 (cond
19827 ((org-at-table-p)
19828 (call-interactively 'org-table-insert-hline))
19829 ((org-region-active-p)
19830 (call-interactively 'org-toggle-item))
19831 ((org-in-item-p)
19832 (call-interactively 'org-cycle-list-bullet))
19834 (call-interactively 'org-toggle-item))))
19836 (defun org-toggle-item (arg)
19837 "Convert headings or normal lines to items, items to normal lines.
19838 If there is no active region, only the current line is considered.
19840 If the first non blank line in the region is an headline, convert
19841 all headlines to items, shifting text accordingly.
19843 If it is an item, convert all items to normal lines.
19845 If it is normal text, change region into an item. With a prefix
19846 argument ARG, change each line in region into an item."
19847 (interactive "P")
19848 (let ((shift-text
19849 (function
19850 ;; Shift text in current section to IND, from point to END.
19851 ;; The function leaves point to END line.
19852 (lambda (ind end)
19853 (let ((min-i 1000) (end (copy-marker end)))
19854 ;; First determine the minimum indentation (MIN-I) of
19855 ;; the text.
19856 (save-excursion
19857 (catch 'exit
19858 (while (< (point) end)
19859 (let ((i (org-get-indentation)))
19860 (cond
19861 ;; Skip blank lines and inline tasks.
19862 ((looking-at "^[ \t]*$"))
19863 ((looking-at org-outline-regexp-bol))
19864 ;; We can't find less than 0 indentation.
19865 ((zerop i) (throw 'exit (setq min-i 0)))
19866 ((< i min-i) (setq min-i i))))
19867 (forward-line))))
19868 ;; Then indent each line so that a line indented to
19869 ;; MIN-I becomes indented to IND. Ignore blank lines
19870 ;; and inline tasks in the process.
19871 (let ((delta (- ind min-i)))
19872 (while (< (point) end)
19873 (unless (or (looking-at "^[ \t]*$")
19874 (looking-at org-outline-regexp-bol))
19875 (org-indent-line-to (+ (org-get-indentation) delta)))
19876 (forward-line)))))))
19877 (skip-blanks
19878 (function
19879 ;; Return beginning of first non-blank line, starting from
19880 ;; line at POS.
19881 (lambda (pos)
19882 (save-excursion
19883 (goto-char pos)
19884 (skip-chars-forward " \r\t\n")
19885 (point-at-bol)))))
19886 beg end)
19887 ;; Determine boundaries of changes.
19888 (if (org-region-active-p)
19889 (setq beg (funcall skip-blanks (region-beginning))
19890 end (copy-marker (region-end)))
19891 (setq beg (funcall skip-blanks (point-at-bol))
19892 end (copy-marker (point-at-eol))))
19893 ;; Depending on the starting line, choose an action on the text
19894 ;; between BEG and END.
19895 (org-with-limited-levels
19896 (save-excursion
19897 (goto-char beg)
19898 (cond
19899 ;; Case 1. Start at an item: de-itemize. Note that it only
19900 ;; happens when a region is active: `org-ctrl-c-minus'
19901 ;; would call `org-cycle-list-bullet' otherwise.
19902 ((org-at-item-p)
19903 (while (< (point) end)
19904 (when (org-at-item-p)
19905 (skip-chars-forward " \t")
19906 (delete-region (point) (match-end 0)))
19907 (forward-line)))
19908 ;; Case 2. Start at an heading: convert to items.
19909 ((org-at-heading-p)
19910 (let* ((bul (org-list-bullet-string "-"))
19911 (bul-len (length bul))
19912 ;; Indentation of the first heading. It should be
19913 ;; relative to the indentation of its parent, if any.
19914 (start-ind (save-excursion
19915 (cond
19916 ((not org-adapt-indentation) 0)
19917 ((not (outline-previous-heading)) 0)
19918 (t (length (match-string 0))))))
19919 ;; Level of first heading. Further headings will be
19920 ;; compared to it to determine hierarchy in the list.
19921 (ref-level (org-reduced-level (org-outline-level))))
19922 (while (< (point) end)
19923 (let* ((level (org-reduced-level (org-outline-level)))
19924 (delta (max 0 (- level ref-level))))
19925 ;; If current headline is less indented than the first
19926 ;; one, set it as reference, in order to preserve
19927 ;; subtrees.
19928 (when (< level ref-level) (setq ref-level level))
19929 (replace-match bul t t)
19930 (org-indent-line-to (+ start-ind (* delta bul-len)))
19931 ;; Ensure all text down to END (or SECTION-END) belongs
19932 ;; to the newly created item.
19933 (let ((section-end (save-excursion
19934 (or (outline-next-heading) (point)))))
19935 (forward-line)
19936 (funcall shift-text
19937 (+ start-ind (* (1+ delta) bul-len))
19938 (min end section-end)))))))
19939 ;; Case 3. Normal line with ARG: turn each non-item line into
19940 ;; an item.
19941 (arg
19942 (while (< (point) end)
19943 (unless (or (org-at-heading-p) (org-at-item-p))
19944 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19945 (replace-match
19946 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19947 (forward-line)))
19948 ;; Case 4. Normal line without ARG: make the first line of
19949 ;; region an item, and shift indentation of others
19950 ;; lines to set them as item's body.
19951 (t (let* ((bul (org-list-bullet-string "-"))
19952 (bul-len (length bul))
19953 (ref-ind (org-get-indentation)))
19954 (skip-chars-forward " \t")
19955 (insert bul)
19956 (forward-line)
19957 (while (< (point) end)
19958 ;; Ensure that lines less indented than first one
19959 ;; still get included in item body.
19960 (funcall shift-text
19961 (+ ref-ind bul-len)
19962 (min end (save-excursion (or (outline-next-heading)
19963 (point)))))
19964 (forward-line)))))))))
19966 (defun org-toggle-heading (&optional nstars)
19967 "Convert headings to normal text, or items or text to headings.
19968 If there is no active region, only the current line is considered.
19970 With a \\[universal-argument] prefix, convert the whole list at
19971 point into heading.
19973 In a region:
19975 - If the first non blank line is an headline, remove the stars
19976 from all headlines in the region.
19978 - If it is a normal line turn each and every normal line (i.e. not an
19979 heading or an item) in the region into a heading.
19981 - If it is a plain list item, turn all plain list items into headings.
19983 When converting a line into a heading, the number of stars is chosen
19984 such that the lines become children of the current entry. However,
19985 when a prefix argument is given, its value determines the number of
19986 stars to add."
19987 (interactive "P")
19988 (let ((skip-blanks
19989 (function
19990 ;; Return beginning of first non-blank line, starting from
19991 ;; line at POS.
19992 (lambda (pos)
19993 (save-excursion
19994 (goto-char pos)
19995 (while (org-at-comment-p) (forward-line))
19996 (skip-chars-forward " \r\t\n")
19997 (point-at-bol)))))
19998 beg end toggled)
19999 ;; Determine boundaries of changes. If a universal prefix has
20000 ;; been given, put the list in a region. If region ends at a bol,
20001 ;; do not consider the last line to be in the region.
20003 (when (and current-prefix-arg (org-at-item-p))
20004 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20005 (org-mark-element))
20007 (if (org-region-active-p)
20008 (setq beg (funcall skip-blanks (region-beginning))
20009 end (copy-marker (save-excursion
20010 (goto-char (region-end))
20011 (if (bolp) (point) (point-at-eol)))))
20012 (setq beg (funcall skip-blanks (point-at-bol))
20013 end (copy-marker (point-at-eol))))
20014 ;; Ensure inline tasks don't count as headings.
20015 (org-with-limited-levels
20016 (save-excursion
20017 (goto-char beg)
20018 (cond
20019 ;; Case 1. Started at an heading: de-star headings.
20020 ((org-at-heading-p)
20021 (while (< (point) end)
20022 (when (org-at-heading-p t)
20023 (looking-at org-outline-regexp) (replace-match "")
20024 (setq toggled t))
20025 (forward-line)))
20026 ;; Case 2. Started at an item: change items into headlines.
20027 ;; One star will be added by `org-list-to-subtree'.
20028 ((org-at-item-p)
20029 (let* ((stars (make-string
20030 (if nstars
20031 ;; subtract the star that will be added again by
20032 ;; `org-list-to-subtree'
20033 (1- (prefix-numeric-value current-prefix-arg))
20034 (or (org-current-level) 0))
20035 ?*))
20036 (add-stars
20037 (cond (nstars "") ; stars from prefix only
20038 ((equal stars "") "") ; before first heading
20039 (org-odd-levels-only "*") ; inside heading, odd
20040 (t "")))) ; inside heading, oddeven
20041 (while (< (point) end)
20042 (when (org-at-item-p)
20043 ;; Pay attention to cases when region ends before list.
20044 (let* ((struct (org-list-struct))
20045 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20046 (save-restriction
20047 (narrow-to-region (point) list-end)
20048 (insert
20049 (org-list-to-subtree
20050 (org-list-parse-list t)
20051 '(:istart (concat stars add-stars (funcall get-stars depth))
20052 :icount (concat stars add-stars (funcall get-stars depth)))))))
20053 (setq toggled t))
20054 (forward-line))))
20055 ;; Case 3. Started at normal text: make every line an heading,
20056 ;; skipping headlines and items.
20057 (t (let* ((stars (make-string
20058 (if nstars
20059 (prefix-numeric-value current-prefix-arg)
20060 (or (org-current-level) 0))
20061 ?*))
20062 (add-stars
20063 (cond (nstars "") ; stars from prefix only
20064 ((equal stars "") "*") ; before first heading
20065 (org-odd-levels-only "**") ; inside heading, odd
20066 (t "*"))) ; inside heading, oddeven
20067 (rpl (concat stars add-stars " ")))
20068 (while (< (point) end)
20069 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20070 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20071 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20072 (forward-line)))))))
20073 (unless toggled (message "Cannot toggle heading from here"))))
20075 (defun org-meta-return (&optional arg)
20076 "Insert a new heading or wrap a region in a table.
20077 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20078 See the individual commands for more information."
20079 (interactive "P")
20080 (cond
20081 ((run-hook-with-args-until-success 'org-metareturn-hook))
20082 ((or (org-at-drawer-p) (org-at-property-p))
20083 (newline-and-indent))
20084 ((org-at-table-p)
20085 (call-interactively 'org-table-wrap-region))
20086 (t (call-interactively 'org-insert-heading))))
20088 ;;; Menu entries
20090 (defsubst org-in-subtree-not-table-p ()
20091 "Are we in a subtree and not in a table?"
20092 (and (not (org-before-first-heading-p))
20093 (not (org-at-table-p))))
20095 ;; Define the Org-mode menus
20096 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20097 '("Tbl"
20098 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20099 ["Next Field" org-cycle (org-at-table-p)]
20100 ["Previous Field" org-shifttab (org-at-table-p)]
20101 ["Next Row" org-return (org-at-table-p)]
20102 "--"
20103 ["Blank Field" org-table-blank-field (org-at-table-p)]
20104 ["Edit Field" org-table-edit-field (org-at-table-p)]
20105 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20106 "--"
20107 ("Column"
20108 ["Move Column Left" org-metaleft (org-at-table-p)]
20109 ["Move Column Right" org-metaright (org-at-table-p)]
20110 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20111 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20112 ("Row"
20113 ["Move Row Up" org-metaup (org-at-table-p)]
20114 ["Move Row Down" org-metadown (org-at-table-p)]
20115 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20116 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20117 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20118 "--"
20119 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20120 ("Rectangle"
20121 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20122 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20123 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20124 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20125 "--"
20126 ("Calculate"
20127 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20128 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20129 ["Edit Formulas" org-edit-special (org-at-table-p)]
20130 "--"
20131 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20132 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20133 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20134 "--"
20135 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20136 "--"
20137 ["Sum Column/Rectangle" org-table-sum
20138 (or (org-at-table-p) (org-region-active-p))]
20139 ["Which Column?" org-table-current-column (org-at-table-p)])
20140 ["Debug Formulas"
20141 org-table-toggle-formula-debugger
20142 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20143 ["Show Col/Row Numbers"
20144 org-table-toggle-coordinate-overlays
20145 :style toggle
20146 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20147 "--"
20148 ["Create" org-table-create (and (not (org-at-table-p))
20149 org-enable-table-editor)]
20150 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20151 ["Import from File" org-table-import (not (org-at-table-p))]
20152 ["Export to File" org-table-export (org-at-table-p)]
20153 "--"
20154 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20156 (easy-menu-define org-org-menu org-mode-map "Org menu"
20157 '("Org"
20158 ("Show/Hide"
20159 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20160 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20161 ["Sparse Tree..." org-sparse-tree t]
20162 ["Reveal Context" org-reveal t]
20163 ["Show All" show-all t]
20164 "--"
20165 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20166 "--"
20167 ["New Heading" org-insert-heading t]
20168 ("Navigate Headings"
20169 ["Up" outline-up-heading t]
20170 ["Next" outline-next-visible-heading t]
20171 ["Previous" outline-previous-visible-heading t]
20172 ["Next Same Level" outline-forward-same-level t]
20173 ["Previous Same Level" outline-backward-same-level t]
20174 "--"
20175 ["Jump" org-goto t])
20176 ("Edit Structure"
20177 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20178 "--"
20179 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20180 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20181 "--"
20182 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20183 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20184 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20185 "--"
20186 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20187 "--"
20188 ["Copy visible text" org-copy-visible t]
20189 "--"
20190 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20191 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20192 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20193 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20194 "--"
20195 ["Sort Region/Children" org-sort t]
20196 "--"
20197 ["Convert to odd levels" org-convert-to-odd-levels t]
20198 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20199 ("Editing"
20200 ["Emphasis..." org-emphasize t]
20201 ["Edit Source Example" org-edit-special t]
20202 "--"
20203 ["Footnote new/jump" org-footnote-action t]
20204 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20205 ("Archive"
20206 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20207 "--"
20208 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20209 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20210 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20212 "--"
20213 ("Hyperlinks"
20214 ["Store Link (Global)" org-store-link t]
20215 ["Find existing link to here" org-occur-link-in-agenda-files t]
20216 ["Insert Link" org-insert-link t]
20217 ["Follow Link" org-open-at-point t]
20218 "--"
20219 ["Next link" org-next-link t]
20220 ["Previous link" org-previous-link t]
20221 "--"
20222 ["Descriptive Links"
20223 org-toggle-link-display
20224 :style radio
20225 :selected org-descriptive-links
20227 ["Literal Links"
20228 org-toggle-link-display
20229 :style radio
20230 :selected (not org-descriptive-links)])
20231 "--"
20232 ("TODO Lists"
20233 ["TODO/DONE/-" org-todo t]
20234 ("Select keyword"
20235 ["Next keyword" org-shiftright (org-at-heading-p)]
20236 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20237 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20238 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20239 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20240 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20241 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20242 "--"
20243 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20244 :selected org-enforce-todo-dependencies :style toggle :active t]
20245 "Settings for tree at point"
20246 ["Do Children sequentially" org-toggle-ordered-property :style radio
20247 :selected (org-entry-get nil "ORDERED")
20248 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20249 ["Do Children parallel" org-toggle-ordered-property :style radio
20250 :selected (not (org-entry-get nil "ORDERED"))
20251 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20252 "--"
20253 ["Set Priority" org-priority t]
20254 ["Priority Up" org-shiftup t]
20255 ["Priority Down" org-shiftdown t]
20256 "--"
20257 ["Get news from all feeds" org-feed-update-all t]
20258 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20259 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20260 ("TAGS and Properties"
20261 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20262 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20263 "--"
20264 ["Set property" org-set-property (not (org-before-first-heading-p))]
20265 ["Column view of properties" org-columns t]
20266 ["Insert Column View DBlock" org-insert-columns-dblock t])
20267 ("Dates and Scheduling"
20268 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20269 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20270 ("Change Date"
20271 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20272 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20273 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20274 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20275 ["Compute Time Range" org-evaluate-time-range t]
20276 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20277 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20278 "--"
20279 ["Custom time format" org-toggle-time-stamp-overlays
20280 :style radio :selected org-display-custom-times]
20281 "--"
20282 ["Goto Calendar" org-goto-calendar t]
20283 ["Date from Calendar" org-date-from-calendar t]
20284 "--"
20285 ["Start/Restart Timer" org-timer-start t]
20286 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20287 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20288 ["Insert Timer String" org-timer t]
20289 ["Insert Timer Item" org-timer-item t])
20290 ("Logging work"
20291 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20292 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20293 ["Clock out" org-clock-out t]
20294 ["Clock cancel" org-clock-cancel t]
20295 "--"
20296 ["Mark as default task" org-clock-mark-default-task t]
20297 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20298 ["Goto running clock" org-clock-goto t]
20299 "--"
20300 ["Display times" org-clock-display t]
20301 ["Create clock table" org-clock-report t]
20302 "--"
20303 ["Record DONE time"
20304 (progn (setq org-log-done (not org-log-done))
20305 (message "Switching to %s will %s record a timestamp"
20306 (car org-done-keywords)
20307 (if org-log-done "automatically" "not")))
20308 :style toggle :selected org-log-done])
20309 "--"
20310 ["Agenda Command..." org-agenda t]
20311 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20312 ("File List for Agenda")
20313 ("Special views current file"
20314 ["TODO Tree" org-show-todo-tree t]
20315 ["Check Deadlines" org-check-deadlines t]
20316 ["Timeline" org-timeline t]
20317 ["Tags/Property tree" org-match-sparse-tree t])
20318 "--"
20319 ["Export/Publish..." org-export-dispatch t]
20320 ("LaTeX"
20321 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20322 :selected org-cdlatex-mode]
20323 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20324 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20325 ["Modify math symbol" org-cdlatex-math-modify
20326 (org-inside-LaTeX-fragment-p)]
20327 ["Insert citation" org-reftex-citation t]
20328 "--"
20329 ["Template for BEAMER" (progn (require 'ox-beamer)
20330 (org-insert-beamer-options-template)) t])
20331 "--"
20332 ("MobileOrg"
20333 ["Push Files and Views" org-mobile-push t]
20334 ["Get Captured and Flagged" org-mobile-pull t]
20335 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20336 "--"
20337 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20338 "--"
20339 ("Documentation"
20340 ["Show Version" org-version t]
20341 ["Info Documentation" org-info t])
20342 ("Customize"
20343 ["Browse Org Group" org-customize t]
20344 "--"
20345 ["Expand This Menu" org-create-customize-menu
20346 (fboundp 'customize-menu-create)])
20347 ["Send bug report" org-submit-bug-report t]
20348 "--"
20349 ("Refresh/Reload"
20350 ["Refresh setup current buffer" org-mode-restart t]
20351 ["Reload Org (after update)" org-reload t]
20352 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20355 (defun org-info (&optional node)
20356 "Read documentation for Org-mode in the info system.
20357 With optional NODE, go directly to that node."
20358 (interactive)
20359 (info (format "(org)%s" (or node ""))))
20361 ;;;###autoload
20362 (defun org-submit-bug-report ()
20363 "Submit a bug report on Org-mode via mail.
20365 Don't hesitate to report any problems or inaccurate documentation.
20367 If you don't have setup sending mail from (X)Emacs, please copy the
20368 output buffer into your mail program, as it gives us important
20369 information about your Org-mode version and configuration."
20370 (interactive)
20371 (require 'reporter)
20372 (org-load-modules-maybe)
20373 (org-require-autoloaded-modules)
20374 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20375 (reporter-submit-bug-report
20376 "emacs-orgmode@gnu.org"
20377 (org-version nil 'full)
20378 (let (list)
20379 (save-window-excursion
20380 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20381 (delete-other-windows)
20382 (erase-buffer)
20383 (insert "You are about to submit a bug report to the Org-mode mailing list.
20385 We would like to add your full Org-mode and Outline configuration to the
20386 bug report. This greatly simplifies the work of the maintainer and
20387 other experts on the mailing list.
20389 HOWEVER, some variables you have customized may contain private
20390 information. The names of customers, colleagues, or friends, might
20391 appear in the form of file names, tags, todo states, or search strings.
20392 If you answer yes to the prompt, you might want to check and remove
20393 such private information before sending the email.")
20394 (add-text-properties (point-min) (point-max) '(face org-warning))
20395 (when (yes-or-no-p "Include your Org-mode configuration ")
20396 (mapatoms
20397 (lambda (v)
20398 (and (boundp v)
20399 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20400 (or (and (symbol-value v)
20401 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20402 (and
20403 (get v 'custom-type) (get v 'standard-value)
20404 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20405 (push v list)))))
20406 (kill-buffer (get-buffer "*Warn about privacy*"))
20407 list))
20408 nil nil
20409 "Remember to cover the basics, that is, what you expected to happen and
20410 what in fact did happen. You don't know how to make a good report? See
20412 http://orgmode.org/manual/Feedback.html#Feedback
20414 Your bug report will be posted to the Org-mode mailing list.
20415 ------------------------------------------------------------------------")
20416 (save-excursion
20417 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20418 (replace-match "\\1Bug: \\3 [\\2]")))))
20421 (defun org-install-agenda-files-menu ()
20422 (let ((bl (buffer-list)))
20423 (save-excursion
20424 (while bl
20425 (set-buffer (pop bl))
20426 (if (derived-mode-p 'org-mode) (setq bl nil)))
20427 (when (derived-mode-p 'org-mode)
20428 (easy-menu-change
20429 '("Org") "File List for Agenda"
20430 (append
20431 (list
20432 ["Edit File List" (org-edit-agenda-file-list) t]
20433 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20434 ["Remove Current File from List" org-remove-file t]
20435 ["Cycle through agenda files" org-cycle-agenda-files t]
20436 ["Occur in all agenda files" org-occur-in-agenda-files t]
20437 "--")
20438 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20440 ;;;; Documentation
20442 (defun org-require-autoloaded-modules ()
20443 (interactive)
20444 (mapc 'require
20445 '(org-agenda org-archive org-attach org-clock org-colview org-id
20446 org-remember org-table org-timer)))
20448 ;;;###autoload
20449 (defun org-reload (&optional uncompiled)
20450 "Reload all org lisp files.
20451 With prefix arg UNCOMPILED, load the uncompiled versions."
20452 (interactive "P")
20453 (require 'loadhist)
20454 (let* ((org-dir (org-find-library-dir "org"))
20455 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20456 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20457 (remove-re (mapconcat 'identity
20458 (mapcar (lambda (f) (concat "^" f "$"))
20459 (list (if (featurep 'xemacs)
20460 "org-colview"
20461 "org-colview-xemacs")
20462 "org" "org-loaddefs" "org-version"))
20463 "\\|"))
20464 (feats (delete-dups
20465 (mapcar 'file-name-sans-extension
20466 (mapcar 'file-name-nondirectory
20467 (delq nil
20468 (mapcar 'feature-file
20469 features))))))
20470 (lfeat (append
20471 (sort
20472 (setq feats
20473 (delq nil (mapcar
20474 (lambda (f)
20475 (if (and (string-match feature-re f)
20476 (not (string-match remove-re f)))
20477 f nil))
20478 feats)))
20479 'string-lessp)
20480 (list "org-version" "org")))
20481 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20482 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20483 load-uncore load-misses)
20484 (setq load-misses
20485 (delq 't
20486 (mapcar (lambda (f)
20487 (or (org-load-noerror-mustsuffix (concat org-dir f))
20488 (and (string= org-dir contrib-dir)
20489 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20490 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20491 (add-to-list 'load-uncore f 'append)
20494 lfeat)))
20495 (if load-uncore
20496 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20497 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20498 (if load-misses
20499 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20500 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20501 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20503 ;;;###autoload
20504 (defun org-customize ()
20505 "Call the customize function with org as argument."
20506 (interactive)
20507 (org-load-modules-maybe)
20508 (org-require-autoloaded-modules)
20509 (customize-browse 'org))
20511 (defun org-create-customize-menu ()
20512 "Create a full customization menu for Org-mode, insert it into the menu."
20513 (interactive)
20514 (org-load-modules-maybe)
20515 (org-require-autoloaded-modules)
20516 (if (fboundp 'customize-menu-create)
20517 (progn
20518 (easy-menu-change
20519 '("Org") "Customize"
20520 `(["Browse Org group" org-customize t]
20521 "--"
20522 ,(customize-menu-create 'org)
20523 ["Set" Custom-set t]
20524 ["Save" Custom-save t]
20525 ["Reset to Current" Custom-reset-current t]
20526 ["Reset to Saved" Custom-reset-saved t]
20527 ["Reset to Standard Settings" Custom-reset-standard t]))
20528 (message "\"Org\"-menu now contains full customization menu"))
20529 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20531 ;;;; Miscellaneous stuff
20533 ;;; Generally useful functions
20535 (defun org-get-at-bol (property)
20536 "Get text property PROPERTY at beginning of line."
20537 (get-text-property (point-at-bol) property))
20539 (defun org-find-text-property-in-string (prop s)
20540 "Return the first non-nil value of property PROP in string S."
20541 (or (get-text-property 0 prop s)
20542 (get-text-property (or (next-single-property-change 0 prop s) 0)
20543 prop s)))
20545 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20546 "Display the given MESSAGE as a warning."
20547 (if (fboundp 'display-warning)
20548 (display-warning 'org message
20549 (if (featurep 'xemacs) 'warning :warning))
20550 (let ((buf (get-buffer-create "*Org warnings*")))
20551 (with-current-buffer buf
20552 (goto-char (point-max))
20553 (insert "Warning (Org): " message)
20554 (unless (bolp)
20555 (newline)))
20556 (display-buffer buf)
20557 (sit-for 0))))
20559 (defun org-eval (form)
20560 "Eval FORM and return result."
20561 (condition-case error
20562 (eval form)
20563 (error (format "%%![Error: %s]" error))))
20565 (defun org-in-clocktable-p ()
20566 "Check if the cursor is in a clocktable."
20567 (let ((pos (point)) start)
20568 (save-excursion
20569 (end-of-line 1)
20570 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20571 (setq start (match-beginning 0))
20572 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20573 (>= (match-end 0) pos)
20574 start))))
20576 (defun org-in-commented-line ()
20577 "Is point in a line starting with `#'?"
20578 (equal (char-after (point-at-bol)) ?#))
20580 (defun org-in-indented-comment-line ()
20581 "Is point in a line starting with `#' after some white space?"
20582 (save-excursion
20583 (save-match-data
20584 (goto-char (point-at-bol))
20585 (looking-at "[ \t]*#"))))
20587 (defun org-in-verbatim-emphasis ()
20588 (save-match-data
20589 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20591 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20592 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20593 (if (and marker (marker-buffer marker)
20594 (buffer-live-p (marker-buffer marker)))
20595 (progn
20596 (org-pop-to-buffer-same-window (marker-buffer marker))
20597 (if (or (> marker (point-max)) (< marker (point-min)))
20598 (widen))
20599 (goto-char marker)
20600 (org-show-context 'org-goto))
20601 (if bookmark
20602 (bookmark-jump bookmark)
20603 (error "Cannot find location"))))
20605 (defun org-quote-csv-field (s)
20606 "Quote field for inclusion in CSV material."
20607 (if (string-match "[\",]" s)
20608 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20611 (defun org-force-self-insert (N)
20612 "Needed to enforce self-insert under remapping."
20613 (interactive "p")
20614 (self-insert-command N))
20616 (defun org-string-width (s)
20617 "Compute width of string, ignoring invisible characters.
20618 This ignores character with invisibility property `org-link', and also
20619 characters with property `org-cwidth', because these will become invisible
20620 upon the next fontification round."
20621 (let (b l)
20622 (when (or (eq t buffer-invisibility-spec)
20623 (assq 'org-link buffer-invisibility-spec))
20624 (while (setq b (text-property-any 0 (length s)
20625 'invisible 'org-link s))
20626 (setq s (concat (substring s 0 b)
20627 (substring s (or (next-single-property-change
20628 b 'invisible s) (length s)))))))
20629 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20630 (setq s (concat (substring s 0 b)
20631 (substring s (or (next-single-property-change
20632 b 'org-cwidth s) (length s))))))
20633 (setq l (string-width s) b -1)
20634 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20635 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20638 (defun org-shorten-string (s maxlength)
20639 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20640 If the string is shorter or has length MAXLENGTH, just return the
20641 original string. If it is longer, the functions finds a space in the
20642 string, breaks this string off at that locations and adds three dots
20643 as ellipsis. Including the ellipsis, the string will not be longer
20644 than MAXLENGTH. If finding a good breaking point in the string does
20645 not work, the string is just chopped off in the middle of a word
20646 if necessary."
20647 (if (<= (length s) maxlength)
20649 (let* ((n (max (- maxlength 4) 1))
20650 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20651 (if (string-match re s)
20652 (concat (match-string 1 s) "...")
20653 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20655 (defun org-get-indentation (&optional line)
20656 "Get the indentation of the current line, interpreting tabs.
20657 When LINE is given, assume it represents a line and compute its indentation."
20658 (if line
20659 (if (string-match "^ *" (org-remove-tabs line))
20660 (match-end 0))
20661 (save-excursion
20662 (beginning-of-line 1)
20663 (skip-chars-forward " \t")
20664 (current-column))))
20666 (defun org-get-string-indentation (s)
20667 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20668 (let ((n -1) (i 0) (w tab-width) c)
20669 (catch 'exit
20670 (while (< (setq n (1+ n)) (length s))
20671 (setq c (aref s n))
20672 (cond ((= c ?\ ) (setq i (1+ i)))
20673 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20674 (t (throw 'exit t)))))
20677 (defun org-remove-tabs (s &optional width)
20678 "Replace tabulators in S with spaces.
20679 Assumes that s is a single line, starting in column 0."
20680 (setq width (or width tab-width))
20681 (while (string-match "\t" s)
20682 (setq s (replace-match
20683 (make-string
20684 (- (* width (/ (+ (match-beginning 0) width) width))
20685 (match-beginning 0)) ?\ )
20686 t t s)))
20689 (defun org-fix-indentation (line ind)
20690 "Fix indentation in LINE.
20691 IND is a cons cell with target and minimum indentation.
20692 If the current indentation in LINE is smaller than the minimum,
20693 leave it alone. If it is larger than ind, set it to the target."
20694 (let* ((l (org-remove-tabs line))
20695 (i (org-get-indentation l))
20696 (i1 (car ind)) (i2 (cdr ind)))
20697 (if (>= i i2) (setq l (substring line i2)))
20698 (if (> i1 0)
20699 (concat (make-string i1 ?\ ) l)
20700 l)))
20702 (defun org-remove-indentation (code &optional n)
20703 "Remove the maximum common indentation from the lines in CODE.
20704 N may optionally be the number of spaces to remove."
20705 (with-temp-buffer
20706 (insert code)
20707 (org-do-remove-indentation n)
20708 (buffer-string)))
20710 (defun org-do-remove-indentation (&optional n)
20711 "Remove the maximum common indentation from the buffer."
20712 (untabify (point-min) (point-max))
20713 (let ((min 10000) re)
20714 (if n
20715 (setq min n)
20716 (goto-char (point-min))
20717 (while (re-search-forward "^ *[^ \n]" nil t)
20718 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20719 (unless (or (= min 0) (= min 10000))
20720 (setq re (format "^ \\{%d\\}" min))
20721 (goto-char (point-min))
20722 (while (re-search-forward re nil t)
20723 (replace-match "")
20724 (end-of-line 1))
20725 min)))
20727 (defun org-fill-template (template alist)
20728 "Find each %key of ALIST in TEMPLATE and replace it."
20729 (let ((case-fold-search nil)
20730 entry key value)
20731 (setq alist (sort (copy-sequence alist)
20732 (lambda (a b) (< (length (car a)) (length (car b))))))
20733 (while (setq entry (pop alist))
20734 (setq template
20735 (replace-regexp-in-string
20736 (concat "%" (regexp-quote (car entry)))
20737 (or (cdr entry) "") template t t)))
20738 template))
20740 (defun org-base-buffer (buffer)
20741 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20742 (if (not buffer)
20743 buffer
20744 (or (buffer-base-buffer buffer)
20745 buffer)))
20747 (defun org-trim (s)
20748 "Remove whitespace at beginning and end of string."
20749 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20750 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20753 (defun org-wrap (string &optional width lines)
20754 "Wrap string to either a number of lines, or a width in characters.
20755 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20756 that costs. If there is a word longer than WIDTH, the text is actually
20757 wrapped to the length of that word.
20758 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20759 many lines, whatever width that takes.
20760 The return value is a list of lines, without newlines at the end."
20761 (let* ((words (org-split-string string "[ \t\n]+"))
20762 (maxword (apply 'max (mapcar 'org-string-width words)))
20763 w ll)
20764 (cond (width
20765 (org-do-wrap words (max maxword width)))
20766 (lines
20767 (setq w maxword)
20768 (setq ll (org-do-wrap words maxword))
20769 (if (<= (length ll) lines)
20771 (setq ll words)
20772 (while (> (length ll) lines)
20773 (setq w (1+ w))
20774 (setq ll (org-do-wrap words w)))
20775 ll))
20776 (t (error "Cannot wrap this")))))
20778 (defun org-do-wrap (words width)
20779 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20780 (let (lines line)
20781 (while words
20782 (setq line (pop words))
20783 (while (and words (< (+ (length line) (length (car words))) width))
20784 (setq line (concat line " " (pop words))))
20785 (setq lines (push line lines)))
20786 (nreverse lines)))
20788 (defun org-split-string (string &optional separators)
20789 "Splits STRING into substrings at SEPARATORS.
20790 No empty strings are returned if there are matches at the beginning
20791 and end of string."
20792 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20793 (start 0)
20794 notfirst
20795 (list nil))
20796 (while (and (string-match rexp string
20797 (if (and notfirst
20798 (= start (match-beginning 0))
20799 (< start (length string)))
20800 (1+ start) start))
20801 (< (match-beginning 0) (length string)))
20802 (setq notfirst t)
20803 (or (eq (match-beginning 0) 0)
20804 (and (eq (match-beginning 0) (match-end 0))
20805 (eq (match-beginning 0) start))
20806 (setq list
20807 (cons (substring string start (match-beginning 0))
20808 list)))
20809 (setq start (match-end 0)))
20810 (or (eq start (length string))
20811 (setq list
20812 (cons (substring string start)
20813 list)))
20814 (nreverse list)))
20816 (defun org-quote-vert (s)
20817 "Replace \"|\" with \"\\vert\"."
20818 (while (string-match "|" s)
20819 (setq s (replace-match "\\vert" t t s)))
20822 (defun org-uuidgen-p (s)
20823 "Is S an ID created by UUIDGEN?"
20824 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20826 (defun org-in-src-block-p (&optional inside)
20827 "Whether point is in a code source block.
20828 When INSIDE is non-nil, don't consider we are within a src block
20829 when point is at #+BEGIN_SRC or #+END_SRC."
20830 (let ((case-fold-search t) ov)
20831 (or (and (setq ov (overlays-at (point)))
20832 (memq 'org-block-background
20833 (overlay-properties (car ov))))
20834 (and (not inside)
20835 (save-match-data
20836 (save-excursion
20837 (beginning-of-line)
20838 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20840 (defun org-context ()
20841 "Return a list of contexts of the current cursor position.
20842 If several contexts apply, all are returned.
20843 Each context entry is a list with a symbol naming the context, and
20844 two positions indicating start and end of the context. Possible
20845 contexts are:
20847 :headline anywhere in a headline
20848 :headline-stars on the leading stars in a headline
20849 :todo-keyword on a TODO keyword (including DONE) in a headline
20850 :tags on the TAGS in a headline
20851 :priority on the priority cookie in a headline
20852 :item on the first line of a plain list item
20853 :item-bullet on the bullet/number of a plain list item
20854 :checkbox on the checkbox in a plain list item
20855 :table in an org-mode table
20856 :table-special on a special filed in a table
20857 :table-table in a table.el table
20858 :clocktable in a clocktable
20859 :src-block in a source block
20860 :link on a hyperlink
20861 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20862 :target on a <<target>>
20863 :radio-target on a <<<radio-target>>>
20864 :latex-fragment on a LaTeX fragment
20865 :latex-preview on a LaTeX fragment with overlaid preview image
20867 This function expects the position to be visible because it uses font-lock
20868 faces as a help to recognize the following contexts: :table-special, :link,
20869 and :keyword."
20870 (let* ((f (get-text-property (point) 'face))
20871 (faces (if (listp f) f (list f)))
20872 (case-fold-search t)
20873 (p (point)) clist o)
20874 ;; First the large context
20875 (cond
20876 ((org-at-heading-p t)
20877 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20878 (when (progn
20879 (beginning-of-line 1)
20880 (looking-at org-todo-line-tags-regexp))
20881 (push (org-point-in-group p 1 :headline-stars) clist)
20882 (push (org-point-in-group p 2 :todo-keyword) clist)
20883 (push (org-point-in-group p 4 :tags) clist))
20884 (goto-char p)
20885 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20886 (if (looking-at "\\[#[A-Z0-9]\\]")
20887 (push (org-point-in-group p 0 :priority) clist)))
20889 ((org-at-item-p)
20890 (push (org-point-in-group p 2 :item-bullet) clist)
20891 (push (list :item (point-at-bol)
20892 (save-excursion (org-end-of-item) (point)))
20893 clist)
20894 (and (org-at-item-checkbox-p)
20895 (push (org-point-in-group p 0 :checkbox) clist)))
20897 ((org-at-table-p)
20898 (push (list :table (org-table-begin) (org-table-end)) clist)
20899 (if (memq 'org-formula faces)
20900 (push (list :table-special
20901 (previous-single-property-change p 'face)
20902 (next-single-property-change p 'face)) clist)))
20903 ((org-at-table-p 'any)
20904 (push (list :table-table) clist)))
20905 (goto-char p)
20907 (let ((case-fold-search t))
20908 ;; New the "medium" contexts: clocktables, source blocks
20909 (cond ((org-in-clocktable-p)
20910 (push (list :clocktable
20911 (and (or (looking-at "#\\+BEGIN: clocktable")
20912 (search-backward "#+BEGIN: clocktable" nil t))
20913 (match-beginning 0))
20914 (and (re-search-forward "#\\+END:?" nil t)
20915 (match-end 0))) clist))
20916 ((org-in-src-block-p)
20917 (push (list :src-block
20918 (and (or (looking-at "#\\+BEGIN_SRC")
20919 (search-backward "#+BEGIN_SRC" nil t))
20920 (match-beginning 0))
20921 (and (search-forward "#+END_SRC" nil t)
20922 (match-beginning 0))) clist))))
20923 (goto-char p)
20925 ;; Now the small context
20926 (cond
20927 ((org-at-timestamp-p)
20928 (push (org-point-in-group p 0 :timestamp) clist))
20929 ((memq 'org-link faces)
20930 (push (list :link
20931 (previous-single-property-change p 'face)
20932 (next-single-property-change p 'face)) clist))
20933 ((memq 'org-special-keyword faces)
20934 (push (list :keyword
20935 (previous-single-property-change p 'face)
20936 (next-single-property-change p 'face)) clist))
20937 ((org-at-target-p)
20938 (push (org-point-in-group p 0 :target) clist)
20939 (goto-char (1- (match-beginning 0)))
20940 (if (looking-at org-radio-target-regexp)
20941 (push (org-point-in-group p 0 :radio-target) clist))
20942 (goto-char p))
20943 ((setq o (car (delq nil
20944 (mapcar
20945 (lambda (x)
20946 (if (memq x org-latex-fragment-image-overlays) x))
20947 (overlays-at (point))))))
20948 (push (list :latex-fragment
20949 (overlay-start o) (overlay-end o)) clist)
20950 (push (list :latex-preview
20951 (overlay-start o) (overlay-end o)) clist))
20952 ((org-inside-LaTeX-fragment-p)
20953 ;; FIXME: positions wrong.
20954 (push (list :latex-fragment (point) (point)) clist)))
20956 (setq clist (nreverse (delq nil clist)))
20957 clist))
20959 ;; FIXME: Compare with at-regexp-p Do we need both?
20960 (defun org-in-regexp (re &optional nlines visually)
20961 "Check if point is inside a match of regexp.
20962 Normally only the current line is checked, but you can include NLINES extra
20963 lines both before and after point into the search.
20964 If VISUALLY is set, require that the cursor is not after the match but
20965 really on, so that the block visually is on the match."
20966 (catch 'exit
20967 (let ((pos (point))
20968 (eol (point-at-eol (+ 1 (or nlines 0))))
20969 (inc (if visually 1 0)))
20970 (save-excursion
20971 (beginning-of-line (- 1 (or nlines 0)))
20972 (while (re-search-forward re eol t)
20973 (if (and (<= (match-beginning 0) pos)
20974 (>= (+ inc (match-end 0)) pos))
20975 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20977 (defun org-at-regexp-p (regexp)
20978 "Is point inside a match of REGEXP in the current line?"
20979 (catch 'exit
20980 (save-excursion
20981 (let ((pos (point)) (end (point-at-eol)))
20982 (beginning-of-line 1)
20983 (while (re-search-forward regexp end t)
20984 (if (and (<= (match-beginning 0) pos)
20985 (>= (match-end 0) pos))
20986 (throw 'exit t)))
20987 nil))))
20989 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20990 "Non-nil when point is between matches of START-RE and END-RE.
20992 Also return a non-nil value when point is on one of the matches.
20994 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20995 buffer positions. Default values are the positions of headlines
20996 surrounding the point.
20998 The functions returns a cons cell whose car (resp. cdr) is the
20999 position before START-RE (resp. after END-RE)."
21000 (save-match-data
21001 (let ((pos (point))
21002 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21003 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21004 beg end)
21005 (save-excursion
21006 ;; Point is on a block when on START-RE or if START-RE can be
21007 ;; found before it...
21008 (and (or (org-at-regexp-p start-re)
21009 (re-search-backward start-re limit-up t))
21010 (setq beg (match-beginning 0))
21011 ;; ... and END-RE after it...
21012 (goto-char (match-end 0))
21013 (re-search-forward end-re limit-down t)
21014 (> (setq end (match-end 0)) pos)
21015 ;; ... without another START-RE in-between.
21016 (goto-char (match-beginning 0))
21017 (not (re-search-backward start-re (1+ beg) t))
21018 ;; Return value.
21019 (cons beg end))))))
21021 (defun org-in-block-p (names)
21022 "Non-nil when point belongs to a block whose name belongs to NAMES.
21024 NAMES is a list of strings containing names of blocks.
21026 Return first block name matched, or nil. Beware that in case of
21027 nested blocks, the returned name may not belong to the closest
21028 block from point."
21029 (save-match-data
21030 (catch 'exit
21031 (let ((case-fold-search t)
21032 (lim-up (save-excursion (outline-previous-heading)))
21033 (lim-down (save-excursion (outline-next-heading))))
21034 (mapc (lambda (name)
21035 (let ((n (regexp-quote name)))
21036 (when (org-between-regexps-p
21037 (concat "^[ \t]*#\\+begin_" n)
21038 (concat "^[ \t]*#\\+end_" n)
21039 lim-up lim-down)
21040 (throw 'exit n))))
21041 names))
21042 nil)))
21044 (defun org-occur-in-agenda-files (regexp &optional nlines)
21045 "Call `multi-occur' with buffers for all agenda files."
21046 (interactive "sOrg-files matching: \np")
21047 (let* ((files (org-agenda-files))
21048 (tnames (mapcar 'file-truename files))
21049 (extra org-agenda-text-search-extra-files)
21051 (when (eq (car extra) 'agenda-archives)
21052 (setq extra (cdr extra))
21053 (setq files (org-add-archive-files files)))
21054 (while (setq f (pop extra))
21055 (unless (member (file-truename f) tnames)
21056 (add-to-list 'files f 'append)
21057 (add-to-list 'tnames (file-truename f) 'append)))
21058 (multi-occur
21059 (mapcar (lambda (x)
21060 (with-current-buffer
21061 (or (get-file-buffer x) (find-file-noselect x))
21062 (widen)
21063 (current-buffer)))
21064 files)
21065 regexp)))
21067 (if (boundp 'occur-mode-find-occurrence-hook)
21068 ;; Emacs 23
21069 (add-hook 'occur-mode-find-occurrence-hook
21070 (lambda ()
21071 (when (derived-mode-p 'org-mode)
21072 (org-reveal))))
21073 ;; Emacs 22
21074 (defadvice occur-mode-goto-occurrence
21075 (after org-occur-reveal activate)
21076 (and (derived-mode-p 'org-mode) (org-reveal)))
21077 (defadvice occur-mode-goto-occurrence-other-window
21078 (after org-occur-reveal activate)
21079 (and (derived-mode-p 'org-mode) (org-reveal)))
21080 (defadvice occur-mode-display-occurrence
21081 (after org-occur-reveal activate)
21082 (when (derived-mode-p 'org-mode)
21083 (let ((pos (occur-mode-find-occurrence)))
21084 (with-current-buffer (marker-buffer pos)
21085 (save-excursion
21086 (goto-char pos)
21087 (org-reveal)))))))
21089 (defun org-occur-link-in-agenda-files ()
21090 "Create a link and search for it in the agendas.
21091 The link is not stored in `org-stored-links', it is just created
21092 for the search purpose."
21093 (interactive)
21094 (let ((link (condition-case nil
21095 (org-store-link nil)
21096 (error "Unable to create a link to here"))))
21097 (org-occur-in-agenda-files (regexp-quote link))))
21099 (defun org-uniquify (list)
21100 "Remove duplicate elements from LIST."
21101 (let (res)
21102 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21103 res))
21105 (defun org-delete-all (elts list)
21106 "Remove all elements in ELTS from LIST."
21107 (while elts
21108 (setq list (delete (pop elts) list)))
21109 list)
21111 (defun org-count (cl-item cl-seq)
21112 "Count the number of occurrences of ITEM in SEQ.
21113 Taken from `count' in cl-seq.el with all keyword arguments removed."
21114 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21115 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21116 (while (< cl-start cl-end)
21117 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21118 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21119 (setq cl-start (1+ cl-start)))
21120 cl-count))
21122 (defun org-remove-if (predicate seq)
21123 "Remove everything from SEQ that fulfills PREDICATE."
21124 (let (res e)
21125 (while seq
21126 (setq e (pop seq))
21127 (if (not (funcall predicate e)) (push e res)))
21128 (nreverse res)))
21130 (defun org-remove-if-not (predicate seq)
21131 "Remove everything from SEQ that does not fulfill PREDICATE."
21132 (let (res e)
21133 (while seq
21134 (setq e (pop seq))
21135 (if (funcall predicate e) (push e res)))
21136 (nreverse res)))
21138 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21139 "Reduce two-argument FUNCTION across SEQ.
21140 Taken from `reduce' in cl-seq.el with all keyword arguments but
21141 \":initial-value\" removed."
21142 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21143 (cadr (memq :initial-value cl-keys)))
21144 (cl-seq (pop cl-seq))
21145 (t (funcall cl-func)))))
21146 (while cl-seq
21147 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21148 cl-accum))
21150 (defun org-back-over-empty-lines ()
21151 "Move backwards over whitespace, to the beginning of the first empty line.
21152 Returns the number of empty lines passed."
21153 (let ((pos (point)))
21154 (if (cdr (assoc 'heading org-blank-before-new-entry))
21155 (skip-chars-backward " \t\n\r")
21156 (unless (eobp)
21157 (forward-line -1)))
21158 (beginning-of-line 2)
21159 (goto-char (min (point) pos))
21160 (count-lines (point) pos)))
21162 (defun org-skip-whitespace ()
21163 (skip-chars-forward " \t\n\r"))
21165 (defun org-point-in-group (point group &optional context)
21166 "Check if POINT is in match-group GROUP.
21167 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21168 match. If the match group does not exist or point is not inside it,
21169 return nil."
21170 (and (match-beginning group)
21171 (>= point (match-beginning group))
21172 (<= point (match-end group))
21173 (if context
21174 (list context (match-beginning group) (match-end group))
21175 t)))
21177 (defun org-switch-to-buffer-other-window (&rest args)
21178 "Switch to buffer in a second window on the current frame.
21179 In particular, do not allow pop-up frames.
21180 Returns the newly created buffer."
21181 (org-no-popups
21182 (apply 'switch-to-buffer-other-window args)))
21184 (defun org-combine-plists (&rest plists)
21185 "Create a single property list from all plists in PLISTS.
21186 The process starts by copying the first list, and then setting properties
21187 from the other lists. Settings in the last list are the most significant
21188 ones and overrule settings in the other lists."
21189 (let ((rtn (copy-sequence (pop plists)))
21190 p v ls)
21191 (while plists
21192 (setq ls (pop plists))
21193 (while ls
21194 (setq p (pop ls) v (pop ls))
21195 (setq rtn (plist-put rtn p v))))
21196 rtn))
21198 (defun org-replace-escapes (string table)
21199 "Replace %-escapes in STRING with values in TABLE.
21200 TABLE is an association list with keys like \"%a\" and string values.
21201 The sequences in STRING may contain normal field width and padding information,
21202 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21203 so values can contain further %-escapes if they are define later in TABLE."
21204 (let ((tbl (copy-alist table))
21205 (case-fold-search nil)
21206 (pchg 0)
21207 e re rpl)
21208 (while (setq e (pop tbl))
21209 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21210 (when (and (cdr e) (string-match re (cdr e)))
21211 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21212 (safe "SREF"))
21213 (add-text-properties 0 3 (list 'sref sref) safe)
21214 (setcdr e (replace-match safe t t (cdr e)))))
21215 (while (string-match re string)
21216 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21217 (cdr e)))
21218 (setq string (replace-match rpl t t string))))
21219 (while (setq pchg (next-property-change pchg string))
21220 (let ((sref (get-text-property pchg 'sref string)))
21221 (when (and sref (string-match "SREF" string pchg))
21222 (setq string (replace-match sref t t string)))))
21223 string))
21225 (defun org-sublist (list start end)
21226 "Return a section of LIST, from START to END.
21227 Counting starts at 1."
21228 (let (rtn (c start))
21229 (setq list (nthcdr (1- start) list))
21230 (while (and list (<= c end))
21231 (push (pop list) rtn)
21232 (setq c (1+ c)))
21233 (nreverse rtn)))
21235 (defun org-find-base-buffer-visiting (file)
21236 "Like `find-buffer-visiting' but always return the base buffer and
21237 not an indirect buffer."
21238 (let ((buf (or (get-file-buffer file)
21239 (find-buffer-visiting file))))
21240 (if buf
21241 (or (buffer-base-buffer buf) buf)
21242 nil)))
21244 (defun org-image-file-name-regexp (&optional extensions)
21245 "Return regexp matching the file names of images.
21246 If EXTENSIONS is given, only match these."
21247 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21248 (image-file-name-regexp)
21249 (let ((image-file-name-extensions
21250 (or extensions
21251 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21252 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21253 (concat "\\."
21254 (regexp-opt (nconc (mapcar 'upcase
21255 image-file-name-extensions)
21256 image-file-name-extensions)
21258 "\\'"))))
21260 (defun org-file-image-p (file &optional extensions)
21261 "Return non-nil if FILE is an image."
21262 (save-match-data
21263 (string-match (org-image-file-name-regexp extensions) file)))
21265 (defun org-get-cursor-date (&optional with-time)
21266 "Return the date at cursor in as a time.
21267 This works in the calendar and in the agenda, anywhere else it just
21268 returns the current time.
21269 If WITH-TIME is non-nil, returns the time of the event at point (in
21270 the agenda) or the current time of the day."
21271 (let (date day defd tp tm hod mod)
21272 (when with-time
21273 (setq tp (get-text-property (point) 'time))
21274 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21275 (setq hod (string-to-number (match-string 1 tp))
21276 mod (string-to-number (match-string 2 tp))))
21277 (or tp (setq hod (nth 2 (decode-time (current-time)))
21278 mod (nth 1 (decode-time (current-time))))))
21279 (cond
21280 ((eq major-mode 'calendar-mode)
21281 (setq date (calendar-cursor-to-date)
21282 defd (encode-time 0 (or mod 0) (or hod 0)
21283 (nth 1 date) (nth 0 date) (nth 2 date))))
21284 ((eq major-mode 'org-agenda-mode)
21285 (setq day (get-text-property (point) 'day))
21286 (if day
21287 (setq date (calendar-gregorian-from-absolute day)
21288 defd (encode-time 0 (or mod 0) (or hod 0)
21289 (nth 1 date) (nth 0 date) (nth 2 date))))))
21290 (or defd (current-time))))
21292 (defun org-mark-subtree (&optional up)
21293 "Mark the current subtree.
21294 This puts point at the start of the current subtree, and mark at
21295 the end. If a numeric prefix UP is given, move up into the
21296 hierarchy of headlines by UP levels before marking the subtree."
21297 (interactive "P")
21298 (org-with-limited-levels
21299 (cond ((org-at-heading-p) (beginning-of-line))
21300 ((org-before-first-heading-p) (error "Not in a subtree"))
21301 (t (outline-previous-visible-heading 1))))
21302 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21303 (if (org-called-interactively-p 'any)
21304 (call-interactively 'org-mark-element)
21305 (org-mark-element)))
21308 ;;; Macros
21310 ;; Macros are expanded with `org-macro-replace-all', which relies
21311 ;; internally on `org-macro-expand'.
21313 ;; Default templates for expansion are stored in the buffer-local
21314 ;; variable `org-macro-templates'. This variable is updated by
21315 ;; `org-macro-initialize-templates'.
21317 ;; Along with macros defined through #+MACRO: keyword, default
21318 ;; templates include the following hard-coded macros:
21319 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21320 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21322 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21323 ;; {{{title}}} will also be provided.
21326 (defvar org-macro-templates nil
21327 "Alist containing all macro templates in current buffer.
21328 Associations are in the shape of (NAME . TEMPLATE) where NAME
21329 stands for macro's name and template for its replacement value,
21330 both as strings. This is an internal variable. Do not set it
21331 directly, use instead:
21333 #+MACRO: name template")
21334 (make-variable-buffer-local 'org-macro-templates)
21336 (defun org-macro-expand (macro templates)
21337 "Return expanded MACRO, as a string.
21338 MACRO is an object, obtained, for example, with
21339 `org-element-context'. TEMPLATES is an alist of templates used
21340 for expansion. See `org-macro-templates' for a buffer-local
21341 default value. Return nil if no template was found."
21342 (let ((template
21343 ;; Macro names are case-insensitive.
21344 (cdr (assoc-string (org-element-property :key macro) templates t))))
21345 (when template
21346 (let ((value (replace-regexp-in-string
21347 "\\$[0-9]+"
21348 (lambda (arg)
21349 (or (nth (1- (string-to-number (substring arg 1)))
21350 (org-element-property :args macro))
21351 ;; No argument provided: remove
21352 ;; place-holder.
21353 ""))
21354 template)))
21355 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21356 (when (string-match "\\`(eval\\>" value)
21357 (setq value (eval (read value))))
21358 ;; Return string.
21359 (format "%s" (or value ""))))))
21361 (defun org-macro-replace-all (templates)
21362 "Replace all macros in current buffer by their expansion.
21363 TEMPLATES is an alist of templates used for expansion. See
21364 `org-macro-templates' for a buffer-local default value."
21365 (save-excursion
21366 (goto-char (point-min))
21367 (let (record)
21368 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21369 (let ((object (org-element-context)))
21370 (when (eq (org-element-type object) 'macro)
21371 (let* ((value (org-macro-expand object templates))
21372 (begin (org-element-property :begin object))
21373 (signature (list begin
21374 object
21375 (org-element-property :args object))))
21376 ;; Avoid circular dependencies by checking if the same
21377 ;; macro with the same arguments is expanded at the same
21378 ;; position twice.
21379 (if (member signature record)
21380 (error "Circular macro expansion: %s"
21381 (org-element-property :key object))
21382 (when value
21383 (push signature record)
21384 (delete-region
21385 begin
21386 ;; Preserve white spaces after the macro.
21387 (progn (goto-char (org-element-property :end object))
21388 (skip-chars-backward " \t")
21389 (point)))
21390 ;; Leave point before replacement in case of recursive
21391 ;; expansions.
21392 (save-excursion (insert value)))))))))))
21394 (defun org-macro-initialize-templates ()
21395 "Collect macro templates defined in current buffer.
21396 Templates are stored in buffer-local variable
21397 `org-macro-templates'. In addition to buffer-defined macros, the
21398 function installs the following ones: \"property\",
21399 \"time\". and, if the buffer is associated to a file,
21400 \"input-file\" and \"modification-time\"."
21401 (let ((case-fold-search t)
21402 (set-template
21403 (lambda (cell)
21404 ;; Add CELL to `org-macro-templates' if there's no
21405 ;; association matching its name already. Otherwise,
21406 ;; replace old association with the new one in that
21407 ;; variable.
21408 (let ((old-template (assoc (car cell) org-macro-templates)))
21409 (if old-template (setcdr old-template (cdr cell))
21410 (push cell org-macro-templates))))))
21411 ;; Install buffer-local macros.
21412 (org-with-wide-buffer
21413 (goto-char (point-min))
21414 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21415 (let ((element (org-element-at-point)))
21416 (when (eq (org-element-type element) 'keyword)
21417 (let ((value (org-element-property :value element)))
21418 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21419 (funcall set-template
21420 (cons (match-string 1 value)
21421 (or (match-string 2 value) "")))))))))
21422 ;; Install hard-coded macros.
21423 (mapc (lambda (cell) (funcall set-template cell))
21424 (list
21425 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21426 (cons "time" "(eval (format-time-string \"$1\"))")))
21427 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21428 (when (and visited-file (file-exists-p visited-file))
21429 (mapc (lambda (cell) (funcall set-template cell))
21430 (list
21431 (cons "input-file" (file-name-nondirectory visited-file))
21432 (cons "modification-time"
21433 (format "(eval (format-time-string \"$1\" '%s))"
21434 (prin1-to-string
21435 (nth 5 (file-attributes visited-file)))))))))))
21438 ;;; Indentation
21440 (defun org-indent-line ()
21441 "Indent line depending on context."
21442 (interactive)
21443 (let* ((pos (point))
21444 (itemp (org-at-item-p))
21445 (case-fold-search t)
21446 (org-drawer-regexp (or org-drawer-regexp "\000"))
21447 (inline-task-p (and (featurep 'org-inlinetask)
21448 (org-inlinetask-in-task-p)))
21449 (inline-re (and inline-task-p
21450 (org-inlinetask-outline-regexp)))
21451 column)
21452 (if (and orgstruct-is-++ (eq pos (point)))
21453 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21454 (indent-according-to-mode))
21455 (beginning-of-line 1)
21456 (cond
21457 ;; Headings
21458 ((looking-at org-outline-regexp) (setq column 0))
21459 ;; Footnote definition
21460 ((looking-at org-footnote-definition-re) (setq column 0))
21461 ;; Literal examples
21462 ((looking-at "[ \t]*:\\( \\|$\\)")
21463 (setq column (org-get-indentation))) ; do nothing
21464 ;; Lists
21465 ((ignore-errors (goto-char (org-in-item-p)))
21466 (setq column (if itemp
21467 (org-get-indentation)
21468 (org-list-item-body-column (point))))
21469 (goto-char pos))
21470 ;; Drawers
21471 ((and (looking-at "[ \t]*:END:")
21472 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21473 (save-excursion
21474 (goto-char (1- (match-beginning 1)))
21475 (setq column (current-column))))
21476 ;; Special blocks
21477 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21478 (save-excursion
21479 (re-search-backward
21480 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21481 (setq column (org-get-indentation (match-string 0))))
21482 ((and (not (looking-at "[ \t]*#\\+begin_"))
21483 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21484 (save-excursion
21485 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21486 (setq column
21487 (cond ((equal (downcase (match-string 1)) "src")
21488 ;; src blocks: let `org-edit-src-exit' handle them
21489 (org-get-indentation))
21490 ((equal (downcase (match-string 1)) "example")
21491 (max (org-get-indentation)
21492 (org-get-indentation (match-string 0))))
21494 (org-get-indentation (match-string 0))))))
21495 ;; This line has nothing special, look at the previous relevant
21496 ;; line to compute indentation
21498 (beginning-of-line 0)
21499 (while (and (not (bobp))
21500 (not (looking-at org-table-line-regexp))
21501 (not (looking-at org-drawer-regexp))
21502 ;; When point started in an inline task, do not move
21503 ;; above task starting line.
21504 (not (and inline-task-p (looking-at inline-re)))
21505 ;; Skip drawers, blocks, empty lines, verbatim,
21506 ;; comments, tables, footnotes definitions, lists,
21507 ;; inline tasks.
21508 (or (and (looking-at "[ \t]*:END:")
21509 (re-search-backward org-drawer-regexp nil t))
21510 (and (looking-at "[ \t]*#\\+end_")
21511 (re-search-backward "[ \t]*#\\+begin_"nil t))
21512 (looking-at "[ \t]*[\n:#|]")
21513 (looking-at org-footnote-definition-re)
21514 (and (ignore-errors (goto-char (org-in-item-p)))
21515 (goto-char
21516 (org-list-get-top-point (org-list-struct))))
21517 (and (not inline-task-p)
21518 (featurep 'org-inlinetask)
21519 (org-inlinetask-in-task-p)
21520 (or (org-inlinetask-goto-beginning) t))))
21521 (beginning-of-line 0))
21522 (cond
21523 ;; There was an heading above.
21524 ((looking-at "\\*+[ \t]+")
21525 (if (not org-adapt-indentation)
21526 (setq column 0)
21527 (goto-char (match-end 0))
21528 (setq column (current-column))))
21529 ;; A drawer had started and is unfinished
21530 ((looking-at org-drawer-regexp)
21531 (goto-char (1- (match-beginning 1)))
21532 (setq column (current-column)))
21533 ;; Else, nothing noticeable found: get indentation and go on.
21534 (t (setq column (org-get-indentation))))))
21535 ;; Now apply indentation and move cursor accordingly
21536 (goto-char pos)
21537 (if (<= (current-column) (current-indentation))
21538 (org-indent-line-to column)
21539 (save-excursion (org-indent-line-to column)))
21540 ;; Special polishing for properties, see `org-property-format'
21541 (setq column (current-column))
21542 (beginning-of-line 1)
21543 (if (looking-at
21544 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21545 (replace-match (concat (match-string 1)
21546 (format org-property-format
21547 (match-string 2) (match-string 3)))
21548 t t))
21549 (org-move-to-column column))))
21551 (defun org-indent-drawer ()
21552 "Indent the drawer at point."
21553 (interactive)
21554 (let ((p (point))
21555 (e (and (save-excursion (re-search-forward ":END:" nil t))
21556 (match-end 0)))
21557 (folded
21558 (save-excursion
21559 (end-of-line)
21560 (when (overlays-at (point))
21561 (member 'invisible (overlay-properties
21562 (car (overlays-at (point)))))))))
21563 (when folded (org-cycle))
21564 (indent-for-tab-command)
21565 (while (and (move-beginning-of-line 2) (< (point) e))
21566 (indent-for-tab-command))
21567 (goto-char p)
21568 (when folded (org-cycle)))
21569 (message "Drawer at point indented"))
21571 (defun org-indent-block ()
21572 "Indent the block at point."
21573 (interactive)
21574 (let ((p (point))
21575 (case-fold-search t)
21576 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21577 (match-end 0)))
21578 (folded
21579 (save-excursion
21580 (end-of-line)
21581 (when (overlays-at (point))
21582 (member 'invisible (overlay-properties
21583 (car (overlays-at (point)))))))))
21584 (when folded (org-cycle))
21585 (indent-for-tab-command)
21586 (while (and (move-beginning-of-line 2) (< (point) e))
21587 (indent-for-tab-command))
21588 (goto-char p)
21589 (when folded (org-cycle)))
21590 (message "Block at point indented"))
21592 (defun org-indent-region (start end)
21593 "Indent region."
21594 (interactive "r")
21595 (save-excursion
21596 (let ((line-end (org-current-line end)))
21597 (goto-char start)
21598 (while (< (org-current-line) line-end)
21599 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21600 (t (call-interactively 'org-indent-line)))
21601 (move-beginning-of-line 2)))))
21604 ;;; Filling
21606 ;; We use our own fill-paragraph and auto-fill functions.
21608 ;; `org-fill-paragraph' relies on adaptive filling and context
21609 ;; checking. Appropriate `fill-prefix' is computed with
21610 ;; `org-adaptive-fill-function'.
21612 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21613 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21614 ;; `org-adaptive-fill-function' value. Internally,
21615 ;; `org-comment-line-break-function' breaks the line.
21617 ;; `org-setup-filling' installs filling and auto-filling related
21618 ;; variables during `org-mode' initialization.
21620 (defun org-setup-filling ()
21621 (interactive)
21622 ;; Prevent auto-fill from inserting unwanted new items.
21623 (when (boundp 'fill-nobreak-predicate)
21624 (org-set-local
21625 'fill-nobreak-predicate
21626 (org-uniquify
21627 (append fill-nobreak-predicate
21628 '(org-fill-paragraph-separate-nobreak-p
21629 org-fill-line-break-nobreak-p)))))
21630 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21631 (org-set-local 'auto-fill-inhibit-regexp nil)
21632 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21633 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21634 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21636 (defvar org-element-paragraph-separate) ; org-element.el
21637 (defun org-fill-paragraph-separate-nobreak-p ()
21638 "Non-nil when a line break at point would insert a new item."
21639 (looking-at (substring org-element-paragraph-separate 1)))
21641 (defun org-fill-line-break-nobreak-p ()
21642 "Non-nil when a line break at point would create an Org line break."
21643 (save-excursion
21644 (skip-chars-backward "[ \t]")
21645 (skip-chars-backward "\\\\")
21646 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21648 (declare-function message-in-body-p "message" ())
21649 (defvar orgtbl-line-start-regexp) ; From org-table.el
21650 (defun org-adaptive-fill-function ()
21651 "Compute a fill prefix for the current line.
21652 Return fill prefix, as a string, or nil if current line isn't
21653 meant to be filled."
21654 (let (prefix)
21655 (catch 'exit
21656 (when (derived-mode-p 'message-mode)
21657 (save-excursion
21658 (beginning-of-line)
21659 (cond ((or (not (message-in-body-p))
21660 (looking-at orgtbl-line-start-regexp))
21661 (throw 'exit nil))
21662 ((looking-at message-cite-prefix-regexp)
21663 (throw 'exit (match-string-no-properties 0)))
21664 ((looking-at org-outline-regexp)
21665 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21666 (org-with-wide-buffer
21667 (let* ((p (line-beginning-position))
21668 (element (save-excursion (beginning-of-line)
21669 (org-element-at-point)))
21670 (type (org-element-type element))
21671 (post-affiliated (org-element-property :post-affiliated element)))
21672 (unless (and post-affiliated (< p post-affiliated))
21673 (case type
21674 (comment (looking-at "[ \t]*# ?") (match-string 0))
21675 (footnote-definition "")
21676 ((item plain-list)
21677 (make-string (org-list-item-body-column
21678 (or post-affiliated
21679 (org-element-property :begin element)))
21680 ? ))
21681 (paragraph
21682 ;; Fill prefix is usually the same as the current line,
21683 ;; except if the paragraph is at the beginning of an item.
21684 (let ((parent (org-element-property :parent element)))
21685 (cond ((eq (org-element-type parent) 'item)
21686 (make-string (org-list-item-body-column
21687 (org-element-property :begin parent))
21688 ? ))
21689 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21690 (match-string 0))
21691 (t ""))))
21692 (comment-block
21693 ;; Only fill contents if P is within block boundaries.
21694 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21695 (forward-line)
21696 (point)))
21697 (cend (save-excursion
21698 (goto-char (org-element-property :end element))
21699 (skip-chars-backward " \r\t\n")
21700 (line-beginning-position))))
21701 (when (and (>= p cbeg) (< p cend))
21702 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21703 (match-string 0)
21704 "")))))))))))
21706 (declare-function message-goto-body "message" ())
21707 (defvar message-cite-prefix-regexp) ; From message.el
21708 (defvar org-element-all-objects) ; From org-element.el
21709 (defun org-fill-paragraph (&optional justify)
21710 "Fill element at point, when applicable.
21712 This function only applies to comment blocks, comments, example
21713 blocks and paragraphs. Also, as a special case, re-align table
21714 when point is at one.
21716 If JUSTIFY is non-nil (interactively, with prefix argument),
21717 justify as well. If `sentence-end-double-space' is non-nil, then
21718 period followed by one space does not end a sentence, so don't
21719 break a line there. The variable `fill-column' controls the
21720 width for filling.
21722 For convenience, when point is at a plain list, an item or
21723 a footnote definition, try to fill the first paragraph within."
21724 (interactive)
21725 (if (and (derived-mode-p 'message-mode)
21726 (or (not (message-in-body-p))
21727 (save-excursion (move-beginning-of-line 1)
21728 (looking-at message-cite-prefix-regexp))))
21729 ;; First ensure filling is correct in message-mode.
21730 (let ((fill-paragraph-function
21731 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21732 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21733 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21734 (paragraph-separate
21735 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21736 (fill-paragraph nil))
21737 (save-excursion
21738 ;; Move to end of line in order to get the first paragraph
21739 ;; within a plain list or a footnote definition.
21740 (end-of-line)
21741 (let ((element (org-element-at-point)))
21742 ;; First check if point is in a blank line at the beginning of
21743 ;; the buffer. In that case, ignore filling.
21744 (if (< (point) (org-element-property :begin element)) t
21745 (case (org-element-type element)
21746 ;; Use major mode filling function is src blocks.
21747 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21748 ;; Align Org tables, leave table.el tables as-is.
21749 (table-row (org-table-align) t)
21750 (table
21751 (when (eq (org-element-property :type element) 'org)
21752 (org-table-align))
21754 (paragraph
21755 ;; Paragraphs may contain `line-break' type objects.
21756 (let ((beg (max (point-min)
21757 (org-element-property :contents-begin element)))
21758 (end (min (point-max)
21759 (org-element-property :contents-end element))))
21760 ;; Do nothing if point is at an affiliated keyword.
21761 (if (< (point) beg) t
21762 (when (derived-mode-p 'message-mode)
21763 ;; In `message-mode', do not fill following
21764 ;; citation in current paragraph nor text before
21765 ;; message body.
21766 (let ((body-start (save-excursion (message-goto-body))))
21767 (when body-start (setq beg (max body-start beg))))
21768 (when (save-excursion
21769 (re-search-forward
21770 (concat "^" message-cite-prefix-regexp) end t))
21771 (setq end (match-beginning 0))))
21772 ;; Fill paragraph, taking line breaks into
21773 ;; consideration. For that, slice the paragraph
21774 ;; using line breaks as separators, and fill the
21775 ;; parts in reverse order to avoid messing with
21776 ;; markers.
21777 (save-excursion
21778 (goto-char end)
21779 (mapc
21780 (lambda (pos)
21781 (fill-region-as-paragraph pos (point) justify)
21782 (goto-char pos))
21783 ;; Find the list of ending positions for line
21784 ;; breaks in the current paragraph. Add paragraph
21785 ;; beginning to include first slice.
21786 (nreverse
21787 (cons
21789 (org-element-map
21790 (org-element--parse-objects
21791 beg end nil org-element-all-objects)
21792 'line-break
21793 (lambda (lb) (org-element-property :end lb)))))))
21794 t)))
21795 ;; Contents of `comment-block' type elements should be
21796 ;; filled as plain text, but only if point is within block
21797 ;; markers.
21798 (comment-block
21799 (let* ((case-fold-search t)
21800 (beg (save-excursion
21801 (goto-char (org-element-property :begin element))
21802 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21803 (forward-line)
21804 (point)))
21805 (end (save-excursion
21806 (goto-char (org-element-property :end element))
21807 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21808 (line-beginning-position))))
21809 (when (and (>= (point) beg) (< (point) end))
21810 (fill-region-as-paragraph
21811 (save-excursion
21812 (end-of-line)
21813 (re-search-backward "^[ \t]*$" beg 'move)
21814 (line-beginning-position))
21815 (save-excursion
21816 (beginning-of-line)
21817 (re-search-forward "^[ \t]*$" end 'move)
21818 (line-beginning-position))
21819 justify)))
21821 ;; Fill comments.
21822 (comment (fill-comment-paragraph justify))
21823 ;; Ignore every other element.
21824 (otherwise t)))))))
21826 (defun org-auto-fill-function ()
21827 "Auto-fill function."
21828 ;; Check if auto-filling is meaningful.
21829 (let ((fc (current-fill-column)))
21830 (when (and fc (> (current-column) fc))
21831 (let* ((fill-prefix (org-adaptive-fill-function))
21832 ;; Enforce empty fill prefix, if required. Otherwise, it
21833 ;; will be computed again.
21834 (adaptive-fill-mode (not (equal fill-prefix ""))))
21835 (when fill-prefix (do-auto-fill))))))
21837 (defun org-comment-line-break-function (&optional soft)
21838 "Break line at point and indent, continuing comment if within one.
21839 The inserted newline is marked hard if variable
21840 `use-hard-newlines' is true, unless optional argument SOFT is
21841 non-nil."
21842 (if soft (insert-and-inherit ?\n) (newline 1))
21843 (save-excursion (forward-char -1) (delete-horizontal-space))
21844 (delete-horizontal-space)
21845 (indent-to-left-margin)
21846 (insert-before-markers-and-inherit fill-prefix))
21849 ;;; Comments
21851 ;; Org comments syntax is quite complex. It requires the entire line
21852 ;; to be just a comment. Also, even with the right syntax at the
21853 ;; beginning of line, some some elements (i.e. verse-block or
21854 ;; example-block) don't accept comments. Usual Emacs comment commands
21855 ;; cannot cope with those requirements. Therefore, Org replaces them.
21857 ;; Org still relies on `comment-dwim', but cannot trust
21858 ;; `comment-only-p'. So, `comment-region-function' and
21859 ;; `uncomment-region-function' both point
21860 ;; to`org-comment-or-uncomment-region'. Eventually,
21861 ;; `org-insert-comment' takes care of insertion of comments at the
21862 ;; beginning of line.
21864 ;; `org-setup-comments-handling' install comments related variables
21865 ;; during `org-mode' initialization.
21867 (defun org-setup-comments-handling ()
21868 (interactive)
21869 (org-set-local 'comment-use-syntax nil)
21870 (org-set-local 'comment-start "# ")
21871 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21872 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21873 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21874 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21876 (defun org-insert-comment ()
21877 "Insert an empty comment above current line.
21878 If the line is empty, insert comment at its beginning."
21879 (beginning-of-line)
21880 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21881 (org-indent-line)
21882 (insert "# "))
21884 (defvar comment-empty-lines) ; From newcomment.el.
21885 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21886 "Comment or uncomment each non-blank line in the region.
21887 Uncomment each non-blank line between BEG and END if it only
21888 contains commented lines. Otherwise, comment them."
21889 (save-restriction
21890 ;; Restrict region
21891 (narrow-to-region (save-excursion (goto-char beg)
21892 (skip-chars-forward " \r\t\n" end)
21893 (line-beginning-position))
21894 (save-excursion (goto-char end)
21895 (skip-chars-backward " \r\t\n" beg)
21896 (line-end-position)))
21897 (let ((uncommentp
21898 ;; UNCOMMENTP is non-nil when every non blank line between
21899 ;; BEG and END is a comment.
21900 (save-excursion
21901 (goto-char (point-min))
21902 (while (and (not (eobp))
21903 (let ((element (org-element-at-point)))
21904 (and (eq (org-element-type element) 'comment)
21905 (goto-char (min (point-max)
21906 (org-element-property
21907 :end element)))))))
21908 (eobp))))
21909 (if uncommentp
21910 ;; Only blank lines and comments in region: uncomment it.
21911 (save-excursion
21912 (goto-char (point-min))
21913 (while (not (eobp))
21914 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21915 (replace-match "" nil nil nil 1))
21916 (forward-line)))
21917 ;; Comment each line in region.
21918 (let ((min-indent (point-max)))
21919 ;; First find the minimum indentation across all lines.
21920 (save-excursion
21921 (goto-char (point-min))
21922 (while (and (not (eobp)) (not (zerop min-indent)))
21923 (unless (looking-at "[ \t]*$")
21924 (setq min-indent (min min-indent (current-indentation))))
21925 (forward-line)))
21926 ;; Then loop over all lines.
21927 (save-excursion
21928 (goto-char (point-min))
21929 (while (not (eobp))
21930 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21931 (org-move-to-column min-indent t)
21932 (insert comment-start))
21933 (forward-line))))))))
21936 ;;; Planning
21938 ;; This section contains tools to operate on timestamp objects, as
21939 ;; returned by, e.g. `org-element-context'.
21941 (defun org-timestamp-has-time-p (timestamp)
21942 "Non-nil when TIMESTAMP has a time specified."
21943 (org-element-property :hour-start timestamp))
21945 (defun org-timestamp-format (timestamp format &optional end utc)
21946 "Format a TIMESTAMP element into a string.
21948 FORMAT is a format specifier to be passed to
21949 `format-time-string'.
21951 When optional argument END is non-nil, use end of date-range or
21952 time-range, if possible.
21954 When optional argument UTC is non-nil, time will be expressed as
21955 Universal Time."
21956 (format-time-string
21957 format
21958 (apply 'encode-time
21959 (cons 0
21960 (mapcar
21961 (lambda (prop) (or (org-element-property prop timestamp) 0))
21962 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21963 '(:minute-start :hour-start :day-start :month-start
21964 :year-start)))))
21965 utc))
21967 (defun org-timestamp-split-range (timestamp &optional end)
21968 "Extract a timestamp object from a date or time range.
21970 TIMESTAMP is a timestamp object. END, when non-nil, means extract
21971 the end of the range. Otherwise, extract its start.
21973 Return a new timestamp object sharing the same parent as
21974 TIMESTAMP."
21975 (let ((type (org-element-property :type timestamp)))
21976 (if (memq type '(active inactive diary)) timestamp
21977 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
21978 ;; Set new type.
21979 (org-element-put-property
21980 split-ts :type (if (eq type 'active-range) 'active 'inactive))
21981 ;; Copy start properties over end properties if END is
21982 ;; non-nil. Otherwise, copy end properties over `start' ones.
21983 (let ((p-alist '((:minute-start . :minute-end)
21984 (:hour-start . :hour-end)
21985 (:day-start . :day-end)
21986 (:month-start . :month-end)
21987 (:year-start . :year-end))))
21988 (dolist (p-cell p-alist)
21989 (org-element-put-property
21990 split-ts
21991 (funcall (if end 'car 'cdr) p-cell)
21992 (org-element-property
21993 (funcall (if end 'cdr 'car) p-cell) split-ts)))
21994 ;; Eventually refresh `:raw-value'.
21995 (org-element-put-property split-ts :raw-value nil)
21996 (org-element-put-property
21997 split-ts :raw-value (org-element-interpret-data split-ts)))))))
21999 (defun org-timestamp-translate (timestamp &optional boundary)
22000 "Apply `org-translate-time' on a TIMESTAMP object.
22001 When optional argument BOUNDARY is non-nil, it is either the
22002 symbol `start' or `end'. In this case, only translate the
22003 starting or ending part of TIMESTAMP if it is a date or time
22004 range. Otherwise, translate both parts."
22005 (if (and (not boundary)
22006 (memq (org-element-property :type timestamp)
22007 '(active-range inactive-range)))
22008 (concat
22009 (org-translate-time
22010 (org-element-property :raw-value
22011 (org-timestamp-split-range timestamp)))
22012 "--"
22013 (org-translate-time
22014 (org-element-property :raw-value
22015 (org-timestamp-split-range timestamp t))))
22016 (org-translate-time
22017 (org-element-property
22018 :raw-value
22019 (if (not boundary) timestamp
22020 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22024 ;;; Other stuff.
22026 (defun org-toggle-fixed-width-section (arg)
22027 "Toggle the fixed-width export.
22028 If there is no active region, the QUOTE keyword at the current headline is
22029 inserted or removed. When present, it causes the text between this headline
22030 and the next to be exported as fixed-width text, and unmodified.
22031 If there is an active region, this command adds or removes a colon as the
22032 first character of this line. If the first character of a line is a colon,
22033 this line is also exported in fixed-width font."
22034 (interactive "P")
22035 (let* ((cc 0)
22036 (regionp (org-region-active-p))
22037 (beg (if regionp (region-beginning) (point)))
22038 (end (if regionp (region-end)))
22039 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22040 (case-fold-search nil)
22041 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22042 off)
22043 (if regionp
22044 (save-excursion
22045 (goto-char beg)
22046 (setq cc (current-column))
22047 (beginning-of-line 1)
22048 (setq off (looking-at re))
22049 (while (> nlines 0)
22050 (setq nlines (1- nlines))
22051 (beginning-of-line 1)
22052 (cond
22053 (arg
22054 (org-move-to-column cc t)
22055 (insert ": \n")
22056 (forward-line -1))
22057 ((and off (looking-at re))
22058 (replace-match "" t t nil 1))
22059 ((not off) (org-move-to-column cc t) (insert ": ")))
22060 (forward-line 1)))
22061 (save-excursion
22062 (org-back-to-heading)
22063 (cond
22064 ((looking-at (format org-heading-keyword-regexp-format
22065 org-quote-string))
22066 (goto-char (match-end 1))
22067 (looking-at (concat " +" org-quote-string))
22068 (replace-match "" t t)
22069 (when (eolp) (insert " ")))
22070 ((looking-at org-outline-regexp)
22071 (goto-char (match-end 0))
22072 (insert org-quote-string " ")))))))
22074 (defun org-reftex-citation ()
22075 "Use reftex-citation to insert a citation into the buffer.
22076 This looks for a line like
22078 #+BIBLIOGRAPHY: foo plain option:-d
22080 and derives from it that foo.bib is the bibliography file relevant
22081 for this document. It then installs the necessary environment for RefTeX
22082 to work in this buffer and calls `reftex-citation' to insert a citation
22083 into the buffer.
22085 Export of such citations to both LaTeX and HTML is handled by the contributed
22086 package org-exp-bibtex by Taru Karttunen."
22087 (interactive)
22088 (let ((reftex-docstruct-symbol 'rds)
22089 (reftex-cite-format "\\cite{%l}")
22090 rds bib)
22091 (save-excursion
22092 (save-restriction
22093 (widen)
22094 (let ((case-fold-search t)
22095 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22096 (if (not (save-excursion
22097 (or (re-search-forward re nil t)
22098 (re-search-backward re nil t))))
22099 (error "No bibliography defined in file")
22100 (setq bib (concat (match-string 1) ".bib")
22101 rds (list (list 'bib bib)))))))
22102 (call-interactively 'reftex-citation)))
22104 ;;;; Functions extending outline functionality
22106 (defun org-beginning-of-line (&optional arg)
22107 "Go to the beginning of the current line. If that is invisible, continue
22108 to a visible line beginning. This makes the function of C-a more intuitive.
22109 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22110 first attempt, and only move to after the tags when the cursor is already
22111 beyond the end of the headline."
22112 (interactive "P")
22113 (let ((pos (point))
22114 (special (if (consp org-special-ctrl-a/e)
22115 (car org-special-ctrl-a/e)
22116 org-special-ctrl-a/e))
22117 refpos)
22118 (if (org-bound-and-true-p visual-line-mode)
22119 (beginning-of-visual-line 1)
22120 (beginning-of-line 1))
22121 (if (and arg (fboundp 'move-beginning-of-line))
22122 (call-interactively 'move-beginning-of-line)
22123 (if (bobp)
22125 (backward-char 1)
22126 (if (org-truely-invisible-p)
22127 (while (and (not (bobp)) (org-truely-invisible-p))
22128 (backward-char 1)
22129 (beginning-of-line 1))
22130 (forward-char 1))))
22131 (when special
22132 (cond
22133 ((and (looking-at org-complex-heading-regexp)
22134 (= (char-after (match-end 1)) ?\ ))
22135 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22136 (point-at-eol)))
22137 (goto-char
22138 (if (eq special t)
22139 (cond ((> pos refpos) refpos)
22140 ((= pos (point)) refpos)
22141 (t (point)))
22142 (cond ((> pos (point)) (point))
22143 ((not (eq last-command this-command)) (point))
22144 (t refpos)))))
22145 ((org-at-item-p)
22146 ;; Being at an item and not looking at an the item means point
22147 ;; was previously moved to beginning of a visual line, which
22148 ;; doesn't contain the item. Therefore, do nothing special,
22149 ;; just stay here.
22150 (when (looking-at org-list-full-item-re)
22151 ;; Set special position at first white space character after
22152 ;; bullet, and check-box, if any.
22153 (let ((after-bullet
22154 (let ((box (match-end 3)))
22155 (if (not box) (match-end 1)
22156 (let ((after (char-after box)))
22157 (if (and after (= after ? )) (1+ box) box))))))
22158 ;; Special case: Move point to special position when
22159 ;; currently after it or at beginning of line.
22160 (if (eq special t)
22161 (when (or (> pos after-bullet) (= (point) pos))
22162 (goto-char after-bullet))
22163 ;; Reversed case: Move point to special position when
22164 ;; point was already at beginning of line and command is
22165 ;; repeated.
22166 (when (and (= (point) pos) (eq last-command this-command))
22167 (goto-char after-bullet))))))))
22168 (org-no-warnings
22169 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22171 (defun org-end-of-line (&optional arg)
22172 "Go to the end of the line.
22173 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22174 tags on the first attempt, and only move to after the tags when
22175 the cursor is already beyond the end of the headline."
22176 (interactive "P")
22177 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22178 org-special-ctrl-a/e))
22179 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22180 'end-of-visual-line)
22181 ((fboundp 'move-end-of-line) 'move-end-of-line)
22182 (t 'end-of-line))))
22183 (if (or (not special) arg) (call-interactively move-fun)
22184 (let* ((element (save-excursion (beginning-of-line)
22185 (org-element-at-point)))
22186 (type (org-element-type element)))
22187 (cond
22188 ((memq type '(headline inlinetask))
22189 (let ((pos (point)))
22190 (beginning-of-line 1)
22191 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22192 (if (eq special t)
22193 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22194 (goto-char (match-beginning 1))
22195 (goto-char (match-end 0)))
22196 (if (or (< pos (match-end 0))
22197 (not (eq this-command last-command)))
22198 (goto-char (match-end 0))
22199 (goto-char (match-beginning 1))))
22200 (call-interactively move-fun))))
22201 ((org-element-property :hiddenp element)
22202 ;; If element is hidden, `move-end-of-line' would put point
22203 ;; after it. Use `end-of-line' to stay on current line.
22204 (call-interactively 'end-of-line))
22205 (t (call-interactively move-fun)))))
22206 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22208 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22209 (define-key org-mode-map "\C-e" 'org-end-of-line)
22211 (defun org-backward-sentence (&optional arg)
22212 "Go to beginning of sentence, or beginning of table field.
22213 This will call `backward-sentence' or `org-table-beginning-of-field',
22214 depending on context."
22215 (interactive "P")
22216 (cond
22217 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22218 (t (call-interactively 'backward-sentence))))
22220 (defun org-forward-sentence (&optional arg)
22221 "Go to end of sentence, or end of table field.
22222 This will call `forward-sentence' or `org-table-end-of-field',
22223 depending on context."
22224 (interactive "P")
22225 (cond
22226 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22227 (t (call-interactively 'forward-sentence))))
22229 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22230 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22232 (defun org-kill-line (&optional arg)
22233 "Kill line, to tags or end of line."
22234 (interactive "P")
22235 (cond
22236 ((or (not org-special-ctrl-k)
22237 (bolp)
22238 (not (org-at-heading-p)))
22239 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22240 org-ctrl-k-protect-subtree)
22241 (if (or (eq org-ctrl-k-protect-subtree 'error)
22242 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22243 (error "C-k aborted - would kill hidden subtree")))
22244 (call-interactively
22245 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22246 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22247 (kill-region (point) (match-beginning 1))
22248 (org-set-tags nil t))
22249 (t (kill-region (point) (point-at-eol)))))
22251 (define-key org-mode-map "\C-k" 'org-kill-line)
22253 (defun org-yank (&optional arg)
22254 "Yank. If the kill is a subtree, treat it specially.
22255 This command will look at the current kill and check if is a single
22256 subtree, or a series of subtrees[1]. If it passes the test, and if the
22257 cursor is at the beginning of a line or after the stars of a currently
22258 empty headline, then the yank is handled specially. How exactly depends
22259 on the value of the following variables, both set by default.
22261 org-yank-folded-subtrees
22262 When set, the subtree(s) will be folded after insertion, but only
22263 if doing so would now swallow text after the yanked text.
22265 org-yank-adjusted-subtrees
22266 When set, the subtree will be promoted or demoted in order to
22267 fit into the local outline tree structure, which means that the level
22268 will be adjusted so that it becomes the smaller one of the two
22269 *visible* surrounding headings.
22271 Any prefix to this command will cause `yank' to be called directly with
22272 no special treatment. In particular, a simple \\[universal-argument] prefix \
22273 will just
22274 plainly yank the text as it is.
22276 \[1] The test checks if the first non-white line is a heading
22277 and if there are no other headings with fewer stars."
22278 (interactive "P")
22279 (org-yank-generic 'yank arg))
22281 (defun org-yank-generic (command arg)
22282 "Perform some yank-like command.
22284 This function implements the behavior described in the `org-yank'
22285 documentation. However, it has been generalized to work for any
22286 interactive command with similar behavior."
22288 ;; pretend to be command COMMAND
22289 (setq this-command command)
22291 (if arg
22292 (call-interactively command)
22294 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22295 (and (org-kill-is-subtree-p)
22296 (or (bolp)
22297 (and (looking-at "[ \t]*$")
22298 (string-match
22299 "\\`\\*+\\'"
22300 (buffer-substring (point-at-bol) (point)))))))
22301 swallowp)
22302 (cond
22303 ((and subtreep org-yank-folded-subtrees)
22304 (let ((beg (point))
22305 end)
22306 (if (and subtreep org-yank-adjusted-subtrees)
22307 (org-paste-subtree nil nil 'for-yank)
22308 (call-interactively command))
22310 (setq end (point))
22311 (goto-char beg)
22312 (when (and (bolp) subtreep
22313 (not (setq swallowp
22314 (org-yank-folding-would-swallow-text beg end))))
22315 (org-with-limited-levels
22316 (or (looking-at org-outline-regexp)
22317 (re-search-forward org-outline-regexp-bol end t))
22318 (while (and (< (point) end) (looking-at org-outline-regexp))
22319 (hide-subtree)
22320 (org-cycle-show-empty-lines 'folded)
22321 (condition-case nil
22322 (outline-forward-same-level 1)
22323 (error (goto-char end))))))
22324 (when swallowp
22325 (message
22326 "Inserted text not folded because that would swallow text"))
22328 (goto-char end)
22329 (skip-chars-forward " \t\n\r")
22330 (beginning-of-line 1)
22331 (push-mark beg 'nomsg)))
22332 ((and subtreep org-yank-adjusted-subtrees)
22333 (let ((beg (point-at-bol)))
22334 (org-paste-subtree nil nil 'for-yank)
22335 (push-mark beg 'nomsg)))
22337 (call-interactively command))))))
22339 (defun org-yank-folding-would-swallow-text (beg end)
22340 "Would hide-subtree at BEG swallow any text after END?"
22341 (let (level)
22342 (org-with-limited-levels
22343 (save-excursion
22344 (goto-char beg)
22345 (when (or (looking-at org-outline-regexp)
22346 (re-search-forward org-outline-regexp-bol end t))
22347 (setq level (org-outline-level)))
22348 (goto-char end)
22349 (skip-chars-forward " \t\r\n\v\f")
22350 (if (or (eobp)
22351 (and (bolp) (looking-at org-outline-regexp)
22352 (<= (org-outline-level) level)))
22353 nil ; Nothing would be swallowed
22354 t))))) ; something would swallow
22356 (define-key org-mode-map "\C-y" 'org-yank)
22358 (defun org-truely-invisible-p ()
22359 "Check if point is at a character currently not visible.
22360 This version does not only check the character property, but also
22361 `visible-mode'."
22362 ;; Early versions of noutline don't have `outline-invisible-p'.
22363 (if (org-bound-and-true-p visible-mode)
22365 (outline-invisible-p)))
22367 (defun org-invisible-p2 ()
22368 "Check if point is at a character currently not visible."
22369 (save-excursion
22370 (if (and (eolp) (not (bobp))) (backward-char 1))
22371 ;; Early versions of noutline don't have `outline-invisible-p'.
22372 (outline-invisible-p)))
22374 (defun org-back-to-heading (&optional invisible-ok)
22375 "Call `outline-back-to-heading', but provide a better error message."
22376 (condition-case nil
22377 (outline-back-to-heading invisible-ok)
22378 (error (error "Before first headline at position %d in buffer %s"
22379 (point) (current-buffer)))))
22381 (defun org-before-first-heading-p ()
22382 "Before first heading?"
22383 (save-excursion
22384 (end-of-line)
22385 (null (re-search-backward org-outline-regexp-bol nil t))))
22387 (defun org-at-heading-p (&optional ignored)
22388 (outline-on-heading-p t))
22389 ;; Compatibility alias with Org versions < 7.8.03
22390 (defalias 'org-on-heading-p 'org-at-heading-p)
22392 (defun org-at-comment-p nil
22393 "Is cursor in a line starting with a # character?"
22394 (save-excursion
22395 (beginning-of-line)
22396 (looking-at "^#")))
22398 (defun org-at-drawer-p nil
22399 "Is cursor at a drawer keyword?"
22400 (save-excursion
22401 (move-beginning-of-line 1)
22402 (looking-at org-drawer-regexp)))
22404 (defun org-at-block-p nil
22405 "Is cursor at a block keyword?"
22406 (save-excursion
22407 (move-beginning-of-line 1)
22408 (looking-at org-block-regexp)))
22410 (defun org-point-at-end-of-empty-headline ()
22411 "If point is at the end of an empty headline, return t, else nil.
22412 If the heading only contains a TODO keyword, it is still still considered
22413 empty."
22414 (and (looking-at "[ \t]*$")
22415 (when org-todo-line-regexp
22416 (save-excursion
22417 (beginning-of-line 1)
22418 (let ((case-fold-search nil))
22419 (looking-at org-todo-line-regexp)
22420 (string= (match-string 3) ""))))))
22422 (defun org-at-heading-or-item-p ()
22423 (or (org-at-heading-p) (org-at-item-p)))
22425 (defun org-at-target-p ()
22426 (or (org-in-regexp org-radio-target-regexp)
22427 (org-in-regexp org-target-regexp)))
22428 ;; Compatibility alias with Org versions < 7.8.03
22429 (defalias 'org-on-target-p 'org-at-target-p)
22431 (defun org-up-heading-all (arg)
22432 "Move to the heading line of which the present line is a subheading.
22433 This function considers both visible and invisible heading lines.
22434 With argument, move up ARG levels."
22435 (if (fboundp 'outline-up-heading-all)
22436 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22437 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22439 (defun org-up-heading-safe ()
22440 "Move to the heading line of which the present line is a subheading.
22441 This version will not throw an error. It will return the level of the
22442 headline found, or nil if no higher level is found.
22444 Also, this function will be a lot faster than `outline-up-heading',
22445 because it relies on stars being the outline starters. This can really
22446 make a significant difference in outlines with very many siblings."
22447 (let (start-level re)
22448 (org-back-to-heading t)
22449 (setq start-level (funcall outline-level))
22450 (if (equal start-level 1)
22452 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22453 (if (re-search-backward re nil t)
22454 (funcall outline-level)))))
22456 (defun org-first-sibling-p ()
22457 "Is this heading the first child of its parents?"
22458 (interactive)
22459 (let ((re org-outline-regexp-bol)
22460 level l)
22461 (unless (org-at-heading-p t)
22462 (error "Not at a heading"))
22463 (setq level (funcall outline-level))
22464 (save-excursion
22465 (if (not (re-search-backward re nil t))
22467 (setq l (funcall outline-level))
22468 (< l level)))))
22470 (defun org-goto-sibling (&optional previous)
22471 "Goto the next sibling, even if it is invisible.
22472 When PREVIOUS is set, go to the previous sibling instead. Returns t
22473 when a sibling was found. When none is found, return nil and don't
22474 move point."
22475 (let ((fun (if previous 're-search-backward 're-search-forward))
22476 (pos (point))
22477 (re org-outline-regexp-bol)
22478 level l)
22479 (when (condition-case nil (org-back-to-heading t) (error nil))
22480 (setq level (funcall outline-level))
22481 (catch 'exit
22482 (or previous (forward-char 1))
22483 (while (funcall fun re nil t)
22484 (setq l (funcall outline-level))
22485 (when (< l level) (goto-char pos) (throw 'exit nil))
22486 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22487 (goto-char pos)
22488 nil))))
22490 (defun org-show-siblings ()
22491 "Show all siblings of the current headline."
22492 (save-excursion
22493 (while (org-goto-sibling) (org-flag-heading nil)))
22494 (save-excursion
22495 (while (org-goto-sibling 'previous)
22496 (org-flag-heading nil))))
22498 (defun org-goto-first-child ()
22499 "Goto the first child, even if it is invisible.
22500 Return t when a child was found. Otherwise don't move point and
22501 return nil."
22502 (let (level (pos (point)) (re org-outline-regexp-bol))
22503 (when (condition-case nil (org-back-to-heading t) (error nil))
22504 (setq level (outline-level))
22505 (forward-char 1)
22506 (if (and (re-search-forward re nil t) (> (outline-level) level))
22507 (progn (goto-char (match-beginning 0)) t)
22508 (goto-char pos) nil))))
22510 (defun org-show-hidden-entry ()
22511 "Show an entry where even the heading is hidden."
22512 (save-excursion
22513 (org-show-entry)))
22515 (defun org-flag-heading (flag &optional entry)
22516 "Flag the current heading. FLAG non-nil means make invisible.
22517 When ENTRY is non-nil, show the entire entry."
22518 (save-excursion
22519 (org-back-to-heading t)
22520 ;; Check if we should show the entire entry
22521 (if entry
22522 (progn
22523 (org-show-entry)
22524 (save-excursion
22525 (and (outline-next-heading)
22526 (org-flag-heading nil))))
22527 (outline-flag-region (max (point-min) (1- (point)))
22528 (save-excursion (outline-end-of-heading) (point))
22529 flag))))
22531 (defun org-get-next-sibling ()
22532 "Move to next heading of the same level, and return point.
22533 If there is no such heading, return nil.
22534 This is like outline-next-sibling, but invisible headings are ok."
22535 (let ((level (funcall outline-level)))
22536 (outline-next-heading)
22537 (while (and (not (eobp)) (> (funcall outline-level) level))
22538 (outline-next-heading))
22539 (if (or (eobp) (< (funcall outline-level) level))
22541 (point))))
22543 (defun org-get-last-sibling ()
22544 "Move to previous heading of the same level, and return point.
22545 If there is no such heading, return nil."
22546 (let ((opoint (point))
22547 (level (funcall outline-level)))
22548 (outline-previous-heading)
22549 (when (and (/= (point) opoint) (outline-on-heading-p t))
22550 (while (and (> (funcall outline-level) level)
22551 (not (bobp)))
22552 (outline-previous-heading))
22553 (if (< (funcall outline-level) level)
22555 (point)))))
22557 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22558 "Goto to the end of a subtree."
22559 ;; This contains an exact copy of the original function, but it uses
22560 ;; `org-back-to-heading', to make it work also in invisible
22561 ;; trees. And is uses an invisible-ok argument.
22562 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22563 ;; Furthermore, when used inside Org, finding the end of a large subtree
22564 ;; with many children and grandchildren etc, this can be much faster
22565 ;; than the outline version.
22566 (org-back-to-heading invisible-ok)
22567 (let ((first t)
22568 (level (funcall outline-level)))
22569 (if (and (derived-mode-p 'org-mode) (< level 1000))
22570 ;; A true heading (not a plain list item), in Org-mode
22571 ;; This means we can easily find the end by looking
22572 ;; only for the right number of stars. Using a regexp to do
22573 ;; this is so much faster than using a Lisp loop.
22574 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22575 (forward-char 1)
22576 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22577 ;; something else, do it the slow way
22578 (while (and (not (eobp))
22579 (or first (> (funcall outline-level) level)))
22580 (setq first nil)
22581 (outline-next-heading)))
22582 (unless to-heading
22583 (if (memq (preceding-char) '(?\n ?\^M))
22584 (progn
22585 ;; Go to end of line before heading
22586 (forward-char -1)
22587 (if (memq (preceding-char) '(?\n ?\^M))
22588 ;; leave blank line before heading
22589 (forward-char -1))))))
22590 (point))
22592 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22593 "Use Org version in org-mode, for dramatic speed-up."
22594 (if (derived-mode-p 'org-mode)
22595 (progn
22596 (org-end-of-subtree nil t)
22597 (unless (eobp) (backward-char 1)))
22598 ad-do-it))
22600 (defun org-end-of-meta-data-and-drawers ()
22601 "Jump to the first text after meta data and drawers in the current entry.
22602 This will move over empty lines, lines with planning time stamps,
22603 clocking lines, and drawers."
22604 (org-back-to-heading t)
22605 (let ((end (save-excursion (outline-next-heading) (point)))
22606 (re (concat "\\(" org-drawer-regexp "\\)"
22607 "\\|" "[ \t]*" org-keyword-time-regexp)))
22608 (forward-line 1)
22609 (while (re-search-forward re end t)
22610 (if (not (match-end 1))
22611 ;; empty or planning line
22612 (forward-line 1)
22613 ;; a drawer, find the end
22614 (re-search-forward "^[ \t]*:END:" end 'move)
22615 (forward-line 1)))
22616 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22617 (point)))
22619 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22620 "Move forward to the arg'th subheading at same level as this one.
22621 Stop at the first and last subheadings of a superior heading.
22622 Normally this only looks at visible headings, but when INVISIBLE-OK is
22623 non-nil it will also look at invisible ones."
22624 (interactive "p")
22625 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22626 (outline-next-heading)
22627 (org-at-heading-p)
22628 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22629 (re (format "^\\*\\{1,%d\\} " level))
22631 (forward-char 1)
22632 (while (> arg 0)
22633 (while (and (re-search-forward re nil 'move)
22634 (setq l (- (match-end 0) (match-beginning 0) 1))
22635 (= l level)
22636 (not invisible-ok)
22637 (progn (backward-char 1) (outline-invisible-p)))
22638 (if (< l level) (setq arg 1)))
22639 (setq arg (1- arg)))
22640 (beginning-of-line 1))))
22642 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22643 "Move backward to the arg'th subheading at same level as this one.
22644 Stop at the first and last subheadings of a superior heading."
22645 (interactive "p")
22646 (if (not (ignore-errors (org-back-to-heading)))
22647 (goto-char (point-min))
22648 (org-at-heading-p)
22649 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22650 (re (format "^\\*\\{1,%d\\} " level))
22652 (while (> arg 0)
22653 (while (and (re-search-backward re nil 'move)
22654 (setq l (- (match-end 0) (match-beginning 0) 1))
22655 (= l level)
22656 (not invisible-ok)
22657 (outline-invisible-p))
22658 (if (< l level) (setq arg 1)))
22659 (setq arg (1- arg))))))
22661 (defun org-forward-element ()
22662 "Move forward by one element.
22663 Move to the next element at the same level, when possible."
22664 (interactive)
22665 (cond ((eobp) (error "Cannot move further down"))
22666 ((org-with-limited-levels (org-at-heading-p))
22667 (let ((origin (point)))
22668 (org-forward-heading-same-level 1)
22669 (unless (org-with-limited-levels (org-at-heading-p))
22670 (goto-char origin)
22671 (error "Cannot move further down"))))
22673 (let* ((elem (org-element-at-point))
22674 (end (org-element-property :end elem))
22675 (parent (org-element-property :parent elem)))
22676 (if (and parent (= (org-element-property :contents-end parent) end))
22677 (goto-char (org-element-property :end parent))
22678 (goto-char end))))))
22680 (defun org-backward-element ()
22681 "Move backward by one element.
22682 Move to the previous element at the same level, when possible."
22683 (interactive)
22684 (cond ((bobp) (error "Cannot move further up"))
22685 ((org-with-limited-levels (org-at-heading-p))
22686 ;; At an headline, move to the previous one, if any, or stay
22687 ;; here.
22688 (let ((origin (point)))
22689 (org-backward-heading-same-level 1)
22690 (unless (org-with-limited-levels (org-at-heading-p))
22691 (goto-char origin)
22692 (error "Cannot move further up"))))
22694 (let* ((trail (org-element-at-point 'keep-trail))
22695 (elem (car trail))
22696 (prev-elem (nth 1 trail))
22697 (beg (org-element-property :begin elem)))
22698 (cond
22699 ;; Move to beginning of current element if point isn't
22700 ;; there already.
22701 ((/= (point) beg) (goto-char beg))
22702 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22703 ((org-before-first-heading-p) (goto-char (point-min)))
22704 (t (org-back-to-heading)))))))
22706 (defun org-up-element ()
22707 "Move to upper element."
22708 (interactive)
22709 (if (org-with-limited-levels (org-at-heading-p))
22710 (unless (org-up-heading-safe) (error "No surrounding element"))
22711 (let* ((elem (org-element-at-point))
22712 (parent (org-element-property :parent elem)))
22713 (if parent (goto-char (org-element-property :begin parent))
22714 (if (org-with-limited-levels (org-before-first-heading-p))
22715 (error "No surrounding element")
22716 (org-with-limited-levels (org-back-to-heading)))))))
22718 (defvar org-element-greater-elements)
22719 (defun org-down-element ()
22720 "Move to inner element."
22721 (interactive)
22722 (let ((element (org-element-at-point)))
22723 (cond
22724 ((memq (org-element-type element) '(plain-list table))
22725 (goto-char (org-element-property :contents-begin element))
22726 (forward-char))
22727 ((memq (org-element-type element) org-element-greater-elements)
22728 ;; If contents are hidden, first disclose them.
22729 (when (org-element-property :hiddenp element) (org-cycle))
22730 (goto-char (or (org-element-property :contents-begin element)
22731 (error "No content for this element"))))
22732 (t (error "No inner element")))))
22734 (defun org-drag-element-backward ()
22735 "Move backward element at point."
22736 (interactive)
22737 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22738 (let* ((trail (org-element-at-point 'keep-trail))
22739 (elem (car trail))
22740 (prev-elem (nth 1 trail)))
22741 ;; Error out if no previous element or previous element is
22742 ;; a parent of the current one.
22743 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22744 (error "Cannot drag element backward")
22745 (let ((pos (point)))
22746 (org-element-swap-A-B prev-elem elem)
22747 (goto-char (+ (org-element-property :begin prev-elem)
22748 (- pos (org-element-property :begin elem)))))))))
22750 (defun org-drag-element-forward ()
22751 "Move forward element at point."
22752 (interactive)
22753 (let* ((pos (point))
22754 (elem (org-element-at-point)))
22755 (when (= (point-max) (org-element-property :end elem))
22756 (error "Cannot drag element forward"))
22757 (goto-char (org-element-property :end elem))
22758 (let ((next-elem (org-element-at-point)))
22759 (when (or (org-element-nested-p elem next-elem)
22760 (and (eq (org-element-type next-elem) 'headline)
22761 (not (eq (org-element-type elem) 'headline))))
22762 (goto-char pos)
22763 (error "Cannot drag element forward"))
22764 ;; Compute new position of point: it's shifted by NEXT-ELEM
22765 ;; body's length (without final blanks) and by the length of
22766 ;; blanks between ELEM and NEXT-ELEM.
22767 (let ((size-next (- (save-excursion
22768 (goto-char (org-element-property :end next-elem))
22769 (skip-chars-backward " \r\t\n")
22770 (forward-line)
22771 ;; Small correction if buffer doesn't end
22772 ;; with a newline character.
22773 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22774 (org-element-property :begin next-elem)))
22775 (size-blank (- (org-element-property :end elem)
22776 (save-excursion
22777 (goto-char (org-element-property :end elem))
22778 (skip-chars-backward " \r\t\n")
22779 (forward-line)
22780 (point)))))
22781 (org-element-swap-A-B elem next-elem)
22782 (goto-char (+ pos size-next size-blank))))))
22784 (defun org-mark-element ()
22785 "Put point at beginning of this element, mark at end.
22787 Interactively, if this command is repeated or (in Transient Mark
22788 mode) if the mark is active, it marks the next element after the
22789 ones already marked."
22790 (interactive)
22791 (let (deactivate-mark)
22792 (if (and (org-called-interactively-p 'any)
22793 (or (and (eq last-command this-command) (mark t))
22794 (and transient-mark-mode mark-active)))
22795 (set-mark
22796 (save-excursion
22797 (goto-char (mark))
22798 (goto-char (org-element-property :end (org-element-at-point)))))
22799 (let ((element (org-element-at-point)))
22800 (end-of-line)
22801 (push-mark (org-element-property :end element) t t)
22802 (goto-char (org-element-property :begin element))))))
22804 (defun org-narrow-to-element ()
22805 "Narrow buffer to current element."
22806 (interactive)
22807 (let ((elem (org-element-at-point)))
22808 (cond
22809 ((eq (car elem) 'headline)
22810 (narrow-to-region
22811 (org-element-property :begin elem)
22812 (org-element-property :end elem)))
22813 ((memq (car elem) org-element-greater-elements)
22814 (narrow-to-region
22815 (org-element-property :contents-begin elem)
22816 (org-element-property :contents-end elem)))
22818 (narrow-to-region
22819 (org-element-property :begin elem)
22820 (org-element-property :end elem))))))
22822 (defun org-transpose-words ()
22823 "Transpose words, using `org-mode' syntax table."
22824 (interactive)
22825 (with-syntax-table org-syntax-table
22826 (call-interactively 'transpose-words)))
22827 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22829 (defun org-transpose-element ()
22830 "Transpose current and previous elements, keeping blank lines between.
22831 Point is moved after both elements."
22832 (interactive)
22833 (org-skip-whitespace)
22834 (let ((end (org-element-property :end (org-element-at-point))))
22835 (org-drag-element-backward)
22836 (goto-char end)))
22838 (defun org-unindent-buffer ()
22839 "Un-indent the visible part of the buffer.
22840 Relative indentation (between items, inside blocks, etc.) isn't
22841 modified."
22842 (interactive)
22843 (unless (eq major-mode 'org-mode)
22844 (error "Cannot un-indent a buffer not in Org mode"))
22845 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22846 unindent-tree ; For byte-compiler.
22847 (unindent-tree
22848 (function
22849 (lambda (contents)
22850 (mapc
22851 (lambda (element)
22852 (if (memq (org-element-type element) '(headline section))
22853 (funcall unindent-tree (org-element-contents element))
22854 (save-excursion
22855 (save-restriction
22856 (narrow-to-region
22857 (org-element-property :begin element)
22858 (org-element-property :end element))
22859 (org-do-remove-indentation)))))
22860 (reverse contents))))))
22861 (funcall unindent-tree (org-element-contents parse-tree))))
22863 (defun org-show-subtree ()
22864 "Show everything after this heading at deeper levels."
22865 (interactive)
22866 (outline-flag-region
22867 (point)
22868 (save-excursion
22869 (org-end-of-subtree t t))
22870 nil))
22872 (defun org-show-entry ()
22873 "Show the body directly following this heading.
22874 Show the heading too, if it is currently invisible."
22875 (interactive)
22876 (save-excursion
22877 (condition-case nil
22878 (progn
22879 (org-back-to-heading t)
22880 (outline-flag-region
22881 (max (point-min) (1- (point)))
22882 (save-excursion
22883 (if (re-search-forward
22884 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22885 (match-beginning 1)
22886 (point-max)))
22887 nil)
22888 (org-cycle-hide-drawers 'children))
22889 (error nil))))
22891 (defun org-make-options-regexp (kwds &optional extra)
22892 "Make a regular expression for keyword lines."
22893 (concat
22894 "^#\\+\\("
22895 (mapconcat 'regexp-quote kwds "\\|")
22896 (if extra (concat "\\|" extra))
22897 "\\):[ \t]*\\(.*\\)"))
22899 ;; Make isearch reveal the necessary context
22900 (defun org-isearch-end ()
22901 "Reveal context after isearch exits."
22902 (when isearch-success ; only if search was successful
22903 (if (featurep 'xemacs)
22904 ;; Under XEmacs, the hook is run in the correct place,
22905 ;; we directly show the context.
22906 (org-show-context 'isearch)
22907 ;; In Emacs the hook runs *before* restoring the overlays.
22908 ;; So we have to use a one-time post-command-hook to do this.
22909 ;; (Emacs 22 has a special variable, see function `org-mode')
22910 (unless (and (boundp 'isearch-mode-end-hook-quit)
22911 isearch-mode-end-hook-quit)
22912 ;; Only when the isearch was not quitted.
22913 (org-add-hook 'post-command-hook 'org-isearch-post-command
22914 'append 'local)))))
22916 (defun org-isearch-post-command ()
22917 "Remove self from hook, and show context."
22918 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22919 (org-show-context 'isearch))
22922 ;;;; Integration with and fixes for other packages
22924 ;;; Imenu support
22926 (defvar org-imenu-markers nil
22927 "All markers currently used by Imenu.")
22928 (make-variable-buffer-local 'org-imenu-markers)
22930 (defun org-imenu-new-marker (&optional pos)
22931 "Return a new marker for use by Imenu, and remember the marker."
22932 (let ((m (make-marker)))
22933 (move-marker m (or pos (point)))
22934 (push m org-imenu-markers)
22937 (defun org-imenu-get-tree ()
22938 "Produce the index for Imenu."
22939 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22940 (setq org-imenu-markers nil)
22941 (let* ((n org-imenu-depth)
22942 (re (concat "^" (org-get-limited-outline-regexp)))
22943 (subs (make-vector (1+ n) nil))
22944 (last-level 0)
22945 m level head)
22946 (save-excursion
22947 (save-restriction
22948 (widen)
22949 (goto-char (point-max))
22950 (while (re-search-backward re nil t)
22951 (setq level (org-reduced-level (funcall outline-level)))
22952 (when (and (<= level n)
22953 (looking-at org-complex-heading-regexp))
22954 (setq head (org-link-display-format
22955 (org-match-string-no-properties 4))
22956 m (org-imenu-new-marker))
22957 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22958 (if (>= level last-level)
22959 (push (cons head m) (aref subs level))
22960 (push (cons head (aref subs (1+ level))) (aref subs level))
22961 (loop for i from (1+ level) to n do (aset subs i nil)))
22962 (setq last-level level)))))
22963 (aref subs 1)))
22965 (eval-after-load "imenu"
22966 '(progn
22967 (add-hook 'imenu-after-jump-hook
22968 (lambda ()
22969 (if (derived-mode-p 'org-mode)
22970 (org-show-context 'org-goto))))))
22972 (defun org-link-display-format (link)
22973 "Replace a link with either the description, or the link target
22974 if no description is present"
22975 (save-match-data
22976 (if (string-match org-bracket-link-analytic-regexp link)
22977 (replace-match (if (match-end 5)
22978 (match-string 5 link)
22979 (concat (match-string 1 link)
22980 (match-string 3 link)))
22981 nil t link)
22982 link)))
22984 (defun org-toggle-link-display ()
22985 "Toggle the literal or descriptive display of links."
22986 (interactive)
22987 (if org-descriptive-links
22988 (progn (org-remove-from-invisibility-spec '(org-link))
22989 (org-restart-font-lock)
22990 (setq org-descriptive-links nil))
22991 (progn (add-to-invisibility-spec '(org-link))
22992 (org-restart-font-lock)
22993 (setq org-descriptive-links t))))
22995 ;; Speedbar support
22997 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22998 "Overlay marking the agenda restriction line in speedbar.")
22999 (overlay-put org-speedbar-restriction-lock-overlay
23000 'face 'org-agenda-restriction-lock)
23001 (overlay-put org-speedbar-restriction-lock-overlay
23002 'help-echo "Agendas are currently limited to this item.")
23003 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23005 (defun org-speedbar-set-agenda-restriction ()
23006 "Restrict future agenda commands to the location at point in speedbar.
23007 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23008 (interactive)
23009 (require 'org-agenda)
23010 (let (p m tp np dir txt)
23011 (cond
23012 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23013 'org-imenu t))
23014 (setq m (get-text-property p 'org-imenu-marker))
23015 (with-current-buffer (marker-buffer m)
23016 (goto-char m)
23017 (org-agenda-set-restriction-lock 'subtree)))
23018 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23019 'speedbar-function 'speedbar-find-file))
23020 (setq tp (previous-single-property-change
23021 (1+ p) 'speedbar-function)
23022 np (next-single-property-change
23023 tp 'speedbar-function)
23024 dir (speedbar-line-directory)
23025 txt (buffer-substring-no-properties (or tp (point-min))
23026 (or np (point-max))))
23027 (with-current-buffer (find-file-noselect
23028 (let ((default-directory dir))
23029 (expand-file-name txt)))
23030 (unless (derived-mode-p 'org-mode)
23031 (error "Cannot restrict to non-Org-mode file"))
23032 (org-agenda-set-restriction-lock 'file)))
23033 (t (error "Don't know how to restrict Org-mode's agenda")))
23034 (move-overlay org-speedbar-restriction-lock-overlay
23035 (point-at-bol) (point-at-eol))
23036 (setq current-prefix-arg nil)
23037 (org-agenda-maybe-redo)))
23039 (eval-after-load "speedbar"
23040 '(progn
23041 (speedbar-add-supported-extension ".org")
23042 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23043 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23044 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23045 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23046 (add-hook 'speedbar-visiting-tag-hook
23047 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23049 ;;; Fixes and Hacks for problems with other packages
23051 ;; Make flyspell not check words in links, to not mess up our keymap
23052 (defvar org-element-affiliated-keywords) ; From org-element.el
23053 (defvar org-element-block-name-alist) ; From org-element.el
23054 (defun org-mode-flyspell-verify ()
23055 "Don't let flyspell put overlays at active buttons, or on
23056 {todo,all-time,additional-option-like}-keywords."
23057 (let ((pos (max (1- (point)) (point-min)))
23058 (word (thing-at-point 'word)))
23059 (and (not (get-text-property pos 'keymap))
23060 (not (get-text-property pos 'org-no-flyspell))
23061 (not (member word org-todo-keywords-1))
23062 (not (member word org-all-time-keywords))
23063 (not (member word org-options-keywords))
23064 (not (member word (mapcar 'car org-startup-options)))
23065 (not (member-ignore-case word org-element-affiliated-keywords))
23066 (not (member-ignore-case word (org-get-export-keywords)))
23067 (not (member-ignore-case
23068 word (mapcar 'car org-element-block-name-alist)))
23069 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23071 (defun org-remove-flyspell-overlays-in (beg end)
23072 "Remove flyspell overlays in region."
23073 (and (org-bound-and-true-p flyspell-mode)
23074 (fboundp 'flyspell-delete-region-overlays)
23075 (flyspell-delete-region-overlays beg end))
23076 (add-text-properties beg end '(org-no-flyspell t)))
23078 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23079 (eval-after-load "bookmark"
23080 '(if (boundp 'bookmark-after-jump-hook)
23081 ;; We can use the hook
23082 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23083 ;; Hook not available, use advice
23084 (defadvice bookmark-jump (after org-make-visible activate)
23085 "Make the position visible."
23086 (org-bookmark-jump-unhide))))
23088 ;; Make sure saveplace shows the location if it was hidden
23089 (eval-after-load "saveplace"
23090 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23091 "Make the position visible."
23092 (org-bookmark-jump-unhide)))
23094 ;; Make sure ecb shows the location if it was hidden
23095 (eval-after-load "ecb"
23096 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23097 "Make hierarchy visible when jumping into location from ECB tree buffer."
23098 (if (derived-mode-p 'org-mode)
23099 (org-show-context))))
23101 (defun org-bookmark-jump-unhide ()
23102 "Unhide the current position, to show the bookmark location."
23103 (and (derived-mode-p 'org-mode)
23104 (or (outline-invisible-p)
23105 (save-excursion (goto-char (max (point-min) (1- (point))))
23106 (outline-invisible-p)))
23107 (org-show-context 'bookmark-jump)))
23109 ;; Make session.el ignore our circular variable
23110 (eval-after-load "session"
23111 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23113 ;;;; Experimental code
23115 (defun org-closed-in-range ()
23116 "Sparse tree of items closed in a certain time range.
23117 Still experimental, may disappear in the future."
23118 (interactive)
23119 ;; Get the time interval from the user.
23120 (let* ((time1 (org-float-time
23121 (org-read-date nil 'to-time nil "Starting date: ")))
23122 (time2 (org-float-time
23123 (org-read-date nil 'to-time nil "End date:")))
23124 ;; callback function
23125 (callback (lambda ()
23126 (let ((time
23127 (org-float-time
23128 (apply 'encode-time
23129 (org-parse-time-string
23130 (match-string 1))))))
23131 ;; check if time in interval
23132 (and (>= time time1) (<= time time2))))))
23133 ;; make tree, check each match with the callback
23134 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23136 ;;;; Finish up
23138 (provide 'org)
23140 (run-hooks 'org-load-hook)
23142 ;;; org.el ends here