org.el (org-open-at-point): Open a plain link even if the cursor is before it
[org-mode.git] / lisp / org.el
blob4176f78554d955f28d75a4091d3a780cf70055fe
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 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-type "org-element" (element))
162 ;; load languages based on value of `org-babel-load-languages'
163 (defvar org-babel-load-languages)
165 ;;;###autoload
166 (defun org-babel-do-load-languages (sym value)
167 "Load the languages defined in `org-babel-load-languages'."
168 (set-default sym value)
169 (mapc (lambda (pair)
170 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
171 (if active
172 (progn
173 (require (intern (concat "ob-" lang))))
174 (progn
175 (funcall 'fmakunbound
176 (intern (concat "org-babel-execute:" lang)))
177 (funcall 'fmakunbound
178 (intern (concat "org-babel-expand-body:" lang)))))))
179 org-babel-load-languages))
181 (defcustom org-babel-load-languages '((emacs-lisp . t))
182 "Languages which can be evaluated in Org-mode buffers.
183 This list can be used to load support for any of the languages
184 below, note that each language will depend on a different set of
185 system executables and/or Emacs modes. When a language is
186 \"loaded\", then code blocks in that language can be evaluated
187 with `org-babel-execute-src-block' bound by default to C-c
188 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
189 be set to remove code block evaluation from the C-c C-c
190 keybinding. By default only Emacs Lisp (which has no
191 requirements) is loaded."
192 :group 'org-babel
193 :set 'org-babel-do-load-languages
194 :version "24.1"
195 :type '(alist :tag "Babel Languages"
196 :key-type
197 (choice
198 (const :tag "Awk" awk)
199 (const :tag "C" C)
200 (const :tag "R" R)
201 (const :tag "Asymptote" asymptote)
202 (const :tag "Calc" calc)
203 (const :tag "Clojure" clojure)
204 (const :tag "CSS" css)
205 (const :tag "Ditaa" ditaa)
206 (const :tag "Dot" dot)
207 (const :tag "Emacs Lisp" emacs-lisp)
208 (const :tag "Fortran" fortran)
209 (const :tag "Gnuplot" gnuplot)
210 (const :tag "Haskell" haskell)
211 (const :tag "IO" io)
212 (const :tag "Java" java)
213 (const :tag "Javascript" js)
214 (const :tag "LaTeX" latex)
215 (const :tag "Ledger" ledger)
216 (const :tag "Lilypond" lilypond)
217 (const :tag "Lisp" lisp)
218 (const :tag "Makefile" makefile)
219 (const :tag "Maxima" maxima)
220 (const :tag "Matlab" matlab)
221 (const :tag "Mscgen" mscgen)
222 (const :tag "Ocaml" ocaml)
223 (const :tag "Octave" octave)
224 (const :tag "Org" org)
225 (const :tag "Perl" perl)
226 (const :tag "Pico Lisp" picolisp)
227 (const :tag "PlantUML" plantuml)
228 (const :tag "Python" python)
229 (const :tag "Ruby" ruby)
230 (const :tag "Sass" sass)
231 (const :tag "Scala" scala)
232 (const :tag "Scheme" scheme)
233 (const :tag "Screen" screen)
234 (const :tag "Shell Script" sh)
235 (const :tag "Shen" shen)
236 (const :tag "Sql" sql)
237 (const :tag "Sqlite" sqlite))
238 :value-type (boolean :tag "Activate" :value t)))
240 ;;;; Customization variables
241 (defcustom org-clone-delete-id nil
242 "Remove ID property of clones of a subtree.
243 When non-nil, clones of a subtree don't inherit the ID property.
244 Otherwise they inherit the ID property with a new unique
245 identifier."
246 :type 'boolean
247 :version "24.1"
248 :group 'org-id)
250 ;;; Version
251 (org-check-version)
253 ;;;###autoload
254 (defun org-version (&optional here full message)
255 "Show the org-mode version in the echo area.
256 With prefix argument HERE, insert it at point.
257 When FULL is non-nil, use a verbose version string.
258 When MESSAGE is non-nil, display a message with the version."
259 (interactive "P")
260 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
261 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
262 (load-suffixes (list ".el"))
263 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
264 (org-trash (or
265 (and (fboundp 'org-release) (fboundp 'org-git-version))
266 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
267 (load-suffixes save-load-suffixes)
268 (org-version (org-release))
269 (git-version (org-git-version))
270 (version (format "Org-mode version %s (%s @ %s)"
271 org-version
272 git-version
273 (if org-install-dir
274 (if (string= org-dir org-install-dir)
275 org-install-dir
276 (concat "mixed installation! " org-install-dir " and " org-dir))
277 "org-loaddefs.el can not be found!")))
278 (_version (if full version org-version)))
279 (if (org-called-interactively-p 'interactive)
280 (if here
281 (insert version)
282 (message version))
283 (if message (message _version))
284 _version)))
286 (defconst org-version (org-version))
288 ;;; Compatibility constants
290 ;;; The custom variables
292 (defgroup org nil
293 "Outline-based notes management and organizer."
294 :tag "Org"
295 :group 'outlines
296 :group 'calendar)
298 (defcustom org-mode-hook nil
299 "Mode hook for Org-mode, run after the mode was turned on."
300 :group 'org
301 :type 'hook)
303 (defcustom org-load-hook nil
304 "Hook that is run after org.el has been loaded."
305 :group 'org
306 :type 'hook)
308 (defcustom org-log-buffer-setup-hook nil
309 "Hook that is run after an Org log buffer is created."
310 :group 'org
311 :version "24.1"
312 :type 'hook)
314 (defvar org-modules) ; defined below
315 (defvar org-modules-loaded nil
316 "Have the modules been loaded already?")
318 (defun org-load-modules-maybe (&optional force)
319 "Load all extensions listed in `org-modules'."
320 (when (or force (not org-modules-loaded))
321 (mapc (lambda (ext)
322 (condition-case nil (require ext)
323 (error (message "Problems while trying to load feature `%s'" ext))))
324 org-modules)
325 (setq org-modules-loaded t)))
327 (defun org-set-modules (var value)
328 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
329 (set var value)
330 (when (featurep 'org)
331 (org-load-modules-maybe 'force)))
333 (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)
334 "Modules that should always be loaded together with org.el.
336 If a description starts with <C>, the file is not part of Emacs
337 and loading it will require that you have downloaded and properly
338 installed the Org mode distribution.
340 You can also use this system to load external packages (i.e. neither Org
341 core modules, nor modules from the CONTRIB directory). Just add symbols
342 to the end of the list. If the package is called org-xyz.el, then you need
343 to add the symbol `xyz', and the package must have a call to:
345 \(provide 'org-xyz)
347 For export specific modules, see also `org-export-backends'."
348 :group 'org
349 :set 'org-set-modules
350 :type
351 '(set :greedy t
352 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
353 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
354 (const :tag " crypt: Encryption of subtrees" org-crypt)
355 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
356 (const :tag " docview: Links to doc-view buffers" org-docview)
357 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
358 (const :tag " id: Global IDs for identifying entries" org-id)
359 (const :tag " info: Links to Info nodes" org-info)
360 (const :tag " habit: Track your consistency with habits" org-habit)
361 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
362 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
363 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
364 (const :tag " mew Links to Mew folders/messages" org-mew)
365 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
366 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
367 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
368 (const :tag " vm: Links to VM folders/messages" org-vm)
369 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
370 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
371 (const :tag " mouse: Additional mouse support" org-mouse)
373 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
374 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
375 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
376 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
377 (const :tag "C collector: Collect properties into tables" org-collector)
378 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
379 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
380 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
381 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
382 (const :tag "C eval: Include command output as text" org-eval)
383 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
384 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
385 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
386 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
387 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
389 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
391 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
392 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
393 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
394 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
395 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
396 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
397 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
398 (const :tag "C mtags: Support for muse-like tags" org-mtags)
399 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
400 (const :tag "C registry: A registry for Org-mode links" org-registry)
401 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
402 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
403 (const :tag "C secretary: Team management with org-mode" org-secretary)
404 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
405 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
406 (const :tag "C track: Keep up with Org-mode development" org-track)
407 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
408 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
409 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
411 (defvar org-export-registered-backends) ; From ox.el
412 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
413 (defcustom org-export-backends '(ascii html icalendar latex)
414 "List of export back-ends that should be always available.
416 If a description starts with <C>, the file is not part of Emacs
417 and loading it will require that you have downloaded and properly
418 installed the Org mode distribution.
420 Unlike to `org-modules', libraries in this list will not be
421 loaded along with Org, but only once the export framework is
422 needed.
424 This variable needs to be set before org.el is loaded. If you
425 need to make a change while Emacs is running, use the customize
426 interface or run the following code, where VALUE stands for the
427 new value of the variable, after updating it:
429 \(progn
430 \(setq org-export-registered-backends
431 \(org-remove-if-not
432 \(lambda (backend)
433 \(or (memq backend val)
434 \(catch 'parentp
435 \(mapc
436 \(lambda (b)
437 \(and (org-export-derived-backend-p b (car backend))
438 \(throw 'parentp t)))
439 val)
440 nil)))
441 org-export-registered-backends))
442 \(let ((new-list (mapcar 'car org-export-registered-backends)))
443 \(dolist (backend val)
444 \(cond
445 \((not (load (format \"ox-%s\" backend) t t))
446 \(message \"Problems while trying to load export back-end `%s'\"
447 backend))
448 \((not (memq backend new-list)) (push backend new-list))))
449 \(set-default var new-list)))
451 Adding a back-end to this list will also pull the back-end it
452 depends on, if any."
453 :group 'org
454 :group 'org-export
455 :set (lambda (var val)
456 (if (not (featurep 'ox)) (set-default var val)
457 ;; Any back-end not required anymore (not present in VAL and not
458 ;; a parent of any back-end in the new value) is removed from the
459 ;; list of registered back-ends.
460 (setq org-export-registered-backends
461 (org-remove-if-not
462 (lambda (backend)
463 (or (memq backend val)
464 (catch 'parentp
465 (mapc
466 (lambda (b)
467 (and (org-export-derived-backend-p b (car backend))
468 (throw 'parentp t)))
469 val)
470 nil)))
471 org-export-registered-backends))
472 ;; Now build NEW-LIST of both new back-ends and required
473 ;; parents.
474 (let ((new-list (mapcar 'car org-export-registered-backends)))
475 (dolist (backend val)
476 (cond
477 ((not (load (format "ox-%s" backend) t t))
478 (message "Problems while trying to load export back-end `%s'"
479 backend))
480 ((not (memq backend new-list)) (push backend new-list))))
481 ;; Set VAR to that list with fixed dependencies.
482 (set-default var new-list))))
483 :type '(set :greedy t
484 (const :tag " ascii Export buffer to ASCII format" ascii)
485 (const :tag " beamer Export buffer to Beamer presentation" beamer)
486 (const :tag " html Export buffer to HTML format" html)
487 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
488 (const :tag " latex Export buffer to LaTeX format" latex)
489 (const :tag " man Export buffer to MAN format" man)
490 (const :tag " md Export buffer to Markdown format" md)
491 (const :tag " odt Export buffer to ODT format" odt)
492 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
493 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" jsinfo)
494 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
495 (const :tag "C groff Export buffer to Groff format" groff)
496 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)))
498 (eval-after-load 'ox
499 '(mapc
500 (lambda (backend)
501 (condition-case nil (require (intern (format "ox-%s" backend)))
502 (error (message "Problems while trying to load export back-end `%s'"
503 backend))))
504 org-export-backends))
506 (defcustom org-support-shift-select nil
507 "Non-nil means make shift-cursor commands select text when possible.
509 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
510 start selecting a region, or enlarge regions started in this way.
511 In Org-mode, in special contexts, these same keys are used for
512 other purposes, important enough to compete with shift selection.
513 Org tries to balance these needs by supporting `shift-select-mode'
514 outside these special contexts, under control of this variable.
516 The default of this variable is nil, to avoid confusing behavior. Shifted
517 cursor keys will then execute Org commands in the following contexts:
518 - on a headline, changing TODO state (left/right) and priority (up/down)
519 - on a time stamp, changing the time
520 - in a plain list item, changing the bullet type
521 - in a property definition line, switching between allowed values
522 - in the BEGIN line of a clock table (changing the time block).
523 Outside these contexts, the commands will throw an error.
525 When this variable is t and the cursor is not in a special
526 context, Org-mode will support shift-selection for making and
527 enlarging regions. To make this more effective, the bullet
528 cycling will no longer happen anywhere in an item line, but only
529 if the cursor is exactly on the bullet.
531 If you set this variable to the symbol `always', then the keys
532 will not be special in headlines, property lines, and item lines,
533 to make shift selection work there as well. If this is what you
534 want, you can use the following alternative commands: `C-c C-t'
535 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
536 can be used to switch TODO sets, `C-c -' to cycle item bullet
537 types, and properties can be edited by hand or in column view.
539 However, when the cursor is on a timestamp, shift-cursor commands
540 will still edit the time stamp - this is just too good to give up.
542 XEmacs user should have this variable set to nil, because
543 `shift-select-mode' is in Emacs 23 or later only."
544 :group 'org
545 :type '(choice
546 (const :tag "Never" nil)
547 (const :tag "When outside special context" t)
548 (const :tag "Everywhere except timestamps" always)))
550 (defcustom org-loop-over-headlines-in-active-region nil
551 "Shall some commands act upon headlines in the active region?
553 When set to `t', some commands will be performed in all headlines
554 within the active region.
556 When set to `start-level', some commands will be performed in all
557 headlines within the active region, provided that these headlines
558 are of the same level than the first one.
560 When set to a string, those commands will be performed on the
561 matching headlines within the active region. Such string must be
562 a tags/property/todo match as it is used in the agenda tags view.
564 The list of commands is: `org-schedule', `org-deadline',
565 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
566 `org-archive-to-archive-sibling'. The archiving commands skip
567 already archived entries."
568 :type '(choice (const :tag "Don't loop" nil)
569 (const :tag "All headlines in active region" t)
570 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
571 (string :tag "Tags/Property/Todo matcher"))
572 :version "24.1"
573 :group 'org-todo
574 :group 'org-archive)
576 (defgroup org-startup nil
577 "Options concerning startup of Org-mode."
578 :tag "Org Startup"
579 :group 'org)
581 (defcustom org-startup-folded t
582 "Non-nil means entering Org-mode will switch to OVERVIEW.
583 This can also be configured on a per-file basis by adding one of
584 the following lines anywhere in the buffer:
586 #+STARTUP: fold (or `overview', this is equivalent)
587 #+STARTUP: nofold (or `showall', this is equivalent)
588 #+STARTUP: content
589 #+STARTUP: showeverything"
590 :group 'org-startup
591 :type '(choice
592 (const :tag "nofold: show all" nil)
593 (const :tag "fold: overview" t)
594 (const :tag "content: all headlines" content)
595 (const :tag "show everything, even drawers" showeverything)))
597 (defcustom org-startup-truncated t
598 "Non-nil means entering Org-mode will set `truncate-lines'.
599 This is useful since some lines containing links can be very long and
600 uninteresting. Also tables look terrible when wrapped."
601 :group 'org-startup
602 :type 'boolean)
604 (defcustom org-startup-indented nil
605 "Non-nil means turn on `org-indent-mode' on startup.
606 This can also be configured on a per-file basis by adding one of
607 the following lines anywhere in the buffer:
609 #+STARTUP: indent
610 #+STARTUP: noindent"
611 :group 'org-structure
612 :type '(choice
613 (const :tag "Not" nil)
614 (const :tag "Globally (slow on startup in large files)" t)))
616 (defcustom org-use-sub-superscripts t
617 "Non-nil means interpret \"_\" and \"^\" for display.
618 When this option is turned on, you can use TeX-like syntax for sub- and
619 superscripts. Several characters after \"_\" or \"^\" will be
620 considered as a single item - so grouping with {} is normally not
621 needed. For example, the following things will be parsed as single
622 sub- or superscripts.
624 10^24 or 10^tau several digits will be considered 1 item.
625 10^-12 or 10^-tau a leading sign with digits or a word
626 x^2-y^3 will be read as x^2 - y^3, because items are
627 terminated by almost any nonword/nondigit char.
628 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
630 Still, ambiguity is possible - so when in doubt use {} to enclose
631 the sub/superscript. If you set this variable to the symbol
632 `{}', the braces are *required* in order to trigger
633 interpretations as sub/superscript. This can be helpful in
634 documents that need \"_\" frequently in plain text."
635 :group 'org-startup
636 :version "24.1"
637 :type '(choice
638 (const :tag "Always interpret" t)
639 (const :tag "Only with braces" {})
640 (const :tag "Never interpret" nil)))
642 (defcustom org-startup-with-beamer-mode nil
643 "Non-nil means turn on `org-beamer-mode' on startup.
644 This can also be configured on a per-file basis by adding one of
645 the following lines anywhere in the buffer:
647 #+STARTUP: beamer"
648 :group 'org-startup
649 :version "24.1"
650 :type 'boolean)
652 (defcustom org-startup-align-all-tables nil
653 "Non-nil means align all tables when visiting a file.
654 This is useful when the column width in tables is forced with <N> cookies
655 in table fields. Such tables will look correct only after the first re-align.
656 This can also be configured on a per-file basis by adding one of
657 the following lines anywhere in the buffer:
658 #+STARTUP: align
659 #+STARTUP: noalign"
660 :group 'org-startup
661 :type 'boolean)
663 (defcustom org-startup-with-inline-images nil
664 "Non-nil means show inline images when loading a new Org file.
665 This can also be configured on a per-file basis by adding one of
666 the following lines anywhere in the buffer:
667 #+STARTUP: inlineimages
668 #+STARTUP: noinlineimages"
669 :group 'org-startup
670 :version "24.1"
671 :type 'boolean)
673 (defcustom org-insert-mode-line-in-empty-file nil
674 "Non-nil means insert the first line setting Org-mode in empty files.
675 When the function `org-mode' is called interactively in an empty file, this
676 normally means that the file name does not automatically trigger Org-mode.
677 To ensure that the file will always be in Org-mode in the future, a
678 line enforcing Org-mode will be inserted into the buffer, if this option
679 has been set."
680 :group 'org-startup
681 :type 'boolean)
683 (defcustom org-replace-disputed-keys nil
684 "Non-nil means use alternative key bindings for some keys.
685 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
686 These keys are also used by other packages like shift-selection-mode'
687 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
688 If you want to use Org-mode together with one of these other modes,
689 or more generally if you would like to move some Org-mode commands to
690 other keys, set this variable and configure the keys with the variable
691 `org-disputed-keys'.
693 This option is only relevant at load-time of Org-mode, and must be set
694 *before* org.el is loaded. Changing it requires a restart of Emacs to
695 become effective."
696 :group 'org-startup
697 :type 'boolean)
699 (defcustom org-use-extra-keys nil
700 "Non-nil means use extra key sequence definitions for certain commands.
701 This happens automatically if you run XEmacs or if `window-system'
702 is nil. This variable lets you do the same manually. You must
703 set it before loading org.
705 Example: on Carbon Emacs 22 running graphically, with an external
706 keyboard on a Powerbook, the default way of setting M-left might
707 not work for either Alt or ESC. Setting this variable will make
708 it work for ESC."
709 :group 'org-startup
710 :type 'boolean)
712 (if (fboundp 'defvaralias)
713 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
715 (defcustom org-disputed-keys
716 '(([(shift up)] . [(meta p)])
717 ([(shift down)] . [(meta n)])
718 ([(shift left)] . [(meta -)])
719 ([(shift right)] . [(meta +)])
720 ([(control shift right)] . [(meta shift +)])
721 ([(control shift left)] . [(meta shift -)]))
722 "Keys for which Org-mode and other modes compete.
723 This is an alist, cars are the default keys, second element specifies
724 the alternative to use when `org-replace-disputed-keys' is t.
726 Keys can be specified in any syntax supported by `define-key'.
727 The value of this option takes effect only at Org-mode's startup,
728 therefore you'll have to restart Emacs to apply it after changing."
729 :group 'org-startup
730 :type 'alist)
732 (defun org-key (key)
733 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
734 Or return the original if not disputed.
735 Also apply the translations defined in `org-xemacs-key-equivalents'."
736 (when org-replace-disputed-keys
737 (let* ((nkey (key-description key))
738 (x (org-find-if (lambda (x)
739 (equal (key-description (car x)) nkey))
740 org-disputed-keys)))
741 (setq key (if x (cdr x) key))))
742 (when (featurep 'xemacs)
743 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
744 key)
746 (defun org-find-if (predicate seq)
747 (catch 'exit
748 (while seq
749 (if (funcall predicate (car seq))
750 (throw 'exit (car seq))
751 (pop seq)))))
753 (defun org-defkey (keymap key def)
754 "Define a key, possibly translated, as returned by `org-key'."
755 (define-key keymap (org-key key) def))
757 (defcustom org-ellipsis nil
758 "The ellipsis to use in the Org-mode outline.
759 When nil, just use the standard three dots. When a string, use that instead,
760 When a face, use the standard 3 dots, but with the specified face.
761 The change affects only Org-mode (which will then use its own display table).
762 Changing this requires executing `M-x org-mode' in a buffer to become
763 effective."
764 :group 'org-startup
765 :type '(choice (const :tag "Default" nil)
766 (face :tag "Face" :value org-warning)
767 (string :tag "String" :value "...#")))
769 (defvar org-display-table nil
770 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
772 (defgroup org-keywords nil
773 "Keywords in Org-mode."
774 :tag "Org Keywords"
775 :group 'org)
777 (defcustom org-deadline-string "DEADLINE:"
778 "String to mark deadline entries.
779 A deadline is this string, followed by a time stamp. Should be a word,
780 terminated by a colon. You can insert a schedule keyword and
781 a timestamp with \\[org-deadline].
782 Changes become only effective after restarting Emacs."
783 :group 'org-keywords
784 :type 'string)
786 (defcustom org-scheduled-string "SCHEDULED:"
787 "String to mark scheduled TODO entries.
788 A schedule is this string, followed by a time stamp. Should be a word,
789 terminated by a colon. You can insert a schedule keyword and
790 a timestamp with \\[org-schedule].
791 Changes become only effective after restarting Emacs."
792 :group 'org-keywords
793 :type 'string)
795 (defcustom org-closed-string "CLOSED:"
796 "String used as the prefix for timestamps logging closing a TODO entry."
797 :group 'org-keywords
798 :type 'string)
800 (defcustom org-clock-string "CLOCK:"
801 "String used as prefix for timestamps clocking work hours on an item."
802 :group 'org-keywords
803 :type 'string)
805 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
806 org-scheduled-string "\\|"
807 org-deadline-string "\\|"
808 org-closed-string "\\|"
809 org-clock-string "\\)")
810 "Matches a line with planning or clock info.")
812 (defcustom org-comment-string "COMMENT"
813 "Entries starting with this keyword will never be exported.
814 An entry can be toggled between COMMENT and normal with
815 \\[org-toggle-comment].
816 Changes become only effective after restarting Emacs."
817 :group 'org-keywords
818 :type 'string)
820 (defcustom org-quote-string "QUOTE"
821 "Entries starting with this keyword will be exported in fixed-width font.
822 Quoting applies only to the text in the entry following the headline, and does
823 not extend beyond the next headline, even if that is lower level.
824 An entry can be toggled between QUOTE and normal with
825 \\[org-toggle-fixed-width-section]."
826 :group 'org-keywords
827 :type 'string)
829 (defconst org-repeat-re
830 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
831 "Regular expression for specifying repeated events.
832 After a match, group 1 contains the repeat expression.")
834 (defgroup org-structure nil
835 "Options concerning the general structure of Org-mode files."
836 :tag "Org Structure"
837 :group 'org)
839 (defgroup org-reveal-location nil
840 "Options about how to make context of a location visible."
841 :tag "Org Reveal Location"
842 :group 'org-structure)
844 (defconst org-context-choice
845 '(choice
846 (const :tag "Always" t)
847 (const :tag "Never" nil)
848 (repeat :greedy t :tag "Individual contexts"
849 (cons
850 (choice :tag "Context"
851 (const agenda)
852 (const org-goto)
853 (const occur-tree)
854 (const tags-tree)
855 (const link-search)
856 (const mark-goto)
857 (const bookmark-jump)
858 (const isearch)
859 (const default))
860 (boolean))))
861 "Contexts for the reveal options.")
863 (defcustom org-show-hierarchy-above '((default . t))
864 "Non-nil means show full hierarchy when revealing a location.
865 Org-mode often shows locations in an org-mode file which might have
866 been invisible before. When this is set, the hierarchy of headings
867 above the exposed location is shown.
868 Turning this off for example for sparse trees makes them very compact.
869 Instead of t, this can also be an alist specifying this option for different
870 contexts. Valid contexts are
871 agenda when exposing an entry from the agenda
872 org-goto when using the command `org-goto' on key C-c C-j
873 occur-tree when using the command `org-occur' on key C-c /
874 tags-tree when constructing a sparse tree based on tags matches
875 link-search when exposing search matches associated with a link
876 mark-goto when exposing the jump goal of a mark
877 bookmark-jump when exposing a bookmark location
878 isearch when exiting from an incremental search
879 default default for all contexts not set explicitly"
880 :group 'org-reveal-location
881 :type org-context-choice)
883 (defcustom org-show-following-heading '((default . nil))
884 "Non-nil means show following heading when revealing a location.
885 Org-mode often shows locations in an org-mode file which might have
886 been invisible before. When this is set, the heading following the
887 match is shown.
888 Turning this off for example for sparse trees makes them very compact,
889 but makes it harder to edit the location of the match. In such a case,
890 use the command \\[org-reveal] to show more context.
891 Instead of t, this can also be an alist specifying this option for different
892 contexts. See `org-show-hierarchy-above' for valid contexts."
893 :group 'org-reveal-location
894 :type org-context-choice)
896 (defcustom org-show-siblings '((default . nil) (isearch t))
897 "Non-nil means show all sibling heading when revealing a location.
898 Org-mode often shows locations in an org-mode file which might have
899 been invisible before. When this is set, the sibling of the current entry
900 heading are all made visible. If `org-show-hierarchy-above' is t,
901 the same happens on each level of the hierarchy above the current entry.
903 By default this is on for the isearch context, off for all other contexts.
904 Turning this off for example for sparse trees makes them very compact,
905 but makes it harder to edit the location of the match. In such a case,
906 use the command \\[org-reveal] to show more context.
907 Instead of t, this can also be an alist specifying this option for different
908 contexts. See `org-show-hierarchy-above' for valid contexts."
909 :group 'org-reveal-location
910 :type org-context-choice)
912 (defcustom org-show-entry-below '((default . nil))
913 "Non-nil means show the entry below a headline when revealing a location.
914 Org-mode often shows locations in an org-mode file which might have
915 been invisible before. When this is set, the text below the headline that is
916 exposed is also shown.
918 By default this is off for all contexts.
919 Instead of t, this can also be an alist specifying this option for different
920 contexts. See `org-show-hierarchy-above' for valid contexts."
921 :group 'org-reveal-location
922 :type org-context-choice)
924 (defcustom org-indirect-buffer-display 'other-window
925 "How should indirect tree buffers be displayed?
926 This applies to indirect buffers created with the commands
927 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
928 Valid values are:
929 current-window Display in the current window
930 other-window Just display in another window.
931 dedicated-frame Create one new frame, and re-use it each time.
932 new-frame Make a new frame each time. Note that in this case
933 previously-made indirect buffers are kept, and you need to
934 kill these buffers yourself."
935 :group 'org-structure
936 :group 'org-agenda-windows
937 :type '(choice
938 (const :tag "In current window" current-window)
939 (const :tag "In current frame, other window" other-window)
940 (const :tag "Each time a new frame" new-frame)
941 (const :tag "One dedicated frame" dedicated-frame)))
943 (defcustom org-use-speed-commands nil
944 "Non-nil means activate single letter commands at beginning of a headline.
945 This may also be a function to test for appropriate locations where speed
946 commands should be active."
947 :group 'org-structure
948 :type '(choice
949 (const :tag "Never" nil)
950 (const :tag "At beginning of headline stars" t)
951 (function)))
953 (defcustom org-speed-commands-user nil
954 "Alist of additional speed commands.
955 This list will be checked before `org-speed-commands-default'
956 when the variable `org-use-speed-commands' is non-nil
957 and when the cursor is at the beginning of a headline.
958 The car if each entry is a string with a single letter, which must
959 be assigned to `self-insert-command' in the global map.
960 The cdr is either a command to be called interactively, a function
961 to be called, or a form to be evaluated.
962 An entry that is just a list with a single string will be interpreted
963 as a descriptive headline that will be added when listing the speed
964 commands in the Help buffer using the `?' speed command."
965 :group 'org-structure
966 :type '(repeat :value ("k" . ignore)
967 (choice :value ("k" . ignore)
968 (list :tag "Descriptive Headline" (string :tag "Headline"))
969 (cons :tag "Letter and Command"
970 (string :tag "Command letter")
971 (choice
972 (function)
973 (sexp))))))
975 (defgroup org-cycle nil
976 "Options concerning visibility cycling in Org-mode."
977 :tag "Org Cycle"
978 :group 'org-structure)
980 (defcustom org-cycle-skip-children-state-if-no-children t
981 "Non-nil means skip CHILDREN state in entries that don't have any."
982 :group 'org-cycle
983 :type 'boolean)
985 (defcustom org-cycle-max-level nil
986 "Maximum level which should still be subject to visibility cycling.
987 Levels higher than this will, for cycling, be treated as text, not a headline.
988 When `org-odd-levels-only' is set, a value of N in this variable actually
989 means 2N-1 stars as the limiting headline.
990 When nil, cycle all levels.
991 Note that the limiting level of cycling is also influenced by
992 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
993 `org-inlinetask-min-level' is, cycling will be limited to levels one less
994 than its value."
995 :group 'org-cycle
996 :type '(choice
997 (const :tag "No limit" nil)
998 (integer :tag "Maximum level")))
1000 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1001 "Names of drawers. Drawers are not opened by cycling on the headline above.
1002 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1003 this:
1004 :DRAWERNAME:
1005 .....
1006 :END:
1007 The drawer \"PROPERTIES\" is special for capturing properties through
1008 the property API.
1010 Drawers can be defined on the per-file basis with a line like:
1012 #+DRAWERS: HIDDEN STATE PROPERTIES"
1013 :group 'org-structure
1014 :group 'org-cycle
1015 :type '(repeat (string :tag "Drawer Name")))
1017 (defcustom org-hide-block-startup nil
1018 "Non-nil means entering Org-mode will fold all blocks.
1019 This can also be set in on a per-file basis with
1021 #+STARTUP: hideblocks
1022 #+STARTUP: showblocks"
1023 :group 'org-startup
1024 :group 'org-cycle
1025 :type 'boolean)
1027 (defcustom org-cycle-global-at-bob nil
1028 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1029 This makes it possible to do global cycling without having to use S-TAB or
1030 \\[universal-argument] TAB. For this special case to work, the first line
1031 of the buffer must not be a headline -- it may be empty or some other text.
1032 When used in this way, `org-cycle-hook' is disabled temporarily to make
1033 sure the cursor stays at the beginning of the buffer. When this option is
1034 nil, don't do anything special at the beginning of the buffer."
1035 :group 'org-cycle
1036 :type 'boolean)
1038 (defcustom org-cycle-level-after-item/entry-creation t
1039 "Non-nil means cycle entry level or item indentation in new empty entries.
1041 When the cursor is at the end of an empty headline, i.e., with only stars
1042 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1043 and then all possible ancestor states, before returning to the original state.
1044 This makes data entry extremely fast: M-RET to create a new headline,
1045 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1047 When the cursor is at the end of an empty plain list item, one TAB will
1048 make it a subitem, two or more tabs will back up to make this an item
1049 higher up in the item hierarchy."
1050 :group 'org-cycle
1051 :type 'boolean)
1053 (defcustom org-cycle-emulate-tab t
1054 "Where should `org-cycle' emulate TAB.
1055 nil Never
1056 white Only in completely white lines
1057 whitestart Only at the beginning of lines, before the first non-white char
1058 t Everywhere except in headlines
1059 exc-hl-bol Everywhere except at the start of a headline
1060 If TAB is used in a place where it does not emulate TAB, the current subtree
1061 visibility is cycled."
1062 :group 'org-cycle
1063 :type '(choice (const :tag "Never" nil)
1064 (const :tag "Only in completely white lines" white)
1065 (const :tag "Before first char in a line" whitestart)
1066 (const :tag "Everywhere except in headlines" t)
1067 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1070 (defcustom org-cycle-separator-lines 2
1071 "Number of empty lines needed to keep an empty line between collapsed trees.
1072 If you leave an empty line between the end of a subtree and the following
1073 headline, this empty line is hidden when the subtree is folded.
1074 Org-mode will leave (exactly) one empty line visible if the number of
1075 empty lines is equal or larger to the number given in this variable.
1076 So the default 2 means at least 2 empty lines after the end of a subtree
1077 are needed to produce free space between a collapsed subtree and the
1078 following headline.
1080 If the number is negative, and the number of empty lines is at least -N,
1081 all empty lines are shown.
1083 Special case: when 0, never leave empty lines in collapsed view."
1084 :group 'org-cycle
1085 :type 'integer)
1086 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1088 (defcustom org-pre-cycle-hook nil
1089 "Hook that is run before visibility cycling is happening.
1090 The function(s) in this hook must accept a single argument which indicates
1091 the new state that will be set right after running this hook. The
1092 argument is a symbol. Before a global state change, it can have the values
1093 `overview', `content', or `all'. Before a local state change, it can have
1094 the values `folded', `children', or `subtree'."
1095 :group 'org-cycle
1096 :type 'hook)
1098 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1099 org-cycle-hide-drawers
1100 org-cycle-hide-inline-tasks
1101 org-cycle-show-empty-lines
1102 org-optimize-window-after-visibility-change)
1103 "Hook that is run after `org-cycle' has changed the buffer visibility.
1104 The function(s) in this hook must accept a single argument which indicates
1105 the new state that was set by the most recent `org-cycle' command. The
1106 argument is a symbol. After a global state change, it can have the values
1107 `overview', `contents', or `all'. After a local state change, it can have
1108 the values `folded', `children', or `subtree'."
1109 :group 'org-cycle
1110 :type 'hook)
1112 (defgroup org-edit-structure nil
1113 "Options concerning structure editing in Org-mode."
1114 :tag "Org Edit Structure"
1115 :group 'org-structure)
1117 (defcustom org-odd-levels-only nil
1118 "Non-nil means skip even levels and only use odd levels for the outline.
1119 This has the effect that two stars are being added/taken away in
1120 promotion/demotion commands. It also influences how levels are
1121 handled by the exporters.
1122 Changing it requires restart of `font-lock-mode' to become effective
1123 for fontification also in regions already fontified.
1124 You may also set this on a per-file basis by adding one of the following
1125 lines to the buffer:
1127 #+STARTUP: odd
1128 #+STARTUP: oddeven"
1129 :group 'org-edit-structure
1130 :group 'org-appearance
1131 :type 'boolean)
1133 (defcustom org-adapt-indentation t
1134 "Non-nil means adapt indentation to outline node level.
1136 When this variable is set, Org assumes that you write outlines by
1137 indenting text in each node to align with the headline (after the stars).
1138 The following issues are influenced by this variable:
1140 - When this is set and the *entire* text in an entry is indented, the
1141 indentation is increased by one space in a demotion command, and
1142 decreased by one in a promotion command. If any line in the entry
1143 body starts with text at column 0, indentation is not changed at all.
1145 - Property drawers and planning information is inserted indented when
1146 this variable s set. When nil, they will not be indented.
1148 - TAB indents a line relative to context. The lines below a headline
1149 will be indented when this variable is set.
1151 Note that this is all about true indentation, by adding and removing
1152 space characters. See also `org-indent.el' which does level-dependent
1153 indentation in a virtual way, i.e. at display time in Emacs."
1154 :group 'org-edit-structure
1155 :type 'boolean)
1157 (defcustom org-special-ctrl-a/e nil
1158 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1160 When t, `C-a' will bring back the cursor to the beginning of the
1161 headline text, i.e. after the stars and after a possible TODO
1162 keyword. In an item, this will be the position after bullet and
1163 check-box, if any. When the cursor is already at that position,
1164 another `C-a' will bring it to the beginning of the line.
1166 `C-e' will jump to the end of the headline, ignoring the presence
1167 of tags in the headline. A second `C-e' will then jump to the
1168 true end of the line, after any tags. This also means that, when
1169 this variable is non-nil, `C-e' also will never jump beyond the
1170 end of the heading of a folded section, i.e. not after the
1171 ellipses.
1173 When set to the symbol `reversed', the first `C-a' or `C-e' works
1174 normally, going to the true line boundary first. Only a directly
1175 following, identical keypress will bring the cursor to the
1176 special positions.
1178 This may also be a cons cell where the behavior for `C-a' and
1179 `C-e' is set separately."
1180 :group 'org-edit-structure
1181 :type '(choice
1182 (const :tag "off" nil)
1183 (const :tag "on: after stars/bullet and before tags first" t)
1184 (const :tag "reversed: true line boundary first" reversed)
1185 (cons :tag "Set C-a and C-e separately"
1186 (choice :tag "Special C-a"
1187 (const :tag "off" nil)
1188 (const :tag "on: after stars/bullet first" t)
1189 (const :tag "reversed: before stars/bullet first" reversed))
1190 (choice :tag "Special C-e"
1191 (const :tag "off" nil)
1192 (const :tag "on: before tags first" t)
1193 (const :tag "reversed: after tags first" reversed)))))
1194 (if (fboundp 'defvaralias)
1195 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1197 (defcustom org-special-ctrl-k nil
1198 "Non-nil means `C-k' will behave specially in headlines.
1199 When nil, `C-k' will call the default `kill-line' command.
1200 When t, the following will happen while the cursor is in the headline:
1202 - When the cursor is at the beginning of a headline, kill the entire
1203 line and possible the folded subtree below the line.
1204 - When in the middle of the headline text, kill the headline up to the tags.
1205 - When after the headline text, kill the tags."
1206 :group 'org-edit-structure
1207 :type 'boolean)
1209 (defcustom org-ctrl-k-protect-subtree nil
1210 "Non-nil means, do not delete a hidden subtree with C-k.
1211 When set to the symbol `error', simply throw an error when C-k is
1212 used to kill (part-of) a headline that has hidden text behind it.
1213 Any other non-nil value will result in a query to the user, if it is
1214 OK to kill that hidden subtree. When nil, kill without remorse."
1215 :group 'org-edit-structure
1216 :version "24.1"
1217 :type '(choice
1218 (const :tag "Do not protect hidden subtrees" nil)
1219 (const :tag "Protect hidden subtrees with a security query" t)
1220 (const :tag "Never kill a hidden subtree with C-k" error)))
1222 (defcustom org-catch-invisible-edits nil
1223 "Check if in invisible region before inserting or deleting a character.
1224 Valid values are:
1226 nil Do not check, so just do invisible edits.
1227 error Throw an error and do nothing.
1228 show Make point visible, and do the requested edit.
1229 show-and-error Make point visible, then throw an error and abort the edit.
1230 smart Make point visible, and do insertion/deletion if it is
1231 adjacent to visible text and the change feels predictable.
1232 Never delete a previously invisible character or add in the
1233 middle or right after an invisible region. Basically, this
1234 allows insertion and backward-delete right before ellipses.
1235 FIXME: maybe in this case we should not even show?"
1236 :group 'org-edit-structure
1237 :version "24.1"
1238 :type '(choice
1239 (const :tag "Do not check" nil)
1240 (const :tag "Throw error when trying to edit" error)
1241 (const :tag "Unhide, but do not do the edit" show-and-error)
1242 (const :tag "Show invisible part and do the edit" show)
1243 (const :tag "Be smart and do the right thing" smart)))
1245 (defcustom org-yank-folded-subtrees t
1246 "Non-nil means when yanking subtrees, fold them.
1247 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1248 it starts with a heading and all other headings in it are either children
1249 or siblings, then fold all the subtrees. However, do this only if no
1250 text after the yank would be swallowed into a folded tree by this action."
1251 :group 'org-edit-structure
1252 :type 'boolean)
1254 (defcustom org-yank-adjusted-subtrees nil
1255 "Non-nil means when yanking subtrees, adjust the level.
1256 With this setting, `org-paste-subtree' is used to insert the subtree, see
1257 this function for details."
1258 :group 'org-edit-structure
1259 :type 'boolean)
1261 (defcustom org-M-RET-may-split-line '((default . t))
1262 "Non-nil means M-RET will split the line at the cursor position.
1263 When nil, it will go to the end of the line before making a
1264 new line.
1265 You may also set this option in a different way for different
1266 contexts. Valid contexts are:
1268 headline when creating a new headline
1269 item when creating a new item
1270 table in a table field
1271 default the value to be used for all contexts not explicitly
1272 customized"
1273 :group 'org-structure
1274 :group 'org-table
1275 :type '(choice
1276 (const :tag "Always" t)
1277 (const :tag "Never" nil)
1278 (repeat :greedy t :tag "Individual contexts"
1279 (cons
1280 (choice :tag "Context"
1281 (const headline)
1282 (const item)
1283 (const table)
1284 (const default))
1285 (boolean)))))
1288 (defcustom org-insert-heading-respect-content nil
1289 "Non-nil means insert new headings after the current subtree.
1290 When nil, the new heading is created directly after the current line.
1291 The commands \\[org-insert-heading-respect-content] and
1292 \\[org-insert-todo-heading-respect-content] turn this variable on
1293 for the duration of the command."
1294 :group 'org-structure
1295 :type 'boolean)
1297 (defcustom org-blank-before-new-entry '((heading . auto)
1298 (plain-list-item . auto))
1299 "Should `org-insert-heading' leave a blank line before new heading/item?
1300 The value is an alist, with `heading' and `plain-list-item' as CAR,
1301 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1302 which case Org will look at the surrounding headings/items and try to
1303 make an intelligent decision whether to insert a blank line or not.
1305 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1306 set, the setting here is ignored and no empty line is inserted, to avoid
1307 breaking the list structure."
1308 :group 'org-edit-structure
1309 :type '(list
1310 (cons (const heading)
1311 (choice (const :tag "Never" nil)
1312 (const :tag "Always" t)
1313 (const :tag "Auto" auto)))
1314 (cons (const plain-list-item)
1315 (choice (const :tag "Never" nil)
1316 (const :tag "Always" t)
1317 (const :tag "Auto" auto)))))
1319 (defcustom org-insert-heading-hook nil
1320 "Hook being run after inserting a new heading."
1321 :group 'org-edit-structure
1322 :type 'hook)
1324 (defcustom org-enable-fixed-width-editor t
1325 "Non-nil means lines starting with \":\" are treated as fixed-width.
1326 This currently only means they are never auto-wrapped.
1327 When nil, such lines will be treated like ordinary lines.
1328 See also the QUOTE keyword."
1329 :group 'org-edit-structure
1330 :type 'boolean)
1332 (defcustom org-goto-auto-isearch t
1333 "Non-nil means typing characters in `org-goto' starts incremental search.
1334 When nil, you can use these keybindings to navigate the buffer:
1336 q Quit the org-goto interface
1337 n Go to the next visible heading
1338 p Go to the previous visible heading
1339 f Go one heading forward on same level
1340 b Go one heading backward on same level
1341 u Go one heading up"
1342 :group 'org-edit-structure
1343 :type 'boolean)
1345 (defgroup org-sparse-trees nil
1346 "Options concerning sparse trees in Org-mode."
1347 :tag "Org Sparse Trees"
1348 :group 'org-structure)
1350 (defcustom org-highlight-sparse-tree-matches t
1351 "Non-nil means highlight all matches that define a sparse tree.
1352 The highlights will automatically disappear the next time the buffer is
1353 changed by an edit command."
1354 :group 'org-sparse-trees
1355 :type 'boolean)
1357 (defcustom org-remove-highlights-with-change t
1358 "Non-nil means any change to the buffer will remove temporary highlights.
1359 Such highlights are created by `org-occur' and `org-clock-display'.
1360 When nil, `C-c C-c needs to be used to get rid of the highlights.
1361 The highlights created by `org-preview-latex-fragment' always need
1362 `C-c C-c' to be removed."
1363 :group 'org-sparse-trees
1364 :group 'org-time
1365 :type 'boolean)
1368 (defcustom org-occur-hook '(org-first-headline-recenter)
1369 "Hook that is run after `org-occur' has constructed a sparse tree.
1370 This can be used to recenter the window to show as much of the structure
1371 as possible."
1372 :group 'org-sparse-trees
1373 :type 'hook)
1375 (defgroup org-imenu-and-speedbar nil
1376 "Options concerning imenu and speedbar in Org-mode."
1377 :tag "Org Imenu and Speedbar"
1378 :group 'org-structure)
1380 (defcustom org-imenu-depth 2
1381 "The maximum level for Imenu access to Org-mode headlines.
1382 This also applied for speedbar access."
1383 :group 'org-imenu-and-speedbar
1384 :type 'integer)
1386 (defgroup org-table nil
1387 "Options concerning tables in Org-mode."
1388 :tag "Org Table"
1389 :group 'org)
1391 (defcustom org-enable-table-editor 'optimized
1392 "Non-nil means lines starting with \"|\" are handled by the table editor.
1393 When nil, such lines will be treated like ordinary lines.
1395 When equal to the symbol `optimized', the table editor will be optimized to
1396 do the following:
1397 - Automatic overwrite mode in front of whitespace in table fields.
1398 This makes the structure of the table stay in tact as long as the edited
1399 field does not exceed the column width.
1400 - Minimize the number of realigns. Normally, the table is aligned each time
1401 TAB or RET are pressed to move to another field. With optimization this
1402 happens only if changes to a field might have changed the column width.
1403 Optimization requires replacing the functions `self-insert-command',
1404 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1405 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1406 very good at guessing when a re-align will be necessary, but you can always
1407 force one with \\[org-ctrl-c-ctrl-c].
1409 If you would like to use the optimized version in Org-mode, but the
1410 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1412 This variable can be used to turn on and off the table editor during a session,
1413 but in order to toggle optimization, a restart is required.
1415 See also the variable `org-table-auto-blank-field'."
1416 :group 'org-table
1417 :type '(choice
1418 (const :tag "off" nil)
1419 (const :tag "on" t)
1420 (const :tag "on, optimized" optimized)))
1422 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1423 (version<= emacs-version "24.1"))
1424 "Non-nil means cluster self-insert commands for undo when possible.
1425 If this is set, then, like in the Emacs command loop, 20 consecutive
1426 characters will be undone together.
1427 This is configurable, because there is some impact on typing performance."
1428 :group 'org-table
1429 :type 'boolean)
1431 (defcustom org-table-tab-recognizes-table.el t
1432 "Non-nil means TAB will automatically notice a table.el table.
1433 When it sees such a table, it moves point into it and - if necessary -
1434 calls `table-recognize-table'."
1435 :group 'org-table-editing
1436 :type 'boolean)
1438 (defgroup org-link nil
1439 "Options concerning links in Org-mode."
1440 :tag "Org Link"
1441 :group 'org)
1443 (defvar org-link-abbrev-alist-local nil
1444 "Buffer-local version of `org-link-abbrev-alist', which see.
1445 The value of this is taken from the #+LINK lines.")
1446 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1448 (defcustom org-link-abbrev-alist nil
1449 "Alist of link abbreviations.
1450 The car of each element is a string, to be replaced at the start of a link.
1451 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1452 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1454 [[linkkey:tag][description]]
1456 The 'linkkey' must be a word word, starting with a letter, followed
1457 by letters, numbers, '-' or '_'.
1459 If REPLACE is a string, the tag will simply be appended to create the link.
1460 If the string contains \"%s\", the tag will be inserted there. If the string
1461 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1462 at that point (see the function `url-hexify-string'). If the string contains
1463 the specifier \"%(my-function)\", then the custom function `my-function' will
1464 be invoked: this function takes the tag as its only argument and must return
1465 a string.
1467 REPLACE may also be a function that will be called with the tag as the
1468 only argument to create the link, which should be returned as a string.
1470 See the manual for examples."
1471 :group 'org-link
1472 :type '(repeat
1473 (cons
1474 (string :tag "Protocol")
1475 (choice
1476 (string :tag "Format")
1477 (function)))))
1479 (defcustom org-descriptive-links t
1480 "Non-nil means Org will display descriptive links.
1481 E.g. [[http://orgmode.org][Org website]] will be displayed as
1482 \"Org Website\", hiding the link itself and just displaying its
1483 description. When set to `nil', Org will display the full links
1484 literally.
1486 You can interactively set the value of this variable by calling
1487 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1488 :group 'org-link
1489 :type 'boolean)
1491 (defcustom org-link-file-path-type 'adaptive
1492 "How the path name in file links should be stored.
1493 Valid values are:
1495 relative Relative to the current directory, i.e. the directory of the file
1496 into which the link is being inserted.
1497 absolute Absolute path, if possible with ~ for home directory.
1498 noabbrev Absolute path, no abbreviation of home directory.
1499 adaptive Use relative path for files in the current directory and sub-
1500 directories of it. For other files, use an absolute path."
1501 :group 'org-link
1502 :type '(choice
1503 (const relative)
1504 (const absolute)
1505 (const noabbrev)
1506 (const adaptive)))
1508 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1509 "Types of links that should be activated in Org-mode files.
1510 This is a list of symbols, each leading to the activation of a certain link
1511 type. In principle, it does not hurt to turn on most link types - there may
1512 be a small gain when turning off unused link types. The types are:
1514 bracket The recommended [[link][description]] or [[link]] links with hiding.
1515 angle Links in angular brackets that may contain whitespace like
1516 <bbdb:Carsten Dominik>.
1517 plain Plain links in normal text, no whitespace, like http://google.com.
1518 radio Text that is matched by a radio target, see manual for details.
1519 tag Tag settings in a headline (link to tag search).
1520 date Time stamps (link to calendar).
1521 footnote Footnote labels.
1523 Changing this variable requires a restart of Emacs to become effective."
1524 :group 'org-link
1525 :type '(set :greedy t
1526 (const :tag "Double bracket links" bracket)
1527 (const :tag "Angular bracket links" angle)
1528 (const :tag "Plain text links" plain)
1529 (const :tag "Radio target matches" radio)
1530 (const :tag "Tags" tag)
1531 (const :tag "Timestamps" date)
1532 (const :tag "Footnotes" footnote)))
1534 (defcustom org-make-link-description-function nil
1535 "Function to use for generating link descriptions from links.
1536 When nil, the link location will be used. This function must take
1537 two parameters: the first one is the link, the second one is the
1538 description generated by `org-insert-link'. The function should
1539 return the description to use."
1540 :group 'org-link
1541 :type 'function)
1543 (defgroup org-link-store nil
1544 "Options concerning storing links in Org-mode."
1545 :tag "Org Store Link"
1546 :group 'org-link)
1548 (defcustom org-url-hexify-p t
1549 "When non-nil, hexify URL when creating a link."
1550 :type 'boolean
1551 :version "24.3"
1552 :group 'org-link-store)
1554 (defcustom org-email-link-description-format "Email %c: %.30s"
1555 "Format of the description part of a link to an email or usenet message.
1556 The following %-escapes will be replaced by corresponding information:
1558 %F full \"From\" field
1559 %f name, taken from \"From\" field, address if no name
1560 %T full \"To\" field
1561 %t first name in \"To\" field, address if no name
1562 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1563 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1564 %s subject
1565 %d date
1566 %m message-id.
1568 You may use normal field width specification between the % and the letter.
1569 This is for example useful to limit the length of the subject.
1571 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1572 :group 'org-link-store
1573 :type 'string)
1575 (defcustom org-from-is-user-regexp
1576 (let (r1 r2)
1577 (when (and user-mail-address (not (string= user-mail-address "")))
1578 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1579 (when (and user-full-name (not (string= user-full-name "")))
1580 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1581 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1582 "Regexp matched against the \"From:\" header of an email or usenet message.
1583 It should match if the message is from the user him/herself."
1584 :group 'org-link-store
1585 :type 'regexp)
1587 (defcustom org-context-in-file-links t
1588 "Non-nil means file links from `org-store-link' contain context.
1589 A search string will be added to the file name with :: as separator and
1590 used to find the context when the link is activated by the command
1591 `org-open-at-point'. When this option is t, the entire active region
1592 will be placed in the search string of the file link. If set to a
1593 positive integer, only the first n lines of context will be stored.
1595 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1596 negates this setting for the duration of the command."
1597 :group 'org-link-store
1598 :type '(choice boolean integer))
1600 (defcustom org-keep-stored-link-after-insertion nil
1601 "Non-nil means keep link in list for entire session.
1603 The command `org-store-link' adds a link pointing to the current
1604 location to an internal list. These links accumulate during a session.
1605 The command `org-insert-link' can be used to insert links into any
1606 Org-mode file (offering completion for all stored links). When this
1607 option is nil, every link which has been inserted once using \\[org-insert-link]
1608 will be removed from the list, to make completing the unused links
1609 more efficient."
1610 :group 'org-link-store
1611 :type 'boolean)
1613 (defgroup org-link-follow nil
1614 "Options concerning following links in Org-mode."
1615 :tag "Org Follow Link"
1616 :group 'org-link)
1618 (defcustom org-link-translation-function nil
1619 "Function to translate links with different syntax to Org syntax.
1620 This can be used to translate links created for example by the Planner
1621 or emacs-wiki packages to Org syntax.
1622 The function must accept two parameters, a TYPE containing the link
1623 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1624 which is everything after the link protocol. It should return a cons
1625 with possibly modified values of type and path.
1626 Org contains a function for this, so if you set this variable to
1627 `org-translate-link-from-planner', you should be able follow many
1628 links created by planner."
1629 :group 'org-link-follow
1630 :type 'function)
1632 (defcustom org-follow-link-hook nil
1633 "Hook that is run after a link has been followed."
1634 :group 'org-link-follow
1635 :type 'hook)
1637 (defcustom org-tab-follows-link nil
1638 "Non-nil means on links TAB will follow the link.
1639 Needs to be set before org.el is loaded.
1640 This really should not be used, it does not make sense, and the
1641 implementation is bad."
1642 :group 'org-link-follow
1643 :type 'boolean)
1645 (defcustom org-return-follows-link nil
1646 "Non-nil means on links RET will follow the link."
1647 :group 'org-link-follow
1648 :type 'boolean)
1650 (defcustom org-mouse-1-follows-link
1651 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1652 "Non-nil means mouse-1 on a link will follow the link.
1653 A longer mouse click will still set point. Does not work on XEmacs.
1654 Needs to be set before org.el is loaded."
1655 :group 'org-link-follow
1656 :type 'boolean)
1658 (defcustom org-mark-ring-length 4
1659 "Number of different positions to be recorded in the ring.
1660 Changing this requires a restart of Emacs to work correctly."
1661 :group 'org-link-follow
1662 :type 'integer)
1664 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1665 "Non-nil means internal links in Org files must exactly match a headline.
1666 When nil, the link search tries to match a phrase with all words
1667 in the search text."
1668 :group 'org-link-follow
1669 :version "24.1"
1670 :type '(choice
1671 (const :tag "Use fuzzy text search" nil)
1672 (const :tag "Match only exact headline" t)
1673 (const :tag "Match exact headline or query to create it"
1674 query-to-create)))
1676 (defcustom org-link-frame-setup
1677 '((vm . vm-visit-folder-other-frame)
1678 (vm-imap . vm-visit-imap-folder-other-frame)
1679 (gnus . org-gnus-no-new-news)
1680 (file . find-file-other-window)
1681 (wl . wl-other-frame))
1682 "Setup the frame configuration for following links.
1683 When following a link with Emacs, it may often be useful to display
1684 this link in another window or frame. This variable can be used to
1685 set this up for the different types of links.
1686 For VM, use any of
1687 `vm-visit-folder'
1688 `vm-visit-folder-other-window'
1689 `vm-visit-folder-other-frame'
1690 For Gnus, use any of
1691 `gnus'
1692 `gnus-other-frame'
1693 `org-gnus-no-new-news'
1694 For FILE, use any of
1695 `find-file'
1696 `find-file-other-window'
1697 `find-file-other-frame'
1698 For Wanderlust use any of
1699 `wl'
1700 `wl-other-frame'
1701 For the calendar, use the variable `calendar-setup'.
1702 For BBDB, it is currently only possible to display the matches in
1703 another window."
1704 :group 'org-link-follow
1705 :type '(list
1706 (cons (const vm)
1707 (choice
1708 (const vm-visit-folder)
1709 (const vm-visit-folder-other-window)
1710 (const vm-visit-folder-other-frame)))
1711 (cons (const gnus)
1712 (choice
1713 (const gnus)
1714 (const gnus-other-frame)
1715 (const org-gnus-no-new-news)))
1716 (cons (const file)
1717 (choice
1718 (const find-file)
1719 (const find-file-other-window)
1720 (const find-file-other-frame)))
1721 (cons (const wl)
1722 (choice
1723 (const wl)
1724 (const wl-other-frame)))))
1726 (defcustom org-display-internal-link-with-indirect-buffer nil
1727 "Non-nil means use indirect buffer to display infile links.
1728 Activating internal links (from one location in a file to another location
1729 in the same file) normally just jumps to the location. When the link is
1730 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1731 is displayed in
1732 another window. When this option is set, the other window actually displays
1733 an indirect buffer clone of the current buffer, to avoid any visibility
1734 changes to the current buffer."
1735 :group 'org-link-follow
1736 :type 'boolean)
1738 (defcustom org-open-non-existing-files nil
1739 "Non-nil means `org-open-file' will open non-existing files.
1740 When nil, an error will be generated.
1741 This variable applies only to external applications because they
1742 might choke on non-existing files. If the link is to a file that
1743 will be opened in Emacs, the variable is ignored."
1744 :group 'org-link-follow
1745 :type 'boolean)
1747 (defcustom org-open-directory-means-index-dot-org nil
1748 "Non-nil means a link to a directory really means to index.org.
1749 When nil, following a directory link will run dired or open a finder/explorer
1750 window on that directory."
1751 :group 'org-link-follow
1752 :type 'boolean)
1754 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1755 "Function and arguments to call for following mailto links.
1756 This is a list with the first element being a Lisp function, and the
1757 remaining elements being arguments to the function. In string arguments,
1758 %a will be replaced by the address, and %s will be replaced by the subject
1759 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1760 :group 'org-link-follow
1761 :type '(choice
1762 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1763 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1764 (const :tag "message-mail" (message-mail "%a" "%s"))
1765 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1767 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1768 "Non-nil means ask for confirmation before executing shell links.
1769 Shell links can be dangerous: just think about a link
1771 [[shell:rm -rf ~/*][Google Search]]
1773 This link would show up in your Org-mode document as \"Google Search\",
1774 but really it would remove your entire home directory.
1775 Therefore we advise against setting this variable to nil.
1776 Just change it to `y-or-n-p' if you want to confirm with a
1777 single keystroke rather than having to type \"yes\"."
1778 :group 'org-link-follow
1779 :type '(choice
1780 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1781 (const :tag "with y-or-n (faster)" y-or-n-p)
1782 (const :tag "no confirmation (dangerous)" nil)))
1783 (put 'org-confirm-shell-link-function
1784 'safe-local-variable
1785 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1787 (defcustom org-confirm-shell-link-not-regexp ""
1788 "A regexp to skip confirmation for shell links."
1789 :group 'org-link-follow
1790 :version "24.1"
1791 :type 'regexp)
1793 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1794 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1795 Elisp links can be dangerous: just think about a link
1797 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1799 This link would show up in your Org-mode document as \"Google Search\",
1800 but really it would remove your entire home directory.
1801 Therefore we advise against setting this variable to nil.
1802 Just change it to `y-or-n-p' if you want to confirm with a
1803 single keystroke rather than having to type \"yes\"."
1804 :group 'org-link-follow
1805 :type '(choice
1806 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1807 (const :tag "with y-or-n (faster)" y-or-n-p)
1808 (const :tag "no confirmation (dangerous)" nil)))
1809 (put 'org-confirm-shell-link-function
1810 'safe-local-variable
1811 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1813 (defcustom org-confirm-elisp-link-not-regexp ""
1814 "A regexp to skip confirmation for Elisp links."
1815 :group 'org-link-follow
1816 :version "24.1"
1817 :type 'regexp)
1819 (defconst org-file-apps-defaults-gnu
1820 '((remote . emacs)
1821 (system . mailcap)
1822 (t . mailcap))
1823 "Default file applications on a UNIX or GNU/Linux system.
1824 See `org-file-apps'.")
1826 (defconst org-file-apps-defaults-macosx
1827 '((remote . emacs)
1828 (t . "open %s")
1829 (system . "open %s")
1830 ("ps.gz" . "gv %s")
1831 ("eps.gz" . "gv %s")
1832 ("dvi" . "xdvi %s")
1833 ("fig" . "xfig %s"))
1834 "Default file applications on a MacOS X system.
1835 The system \"open\" is known as a default, but we use X11 applications
1836 for some files for which the OS does not have a good default.
1837 See `org-file-apps'.")
1839 (defconst org-file-apps-defaults-windowsnt
1840 (list
1841 '(remote . emacs)
1842 (cons t
1843 (list (if (featurep 'xemacs)
1844 'mswindows-shell-execute
1845 'w32-shell-execute)
1846 "open" 'file))
1847 (cons 'system
1848 (list (if (featurep 'xemacs)
1849 'mswindows-shell-execute
1850 'w32-shell-execute)
1851 "open" 'file)))
1852 "Default file applications on a Windows NT system.
1853 The system \"open\" is used for most files.
1854 See `org-file-apps'.")
1856 (defcustom org-file-apps
1858 (auto-mode . emacs)
1859 ("\\.mm\\'" . default)
1860 ("\\.x?html?\\'" . default)
1861 ("\\.pdf\\'" . default)
1863 "External applications for opening `file:path' items in a document.
1864 Org-mode uses system defaults for different file types, but
1865 you can use this variable to set the application for a given file
1866 extension. The entries in this list are cons cells where the car identifies
1867 files and the cdr the corresponding command. Possible values for the
1868 file identifier are
1869 \"string\" A string as a file identifier can be interpreted in different
1870 ways, depending on its contents:
1872 - Alphanumeric characters only:
1873 Match links with this file extension.
1874 Example: (\"pdf\" . \"evince %s\")
1875 to open PDFs with evince.
1877 - Regular expression: Match links where the
1878 filename matches the regexp. If you want to
1879 use groups here, use shy groups.
1881 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1882 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1883 to open *.html and *.xhtml with firefox.
1885 - Regular expression which contains (non-shy) groups:
1886 Match links where the whole link, including \"::\", and
1887 anything after that, matches the regexp.
1888 In a custom command string, %1, %2, etc. are replaced with
1889 the parts of the link that were matched by the groups.
1890 For backwards compatibility, if a command string is given
1891 that does not use any of the group matches, this case is
1892 handled identically to the second one (i.e. match against
1893 file name only).
1894 In a custom lisp form, you can access the group matches with
1895 (match-string n link).
1897 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1898 to open [[file:document.pdf::5]] with evince at page 5.
1900 `directory' Matches a directory
1901 `remote' Matches a remote file, accessible through tramp or efs.
1902 Remote files most likely should be visited through Emacs
1903 because external applications cannot handle such paths.
1904 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1905 so all files Emacs knows how to handle. Using this with
1906 command `emacs' will open most files in Emacs. Beware that this
1907 will also open html files inside Emacs, unless you add
1908 (\"html\" . default) to the list as well.
1909 t Default for files not matched by any of the other options.
1910 `system' The system command to open files, like `open' on Windows
1911 and Mac OS X, and mailcap under GNU/Linux. This is the command
1912 that will be selected if you call `C-c C-o' with a double
1913 \\[universal-argument] \\[universal-argument] prefix.
1915 Possible values for the command are:
1916 `emacs' The file will be visited by the current Emacs process.
1917 `default' Use the default application for this file type, which is the
1918 association for t in the list, most likely in the system-specific
1919 part.
1920 This can be used to overrule an unwanted setting in the
1921 system-specific variable.
1922 `system' Use the system command for opening files, like \"open\".
1923 This command is specified by the entry whose car is `system'.
1924 Most likely, the system-specific version of this variable
1925 does define this command, but you can overrule/replace it
1926 here.
1927 string A command to be executed by a shell; %s will be replaced
1928 by the path to the file.
1929 sexp A Lisp form which will be evaluated. The file path will
1930 be available in the Lisp variable `file'.
1931 For more examples, see the system specific constants
1932 `org-file-apps-defaults-macosx'
1933 `org-file-apps-defaults-windowsnt'
1934 `org-file-apps-defaults-gnu'."
1935 :group 'org-link-follow
1936 :type '(repeat
1937 (cons (choice :value ""
1938 (string :tag "Extension")
1939 (const :tag "System command to open files" system)
1940 (const :tag "Default for unrecognized files" t)
1941 (const :tag "Remote file" remote)
1942 (const :tag "Links to a directory" directory)
1943 (const :tag "Any files that have Emacs modes"
1944 auto-mode))
1945 (choice :value ""
1946 (const :tag "Visit with Emacs" emacs)
1947 (const :tag "Use default" default)
1948 (const :tag "Use the system command" system)
1949 (string :tag "Command")
1950 (sexp :tag "Lisp form")))))
1952 (defcustom org-doi-server-url "http://dx.doi.org/"
1953 "The URL of the DOI server."
1954 :type 'string
1955 :version "24.3"
1956 :group 'org-link-follow)
1958 (defgroup org-refile nil
1959 "Options concerning refiling entries in Org-mode."
1960 :tag "Org Refile"
1961 :group 'org)
1963 (defcustom org-directory "~/org"
1964 "Directory with org files.
1965 This is just a default location to look for Org files. There is no need
1966 at all to put your files into this directory. It is only used in the
1967 following situations:
1969 1. When a capture template specifies a target file that is not an
1970 absolute path. The path will then be interpreted relative to
1971 `org-directory'
1972 2. When a capture note is filed away in an interactive way (when exiting the
1973 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1974 with `org-directory' as the default path."
1975 :group 'org-refile
1976 :group 'org-remember
1977 :group 'org-capture
1978 :type 'directory)
1980 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1981 "Default target for storing notes.
1982 Used as a fall back file for org-remember.el and org-capture.el, for
1983 templates that do not specify a target file."
1984 :group 'org-refile
1985 :group 'org-remember
1986 :group 'org-capture
1987 :type '(choice
1988 (const :tag "Default from remember-data-file" nil)
1989 file))
1991 (defcustom org-goto-interface 'outline
1992 "The default interface to be used for `org-goto'.
1993 Allowed values are:
1994 outline The interface shows an outline of the relevant file
1995 and the correct heading is found by moving through
1996 the outline or by searching with incremental search.
1997 outline-path-completion Headlines in the current buffer are offered via
1998 completion. This is the interface also used by
1999 the refile command."
2000 :group 'org-refile
2001 :type '(choice
2002 (const :tag "Outline" outline)
2003 (const :tag "Outline-path-completion" outline-path-completion)))
2005 (defcustom org-goto-max-level 5
2006 "Maximum target level when running `org-goto' with refile interface."
2007 :group 'org-refile
2008 :type 'integer)
2010 (defcustom org-reverse-note-order nil
2011 "Non-nil means store new notes at the beginning of a file or entry.
2012 When nil, new notes will be filed to the end of a file or entry.
2013 This can also be a list with cons cells of regular expressions that
2014 are matched against file names, and values."
2015 :group 'org-remember
2016 :group 'org-capture
2017 :group 'org-refile
2018 :type '(choice
2019 (const :tag "Reverse always" t)
2020 (const :tag "Reverse never" nil)
2021 (repeat :tag "By file name regexp"
2022 (cons regexp boolean))))
2024 (defcustom org-log-refile nil
2025 "Information to record when a task is refiled.
2027 Possible values are:
2029 nil Don't add anything
2030 time Add a time stamp to the task
2031 note Prompt for a note and add it with template `org-log-note-headings'
2033 This option can also be set with on a per-file-basis with
2035 #+STARTUP: nologrefile
2036 #+STARTUP: logrefile
2037 #+STARTUP: lognoterefile
2039 You can have local logging settings for a subtree by setting the LOGGING
2040 property to one or more of these keywords.
2042 When bulk-refiling from the agenda, the value `note' is forbidden and
2043 will temporarily be changed to `time'."
2044 :group 'org-refile
2045 :group 'org-progress
2046 :version "24.1"
2047 :type '(choice
2048 (const :tag "No logging" nil)
2049 (const :tag "Record timestamp" time)
2050 (const :tag "Record timestamp with note." note)))
2052 (defcustom org-refile-targets nil
2053 "Targets for refiling entries with \\[org-refile].
2054 This is a list of cons cells. Each cell contains:
2055 - a specification of the files to be considered, either a list of files,
2056 or a symbol whose function or variable value will be used to retrieve
2057 a file name or a list of file names. If you use `org-agenda-files' for
2058 that, all agenda files will be scanned for targets. Nil means consider
2059 headings in the current buffer.
2060 - A specification of how to find candidate refile targets. This may be
2061 any of:
2062 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2063 This tag has to be present in all target headlines, inheritance will
2064 not be considered.
2065 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2066 todo keyword.
2067 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2068 headlines that are refiling targets.
2069 - a cons cell (:level . N). Any headline of level N is considered a target.
2070 Note that, when `org-odd-levels-only' is set, level corresponds to
2071 order in hierarchy, not to the number of stars.
2072 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2073 Note that, when `org-odd-levels-only' is set, level corresponds to
2074 order in hierarchy, not to the number of stars.
2076 Each element of this list generates a set of possible targets.
2077 The union of these sets is presented (with completion) to
2078 the user by `org-refile'.
2080 You can set the variable `org-refile-target-verify-function' to a function
2081 to verify each headline found by the simple criteria above.
2083 When this variable is nil, all top-level headlines in the current buffer
2084 are used, equivalent to the value `((nil . (:level . 1))'."
2085 :group 'org-refile
2086 :type '(repeat
2087 (cons
2088 (choice :value org-agenda-files
2089 (const :tag "All agenda files" org-agenda-files)
2090 (const :tag "Current buffer" nil)
2091 (function) (variable) (file))
2092 (choice :tag "Identify target headline by"
2093 (cons :tag "Specific tag" (const :value :tag) (string))
2094 (cons :tag "TODO keyword" (const :value :todo) (string))
2095 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2096 (cons :tag "Level number" (const :value :level) (integer))
2097 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2099 (defcustom org-refile-target-verify-function nil
2100 "Function to verify if the headline at point should be a refile target.
2101 The function will be called without arguments, with point at the
2102 beginning of the headline. It should return t and leave point
2103 where it is if the headline is a valid target for refiling.
2105 If the target should not be selected, the function must return nil.
2106 In addition to this, it may move point to a place from where the search
2107 should be continued. For example, the function may decide that the entire
2108 subtree of the current entry should be excluded and move point to the end
2109 of the subtree."
2110 :group 'org-refile
2111 :type 'function)
2113 (defcustom org-refile-use-cache nil
2114 "Non-nil means cache refile targets to speed up the process.
2115 The cache for a particular file will be updated automatically when
2116 the buffer has been killed, or when any of the marker used for flagging
2117 refile targets no longer points at a live buffer.
2118 If you have added new entries to a buffer that might themselves be targets,
2119 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2120 find that easier, `C-u C-u C-u C-c C-w'."
2121 :group 'org-refile
2122 :version "24.1"
2123 :type 'boolean)
2125 (defcustom org-refile-use-outline-path nil
2126 "Non-nil means provide refile targets as paths.
2127 So a level 3 headline will be available as level1/level2/level3.
2129 When the value is `file', also include the file name (without directory)
2130 into the path. In this case, you can also stop the completion after
2131 the file name, to get entries inserted as top level in the file.
2133 When `full-file-path', include the full file path."
2134 :group 'org-refile
2135 :type '(choice
2136 (const :tag "Not" nil)
2137 (const :tag "Yes" t)
2138 (const :tag "Start with file name" file)
2139 (const :tag "Start with full file path" full-file-path)))
2141 (defcustom org-outline-path-complete-in-steps t
2142 "Non-nil means complete the outline path in hierarchical steps.
2143 When Org-mode uses the refile interface to select an outline path
2144 \(see variable `org-refile-use-outline-path'), the completion of
2145 the path can be done is a single go, or if can be done in steps down
2146 the headline hierarchy. Going in steps is probably the best if you
2147 do not use a special completion package like `ido' or `icicles'.
2148 However, when using these packages, going in one step can be very
2149 fast, while still showing the whole path to the entry."
2150 :group 'org-refile
2151 :type 'boolean)
2153 (defcustom org-refile-allow-creating-parent-nodes nil
2154 "Non-nil means allow to create new nodes as refile targets.
2155 New nodes are then created by adding \"/new node name\" to the completion
2156 of an existing node. When the value of this variable is `confirm',
2157 new node creation must be confirmed by the user (recommended)
2158 When nil, the completion must match an existing entry.
2160 Note that, if the new heading is not seen by the criteria
2161 listed in `org-refile-targets', multiple instances of the same
2162 heading would be created by trying again to file under the new
2163 heading."
2164 :group 'org-refile
2165 :type '(choice
2166 (const :tag "Never" nil)
2167 (const :tag "Always" t)
2168 (const :tag "Prompt for confirmation" confirm)))
2170 (defcustom org-refile-active-region-within-subtree nil
2171 "Non-nil means also refile active region within a subtree.
2173 By default `org-refile' doesn't allow refiling regions if they
2174 don't contain a set of subtrees, but it might be convenient to
2175 do so sometimes: in that case, the first line of the region is
2176 converted to a headline before refiling."
2177 :group 'org-refile
2178 :version "24.1"
2179 :type 'boolean)
2181 (defgroup org-todo nil
2182 "Options concerning TODO items in Org-mode."
2183 :tag "Org TODO"
2184 :group 'org)
2186 (defgroup org-progress nil
2187 "Options concerning Progress logging in Org-mode."
2188 :tag "Org Progress"
2189 :group 'org-time)
2191 (defvar org-todo-interpretation-widgets
2192 '((:tag "Sequence (cycling hits every state)" sequence)
2193 (:tag "Type (cycling directly to DONE)" type))
2194 "The available interpretation symbols for customizing `org-todo-keywords'.
2195 Interested libraries should add to this list.")
2197 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2198 "List of TODO entry keyword sequences and their interpretation.
2199 \\<org-mode-map>This is a list of sequences.
2201 Each sequence starts with a symbol, either `sequence' or `type',
2202 indicating if the keywords should be interpreted as a sequence of
2203 action steps, or as different types of TODO items. The first
2204 keywords are states requiring action - these states will select a headline
2205 for inclusion into the global TODO list Org-mode produces. If one of
2206 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2207 signify that no further action is necessary. If \"|\" is not found,
2208 the last keyword is treated as the only DONE state of the sequence.
2210 The command \\[org-todo] cycles an entry through these states, and one
2211 additional state where no keyword is present. For details about this
2212 cycling, see the manual.
2214 TODO keywords and interpretation can also be set on a per-file basis with
2215 the special #+SEQ_TODO and #+TYP_TODO lines.
2217 Each keyword can optionally specify a character for fast state selection
2218 \(in combination with the variable `org-use-fast-todo-selection')
2219 and specifiers for state change logging, using the same syntax that
2220 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2221 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2222 indicates to record a time stamp each time this state is selected.
2224 Each keyword may also specify if a timestamp or a note should be
2225 recorded when entering or leaving the state, by adding additional
2226 characters in the parenthesis after the keyword. This looks like this:
2227 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2228 record only the time of the state change. With X and Y being either
2229 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2230 Y when leaving the state if and only if the *target* state does not
2231 define X. You may omit any of the fast-selection key or X or /Y,
2232 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2234 For backward compatibility, this variable may also be just a list
2235 of keywords. In this case the interpretation (sequence or type) will be
2236 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2237 :group 'org-todo
2238 :group 'org-keywords
2239 :type '(choice
2240 (repeat :tag "Old syntax, just keywords"
2241 (string :tag "Keyword"))
2242 (repeat :tag "New syntax"
2243 (cons
2244 (choice
2245 :tag "Interpretation"
2246 ;;Quick and dirty way to see
2247 ;;`org-todo-interpretations'. This takes the
2248 ;;place of item arguments
2249 :convert-widget
2250 (lambda (widget)
2251 (widget-put widget
2252 :args (mapcar
2253 #'(lambda (x)
2254 (widget-convert
2255 (cons 'const x)))
2256 org-todo-interpretation-widgets))
2257 widget))
2258 (repeat
2259 (string :tag "Keyword"))))))
2261 (defvar org-todo-keywords-1 nil
2262 "All TODO and DONE keywords active in a buffer.")
2263 (make-variable-buffer-local 'org-todo-keywords-1)
2264 (defvar org-todo-keywords-for-agenda nil)
2265 (defvar org-done-keywords-for-agenda nil)
2266 (defvar org-drawers-for-agenda nil)
2267 (defvar org-todo-keyword-alist-for-agenda nil)
2268 (defvar org-tag-alist-for-agenda nil)
2269 (defvar org-agenda-contributing-files nil)
2270 (defvar org-not-done-keywords nil)
2271 (make-variable-buffer-local 'org-not-done-keywords)
2272 (defvar org-done-keywords nil)
2273 (make-variable-buffer-local 'org-done-keywords)
2274 (defvar org-todo-heads nil)
2275 (make-variable-buffer-local 'org-todo-heads)
2276 (defvar org-todo-sets nil)
2277 (make-variable-buffer-local 'org-todo-sets)
2278 (defvar org-todo-log-states nil)
2279 (make-variable-buffer-local 'org-todo-log-states)
2280 (defvar org-todo-kwd-alist nil)
2281 (make-variable-buffer-local 'org-todo-kwd-alist)
2282 (defvar org-todo-key-alist nil)
2283 (make-variable-buffer-local 'org-todo-key-alist)
2284 (defvar org-todo-key-trigger nil)
2285 (make-variable-buffer-local 'org-todo-key-trigger)
2287 (defcustom org-todo-interpretation 'sequence
2288 "Controls how TODO keywords are interpreted.
2289 This variable is in principle obsolete and is only used for
2290 backward compatibility, if the interpretation of todo keywords is
2291 not given already in `org-todo-keywords'. See that variable for
2292 more information."
2293 :group 'org-todo
2294 :group 'org-keywords
2295 :type '(choice (const sequence)
2296 (const type)))
2298 (defcustom org-use-fast-todo-selection t
2299 "Non-nil means use the fast todo selection scheme with C-c C-t.
2300 This variable describes if and under what circumstances the cycling
2301 mechanism for TODO keywords will be replaced by a single-key, direct
2302 selection scheme.
2304 When nil, fast selection is never used.
2306 When the symbol `prefix', it will be used when `org-todo' is called
2307 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2308 `C-u t' in an agenda buffer.
2310 When t, fast selection is used by default. In this case, the prefix
2311 argument forces cycling instead.
2313 In all cases, the special interface is only used if access keys have
2314 actually been assigned by the user, i.e. if keywords in the configuration
2315 are followed by a letter in parenthesis, like TODO(t)."
2316 :group 'org-todo
2317 :type '(choice
2318 (const :tag "Never" nil)
2319 (const :tag "By default" t)
2320 (const :tag "Only with C-u C-c C-t" prefix)))
2322 (defcustom org-provide-todo-statistics t
2323 "Non-nil means update todo statistics after insert and toggle.
2324 ALL-HEADLINES means update todo statistics by including headlines
2325 with no TODO keyword as well, counting them as not done.
2326 A list of TODO keywords means the same, but skip keywords that are
2327 not in this list.
2329 When this is set, todo statistics is updated in the parent of the
2330 current entry each time a todo state is changed."
2331 :group 'org-todo
2332 :type '(choice
2333 (const :tag "Yes, only for TODO entries" t)
2334 (const :tag "Yes, including all entries" 'all-headlines)
2335 (repeat :tag "Yes, for TODOs in this list"
2336 (string :tag "TODO keyword"))
2337 (other :tag "No TODO statistics" nil)))
2339 (defcustom org-hierarchical-todo-statistics t
2340 "Non-nil means TODO statistics covers just direct children.
2341 When nil, all entries in the subtree are considered.
2342 This has only an effect if `org-provide-todo-statistics' is set.
2343 To set this to nil for only a single subtree, use a COOKIE_DATA
2344 property and include the word \"recursive\" into the value."
2345 :group 'org-todo
2346 :type 'boolean)
2348 (defcustom org-after-todo-state-change-hook nil
2349 "Hook which is run after the state of a TODO item was changed.
2350 The new state (a string with a TODO keyword, or nil) is available in the
2351 Lisp variable `org-state'."
2352 :group 'org-todo
2353 :type 'hook)
2355 (defvar org-blocker-hook nil
2356 "Hook for functions that are allowed to block a state change.
2358 Functions in this hook should not modify the buffer.
2359 Each function gets as its single argument a property list,
2360 see `org-trigger-hook' for more information about this list.
2362 If any of the functions in this hook returns nil, the state change
2363 is blocked.")
2365 (defvar org-trigger-hook nil
2366 "Hook for functions that are triggered by a state change.
2368 Each function gets as its single argument a property list with at
2369 least the following elements:
2371 (:type type-of-change :position pos-at-entry-start
2372 :from old-state :to new-state)
2374 Depending on the type, more properties may be present.
2376 This mechanism is currently implemented for:
2378 TODO state changes
2379 ------------------
2380 :type todo-state-change
2381 :from previous state (keyword as a string), or nil, or a symbol
2382 'todo' or 'done', to indicate the general type of state.
2383 :to new state, like in :from")
2385 (defcustom org-enforce-todo-dependencies nil
2386 "Non-nil means undone TODO entries will block switching the parent to DONE.
2387 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2388 be blocked if any prior sibling is not yet done.
2389 Finally, if the parent is blocked because of ordered siblings of its own,
2390 the child will also be blocked."
2391 :set (lambda (var val)
2392 (set var val)
2393 (if val
2394 (add-hook 'org-blocker-hook
2395 'org-block-todo-from-children-or-siblings-or-parent)
2396 (remove-hook 'org-blocker-hook
2397 'org-block-todo-from-children-or-siblings-or-parent)))
2398 :group 'org-todo
2399 :type 'boolean)
2401 (defcustom org-enforce-todo-checkbox-dependencies nil
2402 "Non-nil means unchecked boxes will block switching the parent to DONE.
2403 When this is nil, checkboxes have no influence on switching TODO states.
2404 When non-nil, you first need to check off all check boxes before the TODO
2405 entry can be switched to DONE.
2406 This variable needs to be set before org.el is loaded, and you need to
2407 restart Emacs after a change to make the change effective. The only way
2408 to change is while Emacs is running is through the customize interface."
2409 :set (lambda (var val)
2410 (set var val)
2411 (if val
2412 (add-hook 'org-blocker-hook
2413 'org-block-todo-from-checkboxes)
2414 (remove-hook 'org-blocker-hook
2415 'org-block-todo-from-checkboxes)))
2416 :group 'org-todo
2417 :type 'boolean)
2419 (defcustom org-treat-insert-todo-heading-as-state-change nil
2420 "Non-nil means inserting a TODO heading is treated as state change.
2421 So when the command \\[org-insert-todo-heading] is used, state change
2422 logging will apply if appropriate. When nil, the new TODO item will
2423 be inserted directly, and no logging will take place."
2424 :group 'org-todo
2425 :type 'boolean)
2427 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2428 "Non-nil means switching TODO states with S-cursor counts as state change.
2429 This is the default behavior. However, setting this to nil allows a
2430 convenient way to select a TODO state and bypass any logging associated
2431 with that."
2432 :group 'org-todo
2433 :type 'boolean)
2435 (defcustom org-todo-state-tags-triggers nil
2436 "Tag changes that should be triggered by TODO state changes.
2437 This is a list. Each entry is
2439 (state-change (tag . flag) .......)
2441 State-change can be a string with a state, and empty string to indicate the
2442 state that has no TODO keyword, or it can be one of the symbols `todo'
2443 or `done', meaning any not-done or done state, respectively."
2444 :group 'org-todo
2445 :group 'org-tags
2446 :type '(repeat
2447 (cons (choice :tag "When changing to"
2448 (const :tag "Not-done state" todo)
2449 (const :tag "Done state" done)
2450 (string :tag "State"))
2451 (repeat
2452 (cons :tag "Tag action"
2453 (string :tag "Tag")
2454 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2456 (defcustom org-log-done nil
2457 "Information to record when a task moves to the DONE state.
2459 Possible values are:
2461 nil Don't add anything, just change the keyword
2462 time Add a time stamp to the task
2463 note Prompt for a note and add it with template `org-log-note-headings'
2465 This option can also be set with on a per-file-basis with
2467 #+STARTUP: nologdone
2468 #+STARTUP: logdone
2469 #+STARTUP: lognotedone
2471 You can have local logging settings for a subtree by setting the LOGGING
2472 property to one or more of these keywords."
2473 :group 'org-todo
2474 :group 'org-progress
2475 :type '(choice
2476 (const :tag "No logging" nil)
2477 (const :tag "Record CLOSED timestamp" time)
2478 (const :tag "Record CLOSED timestamp with note." note)))
2480 ;; Normalize old uses of org-log-done.
2481 (cond
2482 ((eq org-log-done t) (setq org-log-done 'time))
2483 ((and (listp org-log-done) (memq 'done org-log-done))
2484 (setq org-log-done 'note)))
2486 (defcustom org-log-reschedule nil
2487 "Information to record when the scheduling date of a tasks is modified.
2489 Possible values are:
2491 nil Don't add anything, just change the date
2492 time Add a time stamp to the task
2493 note Prompt for a note and add it with template `org-log-note-headings'
2495 This option can also be set with on a per-file-basis with
2497 #+STARTUP: nologreschedule
2498 #+STARTUP: logreschedule
2499 #+STARTUP: lognotereschedule"
2500 :group 'org-todo
2501 :group 'org-progress
2502 :type '(choice
2503 (const :tag "No logging" nil)
2504 (const :tag "Record timestamp" time)
2505 (const :tag "Record timestamp with note." note)))
2507 (defcustom org-log-redeadline nil
2508 "Information to record when the deadline date of a tasks is modified.
2510 Possible values are:
2512 nil Don't add anything, just change the date
2513 time Add a time stamp to the task
2514 note Prompt for a note and add it with template `org-log-note-headings'
2516 This option can also be set with on a per-file-basis with
2518 #+STARTUP: nologredeadline
2519 #+STARTUP: logredeadline
2520 #+STARTUP: lognoteredeadline
2522 You can have local logging settings for a subtree by setting the LOGGING
2523 property to one or more of these keywords."
2524 :group 'org-todo
2525 :group 'org-progress
2526 :type '(choice
2527 (const :tag "No logging" nil)
2528 (const :tag "Record timestamp" time)
2529 (const :tag "Record timestamp with note." note)))
2531 (defcustom org-log-note-clock-out nil
2532 "Non-nil means record a note when clocking out of an item.
2533 This can also be configured on a per-file basis by adding one of
2534 the following lines anywhere in the buffer:
2536 #+STARTUP: lognoteclock-out
2537 #+STARTUP: nolognoteclock-out"
2538 :group 'org-todo
2539 :group 'org-progress
2540 :type 'boolean)
2542 (defcustom org-log-done-with-time t
2543 "Non-nil means the CLOSED time stamp will contain date and time.
2544 When nil, only the date will be recorded."
2545 :group 'org-progress
2546 :type 'boolean)
2548 (defcustom org-log-note-headings
2549 '((done . "CLOSING NOTE %t")
2550 (state . "State %-12s from %-12S %t")
2551 (note . "Note taken on %t")
2552 (reschedule . "Rescheduled from %S on %t")
2553 (delschedule . "Not scheduled, was %S on %t")
2554 (redeadline . "New deadline from %S on %t")
2555 (deldeadline . "Removed deadline, was %S on %t")
2556 (refile . "Refiled on %t")
2557 (clock-out . ""))
2558 "Headings for notes added to entries.
2559 The value is an alist, with the car being a symbol indicating the note
2560 context, and the cdr is the heading to be used. The heading may also be the
2561 empty string.
2562 %t in the heading will be replaced by a time stamp.
2563 %T will be an active time stamp instead the default inactive one
2564 %d will be replaced by a short-format time stamp.
2565 %D will be replaced by an active short-format time stamp.
2566 %s will be replaced by the new TODO state, in double quotes.
2567 %S will be replaced by the old TODO state, in double quotes.
2568 %u will be replaced by the user name.
2569 %U will be replaced by the full user name.
2571 In fact, it is not a good idea to change the `state' entry, because
2572 agenda log mode depends on the format of these entries."
2573 :group 'org-todo
2574 :group 'org-progress
2575 :type '(list :greedy t
2576 (cons (const :tag "Heading when closing an item" done) string)
2577 (cons (const :tag
2578 "Heading when changing todo state (todo sequence only)"
2579 state) string)
2580 (cons (const :tag "Heading when just taking a note" note) string)
2581 (cons (const :tag "Heading when clocking out" clock-out) string)
2582 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2583 (cons (const :tag "Heading when rescheduling" reschedule) string)
2584 (cons (const :tag "Heading when changing deadline" redeadline) string)
2585 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2586 (cons (const :tag "Heading when refiling" refile) string)))
2588 (unless (assq 'note org-log-note-headings)
2589 (push '(note . "%t") org-log-note-headings))
2591 (defcustom org-log-into-drawer nil
2592 "Non-nil means insert state change notes and time stamps into a drawer.
2593 When nil, state changes notes will be inserted after the headline and
2594 any scheduling and clock lines, but not inside a drawer.
2596 The value of this variable should be the name of the drawer to use.
2597 LOGBOOK is proposed as the default drawer for this purpose, you can
2598 also set this to a string to define the drawer of your choice.
2600 A value of t is also allowed, representing \"LOGBOOK\".
2602 A value of t or nil can also be set with on a per-file-basis with
2604 #+STARTUP: logdrawer
2605 #+STARTUP: nologdrawer
2607 If this variable is set, `org-log-state-notes-insert-after-drawers'
2608 will be ignored.
2610 You can set the property LOG_INTO_DRAWER to overrule this setting for
2611 a subtree."
2612 :group 'org-todo
2613 :group 'org-progress
2614 :type '(choice
2615 (const :tag "Not into a drawer" nil)
2616 (const :tag "LOGBOOK" t)
2617 (string :tag "Other")))
2619 (if (fboundp 'defvaralias)
2620 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2622 (defun org-log-into-drawer ()
2623 "Return the value of `org-log-into-drawer', but let properties overrule.
2624 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2625 used instead of the default value."
2626 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2627 (cond
2628 ((not p) org-log-into-drawer)
2629 ((equal p "nil") nil)
2630 ((equal p "t") "LOGBOOK")
2631 (t p))))
2633 (defcustom org-log-state-notes-insert-after-drawers nil
2634 "Non-nil means insert state change notes after any drawers in entry.
2635 Only the drawers that *immediately* follow the headline and the
2636 deadline/scheduled line are skipped.
2637 When nil, insert notes right after the heading and perhaps the line
2638 with deadline/scheduling if present.
2640 This variable will have no effect if `org-log-into-drawer' is
2641 set."
2642 :group 'org-todo
2643 :group 'org-progress
2644 :type 'boolean)
2646 (defcustom org-log-states-order-reversed t
2647 "Non-nil means the latest state note will be directly after heading.
2648 When nil, the state change notes will be ordered according to time.
2650 This option can also be set with on a per-file-basis with
2652 #+STARTUP: logstatesreversed
2653 #+STARTUP: nologstatesreversed"
2654 :group 'org-todo
2655 :group 'org-progress
2656 :type 'boolean)
2658 (defcustom org-todo-repeat-to-state nil
2659 "The TODO state to which a repeater should return the repeating task.
2660 By default this is the first task in a TODO sequence, or the previous state
2661 in a TODO_TYP set. But you can specify another task here.
2662 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2663 :group 'org-todo
2664 :version "24.1"
2665 :type '(choice (const :tag "Head of sequence" nil)
2666 (string :tag "Specific state")))
2668 (defcustom org-log-repeat 'time
2669 "Non-nil means record moving through the DONE state when triggering repeat.
2670 An auto-repeating task is immediately switched back to TODO when
2671 marked DONE. If you are not logging state changes (by adding \"@\"
2672 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2673 record a closing note, there will be no record of the task moving
2674 through DONE. This variable forces taking a note anyway.
2676 nil Don't force a record
2677 time Record a time stamp
2678 note Prompt for a note and add it with template `org-log-note-headings'
2680 This option can also be set with on a per-file-basis with
2682 #+STARTUP: nologrepeat
2683 #+STARTUP: logrepeat
2684 #+STARTUP: lognoterepeat
2686 You can have local logging settings for a subtree by setting the LOGGING
2687 property to one or more of these keywords."
2688 :group 'org-todo
2689 :group 'org-progress
2690 :type '(choice
2691 (const :tag "Don't force a record" nil)
2692 (const :tag "Force recording the DONE state" time)
2693 (const :tag "Force recording a note with the DONE state" note)))
2696 (defgroup org-priorities nil
2697 "Priorities in Org-mode."
2698 :tag "Org Priorities"
2699 :group 'org-todo)
2701 (defcustom org-enable-priority-commands t
2702 "Non-nil means priority commands are active.
2703 When nil, these commands will be disabled, so that you never accidentally
2704 set a priority."
2705 :group 'org-priorities
2706 :type 'boolean)
2708 (defcustom org-highest-priority ?A
2709 "The highest priority of TODO items. A character like ?A, ?B etc.
2710 Must have a smaller ASCII number than `org-lowest-priority'."
2711 :group 'org-priorities
2712 :type 'character)
2714 (defcustom org-lowest-priority ?C
2715 "The lowest priority of TODO items. A character like ?A, ?B etc.
2716 Must have a larger ASCII number than `org-highest-priority'."
2717 :group 'org-priorities
2718 :type 'character)
2720 (defcustom org-default-priority ?B
2721 "The default priority of TODO items.
2722 This is the priority an item gets if no explicit priority is given.
2723 When starting to cycle on an empty priority the first step in the cycle
2724 depends on `org-priority-start-cycle-with-default'. The resulting first
2725 step priority must not exceed the range from `org-highest-priority' to
2726 `org-lowest-priority' which means that `org-default-priority' has to be
2727 in this range exclusive or inclusive the range boundaries. Else the
2728 first step refuses to set the default and the second will fall back
2729 to (depending on the command used) the highest or lowest priority."
2730 :group 'org-priorities
2731 :type 'character)
2733 (defcustom org-priority-start-cycle-with-default t
2734 "Non-nil means start with default priority when starting to cycle.
2735 When this is nil, the first step in the cycle will be (depending on the
2736 command used) one higher or lower than the default priority.
2737 See also `org-default-priority'."
2738 :group 'org-priorities
2739 :type 'boolean)
2741 (defcustom org-get-priority-function nil
2742 "Function to extract the priority from a string.
2743 The string is normally the headline. If this is nil Org computes the
2744 priority from the priority cookie like [#A] in the headline. It returns
2745 an integer, increasing by 1000 for each priority level.
2746 The user can set a different function here, which should take a string
2747 as an argument and return the numeric priority."
2748 :group 'org-priorities
2749 :version "24.1"
2750 :type 'function)
2752 (defgroup org-time nil
2753 "Options concerning time stamps and deadlines in Org-mode."
2754 :tag "Org Time"
2755 :group 'org)
2757 (defcustom org-insert-labeled-timestamps-at-point nil
2758 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2759 When nil, these labeled time stamps are forces into the second line of an
2760 entry, just after the headline. When scheduling from the global TODO list,
2761 the time stamp will always be forced into the second line."
2762 :group 'org-time
2763 :type 'boolean)
2765 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2766 "Formats for `format-time-string' which are used for time stamps.
2767 It is not recommended to change this constant.")
2769 (defcustom org-time-stamp-rounding-minutes '(0 5)
2770 "Number of minutes to round time stamps to.
2771 These are two values, the first applies when first creating a time stamp.
2772 The second applies when changing it with the commands `S-up' and `S-down'.
2773 When changing the time stamp, this means that it will change in steps
2774 of N minutes, as given by the second value.
2776 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2777 numbers should be factors of 60, so for example 5, 10, 15.
2779 When this is larger than 1, you can still force an exact time stamp by using
2780 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2781 and by using a prefix arg to `S-up/down' to specify the exact number
2782 of minutes to shift."
2783 :group 'org-time
2784 :get #'(lambda (var) ; Make sure both elements are there
2785 (if (integerp (default-value var))
2786 (list (default-value var) 5)
2787 (default-value var)))
2788 :type '(list
2789 (integer :tag "when inserting times")
2790 (integer :tag "when modifying times")))
2792 ;; Normalize old customizations of this variable.
2793 (when (integerp org-time-stamp-rounding-minutes)
2794 (setq org-time-stamp-rounding-minutes
2795 (list org-time-stamp-rounding-minutes
2796 org-time-stamp-rounding-minutes)))
2798 (defcustom org-display-custom-times nil
2799 "Non-nil means overlay custom formats over all time stamps.
2800 The formats are defined through the variable `org-time-stamp-custom-formats'.
2801 To turn this on on a per-file basis, insert anywhere in the file:
2802 #+STARTUP: customtime"
2803 :group 'org-time
2804 :set 'set-default
2805 :type 'sexp)
2806 (make-variable-buffer-local 'org-display-custom-times)
2808 (defcustom org-time-stamp-custom-formats
2809 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2810 "Custom formats for time stamps. See `format-time-string' for the syntax.
2811 These are overlaid over the default ISO format if the variable
2812 `org-display-custom-times' is set. Time like %H:%M should be at the
2813 end of the second format. The custom formats are also honored by export
2814 commands, if custom time display is turned on at the time of export."
2815 :group 'org-time
2816 :type 'sexp)
2818 (defun org-time-stamp-format (&optional long inactive)
2819 "Get the right format for a time string."
2820 (let ((f (if long (cdr org-time-stamp-formats)
2821 (car org-time-stamp-formats))))
2822 (if inactive
2823 (concat "[" (substring f 1 -1) "]")
2824 f)))
2826 (defcustom org-time-clocksum-format
2827 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2828 "The format string used when creating CLOCKSUM lines.
2829 This is also used when Org mode generates a time duration.
2831 The value can be a single format string containing two
2832 %-sequences, which will be filled with the number of hours and
2833 minutes in that order.
2835 Alternatively, the value can be a plist associating any of the
2836 keys :years, :months, :weeks, :days, :hours or :minutes with
2837 format strings. The time duration is formatted using only the
2838 time components that are needed and concatenating the results.
2839 If a time unit in absent, it falls back to the next smallest
2840 unit.
2842 The keys :require-years, :require-months, :require-days,
2843 :require-weeks, :require-hours, :require-minutes are also
2844 meaningful. A non-nil value for these keys indicates that the
2845 corresponding time component should always be included, even if
2846 its value is 0.
2849 For example,
2851 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2852 :require-minutes t)
2854 means durations longer than a day will be expressed in days,
2855 hours and minutes, and durations less than a day will always be
2856 expressed in hours and minutes (even for durations less than an
2857 hour).
2859 The value
2861 \(:days \"%dd\" :minutes \"%dm\")
2863 means durations longer than a day will be expressed in days and
2864 minutes, and durations less than a day will be expressed entirely
2865 in minutes (even for durations longer than an hour)."
2866 :group 'org-time
2867 :group 'org-clock
2868 :version "24.3"
2869 :type '(choice (string :tag "Format string")
2870 (set :tag "Plist"
2871 (group :inline t (const :tag "Years" :years)
2872 (string :tag "Format string"))
2873 (group :inline t
2874 (const :tag "Always show years" :require-years)
2875 (const t))
2876 (group :inline t (const :tag "Months" :months)
2877 (string :tag "Format string"))
2878 (group :inline t
2879 (const :tag "Always show months" :require-months)
2880 (const t))
2881 (group :inline t (const :tag "Weeks" :weeks)
2882 (string :tag "Format string"))
2883 (group :inline t
2884 (const :tag "Always show weeks" :require-weeks)
2885 (const t))
2886 (group :inline t (const :tag "Days" :days)
2887 (string :tag "Format string"))
2888 (group :inline t
2889 (const :tag "Always show days" :require-days)
2890 (const t))
2891 (group :inline t (const :tag "Hours" :hours)
2892 (string :tag "Format string"))
2893 (group :inline t
2894 (const :tag "Always show hours" :require-hours)
2895 (const t))
2896 (group :inline t (const :tag "Minutes" :minutes)
2897 (string :tag "Format string"))
2898 (group :inline t
2899 (const :tag "Always show minutes" :require-minutes)
2900 (const t)))))
2902 (defcustom org-time-clocksum-use-fractional nil
2903 "When non-nil, \\[org-clock-display] uses fractional times.
2904 See `org-time-clocksum-format' for more on time clock formats."
2905 :group 'org-time
2906 :group 'org-clock
2907 :version "24.3"
2908 :type 'boolean)
2910 (defcustom org-time-clocksum-use-effort-durations t
2911 "When non-nil, \\[org-clock-display] uses effort durations.
2912 E.g. by default, one day is considered to be a 8 hours effort,
2913 so a task that has been clocked for 16 hours will be displayed
2914 as during 2 days in the clock display or in the clocktable.
2916 See `org-effort-durations' on how to set effort durations
2917 and `org-time-clocksum-format' for more on time clock formats."
2918 :group 'org-time
2919 :group 'org-clock
2920 :version "24.3"
2921 :type 'boolean)
2923 (defcustom org-time-clocksum-fractional-format "%.2f"
2924 "The format string used when creating CLOCKSUM lines,
2925 or when Org mode generates a time duration, if
2926 `org-time-clocksum-use-fractional' is enabled.
2928 The value can be a single format string containing one
2929 %-sequence, which will be filled with the number of hours as
2930 a float.
2932 Alternatively, the value can be a plist associating any of the
2933 keys :years, :months, :weeks, :days, :hours or :minutes with
2934 a format string. The time duration is formatted using the
2935 largest time unit which gives a non-zero integer part. If all
2936 specified formats have zero integer part, the smallest time unit
2937 is used."
2938 :group 'org-time
2939 :type '(choice (string :tag "Format string")
2940 (set (group :inline t (const :tag "Years" :years)
2941 (string :tag "Format string"))
2942 (group :inline t (const :tag "Months" :months)
2943 (string :tag "Format string"))
2944 (group :inline t (const :tag "Weeks" :weeks)
2945 (string :tag "Format string"))
2946 (group :inline t (const :tag "Days" :days)
2947 (string :tag "Format string"))
2948 (group :inline t (const :tag "Hours" :hours)
2949 (string :tag "Format string"))
2950 (group :inline t (const :tag "Minutes" :minutes)
2951 (string :tag "Format string")))))
2953 (defcustom org-deadline-warning-days 14
2954 "Number of days before expiration during which a deadline becomes active.
2955 This variable governs the display in sparse trees and in the agenda.
2956 When 0 or negative, it means use this number (the absolute value of it)
2957 even if a deadline has a different individual lead time specified.
2959 Custom commands can set this variable in the options section."
2960 :group 'org-time
2961 :group 'org-agenda-daily/weekly
2962 :type 'integer)
2964 (defcustom org-scheduled-delay-days 0
2965 "Number of days before a scheduled item becomes active.
2966 This variable governs the display in sparse trees and in the agenda.
2967 The default value (i.e. 0) means: don't delay scheduled item.
2968 When negative, it means use this number (the absolute value of it)
2969 even if a scheduled item has a different individual delay time
2970 specified.
2972 Custom commands can set this variable in the options section."
2973 :group 'org-time
2974 :group 'org-agenda-daily/weekly
2975 :version "24.3"
2976 :type 'integer)
2978 (defcustom org-read-date-prefer-future t
2979 "Non-nil means assume future for incomplete date input from user.
2980 This affects the following situations:
2981 1. The user gives a month but not a year.
2982 For example, if it is April and you enter \"feb 2\", this will be read
2983 as Feb 2, *next* year. \"May 5\", however, will be this year.
2984 2. The user gives a day, but no month.
2985 For example, if today is the 15th, and you enter \"3\", Org-mode will
2986 read this as the third of *next* month. However, if you enter \"17\",
2987 it will be considered as *this* month.
2989 If you set this variable to the symbol `time', then also the following
2990 will work:
2992 3. If the user gives a time.
2993 If the time is before now, it will be interpreted as tomorrow.
2995 Currently none of this works for ISO week specifications.
2997 When this option is nil, the current day, month and year will always be
2998 used as defaults.
3000 See also `org-agenda-jump-prefer-future'."
3001 :group 'org-time
3002 :type '(choice
3003 (const :tag "Never" nil)
3004 (const :tag "Check month and day" t)
3005 (const :tag "Check month, day, and time" time)))
3007 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3008 "Should the agenda jump command prefer the future for incomplete dates?
3009 The default is to do the same as configured in `org-read-date-prefer-future'.
3010 But you can also set a deviating value here.
3011 This may t or nil, or the symbol `org-read-date-prefer-future'."
3012 :group 'org-agenda
3013 :group 'org-time
3014 :version "24.1"
3015 :type '(choice
3016 (const :tag "Use org-read-date-prefer-future"
3017 org-read-date-prefer-future)
3018 (const :tag "Never" nil)
3019 (const :tag "Always" t)))
3021 (defcustom org-read-date-force-compatible-dates t
3022 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3024 Depending on the system Emacs is running on, certain dates cannot
3025 be represented with the type used internally to represent time.
3026 Dates between 1970-1-1 and 2038-1-1 can always be represented
3027 correctly. Some systems allow for earlier dates, some for later,
3028 some for both. One way to find out it to insert any date into an
3029 Org buffer, putting the cursor on the year and hitting S-up and
3030 S-down to test the range.
3032 When this variable is set to t, the date/time prompt will not let
3033 you specify dates outside the 1970-2037 range, so it is certain that
3034 these dates will work in whatever version of Emacs you are
3035 running, and also that you can move a file from one Emacs implementation
3036 to another. WHenever Org is forcing the year for you, it will display
3037 a message and beep.
3039 When this variable is nil, Org will check if the date is
3040 representable in the specific Emacs implementation you are using.
3041 If not, it will force a year, usually the current year, and beep
3042 to remind you. Currently this setting is not recommended because
3043 the likelihood that you will open your Org files in an Emacs that
3044 has limited date range is not negligible.
3046 A workaround for this problem is to use diary sexp dates for time
3047 stamps outside of this range."
3048 :group 'org-time
3049 :version "24.1"
3050 :type 'boolean)
3052 (defcustom org-read-date-display-live t
3053 "Non-nil means display current interpretation of date prompt live.
3054 This display will be in an overlay, in the minibuffer."
3055 :group 'org-time
3056 :type 'boolean)
3058 (defcustom org-read-date-popup-calendar t
3059 "Non-nil means pop up a calendar when prompting for a date.
3060 In the calendar, the date can be selected with mouse-1. However, the
3061 minibuffer will also be active, and you can simply enter the date as well.
3062 When nil, only the minibuffer will be available."
3063 :group 'org-time
3064 :type 'boolean)
3065 (if (fboundp 'defvaralias)
3066 (defvaralias 'org-popup-calendar-for-date-prompt
3067 'org-read-date-popup-calendar))
3069 (make-obsolete-variable
3070 'org-read-date-minibuffer-setup-hook
3071 "Set `org-read-date-minibuffer-local-map' instead." "24.3")
3072 (defcustom org-read-date-minibuffer-setup-hook nil
3073 "Hook to be used to set up keys for the date/time interface.
3074 Add key definitions to `minibuffer-local-map', which will be a
3075 temporary copy.
3077 WARNING: This option is obsolete, you should use
3078 `org-read-date-minibuffer-local-map' to set up keys."
3079 :group 'org-time
3080 :type 'hook)
3082 (defcustom org-extend-today-until 0
3083 "The hour when your day really ends. Must be an integer.
3084 This has influence for the following applications:
3085 - When switching the agenda to \"today\". It it is still earlier than
3086 the time given here, the day recognized as TODAY is actually yesterday.
3087 - When a date is read from the user and it is still before the time given
3088 here, the current date and time will be assumed to be yesterday, 23:59.
3089 Also, timestamps inserted in capture templates follow this rule.
3091 IMPORTANT: This is a feature whose implementation is and likely will
3092 remain incomplete. Really, it is only here because past midnight seems to
3093 be the favorite working time of John Wiegley :-)"
3094 :group 'org-time
3095 :type 'integer)
3097 (defcustom org-use-effective-time nil
3098 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3099 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3100 \"effective time\" of any timestamps between midnight and 8am will be
3101 23:59 of the previous day."
3102 :group 'org-time
3103 :version "24.1"
3104 :type 'boolean)
3106 (defcustom org-use-last-clock-out-time-as-effective-time nil
3107 "When non-nil, use the last clock out time for `org-todo'.
3108 Note that this option has precedence over the combined use of
3109 `org-use-effective-time' and `org-extend-today-until'."
3110 :group 'org-time
3111 ;; :version "24.3"
3112 :type 'boolean)
3114 (defcustom org-edit-timestamp-down-means-later nil
3115 "Non-nil means S-down will increase the time in a time stamp.
3116 When nil, S-up will increase."
3117 :group 'org-time
3118 :type 'boolean)
3120 (defcustom org-calendar-follow-timestamp-change t
3121 "Non-nil means make the calendar window follow timestamp changes.
3122 When a timestamp is modified and the calendar window is visible, it will be
3123 moved to the new date."
3124 :group 'org-time
3125 :type 'boolean)
3127 (defgroup org-tags nil
3128 "Options concerning tags in Org-mode."
3129 :tag "Org Tags"
3130 :group 'org)
3132 (defcustom org-tag-alist nil
3133 "List of tags allowed in Org-mode files.
3134 When this list is nil, Org-mode will base TAG input on what is already in the
3135 buffer.
3136 The value of this variable is an alist, the car of each entry must be a
3137 keyword as a string, the cdr may be a character that is used to select
3138 that tag through the fast-tag-selection interface.
3139 See the manual for details."
3140 :group 'org-tags
3141 :type '(repeat
3142 (choice
3143 (cons (string :tag "Tag name")
3144 (character :tag "Access char"))
3145 (list :tag "Start radio group"
3146 (const :startgroup)
3147 (option (string :tag "Group description")))
3148 (list :tag "End radio group"
3149 (const :endgroup)
3150 (option (string :tag "Group description")))
3151 (const :tag "New line" (:newline)))))
3153 (defcustom org-tag-persistent-alist nil
3154 "List of tags that will always appear in all Org-mode files.
3155 This is in addition to any in buffer settings or customizations
3156 of `org-tag-alist'.
3157 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3158 The value of this variable is an alist, the car of each entry must be a
3159 keyword as a string, the cdr may be a character that is used to select
3160 that tag through the fast-tag-selection interface.
3161 See the manual for details.
3162 To disable these tags on a per-file basis, insert anywhere in the file:
3163 #+STARTUP: noptag"
3164 :group 'org-tags
3165 :type '(repeat
3166 (choice
3167 (cons (string :tag "Tag name")
3168 (character :tag "Access char"))
3169 (const :tag "Start radio group" (:startgroup))
3170 (const :tag "End radio group" (:endgroup))
3171 (const :tag "New line" (:newline)))))
3173 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3174 "If non-nil, always offer completion for all tags of all agenda files.
3175 Instead of customizing this variable directly, you might want to
3176 set it locally for capture buffers, because there no list of
3177 tags in that file can be created dynamically (there are none).
3179 (add-hook 'org-capture-mode-hook
3180 (lambda ()
3181 (set (make-local-variable
3182 'org-complete-tags-always-offer-all-agenda-tags)
3183 t)))"
3184 :group 'org-tags
3185 :version "24.1"
3186 :type 'boolean)
3188 (defvar org-file-tags nil
3189 "List of tags that can be inherited by all entries in the file.
3190 The tags will be inherited if the variable `org-use-tag-inheritance'
3191 says they should be.
3192 This variable is populated from #+FILETAGS lines.")
3194 (defcustom org-use-fast-tag-selection 'auto
3195 "Non-nil means use fast tag selection scheme.
3196 This is a special interface to select and deselect tags with single keys.
3197 When nil, fast selection is never used.
3198 When the symbol `auto', fast selection is used if and only if selection
3199 characters for tags have been configured, either through the variable
3200 `org-tag-alist' or through a #+TAGS line in the buffer.
3201 When t, fast selection is always used and selection keys are assigned
3202 automatically if necessary."
3203 :group 'org-tags
3204 :type '(choice
3205 (const :tag "Always" t)
3206 (const :tag "Never" nil)
3207 (const :tag "When selection characters are configured" 'auto)))
3209 (defcustom org-fast-tag-selection-single-key nil
3210 "Non-nil means fast tag selection exits after first change.
3211 When nil, you have to press RET to exit it.
3212 During fast tag selection, you can toggle this flag with `C-c'.
3213 This variable can also have the value `expert'. In this case, the window
3214 displaying the tags menu is not even shown, until you press C-c again."
3215 :group 'org-tags
3216 :type '(choice
3217 (const :tag "No" nil)
3218 (const :tag "Yes" t)
3219 (const :tag "Expert" expert)))
3221 (defvar org-fast-tag-selection-include-todo nil
3222 "Non-nil means fast tags selection interface will also offer TODO states.
3223 This is an undocumented feature, you should not rely on it.")
3225 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3226 "The column to which tags should be indented in a headline.
3227 If this number is positive, it specifies the column. If it is negative,
3228 it means that the tags should be flushright to that column. For example,
3229 -80 works well for a normal 80 character screen.
3230 When 0, place tags directly after headline text, with only one space in
3231 between."
3232 :group 'org-tags
3233 :type 'integer)
3235 (defcustom org-auto-align-tags t
3236 "Non-nil keeps tags aligned when modifying headlines.
3237 Some operations (i.e. demoting) change the length of a headline and
3238 therefore shift the tags around. With this option turned on, after
3239 each such operation the tags are again aligned to `org-tags-column'."
3240 :group 'org-tags
3241 :type 'boolean)
3243 (defcustom org-use-tag-inheritance t
3244 "Non-nil means tags in levels apply also for sublevels.
3245 When nil, only the tags directly given in a specific line apply there.
3246 This may also be a list of tags that should be inherited, or a regexp that
3247 matches tags that should be inherited. Additional control is possible
3248 with the variable `org-tags-exclude-from-inheritance' which gives an
3249 explicit list of tags to be excluded from inheritance, even if the value of
3250 `org-use-tag-inheritance' would select it for inheritance.
3252 If this option is t, a match early-on in a tree can lead to a large
3253 number of matches in the subtree when constructing the agenda or creating
3254 a sparse tree. If you only want to see the first match in a tree during
3255 a search, check out the variable `org-tags-match-list-sublevels'."
3256 :group 'org-tags
3257 :type '(choice
3258 (const :tag "Not" nil)
3259 (const :tag "Always" t)
3260 (repeat :tag "Specific tags" (string :tag "Tag"))
3261 (regexp :tag "Tags matched by regexp")))
3263 (defcustom org-tags-exclude-from-inheritance nil
3264 "List of tags that should never be inherited.
3265 This is a way to exclude a few tags from inheritance. For way to do
3266 the opposite, to actively allow inheritance for selected tags,
3267 see the variable `org-use-tag-inheritance'."
3268 :group 'org-tags
3269 :type '(repeat (string :tag "Tag")))
3271 (defun org-tag-inherit-p (tag)
3272 "Check if TAG is one that should be inherited."
3273 (cond
3274 ((member tag org-tags-exclude-from-inheritance) nil)
3275 ((eq org-use-tag-inheritance t) t)
3276 ((not org-use-tag-inheritance) nil)
3277 ((stringp org-use-tag-inheritance)
3278 (string-match org-use-tag-inheritance tag))
3279 ((listp org-use-tag-inheritance)
3280 (member tag org-use-tag-inheritance))
3281 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3283 (defcustom org-tags-match-list-sublevels t
3284 "Non-nil means list also sublevels of headlines matching a search.
3285 This variable applies to tags/property searches, and also to stuck
3286 projects because this search is based on a tags match as well.
3288 When set to the symbol `indented', sublevels are indented with
3289 leading dots.
3291 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3292 the sublevels of a headline matching a tag search often also match
3293 the same search. Listing all of them can create very long lists.
3294 Setting this variable to nil causes subtrees of a match to be skipped.
3296 This variable is semi-obsolete and probably should always be true. It
3297 is better to limit inheritance to certain tags using the variables
3298 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3299 :group 'org-tags
3300 :type '(choice
3301 (const :tag "No, don't list them" nil)
3302 (const :tag "Yes, do list them" t)
3303 (const :tag "List them, indented with leading dots" indented)))
3305 (defcustom org-tags-sort-function nil
3306 "When set, tags are sorted using this function as a comparator."
3307 :group 'org-tags
3308 :type '(choice
3309 (const :tag "No sorting" nil)
3310 (const :tag "Alphabetical" string<)
3311 (const :tag "Reverse alphabetical" string>)
3312 (function :tag "Custom function" nil)))
3314 (defvar org-tags-history nil
3315 "History of minibuffer reads for tags.")
3316 (defvar org-last-tags-completion-table nil
3317 "The last used completion table for tags.")
3318 (defvar org-after-tags-change-hook nil
3319 "Hook that is run after the tags in a line have changed.")
3321 (defgroup org-properties nil
3322 "Options concerning properties in Org-mode."
3323 :tag "Org Properties"
3324 :group 'org)
3326 (defcustom org-property-format "%-10s %s"
3327 "How property key/value pairs should be formatted by `indent-line'.
3328 When `indent-line' hits a property definition, it will format the line
3329 according to this format, mainly to make sure that the values are
3330 lined-up with respect to each other."
3331 :group 'org-properties
3332 :type 'string)
3334 (defcustom org-properties-postprocess-alist nil
3335 "Alist of properties and functions to adjust inserted values.
3336 Elements of this alist must be of the form
3338 ([string] [function])
3340 where [string] must be a property name and [function] must be a
3341 lambda expression: this lambda expression must take one argument,
3342 the value to adjust, and return the new value as a string.
3344 For example, this element will allow the property \"Remaining\"
3345 to be updated wrt the relation between the \"Effort\" property
3346 and the clock summary:
3348 ((\"Remaining\" (lambda(value)
3349 (let ((clocksum (org-clock-sum-current-item))
3350 (effort (org-duration-string-to-minutes
3351 (org-entry-get (point) \"Effort\"))))
3352 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3353 :group 'org-properties
3354 :version "24.1"
3355 :type '(alist :key-type (string :tag "Property")
3356 :value-type (function :tag "Function")))
3358 (defcustom org-use-property-inheritance nil
3359 "Non-nil means properties apply also for sublevels.
3361 This setting is chiefly used during property searches. Turning it on can
3362 cause significant overhead when doing a search, which is why it is not
3363 on by default.
3365 When nil, only the properties directly given in the current entry count.
3366 When t, every property is inherited. The value may also be a list of
3367 properties that should have inheritance, or a regular expression matching
3368 properties that should be inherited.
3370 However, note that some special properties use inheritance under special
3371 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3372 and the properties ending in \"_ALL\" when they are used as descriptor
3373 for valid values of a property.
3375 Note for programmers:
3376 When querying an entry with `org-entry-get', you can control if inheritance
3377 should be used. By default, `org-entry-get' looks only at the local
3378 properties. You can request inheritance by setting the inherit argument
3379 to t (to force inheritance) or to `selective' (to respect the setting
3380 in this variable)."
3381 :group 'org-properties
3382 :type '(choice
3383 (const :tag "Not" nil)
3384 (const :tag "Always" t)
3385 (repeat :tag "Specific properties" (string :tag "Property"))
3386 (regexp :tag "Properties matched by regexp")))
3388 (defun org-property-inherit-p (property)
3389 "Check if PROPERTY is one that should be inherited."
3390 (cond
3391 ((eq org-use-property-inheritance t) t)
3392 ((not org-use-property-inheritance) nil)
3393 ((stringp org-use-property-inheritance)
3394 (string-match org-use-property-inheritance property))
3395 ((listp org-use-property-inheritance)
3396 (member property org-use-property-inheritance))
3397 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3399 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3400 "The default column format, if no other format has been defined.
3401 This variable can be set on the per-file basis by inserting a line
3403 #+COLUMNS: %25ITEM ....."
3404 :group 'org-properties
3405 :type 'string)
3407 (defcustom org-columns-ellipses ".."
3408 "The ellipses to be used when a field in column view is truncated.
3409 When this is the empty string, as many characters as possible are shown,
3410 but then there will be no visual indication that the field has been truncated.
3411 When this is a string of length N, the last N characters of a truncated
3412 field are replaced by this string. If the column is narrower than the
3413 ellipses string, only part of the ellipses string will be shown."
3414 :group 'org-properties
3415 :type 'string)
3417 (defcustom org-columns-modify-value-for-display-function nil
3418 "Function that modifies values for display in column view.
3419 For example, it can be used to cut out a certain part from a time stamp.
3420 The function must take 2 arguments:
3422 column-title The title of the column (*not* the property name)
3423 value The value that should be modified.
3425 The function should return the value that should be displayed,
3426 or nil if the normal value should be used."
3427 :group 'org-properties
3428 :type 'function)
3430 (defcustom org-effort-property "Effort"
3431 "The property that is being used to keep track of effort estimates.
3432 Effort estimates given in this property need to have the format H:MM."
3433 :group 'org-properties
3434 :group 'org-progress
3435 :type '(string :tag "Property"))
3437 (defconst org-global-properties-fixed
3438 '(("VISIBILITY_ALL" . "folded children content all")
3439 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3440 "List of property/value pairs that can be inherited by any entry.
3442 These are fixed values, for the preset properties. The user variable
3443 that can be used to add to this list is `org-global-properties'.
3445 The entries in this list are cons cells where the car is a property
3446 name and cdr is a string with the value. If the value represents
3447 multiple items like an \"_ALL\" property, separate the items by
3448 spaces.")
3450 (defcustom org-global-properties nil
3451 "List of property/value pairs that can be inherited by any entry.
3453 This list will be combined with the constant `org-global-properties-fixed'.
3455 The entries in this list are cons cells where the car is a property
3456 name and cdr is a string with the value.
3458 You can set buffer-local values for the same purpose in the variable
3459 `org-file-properties' this by adding lines like
3461 #+PROPERTY: NAME VALUE"
3462 :group 'org-properties
3463 :type '(repeat
3464 (cons (string :tag "Property")
3465 (string :tag "Value"))))
3467 (defvar org-file-properties nil
3468 "List of property/value pairs that can be inherited by any entry.
3469 Valid for the current buffer.
3470 This variable is populated from #+PROPERTY lines.")
3471 (make-variable-buffer-local 'org-file-properties)
3473 (defgroup org-agenda nil
3474 "Options concerning agenda views in Org-mode."
3475 :tag "Org Agenda"
3476 :group 'org)
3478 (defvar org-category nil
3479 "Variable used by org files to set a category for agenda display.
3480 Such files should use a file variable to set it, for example
3482 # -*- mode: org; org-category: \"ELisp\"
3484 or contain a special line
3486 #+CATEGORY: ELisp
3488 If the file does not specify a category, then file's base name
3489 is used instead.")
3490 (make-variable-buffer-local 'org-category)
3491 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3493 (defcustom org-agenda-files nil
3494 "The files to be used for agenda display.
3495 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3496 \\[org-remove-file]. You can also use customize to edit the list.
3498 If an entry is a directory, all files in that directory that are matched by
3499 `org-agenda-file-regexp' will be part of the file list.
3501 If the value of the variable is not a list but a single file name, then
3502 the list of agenda files is actually stored and maintained in that file, one
3503 agenda file per line. In this file paths can be given relative to
3504 `org-directory'. Tilde expansion and environment variable substitution
3505 are also made."
3506 :group 'org-agenda
3507 :type '(choice
3508 (repeat :tag "List of files and directories" file)
3509 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3511 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3512 "Regular expression to match files for `org-agenda-files'.
3513 If any element in the list in that variable contains a directory instead
3514 of a normal file, all files in that directory that are matched by this
3515 regular expression will be included."
3516 :group 'org-agenda
3517 :type 'regexp)
3519 (defcustom org-agenda-text-search-extra-files nil
3520 "List of extra files to be searched by text search commands.
3521 These files will be search in addition to the agenda files by the
3522 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3523 Note that these files will only be searched for text search commands,
3524 not for the other agenda views like todo lists, tag searches or the weekly
3525 agenda. This variable is intended to list notes and possibly archive files
3526 that should also be searched by these two commands.
3527 In fact, if the first element in the list is the symbol `agenda-archives',
3528 than all archive files of all agenda files will be added to the search
3529 scope."
3530 :group 'org-agenda
3531 :type '(set :greedy t
3532 (const :tag "Agenda Archives" agenda-archives)
3533 (repeat :inline t (file))))
3535 (if (fboundp 'defvaralias)
3536 (defvaralias 'org-agenda-multi-occur-extra-files
3537 'org-agenda-text-search-extra-files))
3539 (defcustom org-agenda-skip-unavailable-files nil
3540 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3541 A nil value means to remove them, after a query, from the list."
3542 :group 'org-agenda
3543 :type 'boolean)
3545 (defcustom org-calendar-to-agenda-key [?c]
3546 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3547 The command `org-calendar-goto-agenda' will be bound to this key. The
3548 default is the character `c' because then `c' can be used to switch back and
3549 forth between agenda and calendar."
3550 :group 'org-agenda
3551 :type 'sexp)
3553 (defcustom org-calendar-insert-diary-entry-key [?i]
3554 "The key to be installed in `calendar-mode-map' for adding diary entries.
3555 This option is irrelevant until `org-agenda-diary-file' has been configured
3556 to point to an Org-mode file. When that is the case, the command
3557 `org-agenda-diary-entry' will be bound to the key given here, by default
3558 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3559 if you want to continue doing this, you need to change this to a different
3560 key."
3561 :group 'org-agenda
3562 :type 'sexp)
3564 (defcustom org-agenda-diary-file 'diary-file
3565 "File to which to add new entries with the `i' key in agenda and calendar.
3566 When this is the symbol `diary-file', the functionality in the Emacs
3567 calendar will be used to add entries to the `diary-file'. But when this
3568 points to a file, `org-agenda-diary-entry' will be used instead."
3569 :group 'org-agenda
3570 :type '(choice
3571 (const :tag "The standard Emacs diary file" diary-file)
3572 (file :tag "Special Org file diary entries")))
3574 (eval-after-load "calendar"
3575 '(progn
3576 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3577 'org-calendar-goto-agenda)
3578 (add-hook 'calendar-mode-hook
3579 (lambda ()
3580 (unless (eq org-agenda-diary-file 'diary-file)
3581 (define-key calendar-mode-map
3582 org-calendar-insert-diary-entry-key
3583 'org-agenda-diary-entry))))))
3585 (defgroup org-latex nil
3586 "Options for embedding LaTeX code into Org-mode."
3587 :tag "Org LaTeX"
3588 :group 'org)
3590 (defcustom org-format-latex-options
3591 '(:foreground default :background default :scale 1.0
3592 :html-foreground "Black" :html-background "Transparent"
3593 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3594 "Options for creating images from LaTeX fragments.
3595 This is a property list with the following properties:
3596 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3597 `default' means use the foreground of the default face.
3598 `auto' means use the foreground from the text face.
3599 :background the background color, or \"Transparent\".
3600 `default' means use the background of the default face.
3601 `auto' means use the background from the text face.
3602 :scale a scaling factor for the size of the images, to get more pixels
3603 :html-foreground, :html-background, :html-scale
3604 the same numbers for HTML export.
3605 :matchers a list indicating which matchers should be used to
3606 find LaTeX fragments. Valid members of this list are:
3607 \"begin\" find environments
3608 \"$1\" find single characters surrounded by $.$
3609 \"$\" find math expressions surrounded by $...$
3610 \"$$\" find math expressions surrounded by $$....$$
3611 \"\\(\" find math expressions surrounded by \\(...\\)
3612 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3613 :group 'org-latex
3614 :type 'plist)
3616 (defcustom org-format-latex-signal-error t
3617 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3618 When nil, just push out a message."
3619 :group 'org-latex
3620 :version "24.1"
3621 :type 'boolean)
3623 (defcustom org-latex-to-mathml-jar-file nil
3624 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3625 Use this to specify additional executable file say a jar file.
3627 When using MathToWeb as the converter, specify the full-path to
3628 your mathtoweb.jar file."
3629 :group 'org-latex
3630 :version "24.1"
3631 :type '(choice
3632 (const :tag "None" nil)
3633 (file :tag "JAR file" :must-match t)))
3635 (defcustom org-latex-to-mathml-convert-command nil
3636 "Command to convert LaTeX fragments to MathML.
3637 Replace format-specifiers in the command as noted below and use
3638 `shell-command' to convert LaTeX to MathML.
3639 %j: Executable file in fully expanded form as specified by
3640 `org-latex-to-mathml-jar-file'.
3641 %I: Input LaTeX file in fully expanded form
3642 %o: Output MathML file
3643 This command is used by `org-create-math-formula'.
3645 When using MathToWeb as the converter, set this to
3646 \"java -jar %j -unicode -force -df %o %I\"."
3647 :group 'org-latex
3648 :version "24.1"
3649 :type '(choice
3650 (const :tag "None" nil)
3651 (string :tag "\nShell command")))
3653 (defcustom org-latex-create-formula-image-program 'dvipng
3654 "Program to convert LaTeX fragments with.
3656 dvipng Process the LaTeX fragments to dvi file, then convert
3657 dvi files to png files using dvipng.
3658 This will also include processing of non-math environments.
3659 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3660 to convert pdf files to png files"
3661 :group 'org-latex
3662 :version "24.1"
3663 :type '(choice
3664 (const :tag "dvipng" dvipng)
3665 (const :tag "imagemagick" imagemagick)))
3667 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3668 "Path to store latex preview images.
3669 A relative path here creates many directories relative to the
3670 processed org files paths. An absolute path puts all preview
3671 images at the same place."
3672 :group 'org-latex
3673 :version "24.3"
3674 :type 'string)
3676 (defun org-format-latex-mathml-available-p ()
3677 "Return t if `org-latex-to-mathml-convert-command' is usable."
3678 (save-match-data
3679 (when (and (boundp 'org-latex-to-mathml-convert-command)
3680 org-latex-to-mathml-convert-command)
3681 (let ((executable (car (split-string
3682 org-latex-to-mathml-convert-command))))
3683 (when (executable-find executable)
3684 (if (string-match
3685 "%j" org-latex-to-mathml-convert-command)
3686 (file-readable-p org-latex-to-mathml-jar-file)
3687 t))))))
3689 (defcustom org-format-latex-header "\\documentclass{article}
3690 \\usepackage[usenames]{color}
3691 \\usepackage{amsmath}
3692 \\usepackage[mathscr]{eucal}
3693 \\pagestyle{empty} % do not remove
3694 \[PACKAGES]
3695 \[DEFAULT-PACKAGES]
3696 % The settings below are copied from fullpage.sty
3697 \\setlength{\\textwidth}{\\paperwidth}
3698 \\addtolength{\\textwidth}{-3cm}
3699 \\setlength{\\oddsidemargin}{1.5cm}
3700 \\addtolength{\\oddsidemargin}{-2.54cm}
3701 \\setlength{\\evensidemargin}{\\oddsidemargin}
3702 \\setlength{\\textheight}{\\paperheight}
3703 \\addtolength{\\textheight}{-\\headheight}
3704 \\addtolength{\\textheight}{-\\headsep}
3705 \\addtolength{\\textheight}{-\\footskip}
3706 \\addtolength{\\textheight}{-3cm}
3707 \\setlength{\\topmargin}{1.5cm}
3708 \\addtolength{\\topmargin}{-2.54cm}"
3709 "The document header used for processing LaTeX fragments.
3710 It is imperative that this header make sure that no page number
3711 appears on the page. The package defined in the variables
3712 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3713 will either replace the placeholder \"[PACKAGES]\" in this
3714 header, or they will be appended."
3715 :group 'org-latex
3716 :type 'string)
3718 (defun org-set-packages-alist (var val)
3719 "Set the packages alist and make sure it has 3 elements per entry."
3720 (set var (mapcar (lambda (x)
3721 (if (and (consp x) (= (length x) 2))
3722 (list (car x) (nth 1 x) t)
3724 val)))
3726 (defun org-get-packages-alist (var)
3727 "Get the packages alist and make sure it has 3 elements per entry."
3728 (mapcar (lambda (x)
3729 (if (and (consp x) (= (length x) 2))
3730 (list (car x) (nth 1 x) t)
3732 (default-value var)))
3734 (defcustom org-latex-default-packages-alist
3735 '(("AUTO" "inputenc" t)
3736 ("T1" "fontenc" t)
3737 ("" "fixltx2e" nil)
3738 ("" "graphicx" t)
3739 ("" "longtable" nil)
3740 ("" "float" nil)
3741 ("" "wrapfig" nil)
3742 ("" "soul" t)
3743 ("" "textcomp" t)
3744 ("" "marvosym" t)
3745 ("" "wasysym" t)
3746 ("" "latexsym" t)
3747 ("" "amssymb" t)
3748 ("" "hyperref" nil)
3749 "\\tolerance=1000")
3750 "Alist of default packages to be inserted in the header.
3752 Change this only if one of the packages here causes an
3753 incompatibility with another package you are using.
3755 The packages in this list are needed by one part or another of
3756 Org mode to function properly:
3758 - inputenc, fontenc: for basic font and character selection
3759 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3760 symbols used for interpreting the entities in `org-entities'.
3761 You can skip some of these packages if you don't use any of the
3762 symbols in it.
3763 - graphicx: for including images
3764 - float, wrapfig: for figure placement
3765 - longtable: for long tables
3766 - hyperref: for cross references
3768 Therefore you should not modify this variable unless you know
3769 what you are doing. The one reason to change it anyway is that
3770 you might be loading some other package that conflicts with one
3771 of the default packages. Each cell is of the format
3772 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3773 the package also needs to be included when compiling LaTeX
3774 snippets into images for inclusion into non-LaTeX output."
3775 :group 'org-latex
3776 :group 'org-export-latex
3777 :set 'org-set-packages-alist
3778 :get 'org-get-packages-alist
3779 :version "24.1"
3780 :type '(repeat
3781 (choice
3782 (list :tag "options/package pair"
3783 (string :tag "options")
3784 (string :tag "package")
3785 (boolean :tag "Snippet"))
3786 (string :tag "A line of LaTeX"))))
3788 (defcustom org-latex-packages-alist nil
3789 "Alist of packages to be inserted in every LaTeX header.
3791 These will be inserted after `org-latex-default-packages-alist'.
3792 Each cell is of the format:
3794 \(\"options\" \"package\" snippet-flag)
3796 SNIPPET-FLAG, when t, indicates that this package is also needed
3797 when turning LaTeX snippets into images for inclusion into
3798 non-LaTeX output.
3800 Make sure that you only list packages here which:
3802 - you want in every file
3803 - do not conflict with the setup in `org-format-latex-header'.
3804 - do not conflict with the default packages in
3805 `org-latex-default-packages-alist'."
3806 :group 'org-latex
3807 :group 'org-export-latex
3808 :set 'org-set-packages-alist
3809 :get 'org-get-packages-alist
3810 :type '(repeat
3811 (choice
3812 (list :tag "options/package pair"
3813 (string :tag "options")
3814 (string :tag "package")
3815 (boolean :tag "Snippet"))
3816 (string :tag "A line of LaTeX"))))
3818 (defgroup org-appearance nil
3819 "Settings for Org-mode appearance."
3820 :tag "Org Appearance"
3821 :group 'org)
3823 (defcustom org-level-color-stars-only nil
3824 "Non-nil means fontify only the stars in each headline.
3825 When nil, the entire headline is fontified.
3826 Changing it requires restart of `font-lock-mode' to become effective
3827 also in regions already fontified."
3828 :group 'org-appearance
3829 :type 'boolean)
3831 (defcustom org-hide-leading-stars nil
3832 "Non-nil means hide the first N-1 stars in a headline.
3833 This works by using the face `org-hide' for these stars. This
3834 face is white for a light background, and black for a dark
3835 background. You may have to customize the face `org-hide' to
3836 make this work.
3837 Changing it requires restart of `font-lock-mode' to become effective
3838 also in regions already fontified.
3839 You may also set this on a per-file basis by adding one of the following
3840 lines to the buffer:
3842 #+STARTUP: hidestars
3843 #+STARTUP: showstars"
3844 :group 'org-appearance
3845 :type 'boolean)
3847 (defcustom org-hidden-keywords nil
3848 "List of symbols corresponding to keywords to be hidden the org buffer.
3849 For example, a value '(title) for this list will make the document's title
3850 appear in the buffer without the initial #+TITLE: keyword."
3851 :group 'org-appearance
3852 :version "24.1"
3853 :type '(set (const :tag "#+AUTHOR" author)
3854 (const :tag "#+DATE" date)
3855 (const :tag "#+EMAIL" email)
3856 (const :tag "#+TITLE" title)))
3858 (defcustom org-custom-properties nil
3859 "List of properties (as strings) with a special meaning.
3860 The default use of these custom properties is to let the user
3861 hide them with `org-toggle-custom-properties-visibility'."
3862 :group 'org-properties
3863 :group 'org-appearance
3864 :version "24.3"
3865 :type '(repeat (string :tag "Property Name")))
3867 (defcustom org-fontify-done-headline nil
3868 "Non-nil means change the face of a headline if it is marked DONE.
3869 Normally, only the TODO/DONE keyword indicates the state of a headline.
3870 When this is non-nil, the headline after the keyword is set to the
3871 `org-headline-done' as an additional indication."
3872 :group 'org-appearance
3873 :type 'boolean)
3875 (defcustom org-fontify-emphasized-text t
3876 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3877 Changing this variable requires a restart of Emacs to take effect."
3878 :group 'org-appearance
3879 :type 'boolean)
3881 (defcustom org-fontify-whole-heading-line nil
3882 "Non-nil means fontify the whole line for headings.
3883 This is useful when setting a background color for the
3884 org-level-* faces."
3885 :group 'org-appearance
3886 :type 'boolean)
3888 (defcustom org-hide-emphasis-markers nil
3889 "Non-nil mean font-lock should hide the emphasis marker characters."
3890 :group 'org-appearance
3891 :type 'boolean)
3893 (defcustom org-pretty-entities nil
3894 "Non-nil means show entities as UTF8 characters.
3895 When nil, the \\name form remains in the buffer."
3896 :group 'org-appearance
3897 :version "24.1"
3898 :type 'boolean)
3900 (defcustom org-pretty-entities-include-sub-superscripts t
3901 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3902 :group 'org-appearance
3903 :version "24.1"
3904 :type 'boolean)
3906 (defvar org-emph-re nil
3907 "Regular expression for matching emphasis.
3908 After a match, the match groups contain these elements:
3909 0 The match of the full regular expression, including the characters
3910 before and after the proper match
3911 1 The character before the proper match, or empty at beginning of line
3912 2 The proper match, including the leading and trailing markers
3913 3 The leading marker like * or /, indicating the type of highlighting
3914 4 The text between the emphasis markers, not including the markers
3915 5 The character after the match, empty at the end of a line")
3916 (defvar org-verbatim-re nil
3917 "Regular expression for matching verbatim text.")
3918 (defvar org-emphasis-regexp-components) ; defined just below
3919 (defvar org-emphasis-alist) ; defined just below
3920 (defun org-set-emph-re (var val)
3921 "Set variable and compute the emphasis regular expression."
3922 (set var val)
3923 (when (and (boundp 'org-emphasis-alist)
3924 (boundp 'org-emphasis-regexp-components)
3925 org-emphasis-alist org-emphasis-regexp-components)
3926 (let* ((e org-emphasis-regexp-components)
3927 (pre (car e))
3928 (post (nth 1 e))
3929 (border (nth 2 e))
3930 (body (nth 3 e))
3931 (nl (nth 4 e))
3932 (body1 (concat body "*?"))
3933 (markers (mapconcat 'car org-emphasis-alist ""))
3934 (vmarkers (mapconcat
3935 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3936 org-emphasis-alist "")))
3937 ;; make sure special characters appear at the right position in the class
3938 (if (string-match "\\^" markers)
3939 (setq markers (concat (replace-match "" t t markers) "^")))
3940 (if (string-match "-" markers)
3941 (setq markers (concat (replace-match "" t t markers) "-")))
3942 (if (string-match "\\^" vmarkers)
3943 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3944 (if (string-match "-" vmarkers)
3945 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3946 (if (> nl 0)
3947 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3948 (int-to-string nl) "\\}")))
3949 ;; Make the regexp
3950 (setq org-emph-re
3951 (concat "\\([" pre "]\\|^\\)"
3952 "\\("
3953 "\\([" markers "]\\)"
3954 "\\("
3955 "[^" border "]\\|"
3956 "[^" border "]"
3957 body1
3958 "[^" border "]"
3959 "\\)"
3960 "\\3\\)"
3961 "\\([" post "]\\|$\\)"))
3962 (setq org-verbatim-re
3963 (concat "\\([" pre "]\\|^\\)"
3964 "\\("
3965 "\\([" vmarkers "]\\)"
3966 "\\("
3967 "[^" border "]\\|"
3968 "[^" border "]"
3969 body1
3970 "[^" border "]"
3971 "\\)"
3972 "\\3\\)"
3973 "\\([" post "]\\|$\\)")))))
3975 (defcustom org-emphasis-regexp-components
3976 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3977 "Components used to build the regular expression for emphasis.
3978 This is a list with five entries. Terminology: In an emphasis string
3979 like \" *strong word* \", we call the initial space PREMATCH, the final
3980 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3981 and \"trong wor\" is the body. The different components in this variable
3982 specify what is allowed/forbidden in each part:
3984 pre Chars allowed as prematch. Beginning of line will be allowed too.
3985 post Chars allowed as postmatch. End of line will be allowed too.
3986 border The chars *forbidden* as border characters.
3987 body-regexp A regexp like \".\" to match a body character. Don't use
3988 non-shy groups here, and don't allow newline here.
3989 newline The maximum number of newlines allowed in an emphasis exp.
3991 Use customize to modify this, or restart Emacs after changing it."
3992 :group 'org-appearance
3993 :set 'org-set-emph-re
3994 :type '(list
3995 (sexp :tag "Allowed chars in pre ")
3996 (sexp :tag "Allowed chars in post ")
3997 (sexp :tag "Forbidden chars in border ")
3998 (sexp :tag "Regexp for body ")
3999 (integer :tag "number of newlines allowed")
4000 (option (boolean :tag "Please ignore this button"))))
4002 (defcustom org-emphasis-alist
4003 `(("*" bold "<b>" "</b>")
4004 ("/" italic "<i>" "</i>")
4005 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4006 ("=" org-code "<code>" "</code>" verbatim)
4007 ("~" org-verbatim "<code>" "</code>" verbatim)
4008 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4009 "<del>" "</del>")
4011 "Special syntax for emphasized text.
4012 Text starting and ending with a special character will be emphasized, for
4013 example *bold*, _underlined_ and /italic/. This variable sets the marker
4014 characters, the face to be used by font-lock for highlighting in Org-mode
4015 Emacs buffers, and the HTML tags to be used for this.
4016 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4017 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
4018 Use customize to modify this, or restart Emacs after changing it."
4019 :group 'org-appearance
4020 :set 'org-set-emph-re
4021 :type '(repeat
4022 (list
4023 (string :tag "Marker character")
4024 (choice
4025 (face :tag "Font-lock-face")
4026 (plist :tag "Face property list"))
4027 (string :tag "HTML start tag")
4028 (string :tag "HTML end tag")
4029 (option (const verbatim)))))
4031 (defvar org-syntax-table
4032 (let ((st (make-syntax-table)))
4033 (mapc (lambda(c) (modify-syntax-entry
4034 (string-to-char (car c)) "w p" st))
4035 org-emphasis-alist)
4036 st))
4038 (defvar org-protecting-blocks
4039 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
4040 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4041 This is needed for font-lock setup.")
4043 ;;; Miscellaneous options
4045 (defgroup org-completion nil
4046 "Completion in Org-mode."
4047 :tag "Org Completion"
4048 :group 'org)
4050 (defcustom org-completion-use-ido nil
4051 "Non-nil means use ido completion wherever possible.
4052 Note that `ido-mode' must be active for this variable to be relevant.
4053 If you decide to turn this variable on, you might well want to turn off
4054 `org-outline-path-complete-in-steps'.
4055 See also `org-completion-use-iswitchb'."
4056 :group 'org-completion
4057 :type 'boolean)
4059 (defcustom org-completion-use-iswitchb nil
4060 "Non-nil means use iswitchb completion wherever possible.
4061 Note that `iswitchb-mode' must be active for this variable to be relevant.
4062 If you decide to turn this variable on, you might well want to turn off
4063 `org-outline-path-complete-in-steps'.
4064 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4065 :group 'org-completion
4066 :type 'boolean)
4068 (defcustom org-completion-fallback-command 'hippie-expand
4069 "The expansion command called by \\[pcomplete] in normal context.
4070 Normal means, no org-mode-specific context."
4071 :group 'org-completion
4072 :type 'function)
4074 ;;; Functions and variables from their packages
4075 ;; Declared here to avoid compiler warnings
4077 ;; XEmacs only
4078 (defvar outline-mode-menu-heading)
4079 (defvar outline-mode-menu-show)
4080 (defvar outline-mode-menu-hide)
4081 (defvar zmacs-regions) ; XEmacs regions
4083 ;; Emacs only
4084 (defvar mark-active)
4086 ;; Various packages
4087 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4088 (declare-function calendar-forward-day "cal-move" (arg))
4089 (declare-function calendar-goto-date "cal-move" (date))
4090 (declare-function calendar-goto-today "cal-move" ())
4091 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4092 (defvar calc-embedded-close-formula)
4093 (defvar calc-embedded-open-formula)
4094 (declare-function cdlatex-tab "ext:cdlatex" ())
4095 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4096 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4097 (defvar font-lock-unfontify-region-function)
4098 (declare-function iswitchb-read-buffer "iswitchb"
4099 (prompt &optional default require-match start matches-set))
4100 (defvar iswitchb-temp-buflist)
4101 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4102 (defvar org-agenda-tags-todo-honor-ignore-options)
4103 (declare-function org-agenda-skip "org-agenda" ())
4104 (declare-function
4105 org-agenda-format-item "org-agenda"
4106 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4107 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4108 (declare-function org-agenda-change-all-lines "org-agenda"
4109 (newhead hdmarker &optional fixface just-this))
4110 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4111 (declare-function org-agenda-maybe-redo "org-agenda" ())
4112 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4113 (beg end))
4114 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4115 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4116 "org-agenda" (&optional end))
4117 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4118 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4119 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4120 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4121 (declare-function org-indent-mode "org-indent" (&optional arg))
4122 (declare-function parse-time-string "parse-time" (string))
4123 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4124 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4125 (defvar remember-data-file)
4126 (defvar texmathp-why)
4127 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4128 (declare-function table--at-cell-p "table" (position &optional object at-column))
4130 (defvar org-latex-regexps)
4132 ;;; Autoload and prepare some org modules
4134 ;; Some table stuff that needs to be defined here, because it is used
4135 ;; by the functions setting up org-mode or checking for table context.
4137 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4138 "Detect an org-type or table-type table.")
4139 (defconst org-table-line-regexp "^[ \t]*|"
4140 "Detect an org-type table line.")
4141 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4142 "Detect an org-type table line.")
4143 (defconst org-table-hline-regexp "^[ \t]*|-"
4144 "Detect an org-type table hline.")
4145 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4146 "Detect a table-type table hline.")
4147 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4148 "Detect the first line outside a table when searching from within it.
4149 This works for both table types.")
4151 ;; Autoload the functions in org-table.el that are needed by functions here.
4153 (eval-and-compile
4154 (org-autoload "org-table"
4155 '(org-table-begin org-table-blank-field org-table-end)))
4157 ;;;###autoload
4158 (defun turn-on-orgtbl ()
4159 "Unconditionally turn on `orgtbl-mode'."
4160 (require 'org-table)
4161 (orgtbl-mode 1))
4163 (defun org-at-table-p (&optional table-type)
4164 "Return t if the cursor is inside an org-type table.
4165 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4166 (if org-enable-table-editor
4167 (save-excursion
4168 (beginning-of-line 1)
4169 (looking-at (if table-type org-table-any-line-regexp
4170 org-table-line-regexp)))
4171 nil))
4172 (defsubst org-table-p () (org-at-table-p))
4174 (defun org-at-table.el-p ()
4175 "Return t if and only if we are at a table.el table."
4176 (and (org-at-table-p 'any)
4177 (save-excursion
4178 (goto-char (org-table-begin 'any))
4179 (looking-at org-table1-hline-regexp))))
4180 (defun org-table-recognize-table.el ()
4181 "If there is a table.el table nearby, recognize it and move into it."
4182 (if org-table-tab-recognizes-table.el
4183 (if (org-at-table.el-p)
4184 (progn
4185 (beginning-of-line 1)
4186 (if (looking-at org-table-dataline-regexp)
4188 (if (looking-at org-table1-hline-regexp)
4189 (progn
4190 (beginning-of-line 2)
4191 (if (looking-at org-table-any-border-regexp)
4192 (beginning-of-line -1)))))
4193 (if (re-search-forward "|" (org-table-end t) t)
4194 (progn
4195 (require 'table)
4196 (if (table--at-cell-p (point))
4198 (message "recognizing table.el table...")
4199 (table-recognize-table)
4200 (message "recognizing table.el table...done")))
4201 (error "This should not happen"))
4203 nil)
4204 nil))
4206 (defun org-at-table-hline-p ()
4207 "Return t if the cursor is inside a hline in a table."
4208 (if org-enable-table-editor
4209 (save-excursion
4210 (beginning-of-line 1)
4211 (looking-at org-table-hline-regexp))
4212 nil))
4214 (defvar org-table-clean-did-remove-column nil)
4216 (defun org-table-map-tables (function &optional quietly)
4217 "Apply FUNCTION to the start of all tables in the buffer."
4218 (save-excursion
4219 (save-restriction
4220 (widen)
4221 (goto-char (point-min))
4222 (while (re-search-forward org-table-any-line-regexp nil t)
4223 (unless quietly
4224 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4225 (beginning-of-line 1)
4226 (when (and (looking-at org-table-line-regexp)
4227 ;; Exclude tables in src/example/verbatim/clocktable blocks
4228 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4229 (save-excursion (funcall function))
4230 (or (looking-at org-table-line-regexp)
4231 (forward-char 1)))
4232 (re-search-forward org-table-any-border-regexp nil 1))))
4233 (unless quietly (message "Mapping tables: done")))
4235 ;; Declare and autoload functions from ox.el and al.
4237 (declare-function org-export-get-environment "ox"
4238 (&optional backend subtreep ext-plist))
4239 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4241 ;; Declare and autoload functions from org-agenda.el
4243 (eval-and-compile
4244 (org-autoload "org-agenda"
4245 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4247 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4248 (declare-function org-clock-update-mode-line "org-clock" ())
4249 (declare-function org-resolve-clocks "org-clock"
4250 (&optional also-non-dangling-p prompt last-valid))
4251 (defvar org-clock-start-time)
4252 (defvar org-clock-marker (make-marker)
4253 "Marker recording the last clock-in.")
4254 (defvar org-clock-hd-marker (make-marker)
4255 "Marker recording the last clock-in, but the headline position.")
4256 (defvar org-clock-heading ""
4257 "The heading of the current clock entry.")
4258 (defun org-clock-is-active ()
4259 "Return non-nil if clock is currently running.
4260 The return value is actually the clock marker."
4261 (marker-buffer org-clock-marker))
4263 (eval-and-compile
4264 (org-autoload "org-clock" '(org-clock-remove-overlays
4265 org-clock-update-time-maybe
4266 org-clocktable-shift)))
4268 (defun org-check-running-clock ()
4269 "Check if the current buffer contains the running clock.
4270 If yes, offer to stop it and to save the buffer with the changes."
4271 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4272 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4273 (buffer-name))))
4274 (org-clock-out)
4275 (when (y-or-n-p "Save changed buffer?")
4276 (save-buffer))))
4278 (defun org-clocktable-try-shift (dir n)
4279 "Check if this line starts a clock table, if yes, shift the time block."
4280 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4281 (org-clocktable-shift dir n)))
4283 ;;;###autoload
4284 (defun org-clock-persistence-insinuate ()
4285 "Set up hooks for clock persistence."
4286 (require 'org-clock)
4287 (add-hook 'org-mode-hook 'org-clock-load)
4288 (add-hook 'kill-emacs-hook 'org-clock-save))
4290 ;; Define the variable already here, to make sure we have it.
4291 (defvar org-indent-mode nil
4292 "Non-nil if Org-Indent mode is enabled.
4293 Use the command `org-indent-mode' to change this variable.")
4295 ;; Autoload archiving code
4296 ;; The stuff that is needed for cycling and tags has to be defined here.
4298 (defgroup org-archive nil
4299 "Options concerning archiving in Org-mode."
4300 :tag "Org Archive"
4301 :group 'org-structure)
4303 (defcustom org-archive-location "%s_archive::"
4304 "The location where subtrees should be archived.
4306 The value of this variable is a string, consisting of two parts,
4307 separated by a double-colon. The first part is a filename and
4308 the second part is a headline.
4310 When the filename is omitted, archiving happens in the same file.
4311 %s in the filename will be replaced by the current file
4312 name (without the directory part). Archiving to a different file
4313 is useful to keep archived entries from contributing to the
4314 Org-mode Agenda.
4316 The archived entries will be filed as subtrees of the specified
4317 headline. When the headline is omitted, the subtrees are simply
4318 filed away at the end of the file, as top-level entries. Also in
4319 the heading you can use %s to represent the file name, this can be
4320 useful when using the same archive for a number of different files.
4322 Here are a few examples:
4323 \"%s_archive::\"
4324 If the current file is Projects.org, archive in file
4325 Projects.org_archive, as top-level trees. This is the default.
4327 \"::* Archived Tasks\"
4328 Archive in the current file, under the top-level headline
4329 \"* Archived Tasks\".
4331 \"~/org/archive.org::\"
4332 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4334 \"~/org/archive.org::* From %s\"
4335 Archive in file ~/org/archive.org (absolute path), under headlines
4336 \"From FILENAME\" where file name is the current file name.
4338 \"~/org/datetree.org::datetree/* Finished Tasks\"
4339 The \"datetree/\" string is special, signifying to archive
4340 items to the datetree. Items are placed in either the CLOSED
4341 date of the item, or the current date if there is no CLOSED date.
4342 The heading will be a subentry to the current date. There doesn't
4343 need to be a heading, but there always needs to be a slash after
4344 datetree. For example, to store archived items directly in the
4345 datetree, use \"~/org/datetree.org::datetree/\".
4347 \"basement::** Finished Tasks\"
4348 Archive in file ./basement (relative path), as level 3 trees
4349 below the level 2 heading \"** Finished Tasks\".
4351 You may set this option on a per-file basis by adding to the buffer a
4352 line like
4354 #+ARCHIVE: basement::** Finished Tasks
4356 You may also define it locally for a subtree by setting an ARCHIVE property
4357 in the entry. If such a property is found in an entry, or anywhere up
4358 the hierarchy, it will be used."
4359 :group 'org-archive
4360 :type 'string)
4362 (defcustom org-archive-tag "ARCHIVE"
4363 "The tag that marks a subtree as archived.
4364 An archived subtree does not open during visibility cycling, and does
4365 not contribute to the agenda listings.
4366 After changing this, font-lock must be restarted in the relevant buffers to
4367 get the proper fontification."
4368 :group 'org-archive
4369 :group 'org-keywords
4370 :type 'string)
4372 (defcustom org-agenda-skip-archived-trees t
4373 "Non-nil means the agenda will skip any items located in archived trees.
4374 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4375 variable is no longer recommended, you should leave it at the value t.
4376 Instead, use the key `v' to cycle the archives-mode in the agenda."
4377 :group 'org-archive
4378 :group 'org-agenda-skip
4379 :type 'boolean)
4381 (defcustom org-columns-skip-archived-trees t
4382 "Non-nil means ignore archived trees when creating column view."
4383 :group 'org-archive
4384 :group 'org-properties
4385 :type 'boolean)
4387 (defcustom org-cycle-open-archived-trees nil
4388 "Non-nil means `org-cycle' will open archived trees.
4389 An archived tree is a tree marked with the tag ARCHIVE.
4390 When nil, archived trees will stay folded. You can still open them with
4391 normal outline commands like `show-all', but not with the cycling commands."
4392 :group 'org-archive
4393 :group 'org-cycle
4394 :type 'boolean)
4396 (defcustom org-sparse-tree-open-archived-trees nil
4397 "Non-nil means sparse tree construction shows matches in archived trees.
4398 When nil, matches in these trees are highlighted, but the trees are kept in
4399 collapsed state."
4400 :group 'org-archive
4401 :group 'org-sparse-trees
4402 :type 'boolean)
4404 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4405 "The default date type when building a sparse tree.
4406 When this is nil, a date is a scheduled or a deadline timestamp.
4407 Otherwise, these types are allowed:
4409 all: all timestamps
4410 active: only active timestamps (<...>)
4411 inactive: only inactive timestamps (<...)
4412 scheduled: only scheduled timestamps
4413 deadline: only deadline timestamps"
4414 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4415 (const :tag "All timestamps" all)
4416 (const :tag "Only active timestamps" active)
4417 (const :tag "Only inactive timestamps" inactive)
4418 (const :tag "Only scheduled timestamps" scheduled)
4419 (const :tag "Only deadline timestamps" deadline))
4420 :version "24.3"
4421 :group 'org-sparse-trees)
4423 (defun org-cycle-hide-archived-subtrees (state)
4424 "Re-hide all archived subtrees after a visibility state change."
4425 (when (and (not org-cycle-open-archived-trees)
4426 (not (memq state '(overview folded))))
4427 (save-excursion
4428 (let* ((globalp (memq state '(contents all)))
4429 (beg (if globalp (point-min) (point)))
4430 (end (if globalp (point-max) (org-end-of-subtree t))))
4431 (org-hide-archived-subtrees beg end)
4432 (goto-char beg)
4433 (if (looking-at (concat ".*:" org-archive-tag ":"))
4434 (message "%s" (substitute-command-keys
4435 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4437 (defun org-force-cycle-archived ()
4438 "Cycle subtree even if it is archived."
4439 (interactive)
4440 (setq this-command 'org-cycle)
4441 (let ((org-cycle-open-archived-trees t))
4442 (call-interactively 'org-cycle)))
4444 (defun org-hide-archived-subtrees (beg end)
4445 "Re-hide all archived subtrees after a visibility state change."
4446 (save-excursion
4447 (let* ((re (concat ":" org-archive-tag ":")))
4448 (goto-char beg)
4449 (while (re-search-forward re end t)
4450 (when (org-at-heading-p)
4451 (org-flag-subtree t)
4452 (org-end-of-subtree t))))))
4454 (declare-function outline-end-of-heading "outline" ())
4455 (declare-function outline-flag-region "outline" (from to flag))
4456 (defun org-flag-subtree (flag)
4457 (save-excursion
4458 (org-back-to-heading t)
4459 (outline-end-of-heading)
4460 (outline-flag-region (point)
4461 (progn (org-end-of-subtree t) (point))
4462 flag)))
4464 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4466 (eval-and-compile
4467 (org-autoload "org-archive"
4468 '(org-add-archive-files)))
4470 ;; Autoload Column View Code
4472 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4473 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4474 (declare-function org-columns-compute "org-colview" (property))
4476 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4477 '(org-columns-number-to-string
4478 org-columns-get-format-and-top-level
4479 org-columns-compute
4480 org-columns-remove-overlays))
4482 ;; Autoload ID code
4484 (declare-function org-id-store-link "org-id")
4485 (declare-function org-id-locations-load "org-id")
4486 (declare-function org-id-locations-save "org-id")
4487 (defvar org-id-track-globally)
4488 (org-autoload "org-id"
4489 '(org-id-new
4490 org-id-copy
4491 org-id-get-with-outline-path-completion
4492 org-id-get-with-outline-drilling))
4494 ;;; Variables for pre-computed regular expressions, all buffer local
4496 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4497 "Matches first line of a hidden block.")
4498 (make-variable-buffer-local 'org-drawer-regexp)
4499 (defvar org-todo-regexp nil
4500 "Matches any of the TODO state keywords.")
4501 (make-variable-buffer-local 'org-todo-regexp)
4502 (defvar org-not-done-regexp nil
4503 "Matches any of the TODO state keywords except the last one.")
4504 (make-variable-buffer-local 'org-not-done-regexp)
4505 (defvar org-not-done-heading-regexp nil
4506 "Matches a TODO headline that is not done.")
4507 (make-variable-buffer-local 'org-not-done-regexp)
4508 (defvar org-todo-line-regexp nil
4509 "Matches a headline and puts TODO state into group 2 if present.")
4510 (make-variable-buffer-local 'org-todo-line-regexp)
4511 (defvar org-complex-heading-regexp nil
4512 "Matches a headline and puts everything into groups:
4513 group 1: the stars
4514 group 2: The todo keyword, maybe
4515 group 3: Priority cookie
4516 group 4: True headline
4517 group 5: Tags")
4518 (make-variable-buffer-local 'org-complex-heading-regexp)
4519 (defvar org-complex-heading-regexp-format nil
4520 "Printf format to make regexp to match an exact headline.
4521 This regexp will match the headline of any node which has the
4522 exact headline text that is put into the format, but may have any
4523 TODO state, priority and tags.")
4524 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4525 (defvar org-todo-line-tags-regexp nil
4526 "Matches a headline and puts TODO state into group 2 if present.
4527 Also put tags into group 4 if tags are present.")
4528 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4529 (defvar org-ds-keyword-length 12
4530 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4531 (make-variable-buffer-local 'org-ds-keyword-length)
4532 (defvar org-deadline-regexp nil
4533 "Matches the DEADLINE keyword.")
4534 (make-variable-buffer-local 'org-deadline-regexp)
4535 (defvar org-deadline-time-regexp nil
4536 "Matches the DEADLINE keyword together with a time stamp.")
4537 (make-variable-buffer-local 'org-deadline-time-regexp)
4538 (defvar org-deadline-line-regexp nil
4539 "Matches the DEADLINE keyword and the rest of the line.")
4540 (make-variable-buffer-local 'org-deadline-line-regexp)
4541 (defvar org-scheduled-regexp nil
4542 "Matches the SCHEDULED keyword.")
4543 (make-variable-buffer-local 'org-scheduled-regexp)
4544 (defvar org-scheduled-time-regexp nil
4545 "Matches the SCHEDULED keyword together with a time stamp.")
4546 (make-variable-buffer-local 'org-scheduled-time-regexp)
4547 (defvar org-closed-time-regexp nil
4548 "Matches the CLOSED keyword together with a time stamp.")
4549 (make-variable-buffer-local 'org-closed-time-regexp)
4551 (defvar org-keyword-time-regexp nil
4552 "Matches any of the 4 keywords, together with the time stamp.")
4553 (make-variable-buffer-local 'org-keyword-time-regexp)
4554 (defvar org-keyword-time-not-clock-regexp nil
4555 "Matches any of the 3 keywords, together with the time stamp.")
4556 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4557 (defvar org-maybe-keyword-time-regexp nil
4558 "Matches a timestamp, possibly preceded by a keyword.")
4559 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4560 (defvar org-all-time-keywords nil
4561 "List of time keywords.")
4562 (make-variable-buffer-local 'org-all-time-keywords)
4564 (defconst org-plain-time-of-day-regexp
4565 (concat
4566 "\\(\\<[012]?[0-9]"
4567 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4568 "\\(--?"
4569 "\\(\\<[012]?[0-9]"
4570 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4571 "\\)?")
4572 "Regular expression to match a plain time or time range.
4573 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4574 groups carry important information:
4575 0 the full match
4576 1 the first time, range or not
4577 8 the second time, if it is a range.")
4579 (defconst org-plain-time-extension-regexp
4580 (concat
4581 "\\(\\<[012]?[0-9]"
4582 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4583 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4584 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4585 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4586 groups carry important information:
4587 0 the full match
4588 7 hours of duration
4589 9 minutes of duration")
4591 (defconst org-stamp-time-of-day-regexp
4592 (concat
4593 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4594 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4595 "\\(--?"
4596 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4597 "Regular expression to match a timestamp time or time range.
4598 After a match, the following groups carry important information:
4599 0 the full match
4600 1 date plus weekday, for back referencing to make sure both times are on the same day
4601 2 the first time, range or not
4602 4 the second time, if it is a range.")
4604 (defconst org-startup-options
4605 '(("fold" org-startup-folded t)
4606 ("overview" org-startup-folded t)
4607 ("nofold" org-startup-folded nil)
4608 ("showall" org-startup-folded nil)
4609 ("showeverything" org-startup-folded showeverything)
4610 ("content" org-startup-folded content)
4611 ("indent" org-startup-indented t)
4612 ("noindent" org-startup-indented nil)
4613 ("hidestars" org-hide-leading-stars t)
4614 ("showstars" org-hide-leading-stars nil)
4615 ("odd" org-odd-levels-only t)
4616 ("oddeven" org-odd-levels-only nil)
4617 ("align" org-startup-align-all-tables t)
4618 ("noalign" org-startup-align-all-tables nil)
4619 ("inlineimages" org-startup-with-inline-images t)
4620 ("noinlineimages" org-startup-with-inline-images nil)
4621 ("customtime" org-display-custom-times t)
4622 ("logdone" org-log-done time)
4623 ("lognotedone" org-log-done note)
4624 ("nologdone" org-log-done nil)
4625 ("lognoteclock-out" org-log-note-clock-out t)
4626 ("nolognoteclock-out" org-log-note-clock-out nil)
4627 ("logrepeat" org-log-repeat state)
4628 ("lognoterepeat" org-log-repeat note)
4629 ("logdrawer" org-log-into-drawer t)
4630 ("nologdrawer" org-log-into-drawer nil)
4631 ("logstatesreversed" org-log-states-order-reversed t)
4632 ("nologstatesreversed" org-log-states-order-reversed nil)
4633 ("nologrepeat" org-log-repeat nil)
4634 ("logreschedule" org-log-reschedule time)
4635 ("lognotereschedule" org-log-reschedule note)
4636 ("nologreschedule" org-log-reschedule nil)
4637 ("logredeadline" org-log-redeadline time)
4638 ("lognoteredeadline" org-log-redeadline note)
4639 ("nologredeadline" org-log-redeadline nil)
4640 ("logrefile" org-log-refile time)
4641 ("lognoterefile" org-log-refile note)
4642 ("nologrefile" org-log-refile nil)
4643 ("fninline" org-footnote-define-inline t)
4644 ("nofninline" org-footnote-define-inline nil)
4645 ("fnlocal" org-footnote-section nil)
4646 ("fnauto" org-footnote-auto-label t)
4647 ("fnprompt" org-footnote-auto-label nil)
4648 ("fnconfirm" org-footnote-auto-label confirm)
4649 ("fnplain" org-footnote-auto-label plain)
4650 ("fnadjust" org-footnote-auto-adjust t)
4651 ("nofnadjust" org-footnote-auto-adjust nil)
4652 ("constcgs" constants-unit-system cgs)
4653 ("constSI" constants-unit-system SI)
4654 ("noptag" org-tag-persistent-alist nil)
4655 ("hideblocks" org-hide-block-startup t)
4656 ("nohideblocks" org-hide-block-startup nil)
4657 ("beamer" org-startup-with-beamer-mode t)
4658 ("entitiespretty" org-pretty-entities t)
4659 ("entitiesplain" org-pretty-entities nil))
4660 "Variable associated with STARTUP options for org-mode.
4661 Each element is a list of three items: the startup options (as written
4662 in the #+STARTUP line), the corresponding variable, and the value to set
4663 this variable to if the option is found. An optional forth element PUSH
4664 means to push this value onto the list in the variable.")
4666 (defun org-update-property-plist (key val props)
4667 "Update PROPS with KEY and VAL."
4668 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4669 (key (if appending (substring key 0 (- (length key) 1)) key))
4670 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4671 (previous (cdr (assoc key props))))
4672 (if appending
4673 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4674 (cons (cons key val) remainder))))
4676 (defconst org-block-regexp
4677 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4678 "Regular expression for hiding blocks.")
4679 (defconst org-heading-keyword-regexp-format
4680 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4681 "Printf format for a regexp matching an headline with some keyword.
4682 This regexp will match the headline of any node which has the
4683 exact keyword that is put into the format. The keyword isn't in
4684 any group by default, but the stars and the body are.")
4685 (defconst org-heading-keyword-maybe-regexp-format
4686 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4687 "Printf format for a regexp matching an headline, possibly with some keyword.
4688 This regexp can match any headline with the specified keyword, or
4689 without a keyword. The keyword isn't in any group by default,
4690 but the stars and the body are.")
4692 (defun org-set-regexps-and-options ()
4693 "Precompute regular expressions for current buffer."
4694 (when (derived-mode-p 'org-mode)
4695 (org-set-local 'org-todo-kwd-alist nil)
4696 (org-set-local 'org-todo-key-alist nil)
4697 (org-set-local 'org-todo-key-trigger nil)
4698 (org-set-local 'org-todo-keywords-1 nil)
4699 (org-set-local 'org-done-keywords nil)
4700 (org-set-local 'org-todo-heads nil)
4701 (org-set-local 'org-todo-sets nil)
4702 (org-set-local 'org-todo-log-states nil)
4703 (org-set-local 'org-file-properties nil)
4704 (org-set-local 'org-file-tags nil)
4705 (let ((re (org-make-options-regexp
4706 '("CATEGORY" "TODO" "COLUMNS"
4707 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4708 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4709 "OPTIONS")
4710 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4711 (splitre "[ \t]+")
4712 (scripts org-use-sub-superscripts)
4713 kwds kws0 kwsa key log value cat arch tags const links hw dws
4714 tail sep kws1 prio props ftags drawers beamer-p
4715 ext-setup-or-nil setup-contents (start 0))
4716 (save-excursion
4717 (save-restriction
4718 (widen)
4719 (goto-char (point-min))
4720 (while (or (and ext-setup-or-nil
4721 (string-match re ext-setup-or-nil start)
4722 (setq start (match-end 0)))
4723 (and (setq ext-setup-or-nil nil start 0)
4724 (re-search-forward re nil t)))
4725 (setq key (upcase (match-string 1 ext-setup-or-nil))
4726 value (org-match-string-no-properties 2 ext-setup-or-nil))
4727 (if (stringp value) (setq value (org-trim value)))
4728 (cond
4729 ((equal key "CATEGORY")
4730 (setq cat value))
4731 ((member key '("SEQ_TODO" "TODO"))
4732 (push (cons 'sequence (org-split-string value splitre)) kwds))
4733 ((equal key "TYP_TODO")
4734 (push (cons 'type (org-split-string value splitre)) kwds))
4735 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4736 ;; general TODO-like setup
4737 (push (cons (intern (downcase (match-string 1 key)))
4738 (org-split-string value splitre)) kwds))
4739 ((equal key "TAGS")
4740 (setq tags (append tags (if tags '("\\n") nil)
4741 (org-split-string value splitre))))
4742 ((equal key "COLUMNS")
4743 (org-set-local 'org-columns-default-format value))
4744 ((equal key "LINK")
4745 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4746 (push (cons (match-string 1 value)
4747 (org-trim (match-string 2 value)))
4748 links)))
4749 ((equal key "PRIORITIES")
4750 (setq prio (org-split-string value " +")))
4751 ((equal key "PROPERTY")
4752 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4753 (setq props (org-update-property-plist (match-string 1 value)
4754 (match-string 2 value)
4755 props))))
4756 ((equal key "FILETAGS")
4757 (when (string-match "\\S-" value)
4758 (setq ftags
4759 (append
4760 ftags
4761 (apply 'append
4762 (mapcar (lambda (x) (org-split-string x ":"))
4763 (org-split-string value)))))))
4764 ((equal key "DRAWERS")
4765 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4766 ((equal key "CONSTANTS")
4767 (setq const (append const (org-split-string value splitre))))
4768 ((equal key "STARTUP")
4769 (let ((opts (org-split-string value splitre))
4770 l var val)
4771 (while (setq l (pop opts))
4772 (when (setq l (assoc l org-startup-options))
4773 (setq var (nth 1 l) val (nth 2 l))
4774 (if (not (nth 3 l))
4775 (set (make-local-variable var) val)
4776 (if (not (listp (symbol-value var)))
4777 (set (make-local-variable var) nil))
4778 (set (make-local-variable var) (symbol-value var))
4779 (add-to-list var val))))))
4780 ((equal key "ARCHIVE")
4781 (setq arch value)
4782 (remove-text-properties 0 (length arch)
4783 '(face t fontified t) arch))
4784 ((equal key "LATEX_CLASS")
4785 (setq beamer-p (equal value "beamer")))
4786 ((equal key "OPTIONS")
4787 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4788 (setq scripts (read (match-string 2 value)))))
4789 ((equal key "SETUPFILE")
4790 (setq setup-contents (org-file-contents
4791 (expand-file-name
4792 (org-remove-double-quotes value))
4793 'noerror))
4794 (if (not ext-setup-or-nil)
4795 (setq ext-setup-or-nil setup-contents start 0)
4796 (setq ext-setup-or-nil
4797 (concat (substring ext-setup-or-nil 0 start)
4798 "\n" setup-contents "\n"
4799 (substring ext-setup-or-nil start)))))))
4800 ;; search for property blocks
4801 (goto-char (point-min))
4802 (while (re-search-forward org-block-regexp nil t)
4803 (when (equal "PROPERTY" (upcase (match-string 1)))
4804 (setq value (replace-regexp-in-string
4805 "[\n\r]" " " (match-string 4)))
4806 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4807 (setq props (org-update-property-plist (match-string 1 value)
4808 (match-string 2 value)
4809 props)))))))
4810 (org-set-local 'org-use-sub-superscripts scripts)
4811 (when cat
4812 (org-set-local 'org-category (intern cat))
4813 (push (cons "CATEGORY" cat) props))
4814 (when prio
4815 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4816 (setq prio (mapcar 'string-to-char prio))
4817 (org-set-local 'org-highest-priority (nth 0 prio))
4818 (org-set-local 'org-lowest-priority (nth 1 prio))
4819 (org-set-local 'org-default-priority (nth 2 prio)))
4820 (and props (org-set-local 'org-file-properties (nreverse props)))
4821 (and ftags (org-set-local 'org-file-tags
4822 (mapcar 'org-add-prop-inherited ftags)))
4823 (and drawers (org-set-local 'org-drawers drawers))
4824 (and arch (org-set-local 'org-archive-location arch))
4825 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4826 ;; Process the TODO keywords
4827 (unless kwds
4828 ;; Use the global values as if they had been given locally.
4829 (setq kwds (default-value 'org-todo-keywords))
4830 (if (stringp (car kwds))
4831 (setq kwds (list (cons org-todo-interpretation
4832 (default-value 'org-todo-keywords)))))
4833 (setq kwds (reverse kwds)))
4834 (setq kwds (nreverse kwds))
4835 (let (inter kws kw)
4836 (while (setq kws (pop kwds))
4837 (let ((kws (or
4838 (run-hook-with-args-until-success
4839 'org-todo-setup-filter-hook kws)
4840 kws)))
4841 (setq inter (pop kws) sep (member "|" kws)
4842 kws0 (delete "|" (copy-sequence kws))
4843 kwsa nil
4844 kws1 (mapcar
4845 (lambda (x)
4846 ;; 1 2
4847 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4848 (progn
4849 (setq kw (match-string 1 x)
4850 key (and (match-end 2) (match-string 2 x))
4851 log (org-extract-log-state-settings x))
4852 (push (cons kw (and key (string-to-char key))) kwsa)
4853 (and log (push log org-todo-log-states))
4855 (error "Invalid TODO keyword %s" x)))
4856 kws0)
4857 kwsa (if kwsa (append '((:startgroup))
4858 (nreverse kwsa)
4859 '((:endgroup))))
4860 hw (car kws1)
4861 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4862 tail (list inter hw (car dws) (org-last dws))))
4863 (add-to-list 'org-todo-heads hw 'append)
4864 (push kws1 org-todo-sets)
4865 (setq org-done-keywords (append org-done-keywords dws nil))
4866 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4867 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4868 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4869 (setq org-todo-sets (nreverse org-todo-sets)
4870 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4871 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4872 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4873 ;; Process the constants
4874 (when const
4875 (let (e cst)
4876 (while (setq e (pop const))
4877 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4878 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4879 (setq org-table-formula-constants-local cst)))
4881 ;; Process the tags.
4882 (when tags
4883 (let (e tgs)
4884 (while (setq e (pop tags))
4885 (cond
4886 ((equal e "{") (push '(:startgroup) tgs))
4887 ((equal e "}") (push '(:endgroup) tgs))
4888 ((equal e "\\n") (push '(:newline) tgs))
4889 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4890 (push (cons (match-string 1 e)
4891 (string-to-char (match-string 2 e)))
4892 tgs))
4893 (t (push (list e) tgs))))
4894 (org-set-local 'org-tag-alist nil)
4895 (while (setq e (pop tgs))
4896 (or (and (stringp (car e))
4897 (assoc (car e) org-tag-alist))
4898 (push e org-tag-alist)))))
4900 ;; Compute the regular expressions and other local variables.
4901 ;; Using `org-outline-regexp-bol' would complicate them much,
4902 ;; because of the fixed white space at the end of that string.
4903 (if (not org-done-keywords)
4904 (setq org-done-keywords (and org-todo-keywords-1
4905 (list (org-last org-todo-keywords-1)))))
4906 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4907 (length org-scheduled-string)
4908 (length org-clock-string)
4909 (length org-closed-string)))
4910 org-drawer-regexp
4911 (concat "^[ \t]*:\\("
4912 (mapconcat 'regexp-quote org-drawers "\\|")
4913 "\\):[ \t]*$")
4914 org-not-done-keywords
4915 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4916 org-todo-regexp
4917 (concat "\\("
4918 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4919 "\\)")
4920 org-not-done-regexp
4921 (concat "\\("
4922 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4923 "\\)")
4924 org-not-done-heading-regexp
4925 (format org-heading-keyword-regexp-format org-not-done-regexp)
4926 org-todo-line-regexp
4927 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4928 org-complex-heading-regexp
4929 (concat "^\\(\\*+\\)"
4930 "\\(?: +" org-todo-regexp "\\)?"
4931 "\\(?: +\\(\\[#.\\]\\)\\)?"
4932 "\\(?: +\\(.*?\\)\\)??"
4933 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4934 "[ \t]*$")
4935 org-complex-heading-regexp-format
4936 (concat "^\\(\\*+\\)"
4937 "\\(?: +" org-todo-regexp "\\)?"
4938 "\\(?: +\\(\\[#.\\]\\)\\)?"
4939 "\\(?: +"
4940 ;; Stats cookies can be stuck to body.
4941 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4942 "\\(%s\\)"
4943 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4944 "\\)"
4945 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4946 "[ \t]*$")
4947 org-todo-line-tags-regexp
4948 (concat "^\\(\\*+\\)"
4949 "\\(?: +" org-todo-regexp "\\)?"
4950 "\\(?: +\\(.*?\\)\\)??"
4951 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4952 "[ \t]*$")
4953 org-deadline-regexp (concat "\\<" org-deadline-string)
4954 org-deadline-time-regexp
4955 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4956 org-deadline-line-regexp
4957 (concat "\\<\\(" org-deadline-string "\\).*")
4958 org-scheduled-regexp
4959 (concat "\\<" org-scheduled-string)
4960 org-scheduled-time-regexp
4961 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4962 org-closed-time-regexp
4963 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4964 org-keyword-time-regexp
4965 (concat "\\<\\(" org-scheduled-string
4966 "\\|" org-deadline-string
4967 "\\|" org-closed-string
4968 "\\|" org-clock-string "\\)"
4969 " *[[<]\\([^]>]+\\)[]>]")
4970 org-keyword-time-not-clock-regexp
4971 (concat "\\<\\(" org-scheduled-string
4972 "\\|" org-deadline-string
4973 "\\|" org-closed-string
4974 "\\)"
4975 " *[[<]\\([^]>]+\\)[]>]")
4976 org-maybe-keyword-time-regexp
4977 (concat "\\(\\<\\(" org-scheduled-string
4978 "\\|" org-deadline-string
4979 "\\|" org-closed-string
4980 "\\|" org-clock-string "\\)\\)?"
4981 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4982 org-all-time-keywords
4983 (mapcar (lambda (w) (substring w 0 -1))
4984 (list org-scheduled-string org-deadline-string
4985 org-clock-string org-closed-string)))
4986 (org-set-font-lock-defaults))))
4988 (defun org-file-contents (file &optional noerror)
4989 "Return the contents of FILE, as a string."
4990 (if (or (not file)
4991 (not (file-readable-p file)))
4992 (if noerror
4993 (progn
4994 (message "Cannot read file \"%s\"" file)
4995 (ding) (sit-for 2)
4997 (error "Cannot read file \"%s\"" file))
4998 (with-temp-buffer
4999 (insert-file-contents file)
5000 (buffer-string))))
5002 (defun org-extract-log-state-settings (x)
5003 "Extract the log state setting from a TODO keyword string.
5004 This will extract info from a string like \"WAIT(w@/!)\"."
5005 (let (kw key log1 log2)
5006 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5007 (setq kw (match-string 1 x)
5008 key (and (match-end 2) (match-string 2 x))
5009 log1 (and (match-end 3) (match-string 3 x))
5010 log2 (and (match-end 4) (match-string 4 x)))
5011 (and (or log1 log2)
5012 (list kw
5013 (and log1 (if (equal log1 "!") 'time 'note))
5014 (and log2 (if (equal log2 "!") 'time 'note)))))))
5016 (defun org-remove-keyword-keys (list)
5017 "Remove a pair of parenthesis at the end of each string in LIST."
5018 (mapcar (lambda (x)
5019 (if (string-match "(.*)$" x)
5020 (substring x 0 (match-beginning 0))
5022 list))
5024 (defun org-assign-fast-keys (alist)
5025 "Assign fast keys to a keyword-key alist.
5026 Respect keys that are already there."
5027 (let (new e (alt ?0))
5028 (while (setq e (pop alist))
5029 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5030 (cdr e)) ;; Key already assigned.
5031 (push e new)
5032 (let ((clist (string-to-list (downcase (car e))))
5033 (used (append new alist)))
5034 (when (= (car clist) ?@)
5035 (pop clist))
5036 (while (and clist (rassoc (car clist) used))
5037 (pop clist))
5038 (unless clist
5039 (while (rassoc alt used)
5040 (incf alt)))
5041 (push (cons (car e) (or (car clist) alt)) new))))
5042 (nreverse new)))
5044 ;;; Some variables used in various places
5046 (defvar org-window-configuration nil
5047 "Used in various places to store a window configuration.")
5048 (defvar org-selected-window nil
5049 "Used in various places to store a window configuration.")
5050 (defvar org-finish-function nil
5051 "Function to be called when `C-c C-c' is used.
5052 This is for getting out of special buffers like capture.")
5055 ;; FIXME: Occasionally check by commenting these, to make sure
5056 ;; no other functions uses these, forgetting to let-bind them.
5057 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5058 (defvar org-last-state)
5059 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5061 ;; Defined somewhere in this file, but used before definition.
5062 (defvar org-entities) ;; defined in org-entities.el
5063 (defvar org-struct-menu)
5064 (defvar org-org-menu)
5065 (defvar org-tbl-menu)
5067 ;;;; Define the Org-mode
5069 ;; We use a before-change function to check if a table might need
5070 ;; an update.
5071 (defvar org-table-may-need-update t
5072 "Indicates that a table might need an update.
5073 This variable is set by `org-before-change-function'.
5074 `org-table-align' sets it back to nil.")
5075 (defun org-before-change-function (beg end)
5076 "Every change indicates that a table might need an update."
5077 (setq org-table-may-need-update t))
5078 (defvar org-mode-map)
5079 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5080 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5081 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5082 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5083 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5084 (defvar org-table-buffer-is-an nil)
5086 (defvar bidi-paragraph-direction)
5087 (defvar buffer-face-mode-face)
5089 (require 'outline)
5090 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5091 (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"))
5092 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5094 ;; Other stuff we need.
5095 (require 'time-date)
5096 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5097 (require 'easymenu)
5098 (require 'overlay)
5100 ;; (require 'org-macs) moved higher up in the file before it is first used
5101 (require 'org-entities)
5102 ;; (require 'org-compat) moved higher up in the file before it is first used
5103 (require 'org-faces)
5104 (require 'org-list)
5105 (require 'org-pcomplete)
5106 (require 'org-src)
5107 (require 'org-footnote)
5109 ;; babel
5110 (require 'ob)
5112 ;;;###autoload
5113 (define-derived-mode org-mode outline-mode "Org"
5114 "Outline-based notes management and organizer, alias
5115 \"Carsten's outline-mode for keeping track of everything.\"
5117 Org-mode develops organizational tasks around a NOTES file which
5118 contains information about projects as plain text. Org-mode is
5119 implemented on top of outline-mode, which is ideal to keep the content
5120 of large files well structured. It supports ToDo items, deadlines and
5121 time stamps, which magically appear in the diary listing of the Emacs
5122 calendar. Tables are easily created with a built-in table editor.
5123 Plain text URL-like links connect to websites, emails (VM), Usenet
5124 messages (Gnus), BBDB entries, and any files related to the project.
5125 For printing and sharing of notes, an Org-mode file (or a part of it)
5126 can be exported as a structured ASCII or HTML file.
5128 The following commands are available:
5130 \\{org-mode-map}"
5132 ;; Get rid of Outline menus, they are not needed
5133 ;; Need to do this here because define-derived-mode sets up
5134 ;; the keymap so late. Still, it is a waste to call this each time
5135 ;; we switch another buffer into org-mode.
5136 (if (featurep 'xemacs)
5137 (when (boundp 'outline-mode-menu-heading)
5138 ;; Assume this is Greg's port, it uses easymenu
5139 (easy-menu-remove outline-mode-menu-heading)
5140 (easy-menu-remove outline-mode-menu-show)
5141 (easy-menu-remove outline-mode-menu-hide))
5142 (define-key org-mode-map [menu-bar headings] 'undefined)
5143 (define-key org-mode-map [menu-bar hide] 'undefined)
5144 (define-key org-mode-map [menu-bar show] 'undefined))
5146 (org-load-modules-maybe)
5147 (easy-menu-add org-org-menu)
5148 (easy-menu-add org-tbl-menu)
5149 (org-install-agenda-files-menu)
5150 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5151 (add-to-invisibility-spec '(org-cwidth))
5152 (add-to-invisibility-spec '(org-hide-block . t))
5153 (when (featurep 'xemacs)
5154 (org-set-local 'line-move-ignore-invisible t))
5155 (org-set-local 'outline-regexp org-outline-regexp)
5156 (org-set-local 'outline-level 'org-outline-level)
5157 (setq bidi-paragraph-direction 'left-to-right)
5158 (when (and org-ellipsis
5159 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5160 (fboundp 'make-glyph-code))
5161 (unless org-display-table
5162 (setq org-display-table (make-display-table)))
5163 (set-display-table-slot
5164 org-display-table 4
5165 (vconcat (mapcar
5166 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5167 org-ellipsis)))
5168 (if (stringp org-ellipsis) org-ellipsis "..."))))
5169 (setq buffer-display-table org-display-table))
5170 (org-set-regexps-and-options)
5171 (when (and org-tag-faces (not org-tags-special-faces-re))
5172 ;; tag faces set outside customize.... force initialization.
5173 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5174 ;; Calc embedded
5175 (org-set-local 'calc-embedded-open-mode "# ")
5176 (modify-syntax-entry ?@ "w")
5177 (modify-syntax-entry ?\" "\"")
5178 (if org-startup-truncated (setq truncate-lines t))
5179 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5180 (org-set-local 'font-lock-unfontify-region-function
5181 'org-unfontify-region)
5182 ;; Activate before-change-function
5183 (org-set-local 'org-table-may-need-update t)
5184 (org-add-hook 'before-change-functions 'org-before-change-function nil
5185 'local)
5186 ;; Check for running clock before killing a buffer
5187 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5188 ;; Initialize macros templates.
5189 (org-macro-initialize-templates)
5190 ;; Initialize radio targets.
5191 (org-update-radio-target-regexp)
5192 ;; Indentation.
5193 (org-set-local 'indent-line-function 'org-indent-line)
5194 (org-set-local 'indent-region-function 'org-indent-region)
5195 ;; Filling and auto-filling.
5196 (org-setup-filling)
5197 ;; Comments.
5198 (org-setup-comments-handling)
5199 ;; Beginning/end of defun
5200 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5201 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5202 ;; Next error for sparse trees
5203 (org-set-local 'next-error-function 'org-occur-next-match)
5204 ;; Make sure dependence stuff works reliably, even for users who set it
5205 ;; too late :-(
5206 (if org-enforce-todo-dependencies
5207 (add-hook 'org-blocker-hook
5208 'org-block-todo-from-children-or-siblings-or-parent)
5209 (remove-hook 'org-blocker-hook
5210 'org-block-todo-from-children-or-siblings-or-parent))
5211 (if org-enforce-todo-checkbox-dependencies
5212 (add-hook 'org-blocker-hook
5213 'org-block-todo-from-checkboxes)
5214 (remove-hook 'org-blocker-hook
5215 'org-block-todo-from-checkboxes))
5217 ;; Align options lines
5218 (org-set-local
5219 'align-mode-rules-list
5220 '((org-in-buffer-settings
5221 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5222 (modes . '(org-mode)))))
5224 ;; Imenu
5225 (org-set-local 'imenu-create-index-function
5226 'org-imenu-get-tree)
5228 ;; Make isearch reveal context
5229 (if (or (featurep 'xemacs)
5230 (not (boundp 'outline-isearch-open-invisible-function)))
5231 ;; Emacs 21 and XEmacs make use of the hook
5232 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5233 ;; Emacs 22 deals with this through a special variable
5234 (org-set-local 'outline-isearch-open-invisible-function
5235 (lambda (&rest ignore) (org-show-context 'isearch))))
5237 ;; Setup the pcomplete hooks
5238 (set (make-local-variable 'pcomplete-command-completion-function)
5239 'org-pcomplete-initial)
5240 (set (make-local-variable 'pcomplete-command-name-function)
5241 'org-command-at-point)
5242 (set (make-local-variable 'pcomplete-default-completion-function)
5243 'ignore)
5244 (set (make-local-variable 'pcomplete-parse-arguments-function)
5245 'org-parse-arguments)
5246 (set (make-local-variable 'pcomplete-termination-string) "")
5247 (when (>= emacs-major-version 23)
5248 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5250 ;; If empty file that did not turn on org-mode automatically, make it to.
5251 (if (and org-insert-mode-line-in-empty-file
5252 (org-called-interactively-p 'any)
5253 (= (point-min) (point-max)))
5254 (insert "# -*- mode: org -*-\n\n"))
5255 (unless org-inhibit-startup
5256 (and org-startup-with-beamer-mode (org-beamer-mode))
5257 (when org-startup-align-all-tables
5258 (let ((bmp (buffer-modified-p)))
5259 (org-table-map-tables 'org-table-align 'quietly)
5260 (set-buffer-modified-p bmp)))
5261 (when org-startup-with-inline-images
5262 (org-display-inline-images))
5263 (unless org-inhibit-startup-visibility-stuff
5264 (org-set-startup-visibility)))
5265 ;; Try to set org-hide correctly
5266 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5268 (when (fboundp 'abbrev-table-put)
5269 (abbrev-table-put org-mode-abbrev-table
5270 :parents (list text-mode-abbrev-table)))
5272 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5275 (defun org-find-invisible-foreground ()
5276 (let ((candidates (remove
5277 "unspecified-bg"
5278 (nconc
5279 (list (face-background 'default)
5280 (face-background 'org-default))
5281 (mapcar
5282 (lambda (alist)
5283 (when (boundp alist)
5284 (cdr (assoc 'background-color (symbol-value alist)))))
5285 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5286 (list (face-foreground 'org-hide))))))
5287 (car (remove nil candidates))))
5289 (defun org-current-time (&optional rounding-minutes)
5290 "Current time, possibly rounded to ROUNDING-MINUTES.
5291 When ROUNDING-MINUTES is not an integer, fall back on the car of
5292 `org-time-stamp-rounding-minutes'."
5293 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5294 (car org-time-stamp-rounding-minutes)))
5295 (time (decode-time)))
5296 (if (> r 1)
5297 (apply 'encode-time
5298 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5299 (nthcdr 2 time)))
5300 (current-time))))
5302 (defun org-today ()
5303 "Return today date, considering `org-extend-today-until'."
5304 (time-to-days
5305 (time-subtract (current-time)
5306 (list 0 (* 3600 org-extend-today-until) 0))))
5308 ;;;; Font-Lock stuff, including the activators
5310 (defvar org-mouse-map (make-sparse-keymap))
5311 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5312 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5313 (when org-mouse-1-follows-link
5314 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5315 (when org-tab-follows-link
5316 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5317 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5319 (require 'font-lock)
5321 (defconst org-non-link-chars "]\t\n\r<>")
5322 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5323 "shell" "elisp" "doi" "message"))
5324 (defvar org-link-types-re nil
5325 "Matches a link that has a url-like prefix like \"http:\"")
5326 (defvar org-link-re-with-space nil
5327 "Matches a link with spaces, optional angular brackets around it.")
5328 (defvar org-link-re-with-space2 nil
5329 "Matches a link with spaces, optional angular brackets around it.")
5330 (defvar org-link-re-with-space3 nil
5331 "Matches a link with spaces, only for internal part in bracket links.")
5332 (defvar org-angle-link-re nil
5333 "Matches link with angular brackets, spaces are allowed.")
5334 (defvar org-plain-link-re nil
5335 "Matches plain link, without spaces.")
5336 (defvar org-bracket-link-regexp nil
5337 "Matches a link in double brackets.")
5338 (defvar org-bracket-link-analytic-regexp nil
5339 "Regular expression used to analyze links.
5340 Here is what the match groups contain after a match:
5341 1: http:
5342 2: http
5343 3: path
5344 4: [desc]
5345 5: desc")
5346 (defvar org-bracket-link-analytic-regexp++ nil
5347 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5348 (defvar org-any-link-re nil
5349 "Regular expression matching any link.")
5351 (defconst org-match-sexp-depth 3
5352 "Number of stacked braces for sub/superscript matching.")
5354 (defun org-create-multibrace-regexp (left right n)
5355 "Create a regular expression which will match a balanced sexp.
5356 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5357 as single character strings.
5358 The regexp returned will match the entire expression including the
5359 delimiters. It will also define a single group which contains the
5360 match except for the outermost delimiters. The maximum depth of
5361 stacked delimiters is N. Escaping delimiters is not possible."
5362 (let* ((nothing (concat "[^" left right "]*?"))
5363 (or "\\|")
5364 (re nothing)
5365 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5366 (while (> n 1)
5367 (setq n (1- n)
5368 re (concat re or next)
5369 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5370 (concat left "\\(" re "\\)" right)))
5372 (defvar org-match-substring-regexp
5373 (concat
5374 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5375 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5376 "\\|"
5377 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5378 "\\|"
5379 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5380 "The regular expression matching a sub- or superscript.")
5382 (defvar org-match-substring-with-braces-regexp
5383 (concat
5384 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5385 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5386 "\\)")
5387 "The regular expression matching a sub- or superscript, forcing braces.")
5389 (defun org-make-link-regexps ()
5390 "Update the link regular expressions.
5391 This should be called after the variable `org-link-types' has changed."
5392 (setq org-link-types-re
5393 (concat
5394 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5395 org-link-re-with-space
5396 (concat
5397 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5398 "\\([^" org-non-link-chars " ]"
5399 "[^" org-non-link-chars "]*"
5400 "[^" org-non-link-chars " ]\\)>?")
5401 org-link-re-with-space2
5402 (concat
5403 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5404 "\\([^" org-non-link-chars " ]"
5405 "[^\t\n\r]*"
5406 "[^" org-non-link-chars " ]\\)>?")
5407 org-link-re-with-space3
5408 (concat
5409 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5410 "\\([^" org-non-link-chars " ]"
5411 "[^\t\n\r]*\\)")
5412 org-angle-link-re
5413 (concat
5414 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5415 "\\([^" org-non-link-chars " ]"
5416 "[^" org-non-link-chars "]*"
5417 "\\)>")
5418 org-plain-link-re
5419 (concat
5420 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5421 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5422 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5423 org-bracket-link-regexp
5424 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5425 org-bracket-link-analytic-regexp
5426 (concat
5427 "\\[\\["
5428 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5429 "\\([^]]+\\)"
5430 "\\]"
5431 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5432 "\\]")
5433 org-bracket-link-analytic-regexp++
5434 (concat
5435 "\\[\\["
5436 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5437 "\\([^]]+\\)"
5438 "\\]"
5439 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5440 "\\]")
5441 org-any-link-re
5442 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5443 org-angle-link-re "\\)\\|\\("
5444 org-plain-link-re "\\)")))
5446 (org-make-link-regexps)
5448 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5449 "Regular expression for fast time stamp matching.")
5450 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5451 "Regular expression for fast time stamp matching.")
5452 (defconst org-ts-regexp0
5453 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5454 "Regular expression matching time strings for analysis.
5455 This one does not require the space after the date, so it can be used
5456 on a string that terminates immediately after the date.")
5457 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5458 "Regular expression matching time strings for analysis.")
5459 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5460 "Regular expression matching time stamps, with groups.")
5461 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5462 "Regular expression matching time stamps (also [..]), with groups.")
5463 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5464 "Regular expression matching a time stamp range.")
5465 (defconst org-tr-regexp-both
5466 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5467 "Regular expression matching a time stamp range.")
5468 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5469 org-ts-regexp "\\)?")
5470 "Regular expression matching a time stamp or time stamp range.")
5471 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5472 org-ts-regexp-both "\\)?")
5473 "Regular expression matching a time stamp or time stamp range.
5474 The time stamps may be either active or inactive.")
5476 (defvar org-emph-face nil)
5478 (defun org-do-emphasis-faces (limit)
5479 "Run through the buffer and add overlays to emphasized strings."
5480 (let (rtn a)
5481 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5482 (if (not (= (char-after (match-beginning 3))
5483 (char-after (match-beginning 4))))
5484 (progn
5485 (setq rtn t)
5486 (setq a (assoc (match-string 3) org-emphasis-alist))
5487 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5488 'face
5489 (nth 1 a))
5490 (and (nth 4 a)
5491 (org-remove-flyspell-overlays-in
5492 (match-beginning 0) (match-end 0)))
5493 (add-text-properties (match-beginning 2) (match-end 2)
5494 '(font-lock-multiline t org-emphasis t))
5495 (when org-hide-emphasis-markers
5496 (add-text-properties (match-end 4) (match-beginning 5)
5497 '(invisible org-link))
5498 (add-text-properties (match-beginning 3) (match-end 3)
5499 '(invisible org-link)))))
5500 (backward-char 1))
5501 rtn))
5503 (defun org-emphasize (&optional char)
5504 "Insert or change an emphasis, i.e. a font like bold or italic.
5505 If there is an active region, change that region to a new emphasis.
5506 If there is no region, just insert the marker characters and position
5507 the cursor between them.
5508 CHAR should be either the marker character, or the first character of the
5509 HTML tag associated with that emphasis. If CHAR is a space, the means
5510 to remove the emphasis of the selected region.
5511 If char is not given (for example in an interactive call) it
5512 will be prompted for."
5513 (interactive)
5514 (let ((eal org-emphasis-alist) e det
5515 (erc org-emphasis-regexp-components)
5516 (prompt "")
5517 (string "") beg end move tag c s)
5518 (if (org-region-active-p)
5519 (setq beg (region-beginning) end (region-end)
5520 string (buffer-substring beg end))
5521 (setq move t))
5523 (while (setq e (pop eal))
5524 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5525 c (aref tag 0))
5526 (push (cons c (string-to-char (car e))) det)
5527 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5528 (substring tag 1)))))
5529 (setq det (nreverse det))
5530 (unless char
5531 (message "%s" (concat "Emphasis marker or tag:" prompt))
5532 (setq char (read-char-exclusive)))
5533 (setq char (or (cdr (assoc char det)) char))
5534 (if (equal char ?\ )
5535 (setq s "" move nil)
5536 (unless (assoc (char-to-string char) org-emphasis-alist)
5537 (error "No such emphasis marker: \"%c\"" char))
5538 (setq s (char-to-string char)))
5539 (while (and (> (length string) 1)
5540 (equal (substring string 0 1) (substring string -1))
5541 (assoc (substring string 0 1) org-emphasis-alist))
5542 (setq string (substring string 1 -1)))
5543 (setq string (concat s string s))
5544 (if beg (delete-region beg end))
5545 (unless (or (bolp)
5546 (string-match (concat "[" (nth 0 erc) "\n]")
5547 (char-to-string (char-before (point)))))
5548 (insert " "))
5549 (unless (or (eobp)
5550 (string-match (concat "[" (nth 1 erc) "\n]")
5551 (char-to-string (char-after (point)))))
5552 (insert " ") (backward-char 1))
5553 (insert string)
5554 (and move (backward-char 1))))
5556 (defconst org-nonsticky-props
5557 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5559 (defsubst org-rear-nonsticky-at (pos)
5560 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5562 (defun org-activate-plain-links (limit)
5563 "Run through the buffer and add overlays to links."
5564 (catch 'exit
5565 (let (f hl)
5566 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5567 (not (org-in-src-block-p)))
5568 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5569 (setq f (get-text-property (match-beginning 0) 'face))
5570 (setq hl (org-match-string-no-properties 0))
5571 (if (or (eq f 'org-tag)
5572 (and (listp f) (memq 'org-tag f)))
5574 (add-text-properties (match-beginning 0) (match-end 0)
5575 (list 'mouse-face 'highlight
5576 'face 'org-link
5577 'htmlize-link `(:uri ,hl)
5578 'keymap org-mouse-map))
5579 (org-rear-nonsticky-at (match-end 0)))
5580 t))))
5582 (defun org-activate-code (limit)
5583 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5584 (progn
5585 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5586 (remove-text-properties (match-beginning 0) (match-end 0)
5587 '(display t invisible t intangible t))
5588 t)))
5590 (defcustom org-src-fontify-natively nil
5591 "When non-nil, fontify code in code blocks."
5592 :type 'boolean
5593 :version "24.1"
5594 :group 'org-appearance
5595 :group 'org-babel)
5597 (defcustom org-allow-promoting-top-level-subtree nil
5598 "When non-nil, allow promoting a top level subtree.
5599 The leading star of the top level headline will be replaced
5600 by a #."
5601 :type 'boolean
5602 :version "24.1"
5603 :group 'org-appearance)
5605 (defun org-fontify-meta-lines-and-blocks (limit)
5606 (condition-case nil
5607 (org-fontify-meta-lines-and-blocks-1 limit)
5608 (error (message "org-mode fontification error"))))
5610 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5611 "Fontify #+ lines and blocks, in the correct ways."
5612 (let ((case-fold-search t))
5613 (if (re-search-forward
5614 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5615 limit t)
5616 (let ((beg (match-beginning 0))
5617 (block-start (match-end 0))
5618 (block-end nil)
5619 (lang (match-string 7))
5620 (beg1 (line-beginning-position 2))
5621 (dc1 (downcase (match-string 2)))
5622 (dc3 (downcase (match-string 3)))
5623 end end1 quoting block-type ovl)
5624 (cond
5625 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5626 ;; a single line of backend-specific content
5627 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5628 (remove-text-properties (match-beginning 0) (match-end 0)
5629 '(display t invisible t intangible t))
5630 (add-text-properties (match-beginning 1) (match-end 3)
5631 '(font-lock-fontified t face org-meta-line))
5632 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5633 '(font-lock-fontified t face org-block))
5634 ; for backend-specific code
5636 ((and (match-end 4) (equal dc3 "+begin"))
5637 ;; Truly a block
5638 (setq block-type (downcase (match-string 5))
5639 quoting (member block-type org-protecting-blocks))
5640 (when (re-search-forward
5641 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5642 nil t) ;; on purpose, we look further than LIMIT
5643 (setq end (min (point-max) (match-end 0))
5644 end1 (min (point-max) (1- (match-beginning 0))))
5645 (setq block-end (match-beginning 0))
5646 (when quoting
5647 (remove-text-properties beg end
5648 '(display t invisible t intangible t)))
5649 (add-text-properties
5650 beg end
5651 '(font-lock-fontified t font-lock-multiline t))
5652 (add-text-properties beg beg1 '(face org-meta-line))
5653 (add-text-properties end1 (min (point-max) (1+ end))
5654 '(face org-meta-line)) ; for end_src
5655 (cond
5656 ((and lang (not (string= lang "")) org-src-fontify-natively)
5657 (org-src-font-lock-fontify-block lang block-start block-end)
5658 ;; remove old background overlays
5659 (mapc (lambda (ov)
5660 (if (eq (overlay-get ov 'face) 'org-block-background)
5661 (delete-overlay ov)))
5662 (overlays-at (/ (+ beg1 block-end) 2)))
5663 ;; add a background overlay
5664 (setq ovl (make-overlay beg1 block-end))
5665 (overlay-put ovl 'face 'org-block-background)
5666 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5667 (quoting
5668 (add-text-properties beg1 (min (point-max) (1+ end1))
5669 '(face org-block))) ; end of source block
5670 ((not org-fontify-quote-and-verse-blocks))
5671 ((string= block-type "quote")
5672 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5673 ((string= block-type "verse")
5674 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5675 (add-text-properties beg beg1 '(face org-block-begin-line))
5676 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5677 '(face org-block-end-line))
5679 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5680 (add-text-properties
5681 beg (match-end 3)
5682 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5683 '(font-lock-fontified t invisible t)
5684 '(font-lock-fontified t face org-document-info-keyword)))
5685 (add-text-properties
5686 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5687 (if (string-equal dc1 "+title:")
5688 '(font-lock-fontified t face org-document-title)
5689 '(font-lock-fontified t face org-document-info))))
5690 ((or (equal dc1 "+results")
5691 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5692 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5693 "+call:" "+header:" "+headers:" "+name:"))
5694 (and (match-end 4) (equal dc3 "+attr")))
5695 (add-text-properties
5696 beg (match-end 0)
5697 '(font-lock-fontified t face org-meta-line))
5699 ((member dc3 '(" " ""))
5700 (add-text-properties
5701 beg (match-end 0)
5702 '(font-lock-fontified t face font-lock-comment-face)))
5703 ((not (member (char-after beg) '(?\ ?\t)))
5704 ;; just any other in-buffer setting, but not indented
5705 (add-text-properties
5706 beg (match-end 0)
5707 '(font-lock-fontified t face org-meta-line))
5709 (t nil))))))
5711 (defun org-activate-angle-links (limit)
5712 "Run through the buffer and add overlays to links."
5713 (if (and (re-search-forward org-angle-link-re limit t)
5714 (not (org-in-src-block-p)))
5715 (progn
5716 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5717 (add-text-properties (match-beginning 0) (match-end 0)
5718 (list 'mouse-face 'highlight
5719 'keymap org-mouse-map))
5720 (org-rear-nonsticky-at (match-end 0))
5721 t)))
5723 (defun org-activate-footnote-links (limit)
5724 "Run through the buffer and add overlays to footnotes."
5725 (let ((fn (org-footnote-next-reference-or-definition limit)))
5726 (when fn
5727 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5728 (org-remove-flyspell-overlays-in beg end)
5729 (add-text-properties beg end
5730 (list 'mouse-face 'highlight
5731 'keymap org-mouse-map
5732 'help-echo
5733 (if (= (point-at-bol) beg)
5734 "Footnote definition"
5735 "Footnote reference")
5736 'font-lock-fontified t
5737 'font-lock-multiline t
5738 'face 'org-footnote))))))
5740 (defun org-activate-bracket-links (limit)
5741 "Run through the buffer and add overlays to bracketed links."
5742 (if (and (re-search-forward org-bracket-link-regexp limit t)
5743 (not (org-in-src-block-p)))
5744 (let* ((hl (org-match-string-no-properties 1))
5745 (help (concat "LINK: " hl))
5746 ;; FIXME: Above we should remove the escapes. But that
5747 ;; requires another match, protecting match data, a lot
5748 ;; of overhead for font-lock.
5749 (ip (org-maybe-intangible
5750 (list 'invisible 'org-link
5751 'keymap org-mouse-map 'mouse-face 'highlight
5752 'font-lock-multiline t 'help-echo help
5753 'htmlize-link `(:uri ,hl))))
5754 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5755 'font-lock-multiline t 'help-echo help
5756 'htmlize-link `(:uri ,hl))))
5757 ;; We need to remove the invisible property here. Table narrowing
5758 ;; may have made some of this invisible.
5759 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5760 (remove-text-properties (match-beginning 0) (match-end 0)
5761 '(invisible nil))
5762 (if (match-end 3)
5763 (progn
5764 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5765 (org-rear-nonsticky-at (match-beginning 3))
5766 (add-text-properties (match-beginning 3) (match-end 3) vp)
5767 (org-rear-nonsticky-at (match-end 3))
5768 (add-text-properties (match-end 3) (match-end 0) ip)
5769 (org-rear-nonsticky-at (match-end 0)))
5770 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5771 (org-rear-nonsticky-at (match-beginning 1))
5772 (add-text-properties (match-beginning 1) (match-end 1) vp)
5773 (org-rear-nonsticky-at (match-end 1))
5774 (add-text-properties (match-end 1) (match-end 0) ip)
5775 (org-rear-nonsticky-at (match-end 0)))
5776 t)))
5778 (defun org-activate-dates (limit)
5779 "Run through the buffer and add overlays to dates."
5780 (if (re-search-forward org-tsr-regexp-both limit t)
5781 (progn
5782 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5783 (add-text-properties (match-beginning 0) (match-end 0)
5784 (list 'mouse-face 'highlight
5785 'keymap org-mouse-map))
5786 (org-rear-nonsticky-at (match-end 0))
5787 (when org-display-custom-times
5788 (if (match-end 3)
5789 (org-display-custom-time (match-beginning 3) (match-end 3)))
5790 (org-display-custom-time (match-beginning 1) (match-end 1)))
5791 t)))
5793 (defvar org-target-link-regexp nil
5794 "Regular expression matching radio targets in plain text.")
5795 (make-variable-buffer-local 'org-target-link-regexp)
5796 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5797 "Regular expression matching a link target.")
5798 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5799 "Regular expression matching a radio target.")
5800 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5801 "Regular expression matching any target.")
5803 (defun org-activate-target-links (limit)
5804 "Run through the buffer and add overlays to target matches."
5805 (when org-target-link-regexp
5806 (let ((case-fold-search t))
5807 (if (re-search-forward org-target-link-regexp limit t)
5808 (progn
5809 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5810 (add-text-properties (match-beginning 0) (match-end 0)
5811 (list 'mouse-face 'highlight
5812 'keymap org-mouse-map
5813 'help-echo "Radio target link"
5814 'org-linked-text t))
5815 (org-rear-nonsticky-at (match-end 0))
5816 t)))))
5818 (defun org-update-radio-target-regexp ()
5819 "Find all radio targets in this file and update the regular expression."
5820 (interactive)
5821 (when (memq 'radio org-activate-links)
5822 (setq org-target-link-regexp
5823 (org-make-target-link-regexp (org-all-targets 'radio)))
5824 (org-restart-font-lock)))
5826 (defun org-hide-wide-columns (limit)
5827 (let (s e)
5828 (setq s (text-property-any (point) (or limit (point-max))
5829 'org-cwidth t))
5830 (when s
5831 (setq e (next-single-property-change s 'org-cwidth))
5832 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5833 (goto-char e)
5834 t)))
5836 (defvar org-match-substring-regexp)
5837 (defvar org-match-substring-with-braces-regexp)
5839 (defun org-restart-font-lock ()
5840 "Restart `font-lock-mode', to force refontification."
5841 (when (and (boundp 'font-lock-mode) font-lock-mode)
5842 (font-lock-mode -1)
5843 (font-lock-mode 1)))
5845 (defun org-all-targets (&optional radio)
5846 "Return a list of all targets in this file.
5847 When optional argument RADIO is non-nil, only find radio
5848 targets."
5849 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5850 (save-excursion
5851 (goto-char (point-min))
5852 (while (re-search-forward re nil t)
5853 ;; Make sure point is really within the object.
5854 (backward-char)
5855 (let ((obj (org-element-context)))
5856 (when (memq (org-element-type obj) '(radio-target target))
5857 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5858 rtn)))
5860 (defun org-make-target-link-regexp (targets)
5861 "Make regular expression matching all strings in TARGETS.
5862 The regular expression finds the targets also if there is a line break
5863 between words."
5864 (and targets
5865 (concat
5866 "\\<\\("
5867 (mapconcat
5868 (lambda (x)
5869 (setq x (regexp-quote x))
5870 (while (string-match " +" x)
5871 (setq x (replace-match "\\s-+" t t x)))
5873 targets
5874 "\\|")
5875 "\\)\\>")))
5877 (defun org-activate-tags (limit)
5878 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5879 (progn
5880 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5881 (add-text-properties (match-beginning 1) (match-end 1)
5882 (list 'mouse-face 'highlight
5883 'keymap org-mouse-map))
5884 (org-rear-nonsticky-at (match-end 1))
5885 t)))
5887 (defun org-outline-level ()
5888 "Compute the outline level of the heading at point.
5889 If this is called at a normal headline, the level is the number of stars.
5890 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5891 (save-excursion
5892 (if (not (condition-case nil
5893 (org-back-to-heading t)
5894 (error nil)))
5896 (looking-at org-outline-regexp)
5897 (1- (- (match-end 0) (match-beginning 0))))))
5899 (defvar org-font-lock-keywords nil)
5901 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5902 "Regular expression matching a property line.")
5904 (defvar org-font-lock-hook nil
5905 "Functions to be called for special font lock stuff.")
5907 (defvar org-font-lock-set-keywords-hook nil
5908 "Functions that can manipulate `org-font-lock-extra-keywords'.
5909 This is called after `org-font-lock-extra-keywords' is defined, but before
5910 it is installed to be used by font lock. This can be useful if something
5911 needs to be inserted at a specific position in the font-lock sequence.")
5913 (defun org-font-lock-hook (limit)
5914 "Run `org-font-lock-hook' within LIMIT."
5915 (run-hook-with-args 'org-font-lock-hook limit))
5917 (defun org-set-font-lock-defaults ()
5918 "Set font lock defaults for the current buffer."
5919 (let* ((em org-fontify-emphasized-text)
5920 (lk org-activate-links)
5921 (org-font-lock-extra-keywords
5922 (list
5923 ;; Call the hook
5924 '(org-font-lock-hook)
5925 ;; Headlines
5926 `(,(if org-fontify-whole-heading-line
5927 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5928 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5929 (1 (org-get-level-face 1))
5930 (2 (org-get-level-face 2))
5931 (3 (org-get-level-face 3)))
5932 ;; Table lines
5933 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5934 (1 'org-table t))
5935 ;; Table internals
5936 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5937 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5938 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5939 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5940 ;; Drawers
5941 (list org-drawer-regexp '(0 'org-special-keyword t))
5942 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5943 ;; Properties
5944 (list org-property-re
5945 '(1 'org-special-keyword t)
5946 '(3 'org-property-value t))
5947 ;; Links
5948 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5949 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5950 (if (memq 'plain lk) '(org-activate-plain-links))
5951 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5952 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5953 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5954 (if (memq 'footnote lk) '(org-activate-footnote-links))
5955 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5956 '(org-hide-wide-columns (0 nil append))
5957 ;; TODO keyword
5958 (list (format org-heading-keyword-regexp-format
5959 org-todo-regexp)
5960 '(2 (org-get-todo-face 2) t))
5961 ;; DONE
5962 (if org-fontify-done-headline
5963 (list (format org-heading-keyword-regexp-format
5964 (concat
5965 "\\(?:"
5966 (mapconcat 'regexp-quote org-done-keywords "\\|")
5967 "\\)"))
5968 '(2 'org-headline-done t))
5969 nil)
5970 ;; Priorities
5971 '(org-font-lock-add-priority-faces)
5972 ;; Tags
5973 '(org-font-lock-add-tag-faces)
5974 ;; Special keywords
5975 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5976 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5977 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5978 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5979 ;; Emphasis
5980 (if em
5981 (if (featurep 'xemacs)
5982 '(org-do-emphasis-faces (0 nil append))
5983 '(org-do-emphasis-faces)))
5984 ;; Checkboxes
5985 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5986 1 'org-checkbox prepend)
5987 (if (cdr (assq 'checkbox org-list-automatic-rules))
5988 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5989 (0 (org-get-checkbox-statistics-face) t)))
5990 ;; Description list items
5991 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5992 1 'org-list-dt prepend)
5993 ;; ARCHIVEd headings
5994 (list (concat
5995 org-outline-regexp-bol
5996 "\\(.*:" org-archive-tag ":.*\\)")
5997 '(1 'org-archived prepend))
5998 ;; Specials
5999 '(org-fontify-entities)
6000 '(org-raise-scripts)
6001 ;; Code
6002 '(org-activate-code (1 'org-code t))
6003 ;; COMMENT
6004 (list (format org-heading-keyword-regexp-format
6005 (concat "\\("
6006 org-comment-string "\\|" org-quote-string
6007 "\\)"))
6008 '(2 'org-special-keyword t))
6009 ;; Blocks and meta lines
6010 '(org-fontify-meta-lines-and-blocks)
6012 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6013 (run-hooks 'org-font-lock-set-keywords-hook)
6014 ;; Now set the full font-lock-keywords
6015 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6016 (org-set-local 'font-lock-defaults
6017 '(org-font-lock-keywords t nil nil backward-paragraph))
6018 (kill-local-variable 'font-lock-keywords) nil))
6020 (defun org-toggle-pretty-entities ()
6021 "Toggle the composition display of entities as UTF8 characters."
6022 (interactive)
6023 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6024 (org-restart-font-lock)
6025 (if org-pretty-entities
6026 (message "Entities are displayed as UTF8 characters")
6027 (save-restriction
6028 (widen)
6029 (org-decompose-region (point-min) (point-max))
6030 (message "Entities are displayed plain"))))
6032 (defvar org-custom-properties-overlays nil
6033 "List of overlays used for custom properties.")
6034 (make-variable-buffer-local 'org-custom-properties-overlays)
6036 (defun org-toggle-custom-properties-visibility ()
6037 "Display or hide properties in `org-custom-properties'."
6038 (interactive)
6039 (if org-custom-properties-overlays
6040 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6041 (setq org-custom-properties-overlays nil))
6042 (unless (not org-custom-properties)
6043 (save-excursion
6044 (save-restriction
6045 (widen)
6046 (goto-char (point-min))
6047 (while (re-search-forward org-property-re nil t)
6048 (mapc (lambda(p)
6049 (when (equal p (substring (match-string 1) 1 -1))
6050 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6051 (overlay-put o 'invisible t)
6052 (overlay-put o 'org-custom-property t)
6053 (push o org-custom-properties-overlays))))
6054 org-custom-properties)))))))
6056 (defun org-fontify-entities (limit)
6057 "Find an entity to fontify."
6058 (let (ee)
6059 (when org-pretty-entities
6060 (catch 'match
6061 (while (re-search-forward
6062 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6063 limit t)
6064 (if (and (not (org-in-indented-comment-line))
6065 (setq ee (org-entity-get (match-string 1)))
6066 (= (length (nth 6 ee)) 1))
6067 (let*
6068 ((end (if (equal (match-string 2) "{}")
6069 (match-end 2)
6070 (match-end 1))))
6071 (add-text-properties
6072 (match-beginning 0) end
6073 (list 'font-lock-fontified t))
6074 (compose-region (match-beginning 0) end
6075 (nth 6 ee) nil)
6076 (backward-char 1)
6077 (throw 'match t))))
6078 nil))))
6080 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6081 "Fontify string S like in Org-mode."
6082 (with-temp-buffer
6083 (insert s)
6084 (let ((org-odd-levels-only odd-levels))
6085 (org-mode)
6086 (font-lock-fontify-buffer)
6087 (buffer-string))))
6089 (defvar org-m nil)
6090 (defvar org-l nil)
6091 (defvar org-f nil)
6092 (defun org-get-level-face (n)
6093 "Get the right face for match N in font-lock matching of headlines."
6094 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6095 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6096 (if org-cycle-level-faces
6097 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6098 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6099 (cond
6100 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6101 ((eq n 2) org-f)
6102 (t (if org-level-color-stars-only nil org-f))))
6105 (defun org-get-todo-face (kwd)
6106 "Get the right face for a TODO keyword KWD.
6107 If KWD is a number, get the corresponding match group."
6108 (if (numberp kwd) (setq kwd (match-string kwd)))
6109 (or (org-face-from-face-or-color
6110 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6111 (and (member kwd org-done-keywords) 'org-done)
6112 'org-todo))
6114 (defun org-face-from-face-or-color (context inherit face-or-color)
6115 "Create a face list that inherits INHERIT, but sets the foreground color.
6116 When FACE-OR-COLOR is not a string, just return it."
6117 (if (stringp face-or-color)
6118 (list :inherit inherit
6119 (cdr (assoc context org-faces-easy-properties))
6120 face-or-color)
6121 face-or-color))
6123 (defun org-font-lock-add-tag-faces (limit)
6124 "Add the special tag faces."
6125 (when (and org-tag-faces org-tags-special-faces-re)
6126 (while (re-search-forward org-tags-special-faces-re limit t)
6127 (add-text-properties (match-beginning 1) (match-end 1)
6128 (list 'face (org-get-tag-face 1)
6129 'font-lock-fontified t))
6130 (backward-char 1))))
6132 (defun org-font-lock-add-priority-faces (limit)
6133 "Add the special priority faces."
6134 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6135 (when (save-match-data (org-at-heading-p))
6136 (add-text-properties
6137 (match-beginning 0) (match-end 0)
6138 (list 'face (or (org-face-from-face-or-color
6139 'priority 'org-priority
6140 (cdr (assoc (char-after (match-beginning 1))
6141 org-priority-faces)))
6142 'org-priority)
6143 'font-lock-fontified t)))))
6145 (defun org-get-tag-face (kwd)
6146 "Get the right face for a TODO keyword KWD.
6147 If KWD is a number, get the corresponding match group."
6148 (if (numberp kwd) (setq kwd (match-string kwd)))
6149 (or (org-face-from-face-or-color
6150 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6151 'org-tag))
6153 (defun org-unfontify-region (beg end &optional maybe_loudly)
6154 "Remove fontification and activation overlays from links."
6155 (font-lock-default-unfontify-region beg end)
6156 (let* ((buffer-undo-list t)
6157 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6158 (inhibit-modification-hooks t)
6159 deactivate-mark buffer-file-name buffer-file-truename)
6160 (org-decompose-region beg end)
6161 (remove-text-properties beg end
6162 '(mouse-face t keymap t org-linked-text t
6163 invisible t intangible t
6164 org-no-flyspell t org-emphasis t))
6165 (org-remove-font-lock-display-properties beg end)))
6167 (defconst org-script-display '(((raise -0.3) (height 0.7))
6168 ((raise 0.3) (height 0.7))
6169 ((raise -0.5))
6170 ((raise 0.5)))
6171 "Display properties for showing superscripts and subscripts.")
6173 (defun org-remove-font-lock-display-properties (beg end)
6174 "Remove specific display properties that have been added by font lock.
6175 The will remove the raise properties that are used to show superscripts
6176 and subscripts."
6177 (let (next prop)
6178 (while (< beg end)
6179 (setq next (next-single-property-change beg 'display nil end)
6180 prop (get-text-property beg 'display))
6181 (if (member prop org-script-display)
6182 (put-text-property beg next 'display nil))
6183 (setq beg next))))
6185 (defun org-raise-scripts (limit)
6186 "Add raise properties to sub/superscripts."
6187 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6188 (if (re-search-forward
6189 (if (eq org-use-sub-superscripts t)
6190 org-match-substring-regexp
6191 org-match-substring-with-braces-regexp)
6192 limit t)
6193 (let* ((pos (point)) table-p comment-p
6194 (mpos (match-beginning 3))
6195 (emph-p (get-text-property mpos 'org-emphasis))
6196 (link-p (get-text-property mpos 'mouse-face))
6197 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6198 (goto-char (point-at-bol))
6199 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6200 comment-p (org-looking-at-p "[ \t]*#"))
6201 (goto-char pos)
6202 ;; FIXME: Should we go back one character here, for a_b^c
6203 ;; (goto-char (1- pos)) ;????????????????????
6204 (if (or comment-p emph-p link-p keyw-p)
6206 (put-text-property (match-beginning 3) (match-end 0)
6207 'display
6208 (if (equal (char-after (match-beginning 2)) ?^)
6209 (nth (if table-p 3 1) org-script-display)
6210 (nth (if table-p 2 0) org-script-display)))
6211 (add-text-properties (match-beginning 2) (match-end 2)
6212 (list 'invisible t
6213 'org-dwidth t 'org-dwidth-n 1))
6214 (if (and (eq (char-after (match-beginning 3)) ?{)
6215 (eq (char-before (match-end 3)) ?}))
6216 (progn
6217 (add-text-properties
6218 (match-beginning 3) (1+ (match-beginning 3))
6219 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6220 (add-text-properties
6221 (1- (match-end 3)) (match-end 3)
6222 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6223 t)))))
6225 ;;;; Visibility cycling, including org-goto and indirect buffer
6227 ;;; Cycling
6229 (defvar org-cycle-global-status nil)
6230 (make-variable-buffer-local 'org-cycle-global-status)
6231 (put 'org-cycle-global-status 'org-state t)
6232 (defvar org-cycle-subtree-status nil)
6233 (make-variable-buffer-local 'org-cycle-subtree-status)
6234 (put 'org-cycle-subtree-status 'org-state t)
6236 (defvar org-inlinetask-min-level)
6238 ;;;###autoload
6239 (defun org-cycle (&optional arg)
6240 "TAB-action and visibility cycling for Org-mode.
6242 This is the command invoked in Org-mode by the TAB key. Its main purpose
6243 is outline visibility cycling, but it also invokes other actions
6244 in special contexts.
6246 - When this function is called with a prefix argument, rotate the entire
6247 buffer through 3 states (global cycling)
6248 1. OVERVIEW: Show only top-level headlines.
6249 2. CONTENTS: Show all headlines of all levels, but no body text.
6250 3. SHOW ALL: Show everything.
6251 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6252 determined by the variable `org-startup-folded', and by any VISIBILITY
6253 properties in the buffer.
6254 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6255 including any drawers.
6257 - When inside a table, re-align the table and move to the next field.
6259 - When point is at the beginning of a headline, rotate the subtree started
6260 by this line through 3 different states (local cycling)
6261 1. FOLDED: Only the main headline is shown.
6262 2. CHILDREN: The main headline and the direct children are shown.
6263 From this state, you can move to one of the children
6264 and zoom in further.
6265 3. SUBTREE: Show the entire subtree, including body text.
6266 If there is no subtree, switch directly from CHILDREN to FOLDED.
6268 - When point is at the beginning of an empty headline and the variable
6269 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6270 of the headline by demoting and promoting it to likely levels. This
6271 speeds up creation document structure by pressing TAB once or several
6272 times right after creating a new headline.
6274 - When there is a numeric prefix, go up to a heading with level ARG, do
6275 a `show-subtree' and return to the previous cursor position. If ARG
6276 is negative, go up that many levels.
6278 - When point is not at the beginning of a headline, execute the global
6279 binding for TAB, which is re-indenting the line. See the option
6280 `org-cycle-emulate-tab' for details.
6282 - Special case: if point is at the beginning of the buffer and there is
6283 no headline in line 1, this function will act as if called with prefix arg
6284 (C-u TAB, same as S-TAB) also when called without prefix arg.
6285 But only if also the variable `org-cycle-global-at-bob' is t."
6286 (interactive "P")
6287 (org-load-modules-maybe)
6288 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6289 (and org-cycle-level-after-item/entry-creation
6290 (or (org-cycle-level)
6291 (org-cycle-item-indentation))))
6292 (let* (message-log-max ; Don't populate the *Messages* buffer
6293 (limit-level
6294 (or org-cycle-max-level
6295 (and (boundp 'org-inlinetask-min-level)
6296 org-inlinetask-min-level
6297 (1- org-inlinetask-min-level))))
6298 (nstars (and limit-level
6299 (if org-odd-levels-only
6300 (and limit-level (1- (* limit-level 2)))
6301 limit-level)))
6302 (org-outline-regexp
6303 (if (not (derived-mode-p 'org-mode))
6304 outline-regexp
6305 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6306 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6307 (not (looking-at org-outline-regexp))))
6308 (org-cycle-hook
6309 (if bob-special
6310 (delq 'org-optimize-window-after-visibility-change
6311 (copy-sequence org-cycle-hook))
6312 org-cycle-hook))
6313 (pos (point)))
6315 (if (or bob-special (equal arg '(4)))
6316 ;; special case: use global cycling
6317 (setq arg t))
6319 (cond
6321 ((equal arg '(16))
6322 (setq last-command 'dummy)
6323 (org-set-startup-visibility)
6324 (message "Startup visibility, plus VISIBILITY properties"))
6326 ((equal arg '(64))
6327 (show-all)
6328 (message "Entire buffer visible, including drawers"))
6330 ;; Table: enter it or move to the next field.
6331 ((org-at-table-p 'any)
6332 (if (org-at-table.el-p)
6333 (message "Use C-c ' to edit table.el tables")
6334 (if arg (org-table-edit-field t)
6335 (org-table-justify-field-maybe)
6336 (call-interactively 'org-table-next-field))))
6338 ((run-hook-with-args-until-success
6339 'org-tab-after-check-for-table-hook))
6341 ;; Global cycling: delegate to `org-cycle-internal-global'.
6342 ((eq arg t) (org-cycle-internal-global))
6344 ;; Drawers: delegate to `org-flag-drawer'.
6345 ((and org-drawers org-drawer-regexp
6346 (save-excursion
6347 (beginning-of-line 1)
6348 (looking-at org-drawer-regexp)))
6349 (org-flag-drawer ; toggle block visibility
6350 (not (get-char-property (match-end 0) 'invisible))))
6352 ;; Show-subtree, ARG levels up from here.
6353 ((integerp arg)
6354 (save-excursion
6355 (org-back-to-heading)
6356 (outline-up-heading (if (< arg 0) (- arg)
6357 (- (funcall outline-level) arg)))
6358 (org-show-subtree)))
6360 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6361 ((and (featurep 'org-inlinetask)
6362 (org-inlinetask-at-task-p)
6363 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6364 (org-inlinetask-toggle-visibility))
6366 ((org-try-cdlatex-tab))
6368 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6369 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6370 (save-excursion (beginning-of-line 1)
6371 (looking-at org-outline-regexp)))
6372 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6373 (org-cycle-internal-local))
6375 ;; From there: TAB emulation and template completion.
6376 (buffer-read-only (org-back-to-heading))
6378 ((run-hook-with-args-until-success
6379 'org-tab-after-check-for-cycling-hook))
6381 ((org-try-structure-completion))
6383 ((run-hook-with-args-until-success
6384 'org-tab-before-tab-emulation-hook))
6386 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6387 (or (not (bolp))
6388 (not (looking-at org-outline-regexp))))
6389 (call-interactively (global-key-binding "\t")))
6391 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6392 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6393 (or (and (eq org-cycle-emulate-tab 'white)
6394 (= (match-end 0) (point-at-eol)))
6395 (and (eq org-cycle-emulate-tab 'whitestart)
6396 (>= (match-end 0) pos))))
6398 (eq org-cycle-emulate-tab t))
6399 (call-interactively (global-key-binding "\t")))
6401 (t (save-excursion
6402 (org-back-to-heading)
6403 (org-cycle)))))))
6405 (defun org-cycle-internal-global ()
6406 "Do the global cycling action."
6407 ;; Hack to avoid display of messages for .org attachments in Gnus
6408 (let (message-log-max ; Don't populate the *Messages* buffer
6409 (ga (string-match "\\*fontification" (buffer-name))))
6410 (cond
6411 ((and (eq last-command this-command)
6412 (eq org-cycle-global-status 'overview))
6413 ;; We just created the overview - now do table of contents
6414 ;; This can be slow in very large buffers, so indicate action
6415 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6416 (unless ga (message "CONTENTS..."))
6417 (org-content)
6418 (unless ga (message "CONTENTS...done"))
6419 (setq org-cycle-global-status 'contents)
6420 (run-hook-with-args 'org-cycle-hook 'contents))
6422 ((and (eq last-command this-command)
6423 (eq org-cycle-global-status 'contents))
6424 ;; We just showed the table of contents - now show everything
6425 (run-hook-with-args 'org-pre-cycle-hook 'all)
6426 (show-all)
6427 (unless ga (message "SHOW ALL"))
6428 (setq org-cycle-global-status 'all)
6429 (run-hook-with-args 'org-cycle-hook 'all))
6432 ;; Default action: go to overview
6433 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6434 (org-overview)
6435 (unless ga (message "OVERVIEW"))
6436 (setq org-cycle-global-status 'overview)
6437 (run-hook-with-args 'org-cycle-hook 'overview)))))
6439 (defun org-cycle-internal-local ()
6440 "Do the local cycling action."
6441 (let (message-log-max ; Don't populate the *Messages* buffer
6442 (goal-column 0) eoh eol eos has-children children-skipped struct)
6443 ;; First, determine end of headline (EOH), end of subtree or item
6444 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6445 (save-excursion
6446 (if (org-at-item-p)
6447 (progn
6448 (beginning-of-line)
6449 (setq struct (org-list-struct))
6450 (setq eoh (point-at-eol))
6451 (setq eos (org-list-get-item-end-before-blank (point) struct))
6452 (setq has-children (org-list-has-child-p (point) struct)))
6453 (org-back-to-heading)
6454 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6455 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6456 (setq has-children
6457 (or (save-excursion
6458 (let ((level (funcall outline-level)))
6459 (outline-next-heading)
6460 (and (org-at-heading-p t)
6461 (> (funcall outline-level) level))))
6462 (save-excursion
6463 (org-list-search-forward (org-item-beginning-re) eos t)))))
6464 ;; Determine end invisible part of buffer (EOL)
6465 (beginning-of-line 2)
6466 ;; XEmacs doesn't have `next-single-char-property-change'
6467 (if (featurep 'xemacs)
6468 (while (and (not (eobp)) ;; this is like `next-line'
6469 (get-char-property (1- (point)) 'invisible))
6470 (beginning-of-line 2))
6471 (while (and (not (eobp)) ;; this is like `next-line'
6472 (get-char-property (1- (point)) 'invisible))
6473 (goto-char (next-single-char-property-change (point) 'invisible))
6474 (and (eolp) (beginning-of-line 2))))
6475 (setq eol (point)))
6476 ;; Find out what to do next and set `this-command'
6477 (cond
6478 ((= eos eoh)
6479 ;; Nothing is hidden behind this heading
6480 (unless (org-before-first-heading-p)
6481 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6482 (message "EMPTY ENTRY")
6483 (setq org-cycle-subtree-status nil)
6484 (save-excursion
6485 (goto-char eos)
6486 (outline-next-heading)
6487 (if (outline-invisible-p) (org-flag-heading nil))))
6488 ((and (or (>= eol eos)
6489 (not (string-match "\\S-" (buffer-substring eol eos))))
6490 (or has-children
6491 (not (setq children-skipped
6492 org-cycle-skip-children-state-if-no-children))))
6493 ;; Entire subtree is hidden in one line: children view
6494 (unless (org-before-first-heading-p)
6495 (run-hook-with-args 'org-pre-cycle-hook 'children))
6496 (if (org-at-item-p)
6497 (org-list-set-item-visibility (point-at-bol) struct 'children)
6498 (org-show-entry)
6499 (org-with-limited-levels (show-children))
6500 ;; FIXME: This slows down the func way too much.
6501 ;; How keep drawers hidden in subtree anyway?
6502 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6503 ;; (org-cycle-hide-drawers 'subtree))
6505 ;; Fold every list in subtree to top-level items.
6506 (when (eq org-cycle-include-plain-lists 'integrate)
6507 (save-excursion
6508 (org-back-to-heading)
6509 (while (org-list-search-forward (org-item-beginning-re) eos t)
6510 (beginning-of-line 1)
6511 (let* ((struct (org-list-struct))
6512 (prevs (org-list-prevs-alist struct))
6513 (end (org-list-get-bottom-point struct)))
6514 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6515 (org-list-get-all-items (point) struct prevs))
6516 (goto-char end))))))
6517 (message "CHILDREN")
6518 (save-excursion
6519 (goto-char eos)
6520 (outline-next-heading)
6521 (if (outline-invisible-p) (org-flag-heading nil)))
6522 (setq org-cycle-subtree-status 'children)
6523 (unless (org-before-first-heading-p)
6524 (run-hook-with-args 'org-cycle-hook 'children)))
6525 ((or children-skipped
6526 (and (eq last-command this-command)
6527 (eq org-cycle-subtree-status 'children)))
6528 ;; We just showed the children, or no children are there,
6529 ;; now show everything.
6530 (unless (org-before-first-heading-p)
6531 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6532 (outline-flag-region eoh eos nil)
6533 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6534 (setq org-cycle-subtree-status 'subtree)
6535 (unless (org-before-first-heading-p)
6536 (run-hook-with-args 'org-cycle-hook 'subtree)))
6538 ;; Default action: hide the subtree.
6539 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6540 (outline-flag-region eoh eos t)
6541 (message "FOLDED")
6542 (setq org-cycle-subtree-status 'folded)
6543 (unless (org-before-first-heading-p)
6544 (run-hook-with-args 'org-cycle-hook 'folded))))))
6546 ;;;###autoload
6547 (defun org-global-cycle (&optional arg)
6548 "Cycle the global visibility. For details see `org-cycle'.
6549 With \\[universal-argument] prefix arg, switch to startup visibility.
6550 With a numeric prefix, show all headlines up to that level."
6551 (interactive "P")
6552 (let ((org-cycle-include-plain-lists
6553 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6554 (cond
6555 ((integerp arg)
6556 (show-all)
6557 (hide-sublevels arg)
6558 (setq org-cycle-global-status 'contents))
6559 ((equal arg '(4))
6560 (org-set-startup-visibility)
6561 (message "Startup visibility, plus VISIBILITY properties."))
6563 (org-cycle '(4))))))
6565 (defun org-set-startup-visibility ()
6566 "Set the visibility required by startup options and properties."
6567 (cond
6568 ((eq org-startup-folded t)
6569 (org-cycle '(4)))
6570 ((eq org-startup-folded 'content)
6571 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6572 (org-cycle '(4)) (org-cycle '(4)))))
6573 (unless (eq org-startup-folded 'showeverything)
6574 (if org-hide-block-startup (org-hide-block-all))
6575 (org-set-visibility-according-to-property 'no-cleanup)
6576 (org-cycle-hide-archived-subtrees 'all)
6577 (org-cycle-hide-drawers 'all)
6578 (org-cycle-show-empty-lines t)))
6580 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6581 "Switch subtree visibilities according to :VISIBILITY: property."
6582 (interactive)
6583 (let (org-show-entry-below state)
6584 (save-excursion
6585 (goto-char (point-min))
6586 (while (re-search-forward
6587 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6588 nil t)
6589 (setq state (match-string 1))
6590 (save-excursion
6591 (org-back-to-heading t)
6592 (hide-subtree)
6593 (org-reveal)
6594 (cond
6595 ((equal state '("fold" "folded"))
6596 (hide-subtree))
6597 ((equal state "children")
6598 (org-show-hidden-entry)
6599 (show-children))
6600 ((equal state "content")
6601 (save-excursion
6602 (save-restriction
6603 (org-narrow-to-subtree)
6604 (org-content))))
6605 ((member state '("all" "showall"))
6606 (show-subtree)))))
6607 (unless no-cleanup
6608 (org-cycle-hide-archived-subtrees 'all)
6609 (org-cycle-hide-drawers 'all)
6610 (org-cycle-show-empty-lines 'all)))))
6612 ;; This function uses outline-regexp instead of the more fundamental
6613 ;; org-outline-regexp so that org-cycle-global works outside of Org
6614 ;; buffers, where outline-regexp is needed.
6615 (defun org-overview ()
6616 "Switch to overview mode, showing only top-level headlines.
6617 Really, this shows all headlines with level equal or greater than the level
6618 of the first headline in the buffer. This is important, because if the
6619 first headline is not level one, then (hide-sublevels 1) gives confusing
6620 results."
6621 (interactive)
6622 (let ((level (save-excursion
6623 (goto-char (point-min))
6624 (if (re-search-forward (concat "^" outline-regexp) nil t)
6625 (progn
6626 (goto-char (match-beginning 0))
6627 (funcall outline-level))))))
6628 (and level (hide-sublevels level))))
6630 (defun org-content (&optional arg)
6631 "Show all headlines in the buffer, like a table of contents.
6632 With numerical argument N, show content up to level N."
6633 (interactive "P")
6634 (save-excursion
6635 ;; Visit all headings and show their offspring
6636 (and (integerp arg) (org-overview))
6637 (goto-char (point-max))
6638 (catch 'exit
6639 (while (and (progn (condition-case nil
6640 (outline-previous-visible-heading 1)
6641 (error (goto-char (point-min))))
6643 (looking-at org-outline-regexp))
6644 (if (integerp arg)
6645 (show-children (1- arg))
6646 (show-branches))
6647 (if (bobp) (throw 'exit nil))))))
6650 (defun org-optimize-window-after-visibility-change (state)
6651 "Adjust the window after a change in outline visibility.
6652 This function is the default value of the hook `org-cycle-hook'."
6653 (when (get-buffer-window (current-buffer))
6654 (cond
6655 ((eq state 'content) nil)
6656 ((eq state 'all) nil)
6657 ((eq state 'folded) nil)
6658 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6659 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6661 (defun org-remove-empty-overlays-at (pos)
6662 "Remove outline overlays that do not contain non-white stuff."
6663 (mapc
6664 (lambda (o)
6665 (and (eq 'outline (overlay-get o 'invisible))
6666 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6667 (overlay-end o))))
6668 (delete-overlay o)))
6669 (overlays-at pos)))
6671 (defun org-clean-visibility-after-subtree-move ()
6672 "Fix visibility issues after moving a subtree."
6673 ;; First, find a reasonable region to look at:
6674 ;; Start two siblings above, end three below
6675 (let* ((beg (save-excursion
6676 (and (org-get-last-sibling)
6677 (org-get-last-sibling))
6678 (point)))
6679 (end (save-excursion
6680 (and (org-get-next-sibling)
6681 (org-get-next-sibling)
6682 (org-get-next-sibling))
6683 (if (org-at-heading-p)
6684 (point-at-eol)
6685 (point))))
6686 (level (looking-at "\\*+"))
6687 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6688 (save-excursion
6689 (save-restriction
6690 (narrow-to-region beg end)
6691 (when re
6692 ;; Properly fold already folded siblings
6693 (goto-char (point-min))
6694 (while (re-search-forward re nil t)
6695 (if (and (not (outline-invisible-p))
6696 (save-excursion
6697 (goto-char (point-at-eol)) (outline-invisible-p)))
6698 (hide-entry))))
6699 (org-cycle-show-empty-lines 'overview)
6700 (org-cycle-hide-drawers 'overview)))))
6702 (defun org-cycle-show-empty-lines (state)
6703 "Show empty lines above all visible headlines.
6704 The region to be covered depends on STATE when called through
6705 `org-cycle-hook'. Lisp program can use t for STATE to get the
6706 entire buffer covered. Note that an empty line is only shown if there
6707 are at least `org-cycle-separator-lines' empty lines before the headline."
6708 (when (not (= org-cycle-separator-lines 0))
6709 (save-excursion
6710 (let* ((n (abs org-cycle-separator-lines))
6711 (re (cond
6712 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6713 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6714 (t (let ((ns (number-to-string (- n 2))))
6715 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6716 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6717 beg end b e)
6718 (cond
6719 ((memq state '(overview contents t))
6720 (setq beg (point-min) end (point-max)))
6721 ((memq state '(children folded))
6722 (setq beg (point) end (progn (org-end-of-subtree t t)
6723 (beginning-of-line 2)
6724 (point)))))
6725 (when beg
6726 (goto-char beg)
6727 (while (re-search-forward re end t)
6728 (unless (get-char-property (match-end 1) 'invisible)
6729 (setq e (match-end 1))
6730 (if (< org-cycle-separator-lines 0)
6731 (setq b (save-excursion
6732 (goto-char (match-beginning 0))
6733 (org-back-over-empty-lines)
6734 (if (save-excursion
6735 (goto-char (max (point-min) (1- (point))))
6736 (org-at-heading-p))
6737 (1- (point))
6738 (point))))
6739 (setq b (match-beginning 1)))
6740 (outline-flag-region b e nil)))))))
6741 ;; Never hide empty lines at the end of the file.
6742 (save-excursion
6743 (goto-char (point-max))
6744 (outline-previous-heading)
6745 (outline-end-of-heading)
6746 (if (and (looking-at "[ \t\n]+")
6747 (= (match-end 0) (point-max)))
6748 (outline-flag-region (point) (match-end 0) nil))))
6750 (defun org-show-empty-lines-in-parent ()
6751 "Move to the parent and re-show empty lines before visible headlines."
6752 (save-excursion
6753 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6754 (org-cycle-show-empty-lines context))))
6756 (defun org-files-list ()
6757 "Return `org-agenda-files' list, plus all open org-mode files.
6758 This is useful for operations that need to scan all of a user's
6759 open and agenda-wise Org files."
6760 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6761 (dolist (buf (buffer-list))
6762 (with-current-buffer buf
6763 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6764 (let ((file (expand-file-name (buffer-file-name))))
6765 (unless (member file files)
6766 (push file files))))))
6767 files))
6769 (defsubst org-entry-beginning-position ()
6770 "Return the beginning position of the current entry."
6771 (save-excursion (outline-back-to-heading t) (point)))
6773 (defsubst org-entry-end-position ()
6774 "Return the end position of the current entry."
6775 (save-excursion (outline-next-heading) (point)))
6777 (defun org-cycle-hide-drawers (state)
6778 "Re-hide all drawers after a visibility state change."
6779 (when (and (derived-mode-p 'org-mode)
6780 (not (memq state '(overview folded contents))))
6781 (save-excursion
6782 (let* ((globalp (memq state '(contents all)))
6783 (beg (if globalp (point-min) (point)))
6784 (end (if globalp (point-max)
6785 (if (eq state 'children)
6786 (save-excursion (outline-next-heading) (point))
6787 (org-end-of-subtree t)))))
6788 (goto-char beg)
6789 (while (re-search-forward org-drawer-regexp end t)
6790 (org-flag-drawer t))))))
6792 (defun org-cycle-hide-inline-tasks (state)
6793 "Re-hide inline task when switching to 'contents visibility state."
6794 (when (and (eq state 'contents)
6795 (boundp 'org-inlinetask-min-level)
6796 org-inlinetask-min-level)
6797 (hide-sublevels (1- org-inlinetask-min-level))))
6799 (defun org-flag-drawer (flag)
6800 "When FLAG is non-nil, hide the drawer we are within.
6801 Otherwise make it visible."
6802 (save-excursion
6803 (beginning-of-line 1)
6804 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6805 (let ((b (match-end 0)))
6806 (if (re-search-forward
6807 "^[ \t]*:END:"
6808 (save-excursion (outline-next-heading) (point)) t)
6809 (outline-flag-region b (point-at-eol) flag)
6810 (error ":END: line missing at position %s" b))))))
6812 (defun org-subtree-end-visible-p ()
6813 "Is the end of the current subtree visible?"
6814 (pos-visible-in-window-p
6815 (save-excursion (org-end-of-subtree t) (point))))
6817 (defun org-first-headline-recenter (&optional N)
6818 "Move cursor to the first headline and recenter the headline.
6819 Optional argument N means put the headline into the Nth line of the window."
6820 (goto-char (point-min))
6821 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6822 (beginning-of-line)
6823 (recenter (prefix-numeric-value N))))
6825 ;;; Saving and restoring visibility
6827 (defun org-outline-overlay-data (&optional use-markers)
6828 "Return a list of the locations of all outline overlays.
6829 These are overlays with the `invisible' property value `outline'.
6830 The return value is a list of cons cells, with start and stop
6831 positions for each overlay.
6832 If USE-MARKERS is set, return the positions as markers."
6833 (let (beg end)
6834 (save-excursion
6835 (save-restriction
6836 (widen)
6837 (delq nil
6838 (mapcar (lambda (o)
6839 (when (eq (overlay-get o 'invisible) 'outline)
6840 (setq beg (overlay-start o)
6841 end (overlay-end o))
6842 (and beg end (> end beg)
6843 (if use-markers
6844 (cons (move-marker (make-marker) beg)
6845 (move-marker (make-marker) end))
6846 (cons beg end)))))
6847 (overlays-in (point-min) (point-max))))))))
6849 (defun org-set-outline-overlay-data (data)
6850 "Create visibility overlays for all positions in DATA.
6851 DATA should have been made by `org-outline-overlay-data'."
6852 (let (o)
6853 (save-excursion
6854 (save-restriction
6855 (widen)
6856 (show-all)
6857 (mapc (lambda (c)
6858 (outline-flag-region (car c) (cdr c) t))
6859 data)))))
6861 ;;; Folding of blocks
6863 (defvar org-hide-block-overlays nil
6864 "Overlays hiding blocks.")
6865 (make-variable-buffer-local 'org-hide-block-overlays)
6867 (defun org-block-map (function &optional start end)
6868 "Call FUNCTION at the head of all source blocks in the current buffer.
6869 Optional arguments START and END can be used to limit the range."
6870 (let ((start (or start (point-min)))
6871 (end (or end (point-max))))
6872 (save-excursion
6873 (goto-char start)
6874 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6875 (save-excursion
6876 (save-match-data
6877 (goto-char (match-beginning 0))
6878 (funcall function)))))))
6880 (defun org-hide-block-toggle-all ()
6881 "Toggle the visibility of all blocks in the current buffer."
6882 (org-block-map #'org-hide-block-toggle))
6884 (defun org-hide-block-all ()
6885 "Fold all blocks in the current buffer."
6886 (interactive)
6887 (org-show-block-all)
6888 (org-block-map #'org-hide-block-toggle-maybe))
6890 (defun org-show-block-all ()
6891 "Unfold all blocks in the current buffer."
6892 (interactive)
6893 (mapc 'delete-overlay org-hide-block-overlays)
6894 (setq org-hide-block-overlays nil))
6896 (defun org-hide-block-toggle-maybe ()
6897 "Toggle visibility of block at point."
6898 (interactive)
6899 (let ((case-fold-search t))
6900 (if (save-excursion
6901 (beginning-of-line 1)
6902 (looking-at org-block-regexp))
6903 (progn (org-hide-block-toggle)
6904 t) ;; to signal that we took action
6905 nil))) ;; to signal that we did not
6907 (defun org-hide-block-toggle (&optional force)
6908 "Toggle the visibility of the current block."
6909 (interactive)
6910 (save-excursion
6911 (beginning-of-line)
6912 (if (re-search-forward org-block-regexp nil t)
6913 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6914 (end (match-end 0)) ;; end of entire body
6916 (if (memq t (mapcar (lambda (overlay)
6917 (eq (overlay-get overlay 'invisible)
6918 'org-hide-block))
6919 (overlays-at start)))
6920 (if (or (not force) (eq force 'off))
6921 (mapc (lambda (ov)
6922 (when (member ov org-hide-block-overlays)
6923 (setq org-hide-block-overlays
6924 (delq ov org-hide-block-overlays)))
6925 (when (eq (overlay-get ov 'invisible)
6926 'org-hide-block)
6927 (delete-overlay ov)))
6928 (overlays-at start)))
6929 (setq ov (make-overlay start end))
6930 (overlay-put ov 'invisible 'org-hide-block)
6931 ;; make the block accessible to isearch
6932 (overlay-put
6933 ov 'isearch-open-invisible
6934 (lambda (ov)
6935 (when (member ov org-hide-block-overlays)
6936 (setq org-hide-block-overlays
6937 (delq ov org-hide-block-overlays)))
6938 (when (eq (overlay-get ov 'invisible)
6939 'org-hide-block)
6940 (delete-overlay ov))))
6941 (push ov org-hide-block-overlays)))
6942 (error "Not looking at a source block"))))
6944 ;; org-tab-after-check-for-cycling-hook
6945 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6946 ;; Remove overlays when changing major mode
6947 (add-hook 'org-mode-hook
6948 (lambda () (org-add-hook 'change-major-mode-hook
6949 'org-show-block-all 'append 'local)))
6951 ;;; Org-goto
6953 (defvar org-goto-window-configuration nil)
6954 (defvar org-goto-marker nil)
6955 (defvar org-goto-map)
6956 (defun org-goto-map ()
6957 "Set the keymap `org-goto'."
6958 (setq org-goto-map
6959 (let ((map (make-sparse-keymap)))
6960 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6961 mouse-drag-region universal-argument org-occur))
6962 cmd)
6963 (while (setq cmd (pop cmds))
6964 (substitute-key-definition cmd cmd map global-map)))
6965 (suppress-keymap map)
6966 (org-defkey map "\C-m" 'org-goto-ret)
6967 (org-defkey map [(return)] 'org-goto-ret)
6968 (org-defkey map [(left)] 'org-goto-left)
6969 (org-defkey map [(right)] 'org-goto-right)
6970 (org-defkey map [(control ?g)] 'org-goto-quit)
6971 (org-defkey map "\C-i" 'org-cycle)
6972 (org-defkey map [(tab)] 'org-cycle)
6973 (org-defkey map [(down)] 'outline-next-visible-heading)
6974 (org-defkey map [(up)] 'outline-previous-visible-heading)
6975 (if org-goto-auto-isearch
6976 (if (fboundp 'define-key-after)
6977 (define-key-after map [t] 'org-goto-local-auto-isearch)
6978 nil)
6979 (org-defkey map "q" 'org-goto-quit)
6980 (org-defkey map "n" 'outline-next-visible-heading)
6981 (org-defkey map "p" 'outline-previous-visible-heading)
6982 (org-defkey map "f" 'outline-forward-same-level)
6983 (org-defkey map "b" 'outline-backward-same-level)
6984 (org-defkey map "u" 'outline-up-heading))
6985 (org-defkey map "/" 'org-occur)
6986 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6987 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6988 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6989 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6990 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6991 map)))
6993 (defconst org-goto-help
6994 "Browse buffer copy, to find location or copy text.%s
6995 RET=jump to location C-g=quit and return to previous location
6996 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6998 (defvar org-goto-start-pos) ; dynamically scoped parameter
7000 ;; FIXME: Docstring does not mention both interfaces
7001 (defun org-goto (&optional alternative-interface)
7002 "Look up a different location in the current file, keeping current visibility.
7004 When you want look-up or go to a different location in a
7005 document, the fastest way is often to fold the entire buffer and
7006 then dive into the tree. This method has the disadvantage, that
7007 the previous location will be folded, which may not be what you
7008 want.
7010 This command works around this by showing a copy of the current
7011 buffer in an indirect buffer, in overview mode. You can dive
7012 into the tree in that copy, use org-occur and incremental search
7013 to find a location. When pressing RET or `Q', the command
7014 returns to the original buffer in which the visibility is still
7015 unchanged. After RET it will also jump to the location selected
7016 in the indirect buffer and expose the headline hierarchy above.
7018 With a prefix argument, use the alternative interface: e.g. if
7019 `org-goto-interface' is 'outline use 'outline-path-completion."
7020 (interactive "P")
7021 (org-goto-map)
7022 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7023 (org-refile-use-outline-path t)
7024 (org-refile-target-verify-function nil)
7025 (interface
7026 (if (not alternative-interface)
7027 org-goto-interface
7028 (if (eq org-goto-interface 'outline)
7029 'outline-path-completion
7030 'outline)))
7031 (org-goto-start-pos (point))
7032 (selected-point
7033 (if (eq interface 'outline)
7034 (car (org-get-location (current-buffer) org-goto-help))
7035 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7036 (org-refile-check-position pa)
7037 (nth 3 pa)))))
7038 (if selected-point
7039 (progn
7040 (org-mark-ring-push org-goto-start-pos)
7041 (goto-char selected-point)
7042 (if (or (outline-invisible-p) (org-invisible-p2))
7043 (org-show-context 'org-goto)))
7044 (message "Quit"))))
7046 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7047 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7048 (defvar org-goto-local-auto-isearch-map) ; defined below
7050 (defun org-get-location (buf help)
7051 "Let the user select a location in the Org-mode buffer BUF.
7052 This function uses a recursive edit. It returns the selected position
7053 or nil."
7054 (org-no-popups
7055 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7056 (isearch-hide-immediately nil)
7057 (isearch-search-fun-function
7058 (lambda () 'org-goto-local-search-headings))
7059 (org-goto-selected-point org-goto-exit-command))
7060 (save-excursion
7061 (save-window-excursion
7062 (delete-other-windows)
7063 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7064 (org-pop-to-buffer-same-window
7065 (condition-case nil
7066 (make-indirect-buffer (current-buffer) "*org-goto*")
7067 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7068 (with-output-to-temp-buffer "*Org Help*"
7069 (princ (format help (if org-goto-auto-isearch
7070 " Just type for auto-isearch."
7071 " n/p/f/b/u to navigate, q to quit."))))
7072 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7073 (setq buffer-read-only nil)
7074 (let ((org-startup-truncated t)
7075 (org-startup-folded nil)
7076 (org-startup-align-all-tables nil))
7077 (org-mode)
7078 (org-overview))
7079 (setq buffer-read-only t)
7080 (if (and (boundp 'org-goto-start-pos)
7081 (integer-or-marker-p org-goto-start-pos))
7082 (let ((org-show-hierarchy-above t)
7083 (org-show-siblings t)
7084 (org-show-following-heading t))
7085 (goto-char org-goto-start-pos)
7086 (and (outline-invisible-p) (org-show-context)))
7087 (goto-char (point-min)))
7088 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7089 (message "Select location and press RET")
7090 (use-local-map org-goto-map)
7091 (recursive-edit)))
7092 (kill-buffer "*org-goto*")
7093 (cons org-goto-selected-point org-goto-exit-command))))
7095 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7096 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7097 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7098 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7100 (defun org-goto-local-search-headings (string bound noerror)
7101 "Search and make sure that any matches are in headlines."
7102 (catch 'return
7103 (while (if isearch-forward
7104 (search-forward string bound noerror)
7105 (search-backward string bound noerror))
7106 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7107 (and (member :headline context)
7108 (not (member :tags context))))
7109 (throw 'return (point))))))
7111 (defun org-goto-local-auto-isearch ()
7112 "Start isearch."
7113 (interactive)
7114 (goto-char (point-min))
7115 (let ((keys (this-command-keys)))
7116 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7117 (isearch-mode t)
7118 (isearch-process-search-char (string-to-char keys)))))
7120 (defun org-goto-ret (&optional arg)
7121 "Finish `org-goto' by going to the new location."
7122 (interactive "P")
7123 (setq org-goto-selected-point (point)
7124 org-goto-exit-command 'return)
7125 (throw 'exit nil))
7127 (defun org-goto-left ()
7128 "Finish `org-goto' by going to the new location."
7129 (interactive)
7130 (if (org-at-heading-p)
7131 (progn
7132 (beginning-of-line 1)
7133 (setq org-goto-selected-point (point)
7134 org-goto-exit-command 'left)
7135 (throw 'exit nil))
7136 (error "Not on a heading")))
7138 (defun org-goto-right ()
7139 "Finish `org-goto' by going to the new location."
7140 (interactive)
7141 (if (org-at-heading-p)
7142 (progn
7143 (setq org-goto-selected-point (point)
7144 org-goto-exit-command 'right)
7145 (throw 'exit nil))
7146 (error "Not on a heading")))
7148 (defun org-goto-quit ()
7149 "Finish `org-goto' without cursor motion."
7150 (interactive)
7151 (setq org-goto-selected-point nil)
7152 (setq org-goto-exit-command 'quit)
7153 (throw 'exit nil))
7155 ;;; Indirect buffer display of subtrees
7157 (defvar org-indirect-dedicated-frame nil
7158 "This is the frame being used for indirect tree display.")
7159 (defvar org-last-indirect-buffer nil)
7161 (defun org-tree-to-indirect-buffer (&optional arg)
7162 "Create indirect buffer and narrow it to current subtree.
7163 With a numerical prefix ARG, go up to this level and then take that tree.
7164 If ARG is negative, go up that many levels.
7166 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7167 indirect buffer previously made with this command, to avoid proliferation of
7168 indirect buffers. However, when you call the command with a \
7169 \\[universal-argument] prefix, or
7170 when `org-indirect-buffer-display' is `new-frame', the last buffer
7171 is kept so that you can work with several indirect buffers at the same time.
7172 If `org-indirect-buffer-display' is `dedicated-frame', the \
7173 \\[universal-argument] prefix also
7174 requests that a new frame be made for the new buffer, so that the dedicated
7175 frame is not changed."
7176 (interactive "P")
7177 (let ((cbuf (current-buffer))
7178 (cwin (selected-window))
7179 (pos (point))
7180 beg end level heading ibuf)
7181 (save-excursion
7182 (org-back-to-heading t)
7183 (when (numberp arg)
7184 (setq level (org-outline-level))
7185 (if (< arg 0) (setq arg (+ level arg)))
7186 (while (> (setq level (org-outline-level)) arg)
7187 (org-up-heading-safe)))
7188 (setq beg (point)
7189 heading (org-get-heading))
7190 (org-end-of-subtree t t)
7191 (if (org-at-heading-p) (backward-char 1))
7192 (setq end (point)))
7193 (if (and (buffer-live-p org-last-indirect-buffer)
7194 (not (eq org-indirect-buffer-display 'new-frame))
7195 (not arg))
7196 (kill-buffer org-last-indirect-buffer))
7197 (setq ibuf (org-get-indirect-buffer cbuf)
7198 org-last-indirect-buffer ibuf)
7199 (cond
7200 ((or (eq org-indirect-buffer-display 'new-frame)
7201 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7202 (select-frame (make-frame))
7203 (delete-other-windows)
7204 (org-pop-to-buffer-same-window ibuf)
7205 (org-set-frame-title heading))
7206 ((eq org-indirect-buffer-display 'dedicated-frame)
7207 (raise-frame
7208 (select-frame (or (and org-indirect-dedicated-frame
7209 (frame-live-p org-indirect-dedicated-frame)
7210 org-indirect-dedicated-frame)
7211 (setq org-indirect-dedicated-frame (make-frame)))))
7212 (delete-other-windows)
7213 (org-pop-to-buffer-same-window ibuf)
7214 (org-set-frame-title (concat "Indirect: " heading)))
7215 ((eq org-indirect-buffer-display 'current-window)
7216 (org-pop-to-buffer-same-window ibuf))
7217 ((eq org-indirect-buffer-display 'other-window)
7218 (pop-to-buffer ibuf))
7219 (t (error "Invalid value")))
7220 (if (featurep 'xemacs)
7221 (save-excursion (org-mode) (turn-on-font-lock)))
7222 (narrow-to-region beg end)
7223 (show-all)
7224 (goto-char pos)
7225 (run-hook-with-args 'org-cycle-hook 'all)
7226 (and (window-live-p cwin) (select-window cwin))))
7228 (defun org-get-indirect-buffer (&optional buffer)
7229 (setq buffer (or buffer (current-buffer)))
7230 (let ((n 1) (base (buffer-name buffer)) bname)
7231 (while (buffer-live-p
7232 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7233 (setq n (1+ n)))
7234 (condition-case nil
7235 (make-indirect-buffer buffer bname 'clone)
7236 (error (make-indirect-buffer buffer bname)))))
7238 (defun org-set-frame-title (title)
7239 "Set the title of the current frame to the string TITLE."
7240 ;; FIXME: how to name a single frame in XEmacs???
7241 (unless (featurep 'xemacs)
7242 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7244 ;;;; Structure editing
7246 ;;; Inserting headlines
7248 (defun org-previous-line-empty-p ()
7249 (save-excursion
7250 (and (not (bobp))
7251 (or (beginning-of-line 0) t)
7252 (save-match-data
7253 (looking-at "[ \t]*$")))))
7255 (defun org-insert-heading (&optional force-heading invisible-ok)
7256 "Insert a new heading or item with same depth at point.
7257 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7258 If point is at the beginning of a headline, insert a sibling before the
7259 current headline. If point is not at the beginning, split the line,
7260 create the new headline with the text in the current line after point
7261 \(but see also the variable `org-M-RET-may-split-line').
7263 With a double prefix arg, force the heading to be inserted at the
7264 end of the parent subtree.
7266 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7267 This is important for non-interactive uses of the command."
7268 (interactive "P")
7269 (if (or (= (buffer-size) 0)
7270 (and (not (save-excursion
7271 (and (ignore-errors (org-back-to-heading invisible-ok))
7272 (org-at-heading-p))))
7273 (or force-heading (not (org-in-item-p)))))
7274 (progn
7275 (insert "\n* ")
7276 (run-hooks 'org-insert-heading-hook))
7277 (when (or force-heading (not (org-insert-item)))
7278 (let* ((empty-line-p nil)
7279 (level nil)
7280 (on-heading (org-at-heading-p))
7281 (head (save-excursion
7282 (condition-case nil
7283 (progn
7284 (org-back-to-heading invisible-ok)
7285 (when (and (not on-heading)
7286 (featurep 'org-inlinetask)
7287 (integerp org-inlinetask-min-level)
7288 (>= (length (match-string 0))
7289 org-inlinetask-min-level))
7290 ;; Find a heading level before the inline task
7291 (while (and (setq level (org-up-heading-safe))
7292 (>= level org-inlinetask-min-level)))
7293 (if (org-at-heading-p)
7294 (org-back-to-heading invisible-ok)
7295 (error "This should not happen")))
7296 (setq empty-line-p (org-previous-line-empty-p))
7297 (match-string 0))
7298 (error "*"))))
7299 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7300 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7301 pos hide-previous previous-pos)
7302 (cond
7303 ((and (org-at-heading-p) (bolp)
7304 (or (bobp)
7305 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7306 ;; insert before the current line
7307 (open-line (if blank 2 1)))
7308 ((and (bolp)
7309 (not org-insert-heading-respect-content)
7310 (or (bobp)
7311 (save-excursion
7312 (backward-char 1) (not (outline-invisible-p)))))
7313 ;; insert right here
7314 nil)
7316 ;; somewhere in the line
7317 (save-excursion
7318 (setq previous-pos (point-at-bol))
7319 (end-of-line)
7320 (setq hide-previous (outline-invisible-p)))
7321 (and org-insert-heading-respect-content (org-show-subtree))
7322 (let ((split
7323 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7324 (save-excursion
7325 (let ((p (point)))
7326 (goto-char (point-at-bol))
7327 (and (looking-at org-complex-heading-regexp)
7328 (match-beginning 4)
7329 (> p (match-beginning 4)))))))
7330 tags pos)
7331 (cond
7332 (org-insert-heading-respect-content
7333 (if (not (equal force-heading '(16)))
7334 (org-end-of-subtree nil t)
7335 (org-up-heading-safe)
7336 (org-end-of-subtree nil t))
7337 (when (featurep 'org-inlinetask)
7338 (while (and (not (eobp))
7339 (looking-at "\\(\\*+\\)[ \t]+")
7340 (>= (length (match-string 1))
7341 org-inlinetask-min-level))
7342 (org-end-of-subtree nil t)))
7343 (or (bolp) (newline))
7344 (or (org-previous-line-empty-p)
7345 (and blank (newline)))
7346 (open-line 1))
7347 ((org-at-heading-p)
7348 (when hide-previous
7349 (show-children)
7350 (org-show-entry))
7351 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7352 (setq tags (and (match-end 2) (match-string 2)))
7353 (and (match-end 1)
7354 (delete-region (match-beginning 1) (match-end 1)))
7355 (setq pos (point-at-bol))
7356 (or split (end-of-line 1))
7357 (delete-horizontal-space)
7358 (if (string-match "\\`\\*+\\'"
7359 (buffer-substring (point-at-bol) (point)))
7360 (insert " "))
7361 (newline (if blank 2 1))
7362 (when tags
7363 (save-excursion
7364 (goto-char pos)
7365 (end-of-line 1)
7366 (insert " " tags)
7367 (org-set-tags nil 'align))))
7369 (or split (end-of-line 1))
7370 (newline (if blank 2 1)))))))
7371 (insert head) (just-one-space)
7372 (setq pos (point))
7373 (end-of-line 1)
7374 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7375 (when (and org-insert-heading-respect-content hide-previous)
7376 (save-excursion
7377 (goto-char previous-pos)
7378 (hide-subtree)))
7379 (run-hooks 'org-insert-heading-hook)))))
7381 (defun org-get-heading (&optional no-tags no-todo)
7382 "Return the heading of the current entry, without the stars.
7383 When NO-TAGS is non-nil, don't include tags.
7384 When NO-TODO is non-nil, don't include TODO keywords."
7385 (save-excursion
7386 (org-back-to-heading t)
7387 (cond
7388 ((and no-tags no-todo)
7389 (looking-at org-complex-heading-regexp)
7390 (match-string 4))
7391 (no-tags
7392 (looking-at (concat org-outline-regexp
7393 "\\(.*?\\)"
7394 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7395 (match-string 1))
7396 (no-todo
7397 (looking-at org-todo-line-regexp)
7398 (match-string 3))
7399 (t (looking-at org-heading-regexp)
7400 (match-string 2)))))
7402 (defvar orgstruct-mode) ; defined below
7404 (defun org-heading-components ()
7405 "Return the components of the current heading.
7406 This is a list with the following elements:
7407 - the level as an integer
7408 - the reduced level, different if `org-odd-levels-only' is set.
7409 - the TODO keyword, or nil
7410 - the priority character, like ?A, or nil if no priority is given
7411 - the headline text itself, or the tags string if no headline text
7412 - the tags string, or nil."
7413 (save-excursion
7414 (org-back-to-heading t)
7415 (if (let (case-fold-search)
7416 (looking-at
7417 (if orgstruct-mode
7418 org-heading-regexp
7419 org-complex-heading-regexp)))
7420 (if orgstruct-mode
7421 (list (length (match-string 1))
7422 (org-reduced-level (length (match-string 1)))
7425 (match-string 2)
7426 nil)
7427 (list (length (match-string 1))
7428 (org-reduced-level (length (match-string 1)))
7429 (org-match-string-no-properties 2)
7430 (and (match-end 3) (aref (match-string 3) 2))
7431 (org-match-string-no-properties 4)
7432 (org-match-string-no-properties 5))))))
7434 (defun org-get-entry ()
7435 "Get the entry text, after heading, entire subtree."
7436 (save-excursion
7437 (org-back-to-heading t)
7438 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7440 (defun org-insert-heading-after-current ()
7441 "Insert a new heading with same level as current, after current subtree."
7442 (interactive)
7443 (org-back-to-heading)
7444 (org-insert-heading)
7445 (org-move-subtree-down)
7446 (end-of-line 1))
7448 (defun org-insert-heading-respect-content ()
7449 (interactive)
7450 (let ((org-insert-heading-respect-content t))
7451 (org-insert-heading t)))
7453 (defun org-insert-todo-heading-respect-content (&optional force-state)
7454 (interactive "P")
7455 (let ((org-insert-heading-respect-content t))
7456 (org-insert-todo-heading force-state t)))
7458 (defun org-insert-todo-heading (arg &optional force-heading)
7459 "Insert a new heading with the same level and TODO state as current heading.
7460 If the heading has no TODO state, or if the state is DONE, use the first
7461 state (TODO by default). Also one prefix arg, force first state. With two
7462 prefix args, force inserting at the end of the parent subtree."
7463 (interactive "P")
7464 (when (or force-heading (not (org-insert-item 'checkbox)))
7465 (org-insert-heading (or (and (equal arg '(16)) '(16))
7466 force-heading))
7467 (save-excursion
7468 (org-back-to-heading)
7469 (outline-previous-heading)
7470 (looking-at org-todo-line-regexp))
7471 (let*
7472 ((new-mark-x
7473 (if (or arg
7474 (not (match-beginning 2))
7475 (member (match-string 2) org-done-keywords))
7476 (car org-todo-keywords-1)
7477 (match-string 2)))
7478 (new-mark
7480 (run-hook-with-args-until-success
7481 'org-todo-get-default-hook new-mark-x nil)
7482 new-mark-x)))
7483 (beginning-of-line 1)
7484 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7485 (if org-treat-insert-todo-heading-as-state-change
7486 (org-todo new-mark)
7487 (insert new-mark " "))))
7488 (when org-provide-todo-statistics
7489 (org-update-parent-todo-statistics))))
7491 (defun org-insert-subheading (arg)
7492 "Insert a new subheading and demote it.
7493 Works for outline headings and for plain lists alike."
7494 (interactive "P")
7495 (org-insert-heading arg)
7496 (cond
7497 ((org-at-heading-p) (org-do-demote))
7498 ((org-at-item-p) (org-indent-item))))
7500 (defun org-insert-todo-subheading (arg)
7501 "Insert a new subheading with TODO keyword or checkbox and demote it.
7502 Works for outline headings and for plain lists alike."
7503 (interactive "P")
7504 (org-insert-todo-heading arg)
7505 (cond
7506 ((org-at-heading-p) (org-do-demote))
7507 ((org-at-item-p) (org-indent-item))))
7509 ;;; Promotion and Demotion
7511 (defvar org-after-demote-entry-hook nil
7512 "Hook run after an entry has been demoted.
7513 The cursor will be at the beginning of the entry.
7514 When a subtree is being demoted, the hook will be called for each node.")
7516 (defvar org-after-promote-entry-hook nil
7517 "Hook run after an entry has been promoted.
7518 The cursor will be at the beginning of the entry.
7519 When a subtree is being promoted, the hook will be called for each node.")
7521 (defun org-promote-subtree ()
7522 "Promote the entire subtree.
7523 See also `org-promote'."
7524 (interactive)
7525 (save-excursion
7526 (org-with-limited-levels (org-map-tree 'org-promote)))
7527 (org-fix-position-after-promote))
7529 (defun org-demote-subtree ()
7530 "Demote the entire subtree. See `org-demote'.
7531 See also `org-promote'."
7532 (interactive)
7533 (save-excursion
7534 (org-with-limited-levels (org-map-tree 'org-demote)))
7535 (org-fix-position-after-promote))
7538 (defun org-do-promote ()
7539 "Promote the current heading higher up the tree.
7540 If the region is active in `transient-mark-mode', promote all headings
7541 in the region."
7542 (interactive)
7543 (save-excursion
7544 (if (org-region-active-p)
7545 (org-map-region 'org-promote (region-beginning) (region-end))
7546 (org-promote)))
7547 (org-fix-position-after-promote))
7549 (defun org-do-demote ()
7550 "Demote the current heading lower down the tree.
7551 If the region is active in `transient-mark-mode', demote all headings
7552 in the region."
7553 (interactive)
7554 (save-excursion
7555 (if (org-region-active-p)
7556 (org-map-region 'org-demote (region-beginning) (region-end))
7557 (org-demote)))
7558 (org-fix-position-after-promote))
7560 (defun org-fix-position-after-promote ()
7561 "Make sure that after pro/demotion cursor position is right."
7562 (let ((pos (point)))
7563 (when (save-excursion
7564 (beginning-of-line 1)
7565 (looking-at org-todo-line-regexp)
7566 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7567 (cond ((eobp) (insert " "))
7568 ((eolp) (insert " "))
7569 ((equal (char-after) ?\ ) (forward-char 1))))))
7571 (defun org-current-level ()
7572 "Return the level of the current entry, or nil if before the first headline.
7573 The level is the number of stars at the beginning of the headline."
7574 (save-excursion
7575 (org-with-limited-levels
7576 (if (ignore-errors (org-back-to-heading t))
7577 (funcall outline-level)))))
7579 (defun org-get-previous-line-level ()
7580 "Return the outline depth of the last headline before the current line.
7581 Returns 0 for the first headline in the buffer, and nil if before the
7582 first headline."
7583 (let ((current-level (org-current-level))
7584 (prev-level (when (> (line-number-at-pos) 1)
7585 (save-excursion
7586 (beginning-of-line 0)
7587 (org-current-level)))))
7588 (cond ((null current-level) nil) ; Before first headline
7589 ((null prev-level) 0) ; At first headline
7590 (prev-level))))
7592 (defun org-reduced-level (l)
7593 "Compute the effective level of a heading.
7594 This takes into account the setting of `org-odd-levels-only'."
7595 (cond
7596 ((zerop l) 0)
7597 (org-odd-levels-only (1+ (floor (/ l 2))))
7598 (t l)))
7600 (defun org-level-increment ()
7601 "Return the number of stars that will be added or removed at a
7602 time to headlines when structure editing, based on the value of
7603 `org-odd-levels-only'."
7604 (if org-odd-levels-only 2 1))
7606 (defun org-get-valid-level (level &optional change)
7607 "Rectify a level change under the influence of `org-odd-levels-only'
7608 LEVEL is a current level, CHANGE is by how much the level should be
7609 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7610 even level numbers will become the next higher odd number."
7611 (if org-odd-levels-only
7612 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7613 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7614 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7615 (max 1 (+ level (or change 0)))))
7617 (if (boundp 'define-obsolete-function-alias)
7618 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7619 (define-obsolete-function-alias 'org-get-legal-level
7620 'org-get-valid-level)
7621 (define-obsolete-function-alias 'org-get-legal-level
7622 'org-get-valid-level "23.1")))
7624 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7625 ;; ̀org-with-limited-levels'
7626 (defun org-promote ()
7627 "Promote the current heading higher up the tree.
7628 If the region is active in `transient-mark-mode', promote all headings
7629 in the region."
7630 (org-back-to-heading t)
7631 (let* ((level (save-match-data (funcall outline-level)))
7632 (after-change-functions (remove 'flyspell-after-change-function
7633 after-change-functions))
7634 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7635 (diff (abs (- level (length up-head) -1))))
7636 (cond ((and (= level 1) org-called-with-limited-levels
7637 org-allow-promoting-top-level-subtree)
7638 (replace-match "# " nil t))
7639 ((= level 1)
7640 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7641 (t (replace-match up-head nil t)))
7642 ;; Fixup tag positioning
7643 (unless (= level 1)
7644 (and org-auto-align-tags (org-set-tags nil t))
7645 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7646 (run-hooks 'org-after-promote-entry-hook)))
7648 (defun org-demote ()
7649 "Demote the current heading lower down the tree.
7650 If the region is active in `transient-mark-mode', demote all headings
7651 in the region."
7652 (org-back-to-heading t)
7653 (let* ((level (save-match-data (funcall outline-level)))
7654 (after-change-functions (remove 'flyspell-after-change-function
7655 after-change-functions))
7656 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7657 (diff (abs (- level (length down-head) -1))))
7658 (replace-match down-head nil t)
7659 ;; Fixup tag positioning
7660 (and org-auto-align-tags (org-set-tags nil t))
7661 (if org-adapt-indentation (org-fixup-indentation diff))
7662 (run-hooks 'org-after-demote-entry-hook)))
7664 (defun org-cycle-level ()
7665 "Cycle the level of an empty headline through possible states.
7666 This goes first to child, then to parent, level, then up the hierarchy.
7667 After top level, it switches back to sibling level."
7668 (interactive)
7669 (let ((org-adapt-indentation nil))
7670 (when (org-point-at-end-of-empty-headline)
7671 (setq this-command 'org-cycle-level) ; Only needed for caching
7672 (let ((cur-level (org-current-level))
7673 (prev-level (org-get-previous-line-level)))
7674 (cond
7675 ;; If first headline in file, promote to top-level.
7676 ((= prev-level 0)
7677 (loop repeat (/ (- cur-level 1) (org-level-increment))
7678 do (org-do-promote)))
7679 ;; If same level as prev, demote one.
7680 ((= prev-level cur-level)
7681 (org-do-demote))
7682 ;; If parent is top-level, promote to top level if not already.
7683 ((= prev-level 1)
7684 (loop repeat (/ (- cur-level 1) (org-level-increment))
7685 do (org-do-promote)))
7686 ;; If top-level, return to prev-level.
7687 ((= cur-level 1)
7688 (loop repeat (/ (- prev-level 1) (org-level-increment))
7689 do (org-do-demote)))
7690 ;; If less than prev-level, promote one.
7691 ((< cur-level prev-level)
7692 (org-do-promote))
7693 ;; If deeper than prev-level, promote until higher than
7694 ;; prev-level.
7695 ((> cur-level prev-level)
7696 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7697 do (org-do-promote))))
7698 t))))
7700 (defun org-map-tree (fun)
7701 "Call FUN for every heading underneath the current one."
7702 (org-back-to-heading)
7703 (let ((level (funcall outline-level)))
7704 (save-excursion
7705 (funcall fun)
7706 (while (and (progn
7707 (outline-next-heading)
7708 (> (funcall outline-level) level))
7709 (not (eobp)))
7710 (funcall fun)))))
7712 (defun org-map-region (fun beg end)
7713 "Call FUN for every heading between BEG and END."
7714 (let ((org-ignore-region t))
7715 (save-excursion
7716 (setq end (copy-marker end))
7717 (goto-char beg)
7718 (if (and (re-search-forward org-outline-regexp-bol nil t)
7719 (< (point) end))
7720 (funcall fun))
7721 (while (and (progn
7722 (outline-next-heading)
7723 (< (point) end))
7724 (not (eobp)))
7725 (funcall fun)))))
7727 (defvar org-property-end-re) ; silence byte-compiler
7728 (defun org-fixup-indentation (diff)
7729 "Change the indentation in the current entry by DIFF.
7730 However, if any line in the current entry has no indentation, or if it
7731 would end up with no indentation after the change, nothing at all is done."
7732 (save-excursion
7733 (let ((end (save-excursion (outline-next-heading)
7734 (point-marker)))
7735 (prohibit (if (> diff 0)
7736 "^\\S-"
7737 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7738 col)
7739 (unless (save-excursion (end-of-line 1)
7740 (re-search-forward prohibit end t))
7741 (while (and (< (point) end)
7742 (re-search-forward "^[ \t]+" end t))
7743 (goto-char (match-end 0))
7744 (setq col (current-column))
7745 (if (< diff 0) (replace-match ""))
7746 (org-indent-to-column (+ diff col))))
7747 (move-marker end nil))))
7749 (defun org-convert-to-odd-levels ()
7750 "Convert an org-mode file with all levels allowed to one with odd levels.
7751 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7752 level 5 etc."
7753 (interactive)
7754 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7755 (let ((outline-level 'org-outline-level)
7756 (org-odd-levels-only nil) n)
7757 (save-excursion
7758 (goto-char (point-min))
7759 (while (re-search-forward "^\\*\\*+ " nil t)
7760 (setq n (- (length (match-string 0)) 2))
7761 (while (>= (setq n (1- n)) 0)
7762 (org-demote))
7763 (end-of-line 1))))))
7765 (defun org-convert-to-oddeven-levels ()
7766 "Convert an org-mode file with only odd levels to one with odd/even levels.
7767 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7768 file contains a section with an even level, conversion would
7769 destroy the structure of the file. An error is signaled in this
7770 case."
7771 (interactive)
7772 (goto-char (point-min))
7773 ;; First check if there are no even levels
7774 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7775 (org-show-context t)
7776 (error "Not all levels are odd in this file. Conversion not possible"))
7777 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7778 (let ((outline-regexp org-outline-regexp)
7779 (outline-level 'org-outline-level)
7780 (org-odd-levels-only nil) n)
7781 (save-excursion
7782 (goto-char (point-min))
7783 (while (re-search-forward "^\\*\\*+ " nil t)
7784 (setq n (/ (1- (length (match-string 0))) 2))
7785 (while (>= (setq n (1- n)) 0)
7786 (org-promote))
7787 (end-of-line 1))))))
7789 (defun org-tr-level (n)
7790 "Make N odd if required."
7791 (if org-odd-levels-only (1+ (/ n 2)) n))
7793 ;;; Vertical tree motion, cutting and pasting of subtrees
7795 (defun org-move-subtree-up (&optional arg)
7796 "Move the current subtree up past ARG headlines of the same level."
7797 (interactive "p")
7798 (org-move-subtree-down (- (prefix-numeric-value arg))))
7800 (defun org-move-subtree-down (&optional arg)
7801 "Move the current subtree down past ARG headlines of the same level."
7802 (interactive "p")
7803 (setq arg (prefix-numeric-value arg))
7804 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7805 'org-get-last-sibling))
7806 (ins-point (make-marker))
7807 (cnt (abs arg))
7808 (col (current-column))
7809 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7810 ;; Select the tree
7811 (org-back-to-heading)
7812 (setq beg0 (point))
7813 (save-excursion
7814 (setq ne-beg (org-back-over-empty-lines))
7815 (setq beg (point)))
7816 (save-match-data
7817 (save-excursion (outline-end-of-heading)
7818 (setq folded (outline-invisible-p)))
7819 (outline-end-of-subtree))
7820 (outline-next-heading)
7821 (setq ne-end (org-back-over-empty-lines))
7822 (setq end (point))
7823 (goto-char beg0)
7824 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7825 ;; include less whitespace
7826 (save-excursion
7827 (goto-char beg)
7828 (forward-line (- ne-beg ne-end))
7829 (setq beg (point))))
7830 ;; Find insertion point, with error handling
7831 (while (> cnt 0)
7832 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7833 (progn (goto-char beg0)
7834 (error "Cannot move past superior level or buffer limit")))
7835 (setq cnt (1- cnt)))
7836 (if (> arg 0)
7837 ;; Moving forward - still need to move over subtree
7838 (progn (org-end-of-subtree t t)
7839 (save-excursion
7840 (org-back-over-empty-lines)
7841 (or (bolp) (newline)))))
7842 (setq ne-ins (org-back-over-empty-lines))
7843 (move-marker ins-point (point))
7844 (setq txt (buffer-substring beg end))
7845 (org-save-markers-in-region beg end)
7846 (delete-region beg end)
7847 (org-remove-empty-overlays-at beg)
7848 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7849 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7850 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7851 (let ((bbb (point)))
7852 (insert-before-markers txt)
7853 (org-reinstall-markers-in-region bbb)
7854 (move-marker ins-point bbb))
7855 (or (bolp) (insert "\n"))
7856 (setq ins-end (point))
7857 (goto-char ins-point)
7858 (org-skip-whitespace)
7859 (when (and (< arg 0)
7860 (org-first-sibling-p)
7861 (> ne-ins ne-beg))
7862 ;; Move whitespace back to beginning
7863 (save-excursion
7864 (goto-char ins-end)
7865 (let ((kill-whole-line t))
7866 (kill-line (- ne-ins ne-beg)) (point)))
7867 (insert (make-string (- ne-ins ne-beg) ?\n)))
7868 (move-marker ins-point nil)
7869 (if folded
7870 (hide-subtree)
7871 (org-show-entry)
7872 (show-children)
7873 (org-cycle-hide-drawers 'children))
7874 (org-clean-visibility-after-subtree-move)
7875 ;; move back to the initial column we were at
7876 (move-to-column col)))
7878 (defvar org-subtree-clip ""
7879 "Clipboard for cut and paste of subtrees.
7880 This is actually only a copy of the kill, because we use the normal kill
7881 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7883 (defvar org-subtree-clip-folded nil
7884 "Was the last copied subtree folded?
7885 This is used to fold the tree back after pasting.")
7887 (defun org-cut-subtree (&optional n)
7888 "Cut the current subtree into the clipboard.
7889 With prefix arg N, cut this many sequential subtrees.
7890 This is a short-hand for marking the subtree and then cutting it."
7891 (interactive "p")
7892 (org-copy-subtree n 'cut))
7894 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
7895 "Cut the current subtree into the clipboard.
7896 With prefix arg N, cut this many sequential subtrees.
7897 This is a short-hand for marking the subtree and then copying it.
7898 If CUT is non-nil, actually cut the subtree.
7899 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7900 of some markers in the region, even if CUT is non-nil. This is
7901 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7902 (interactive "p")
7903 (let (beg end folded (beg0 (point)))
7904 (if (org-called-interactively-p 'any)
7905 (org-back-to-heading nil) ; take what looks like a subtree
7906 (org-back-to-heading t)) ; take what is really there
7907 (setq beg (point))
7908 (skip-chars-forward " \t\r\n")
7909 (save-match-data
7910 (if nosubtrees
7911 (outline-next-heading)
7912 (save-excursion (outline-end-of-heading)
7913 (setq folded (outline-invisible-p)))
7914 (condition-case nil
7915 (org-forward-heading-same-level (1- n) t)
7916 (error nil))
7917 (org-end-of-subtree t t)))
7918 (setq end (point))
7919 (goto-char beg0)
7920 (when (> end beg)
7921 (setq org-subtree-clip-folded folded)
7922 (when (or cut force-store-markers)
7923 (org-save-markers-in-region beg end))
7924 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7925 (setq org-subtree-clip (current-kill 0))
7926 (message "%s: Subtree(s) with %d characters"
7927 (if cut "Cut" "Copied")
7928 (length org-subtree-clip)))))
7930 (defun org-paste-subtree (&optional level tree for-yank)
7931 "Paste the clipboard as a subtree, with modification of headline level.
7932 The entire subtree is promoted or demoted in order to match a new headline
7933 level.
7935 If the cursor is at the beginning of a headline, the same level as
7936 that headline is used to paste the tree.
7938 If not, the new level is derived from the *visible* headings
7939 before and after the insertion point, and taken to be the inferior headline
7940 level of the two. So if the previous visible heading is level 3 and the
7941 next is level 4 (or vice versa), level 4 will be used for insertion.
7942 This makes sure that the subtree remains an independent subtree and does
7943 not swallow low level entries.
7945 You can also force a different level, either by using a numeric prefix
7946 argument, or by inserting the heading marker by hand. For example, if the
7947 cursor is after \"*****\", then the tree will be shifted to level 5.
7949 If optional TREE is given, use this text instead of the kill ring.
7951 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7952 move back over whitespace before inserting, and move point to the end of
7953 the inserted text when done."
7954 (interactive "P")
7955 (setq tree (or tree (and kill-ring (current-kill 0))))
7956 (unless (org-kill-is-subtree-p tree)
7957 (error "%s"
7958 (substitute-command-keys
7959 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7960 (org-with-limited-levels
7961 (let* ((visp (not (outline-invisible-p)))
7962 (txt tree)
7963 (^re_ "\\(\\*+\\)[ \t]*")
7964 (old-level (if (string-match org-outline-regexp-bol txt)
7965 (- (match-end 0) (match-beginning 0) 1)
7966 -1))
7967 (force-level (cond (level (prefix-numeric-value level))
7968 ((and (looking-at "[ \t]*$")
7969 (string-match
7970 "^\\*+$" (buffer-substring
7971 (point-at-bol) (point))))
7972 (- (match-end 1) (match-beginning 1)))
7973 ((and (bolp)
7974 (looking-at org-outline-regexp))
7975 (- (match-end 0) (point) 1))))
7976 (previous-level (save-excursion
7977 (condition-case nil
7978 (progn
7979 (outline-previous-visible-heading 1)
7980 (if (looking-at ^re_)
7981 (- (match-end 0) (match-beginning 0) 1)
7983 (error 1))))
7984 (next-level (save-excursion
7985 (condition-case nil
7986 (progn
7987 (or (looking-at org-outline-regexp)
7988 (outline-next-visible-heading 1))
7989 (if (looking-at ^re_)
7990 (- (match-end 0) (match-beginning 0) 1)
7992 (error 1))))
7993 (new-level (or force-level (max previous-level next-level)))
7994 (shift (if (or (= old-level -1)
7995 (= new-level -1)
7996 (= old-level new-level))
7998 (- new-level old-level)))
7999 (delta (if (> shift 0) -1 1))
8000 (func (if (> shift 0) 'org-demote 'org-promote))
8001 (org-odd-levels-only nil)
8002 beg end newend)
8003 ;; Remove the forced level indicator
8004 (if force-level
8005 (delete-region (point-at-bol) (point)))
8006 ;; Paste
8007 (beginning-of-line (if (bolp) 1 2))
8008 (setq beg (point))
8009 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8010 (insert-before-markers txt)
8011 (unless (string-match "\n\\'" txt) (insert "\n"))
8012 (setq newend (point))
8013 (org-reinstall-markers-in-region beg)
8014 (setq end (point))
8015 (goto-char beg)
8016 (skip-chars-forward " \t\n\r")
8017 (setq beg (point))
8018 (if (and (outline-invisible-p) visp)
8019 (save-excursion (outline-show-heading)))
8020 ;; Shift if necessary
8021 (unless (= shift 0)
8022 (save-restriction
8023 (narrow-to-region beg end)
8024 (while (not (= shift 0))
8025 (org-map-region func (point-min) (point-max))
8026 (setq shift (+ delta shift)))
8027 (goto-char (point-min))
8028 (setq newend (point-max))))
8029 (when (or (org-called-interactively-p 'interactive) for-yank)
8030 (message "Clipboard pasted as level %d subtree" new-level))
8031 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8032 kill-ring
8033 (eq org-subtree-clip (current-kill 0))
8034 org-subtree-clip-folded)
8035 ;; The tree was folded before it was killed/copied
8036 (hide-subtree))
8037 (and for-yank (goto-char newend)))))
8039 (defun org-kill-is-subtree-p (&optional txt)
8040 "Check if the current kill is an outline subtree, or a set of trees.
8041 Returns nil if kill does not start with a headline, or if the first
8042 headline level is not the largest headline level in the tree.
8043 So this will actually accept several entries of equal levels as well,
8044 which is OK for `org-paste-subtree'.
8045 If optional TXT is given, check this string instead of the current kill."
8046 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8047 (re (org-get-limited-outline-regexp))
8048 (^re (concat "^" re))
8049 (start-level (and kill
8050 (string-match
8051 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8052 kill)
8053 (- (match-end 2) (match-beginning 2) 1)))
8054 (start (1+ (or (match-beginning 2) -1))))
8055 (if (not start-level)
8056 (progn
8057 nil) ;; does not even start with a heading
8058 (catch 'exit
8059 (while (setq start (string-match ^re kill (1+ start)))
8060 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8061 (throw 'exit nil)))
8062 t))))
8064 (defvar org-markers-to-move nil
8065 "Markers that should be moved with a cut-and-paste operation.
8066 Those markers are stored together with their positions relative to
8067 the start of the region.")
8069 (defun org-save-markers-in-region (beg end)
8070 "Check markers in region.
8071 If these markers are between BEG and END, record their position relative
8072 to BEG, so that after moving the block of text, we can put the markers back
8073 into place.
8074 This function gets called just before an entry or tree gets cut from the
8075 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8076 called immediately, to move the markers with the entries."
8077 (setq org-markers-to-move nil)
8078 (when (featurep 'org-clock)
8079 (org-clock-save-markers-for-cut-and-paste beg end))
8080 (when (featurep 'org-agenda)
8081 (org-agenda-save-markers-for-cut-and-paste beg end)))
8083 (defun org-check-and-save-marker (marker beg end)
8084 "Check if MARKER is between BEG and END.
8085 If yes, remember the marker and the distance to BEG."
8086 (when (and (marker-buffer marker)
8087 (equal (marker-buffer marker) (current-buffer)))
8088 (if (and (>= marker beg) (< marker end))
8089 (push (cons marker (- marker beg)) org-markers-to-move))))
8091 (defun org-reinstall-markers-in-region (beg)
8092 "Move all remembered markers to their position relative to BEG."
8093 (mapc (lambda (x)
8094 (move-marker (car x) (+ beg (cdr x))))
8095 org-markers-to-move)
8096 (setq org-markers-to-move nil))
8098 (defun org-narrow-to-subtree ()
8099 "Narrow buffer to the current subtree."
8100 (interactive)
8101 (save-excursion
8102 (save-match-data
8103 (org-with-limited-levels
8104 (narrow-to-region
8105 (progn (org-back-to-heading t) (point))
8106 (progn (org-end-of-subtree t t)
8107 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8108 (point)))))))
8110 (defun org-narrow-to-block ()
8111 "Narrow buffer to the current block."
8112 (interactive)
8113 (let* ((case-fold-search t)
8114 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8115 "^[ \t]*#\\+end_.*")))
8116 (if blockp
8117 (narrow-to-region (car blockp) (cdr blockp))
8118 (error "Not in a block"))))
8120 (eval-when-compile
8121 (defvar org-property-drawer-re))
8123 (defvar org-property-start-re) ;; defined below
8124 (defun org-clone-subtree-with-time-shift (n &optional shift)
8125 "Clone the task (subtree) at point N times.
8126 The clones will be inserted as siblings.
8128 In interactive use, the user will be prompted for the number of
8129 clones to be produced, and for a time SHIFT, which may be a
8130 repeater as used in time stamps, for example `+3d'.
8132 When a valid repeater is given and the entry contains any time
8133 stamps, the clones will become a sequence in time, with time
8134 stamps in the subtree shifted for each clone produced. If SHIFT
8135 is nil or the empty string, time stamps will be left alone. The
8136 ID property of the original subtree is removed.
8138 If the original subtree did contain time stamps with a repeater,
8139 the following will happen:
8140 - the repeater will be removed in each clone
8141 - an additional clone will be produced, with the current, unshifted
8142 date(s) in the entry.
8143 - the original entry will be placed *after* all the clones, with
8144 repeater intact.
8145 - the start days in the repeater in the original entry will be shifted
8146 to past the last clone.
8147 In this way you can spell out a number of instances of a repeating task,
8148 and still retain the repeater to cover future instances of the task."
8149 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8150 (let (beg end template task idprop
8151 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8152 (drawer-re org-drawer-regexp))
8153 (if (not (and (integerp n) (> n 0)))
8154 (error "Invalid number of replications %s" n))
8155 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8156 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8157 shift)))
8158 (error "Invalid shift specification %s" shift))
8159 (when doshift
8160 (setq shift-n (string-to-number (match-string 1 shift))
8161 shift-what (cdr (assoc (match-string 2 shift)
8162 '(("d" . day) ("w" . week)
8163 ("m" . month) ("y" . year))))))
8164 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8165 (setq nmin 1 nmax n)
8166 (org-back-to-heading t)
8167 (setq beg (point))
8168 (setq idprop (org-entry-get nil "ID"))
8169 (org-end-of-subtree t t)
8170 (or (bolp) (insert "\n"))
8171 (setq end (point))
8172 (setq template (buffer-substring beg end))
8173 (when (and doshift
8174 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8175 (delete-region beg end)
8176 (setq end beg)
8177 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8178 (goto-char end)
8179 (loop for n from nmin to nmax do
8180 ;; prepare clone
8181 (with-temp-buffer
8182 (insert template)
8183 (org-mode)
8184 (goto-char (point-min))
8185 (org-show-subtree)
8186 (and idprop (if org-clone-delete-id
8187 (org-entry-delete nil "ID")
8188 (org-id-get-create t)))
8189 (unless (= n 0)
8190 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8191 (kill-whole-line))
8192 (goto-char (point-min))
8193 (while (re-search-forward drawer-re nil t)
8194 (mapc (lambda (d)
8195 (org-remove-empty-drawer-at d (point))) org-drawers)))
8196 (goto-char (point-min))
8197 (when doshift
8198 (while (re-search-forward org-ts-regexp-both nil t)
8199 (org-timestamp-change (* n shift-n) shift-what))
8200 (unless (= n n-no-remove)
8201 (goto-char (point-min))
8202 (while (re-search-forward org-ts-regexp nil t)
8203 (save-excursion
8204 (goto-char (match-beginning 0))
8205 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8206 (delete-region (match-beginning 1) (match-end 1)))))))
8207 (setq task (buffer-string)))
8208 (insert task))
8209 (goto-char beg)))
8211 ;;; Outline Sorting
8213 (defun org-sort (with-case)
8214 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8215 Optional argument WITH-CASE means sort case-sensitively."
8216 (interactive "P")
8217 (cond
8218 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8219 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8221 (org-call-with-arg 'org-sort-entries with-case))))
8223 (defun org-sort-remove-invisible (s)
8224 (remove-text-properties 0 (length s) org-rm-props s)
8225 (while (string-match org-bracket-link-regexp s)
8226 (setq s (replace-match (if (match-end 2)
8227 (match-string 3 s)
8228 (match-string 1 s)) t t s)))
8231 (defvar org-priority-regexp) ; defined later in the file
8233 (defvar org-after-sorting-entries-or-items-hook nil
8234 "Hook that is run after a bunch of entries or items have been sorted.
8235 When children are sorted, the cursor is in the parent line when this
8236 hook gets called. When a region or a plain list is sorted, the cursor
8237 will be in the first entry of the sorted region/list.")
8239 (defun org-sort-entries
8240 (&optional with-case sorting-type getkey-func compare-func property)
8241 "Sort entries on a certain level of an outline tree.
8242 If there is an active region, the entries in the region are sorted.
8243 Else, if the cursor is before the first entry, sort the top-level items.
8244 Else, the children of the entry at point are sorted.
8246 Sorting can be alphabetically, numerically, by date/time as given by
8247 a time stamp, by a property or by priority.
8249 The command prompts for the sorting type unless it has been given to the
8250 function through the SORTING-TYPE argument, which needs to be a character,
8251 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8252 precise meaning of each character:
8254 n Numerically, by converting the beginning of the entry/item to a number.
8255 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8256 o By order of TODO keywords.
8257 t By date/time, either the first active time stamp in the entry, or, if
8258 none exist, by the first inactive one.
8259 s By the scheduled date/time.
8260 d By deadline date/time.
8261 c By creation time, which is assumed to be the first inactive time stamp
8262 at the beginning of a line.
8263 p By priority according to the cookie.
8264 r By the value of a property.
8266 Capital letters will reverse the sort order.
8268 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8269 called with point at the beginning of the record. It must return either
8270 a string or a number that should serve as the sorting key for that record.
8272 Comparing entries ignores case by default. However, with an optional argument
8273 WITH-CASE, the sorting considers case as well."
8274 (interactive "P")
8275 (let ((case-func (if with-case 'identity 'downcase))
8276 (cmstr
8277 ;; The clock marker is lost when using `sort-subr', let's
8278 ;; store the clocking string.
8279 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8280 (save-excursion
8281 (goto-char org-clock-marker)
8282 (looking-back "^.*") (match-string-no-properties 0))))
8283 start beg end stars re re2
8284 txt what tmp)
8285 ;; Find beginning and end of region to sort
8286 (cond
8287 ((org-region-active-p)
8288 ;; we will sort the region
8289 (setq end (region-end)
8290 what "region")
8291 (goto-char (region-beginning))
8292 (if (not (org-at-heading-p)) (outline-next-heading))
8293 (setq start (point)))
8294 ((or (org-at-heading-p)
8295 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8296 ;; we will sort the children of the current headline
8297 (org-back-to-heading)
8298 (setq start (point)
8299 end (progn (org-end-of-subtree t t)
8300 (or (bolp) (insert "\n"))
8301 (org-back-over-empty-lines)
8302 (point))
8303 what "children")
8304 (goto-char start)
8305 (show-subtree)
8306 (outline-next-heading))
8308 ;; we will sort the top-level entries in this file
8309 (goto-char (point-min))
8310 (or (org-at-heading-p) (outline-next-heading))
8311 (setq start (point))
8312 (goto-char (point-max))
8313 (beginning-of-line 1)
8314 (when (looking-at ".*?\\S-")
8315 ;; File ends in a non-white line
8316 (end-of-line 1)
8317 (insert "\n"))
8318 (setq end (point-max))
8319 (setq what "top-level")
8320 (goto-char start)
8321 (show-all)))
8323 (setq beg (point))
8324 (if (>= beg end) (error "Nothing to sort"))
8326 (looking-at "\\(\\*+\\)")
8327 (setq stars (match-string 1)
8328 re (concat "^" (regexp-quote stars) " +")
8329 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8330 txt (buffer-substring beg end))
8331 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8332 (if (and (not (equal stars "*")) (string-match re2 txt))
8333 (error "Region to sort contains a level above the first entry"))
8335 (unless sorting-type
8336 (message
8337 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8338 [t]ime [s]cheduled [d]eadline [c]reated
8339 A/N/P/R/O/F/T/S/D/C means reversed:"
8340 what)
8341 (setq sorting-type (read-char-exclusive))
8343 (unless getkey-func
8344 (and (= (downcase sorting-type) ?f)
8345 (setq getkey-func
8346 (org-icompleting-read "Sort using function: "
8347 obarray 'fboundp t nil nil))
8348 (setq getkey-func (intern getkey-func))))
8350 (and (= (downcase sorting-type) ?r)
8351 (not property)
8352 (setq property
8353 (org-icompleting-read "Property: "
8354 (mapcar 'list (org-buffer-property-keys t))
8355 nil t))))
8357 (message "Sorting entries...")
8359 (save-restriction
8360 (narrow-to-region start end)
8361 (let ((dcst (downcase sorting-type))
8362 (case-fold-search nil)
8363 (now (current-time)))
8364 (sort-subr
8365 (/= dcst sorting-type)
8366 ;; This function moves to the beginning character of the "record" to
8367 ;; be sorted.
8368 (lambda nil
8369 (if (re-search-forward re nil t)
8370 (goto-char (match-beginning 0))
8371 (goto-char (point-max))))
8372 ;; This function moves to the last character of the "record" being
8373 ;; sorted.
8374 (lambda nil
8375 (save-match-data
8376 (condition-case nil
8377 (outline-forward-same-level 1)
8378 (error
8379 (goto-char (point-max))))))
8380 ;; This function returns the value that gets sorted against.
8381 (lambda nil
8382 (cond
8383 ((= dcst ?n)
8384 (if (looking-at org-complex-heading-regexp)
8385 (string-to-number (match-string 4))
8386 nil))
8387 ((= dcst ?a)
8388 (if (looking-at org-complex-heading-regexp)
8389 (funcall case-func (match-string 4))
8390 nil))
8391 ((= dcst ?t)
8392 (let ((end (save-excursion (outline-next-heading) (point))))
8393 (if (or (re-search-forward org-ts-regexp end t)
8394 (re-search-forward org-ts-regexp-both end t))
8395 (org-time-string-to-seconds (match-string 0))
8396 (org-float-time now))))
8397 ((= dcst ?c)
8398 (let ((end (save-excursion (outline-next-heading) (point))))
8399 (if (re-search-forward
8400 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8401 end t)
8402 (org-time-string-to-seconds (match-string 0))
8403 (org-float-time now))))
8404 ((= dcst ?s)
8405 (let ((end (save-excursion (outline-next-heading) (point))))
8406 (if (re-search-forward org-scheduled-time-regexp end t)
8407 (org-time-string-to-seconds (match-string 1))
8408 (org-float-time now))))
8409 ((= dcst ?d)
8410 (let ((end (save-excursion (outline-next-heading) (point))))
8411 (if (re-search-forward org-deadline-time-regexp end t)
8412 (org-time-string-to-seconds (match-string 1))
8413 (org-float-time now))))
8414 ((= dcst ?p)
8415 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8416 (string-to-char (match-string 2))
8417 org-default-priority))
8418 ((= dcst ?r)
8419 (or (org-entry-get nil property) ""))
8420 ((= dcst ?o)
8421 (if (looking-at org-complex-heading-regexp)
8422 (- 9999 (length (member (match-string 2)
8423 org-todo-keywords-1)))))
8424 ((= dcst ?f)
8425 (if getkey-func
8426 (progn
8427 (setq tmp (funcall getkey-func))
8428 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8429 tmp)
8430 (error "Invalid key function `%s'" getkey-func)))
8431 (t (error "Invalid sorting type `%c'" sorting-type))))
8433 (cond
8434 ((= dcst ?a) 'string<)
8435 ((= dcst ?f) compare-func)
8436 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8437 (run-hooks 'org-after-sorting-entries-or-items-hook)
8438 ;; Reset the clock marker if needed
8439 (when cmstr
8440 (save-excursion
8441 (goto-char start)
8442 (search-forward cmstr nil t)
8443 (move-marker org-clock-marker (point))))
8444 (message "Sorting entries...done")))
8446 (defun org-do-sort (table what &optional with-case sorting-type)
8447 "Sort TABLE of WHAT according to SORTING-TYPE.
8448 The user will be prompted for the SORTING-TYPE if the call to this
8449 function does not specify it. WHAT is only for the prompt, to indicate
8450 what is being sorted. The sorting key will be extracted from
8451 the car of the elements of the table.
8452 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8453 (unless sorting-type
8454 (message
8455 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8456 what)
8457 (setq sorting-type (read-char-exclusive)))
8458 (let ((dcst (downcase sorting-type))
8459 extractfun comparefun)
8460 ;; Define the appropriate functions
8461 (cond
8462 ((= dcst ?n)
8463 (setq extractfun 'string-to-number
8464 comparefun (if (= dcst sorting-type) '< '>)))
8465 ((= dcst ?a)
8466 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8467 (lambda(x) (downcase (org-sort-remove-invisible x))))
8468 comparefun (if (= dcst sorting-type)
8469 'string<
8470 (lambda (a b) (and (not (string< a b))
8471 (not (string= a b)))))))
8472 ((= dcst ?t)
8473 (setq extractfun
8474 (lambda (x)
8475 (if (or (string-match org-ts-regexp x)
8476 (string-match org-ts-regexp-both x))
8477 (org-float-time
8478 (org-time-string-to-time (match-string 0 x)))
8480 comparefun (if (= dcst sorting-type) '< '>)))
8481 (t (error "Invalid sorting type `%c'" sorting-type)))
8483 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8484 table)
8485 (lambda (a b) (funcall comparefun (car a) (car b))))))
8488 ;;; The orgstruct minor mode
8490 ;; Define a minor mode which can be used in other modes in order to
8491 ;; integrate the org-mode structure editing commands.
8493 ;; This is really a hack, because the org-mode structure commands use
8494 ;; keys which normally belong to the major mode. Here is how it
8495 ;; works: The minor mode defines all the keys necessary to operate the
8496 ;; structure commands, but wraps the commands into a function which
8497 ;; tests if the cursor is currently at a headline or a plain list
8498 ;; item. If that is the case, the structure command is used,
8499 ;; temporarily setting many Org-mode variables like regular
8500 ;; expressions for filling etc. However, when any of those keys is
8501 ;; used at a different location, function uses `key-binding' to look
8502 ;; up if the key has an associated command in another currently active
8503 ;; keymap (minor modes, major mode, global), and executes that
8504 ;; command. There might be problems if any of the keys is otherwise
8505 ;; used as a prefix key.
8507 (defcustom orgstruct-heading-prefix-regexp ""
8508 "Regexp that matches the custom prefix of Org headlines in
8509 orgstruct(++)-mode."
8510 :group 'org
8511 :type 'string)
8512 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8514 (defcustom orgstruct-setup-hook nil
8515 "Hook run after orgstruct-mode-map is filled."
8516 :group 'org
8517 :type 'hook)
8519 (defvar orgstruct-initialized nil)
8521 (defvar org-local-vars nil
8522 "List of local variables, for use by `orgstruct-mode'.")
8524 ;;;###autoload
8525 (define-minor-mode orgstruct-mode
8526 "Toggle the minor mode `orgstruct-mode'.
8527 This mode is for using Org-mode structure commands in other
8528 modes. The following keys behave as if Org-mode were active, if
8529 the cursor is on a headline, or on a plain list item (both as
8530 defined by Org-mode)."
8531 nil " OrgStruct" (make-sparse-keymap)
8532 (when orgstruct-mode
8533 (org-load-modules-maybe)
8534 (unless orgstruct-initialized
8535 (orgstruct-setup)
8536 (setq orgstruct-initialized t))))
8538 ;;;###autoload
8539 (defun turn-on-orgstruct ()
8540 "Unconditionally turn on `orgstruct-mode'."
8541 (orgstruct-mode 1))
8543 (defvar org-fb-vars nil)
8544 (make-variable-buffer-local 'org-fb-vars)
8545 (defun orgstruct++-mode (&optional arg)
8546 "Toggle `orgstruct-mode', the enhanced version of it.
8547 In addition to setting orgstruct-mode, this also exports all
8548 indentation and autofilling variables from org-mode into the
8549 buffer. It will also recognize item context in multiline items."
8550 (interactive "P")
8551 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8552 (if (< arg 1)
8553 (progn (orgstruct-mode -1)
8554 (mapc (lambda(v)
8555 (org-set-local (car v)
8556 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8557 org-fb-vars))
8558 (orgstruct-mode 1)
8559 (setq org-fb-vars nil)
8560 (let (var val)
8561 (mapc
8562 (lambda (x)
8563 (when (string-match
8564 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8565 (symbol-name (car x)))
8566 (setq var (car x) val (nth 1 x))
8567 (push (list var `(quote ,(eval var))) org-fb-vars)
8568 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8569 org-local-vars)
8570 (org-set-local 'orgstruct-is-++ t))))
8572 (defvar orgstruct-is-++ nil
8573 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8574 (make-variable-buffer-local 'orgstruct-is-++)
8576 ;;;###autoload
8577 (defun turn-on-orgstruct++ ()
8578 "Unconditionally turn on `orgstruct++-mode'."
8579 (orgstruct++-mode 1))
8581 (defun orgstruct-error ()
8582 "Error when there is no default binding for a structure key."
8583 (interactive)
8584 (error "This key has no function outside structure elements"))
8586 (defun orgstruct-setup ()
8587 "Setup orgstruct keymap."
8588 (dolist (f
8589 '("org-meta"
8590 "org-shiftmeta"
8591 org-shifttab
8592 org-backward-element
8593 org-backward-heading-same-level
8594 org-ctrl-c-ret
8595 org-cycle
8596 org-forward-heading-same-level
8597 org-insert-heading
8598 org-insert-heading-respect-content
8599 org-kill-note-or-show-branches
8600 org-mark-subtree
8601 org-narrow-to-subtree
8602 org-promote-subtree
8603 org-reveal
8604 org-show-subtree
8605 org-sort
8606 org-up-element
8607 outline-demote
8608 outline-next-visible-heading
8609 outline-previous-visible-heading
8610 outline-promote
8611 outline-up-heading
8612 show-children))
8613 (dolist (f (if (stringp f)
8614 (let ((flist))
8615 (dolist (postfix
8616 '("-return" "tab" "left" "right" "up" "down")
8617 flist)
8618 (let ((f (intern (concat f postfix))))
8619 (when (fboundp f)
8620 (push f flist)))))
8621 (list f)))
8622 (dolist (binding (nconc (where-is-internal f org-mode-map)
8623 (where-is-internal f outline-mode-map)))
8624 ;; TODO use local-function-key-map
8625 (dolist (rep '(("<tab>" . "TAB")
8626 ("<ret>" . "RET")
8627 ("<esc>" . "ESC")
8628 ("<del>" . "DEL")))
8629 (setq binding (read-kbd-macro (replace-regexp-in-string
8630 (regexp-quote (car rep))
8631 (cdr rep)
8632 (key-description binding)))))
8633 (let ((key (lookup-key orgstruct-mode-map binding)))
8634 (when (or (not key) (numberp key))
8635 (condition-case nil
8636 (org-defkey orgstruct-mode-map
8637 binding
8638 (orgstruct-make-binding f binding))
8639 (error nil)))))))
8640 (run-hooks 'orgstruct-setup-hook))
8642 (defun orgstruct-make-binding (fun key)
8643 "Create a function for binding in the structure minor mode.
8644 FUN is the command to call inside a table. KEY is the key that
8645 should be checked in for a command to execute outside of tables."
8646 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8647 (let ((nname name)
8648 (i 0))
8649 (while (fboundp (intern nname))
8650 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8651 (setq name (intern nname)))
8652 (eval
8653 `(defun ,name (arg)
8654 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8655 "Outside of structure, run the binding of `"
8656 (key-description key) "'.")
8657 (interactive "p")
8658 (unless
8659 (let* ((org-heading-regexp
8660 (concat "^"
8661 orgstruct-heading-prefix-regexp
8662 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8663 (org-outline-regexp
8664 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8665 (org-outline-regexp-bol
8666 (concat "^" org-outline-regexp))
8667 (outline-regexp org-outline-regexp)
8668 (outline-heading-end-regexp "\n")
8669 (outline-level 'outline-level)
8670 (outline-heading-alist))
8671 (when (org-context-p 'headline 'item
8672 ,(when (memq fun '(org-insert-heading))
8673 '(when orgstruct-is-++
8674 'item-body)))
8675 (org-run-like-in-org-mode ',fun)
8677 (let* ((orgstruct-mode)
8678 (binding (key-binding ,key)))
8679 (if (keymapp binding)
8680 (set-temporary-overlay-map binding)
8681 (call-interactively
8682 (or binding 'orgstruct-error)))))))
8683 name))
8685 (defun org-contextualize-keys (alist contexts)
8686 "Return valid elements in ALIST depending on CONTEXTS.
8688 `org-agenda-custom-commands' or `org-capture-templates' are the
8689 values used for ALIST, and `org-agenda-custom-commands-contexts'
8690 or `org-capture-templates-contexts' are the associated contexts
8691 definitions."
8692 (let ((contexts
8693 ;; normalize contexts
8694 (mapcar
8695 (lambda(c) (cond ((listp (cadr c))
8696 (list (car c) (car c) (cadr c)))
8697 ((string= "" (cadr c))
8698 (list (car c) (car c) (caddr c)))
8699 (t c))) contexts))
8700 (a alist) c r s)
8701 ;; loop over all commands or templates
8702 (while (setq c (pop a))
8703 (let (vrules repl)
8704 (cond
8705 ((not (assoc (car c) contexts))
8706 (push c r))
8707 ((and (assoc (car c) contexts)
8708 (setq vrules (org-contextualize-validate-key
8709 (car c) contexts)))
8710 (mapc (lambda (vr)
8711 (when (not (equal (car vr) (cadr vr)))
8712 (setq repl vr))) vrules)
8713 (if (not repl) (push c r)
8714 (push (cadr repl) s)
8715 (push
8716 (cons (car c)
8717 (cdr (or (assoc (cadr repl) alist)
8718 (error "Undefined key `%s' as contextual replacement for `%s'"
8719 (cadr repl) (car c)))))
8720 r))))))
8721 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8722 (delq
8724 (delete-dups
8725 (mapcar (lambda (x)
8726 (let ((tpl (car x)))
8727 (when (not (delq
8729 (mapcar (lambda(y)
8730 (equal y tpl)) s))) x)))
8731 (reverse r))))))
8733 (defun org-contextualize-validate-key (key contexts)
8734 "Check CONTEXTS for agenda or capture KEY."
8735 (let (r rr res)
8736 (while (setq r (pop contexts))
8737 (mapc
8738 (lambda (rr)
8739 (when
8740 (and (equal key (car r))
8741 (if (functionp rr) (funcall rr)
8742 (or (and (eq (car rr) 'in-file)
8743 (buffer-file-name)
8744 (string-match (cdr rr) (buffer-file-name)))
8745 (and (eq (car rr) 'in-mode)
8746 (string-match (cdr rr) (symbol-name major-mode)))
8747 (and (eq (car rr) 'in-buffer)
8748 (string-match (cdr rr) (buffer-name)))
8749 (when (and (eq (car rr) 'not-in-file)
8750 (buffer-file-name))
8751 (not (string-match (cdr rr) (buffer-file-name))))
8752 (when (eq (car rr) 'not-in-mode)
8753 (not (string-match (cdr rr) (symbol-name major-mode))))
8754 (when (eq (car rr) 'not-in-buffer)
8755 (not (string-match (cdr rr) (buffer-name)))))))
8756 (push r res)))
8757 (car (last r))))
8758 (delete-dups (delq nil res))))
8760 (defun org-context-p (&rest contexts)
8761 "Check if local context is any of CONTEXTS.
8762 Possible values in the list of contexts are `table', `headline', and `item'."
8763 (let ((pos (point)))
8764 (goto-char (point-at-bol))
8765 (prog1 (or (and (memq 'table contexts)
8766 (looking-at "[ \t]*|"))
8767 (and (memq 'headline contexts)
8768 (looking-at org-outline-regexp))
8769 (and (memq 'item contexts)
8770 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8771 (and (memq 'item-body contexts)
8772 (org-in-item-p)))
8773 (goto-char pos))))
8775 (defun org-get-local-variables ()
8776 "Return a list of all local variables in an Org mode buffer."
8777 (let (varlist)
8778 (with-current-buffer (get-buffer-create "*Org tmp*")
8779 (erase-buffer)
8780 (org-mode)
8781 (setq varlist (buffer-local-variables)))
8782 (kill-buffer "*Org tmp*")
8783 (delq nil
8784 (mapcar
8785 (lambda (x)
8786 (setq x
8787 (if (symbolp x)
8788 (list x)
8789 (list (car x) (cdr x))))
8790 (if (and (not (get (car x) 'org-state))
8791 (string-match
8792 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8793 (symbol-name (car x))))
8794 x nil))
8795 varlist))))
8797 (defun org-clone-local-variables (from-buffer &optional regexp)
8798 "Clone local variables from FROM-BUFFER.
8799 Optional argument REGEXP selects variables to clone."
8800 (mapc
8801 (lambda (pair)
8802 (and (symbolp (car pair))
8803 (or (null regexp)
8804 (string-match regexp (symbol-name (car pair))))
8805 (set (make-local-variable (car pair))
8806 (cdr pair))))
8807 (buffer-local-variables from-buffer)))
8809 ;;;###autoload
8810 (defun org-run-like-in-org-mode (cmd)
8811 "Run a command, pretending that the current buffer is in Org-mode.
8812 This will temporarily bind local variables that are typically bound in
8813 Org-mode to the values they have in Org-mode, and then interactively
8814 call CMD."
8815 (org-load-modules-maybe)
8816 (unless org-local-vars
8817 (setq org-local-vars (org-get-local-variables)))
8818 (let (binds)
8819 (dolist (var org-local-vars)
8820 (when (or (not (boundp (car var)))
8821 (eq (symbol-value (car var))
8822 (default-value (car var))))
8823 (push (list (car var) `(quote ,(cadr var))) binds)))
8824 (eval `(let ,binds
8825 (call-interactively (quote ,cmd))))))
8827 ;;;; Archiving
8829 (defun org-get-category (&optional pos force-refresh)
8830 "Get the category applying to position POS."
8831 (save-match-data
8832 (if force-refresh (org-refresh-category-properties))
8833 (let ((pos (or pos (point))))
8834 (or (get-text-property pos 'org-category)
8835 (progn (org-refresh-category-properties)
8836 (get-text-property pos 'org-category))))))
8838 (defun org-refresh-category-properties ()
8839 "Refresh category text properties in the buffer."
8840 (let ((case-fold-search t)
8841 (inhibit-read-only t)
8842 (def-cat (cond
8843 ((null org-category)
8844 (if buffer-file-name
8845 (file-name-sans-extension
8846 (file-name-nondirectory buffer-file-name))
8847 "???"))
8848 ((symbolp org-category) (symbol-name org-category))
8849 (t org-category)))
8850 beg end cat pos optionp)
8851 (org-unmodified
8852 (save-excursion
8853 (save-restriction
8854 (widen)
8855 (goto-char (point-min))
8856 (put-text-property (point) (point-max) 'org-category def-cat)
8857 (while (re-search-forward
8858 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8859 (setq pos (match-end 0)
8860 optionp (equal (char-after (match-beginning 0)) ?#)
8861 cat (org-trim (match-string 2)))
8862 (if optionp
8863 (setq beg (point-at-bol) end (point-max))
8864 (org-back-to-heading t)
8865 (setq beg (point) end (org-end-of-subtree t t)))
8866 (put-text-property beg end 'org-category cat)
8867 (put-text-property beg end 'org-category-position beg)
8868 (goto-char pos)))))))
8870 (defun org-refresh-properties (dprop tprop)
8871 "Refresh buffer text properties.
8872 DPROP is the drawer property and TPROP is the corresponding text
8873 property to set."
8874 (let ((case-fold-search t)
8875 (inhibit-read-only t) p)
8876 (org-unmodified
8877 (save-excursion
8878 (save-restriction
8879 (widen)
8880 (goto-char (point-min))
8881 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8882 (setq p (org-match-string-no-properties 1))
8883 (save-excursion
8884 (org-back-to-heading t)
8885 (put-text-property
8886 (point-at-bol) (point-at-eol) tprop p))))))))
8889 ;;;; Link Stuff
8891 ;;; Link abbreviations
8893 (defun org-link-expand-abbrev (link)
8894 "Apply replacements as defined in `org-link-abbrev-alist'."
8895 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8896 (let* ((key (match-string 1 link))
8897 (as (or (assoc key org-link-abbrev-alist-local)
8898 (assoc key org-link-abbrev-alist)))
8899 (tag (and (match-end 2) (match-string 3 link)))
8900 rpl)
8901 (if (not as)
8902 link
8903 (setq rpl (cdr as))
8904 (cond
8905 ((symbolp rpl) (funcall rpl tag))
8906 ((string-match "%(\\([^)]+\\))" rpl)
8907 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8908 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8909 ((string-match "%h" rpl)
8910 (replace-match (url-hexify-string (or tag "")) t t rpl))
8911 (t (concat rpl tag)))))
8912 link))
8914 ;;; Storing and inserting links
8916 (defvar org-insert-link-history nil
8917 "Minibuffer history for links inserted with `org-insert-link'.")
8919 (defvar org-stored-links nil
8920 "Contains the links stored with `org-store-link'.")
8922 (defvar org-store-link-plist nil
8923 "Plist with info about the most recently link created with `org-store-link'.")
8925 (defvar org-link-protocols nil
8926 "Link protocols added to Org-mode using `org-add-link-type'.")
8928 (defvar org-store-link-functions nil
8929 "List of functions that are called to create and store a link.
8930 Each function will be called in turn until one returns a non-nil
8931 value. Each function should check if it is responsible for creating
8932 this link (for example by looking at the major mode).
8933 If not, it must exit and return nil.
8934 If yes, it should return a non-nil value after a calling
8935 `org-store-link-props' with a list of properties and values.
8936 Special properties are:
8938 :type The link prefix, like \"http\". This must be given.
8939 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8940 This is obligatory as well.
8941 :description Optional default description for the second pair
8942 of brackets in an Org-mode link. The user can still change
8943 this when inserting this link into an Org-mode buffer.
8945 In addition to these, any additional properties can be specified
8946 and then used in capture templates.")
8948 (defun org-add-link-type (type &optional follow export)
8949 "Add TYPE to the list of `org-link-types'.
8950 Re-compute all regular expressions depending on `org-link-types'
8952 FOLLOW and EXPORT are two functions.
8954 FOLLOW should take the link path as the single argument and do whatever
8955 is necessary to follow the link, for example find a file or display
8956 a mail message.
8958 EXPORT should format the link path for export to one of the export formats.
8959 It should be a function accepting three arguments:
8961 path the path of the link, the text after the prefix (like \"http:\")
8962 desc the description of the link, if any, or a description added by
8963 org-export-normalize-links if there is none
8964 format the export format, a symbol like `html' or `latex' or `ascii'..
8966 The function may use the FORMAT information to return different values
8967 depending on the format. The return value will be put literally into
8968 the exported file. If the return value is nil, this means Org should
8969 do what it normally does with links which do not have EXPORT defined.
8971 Org-mode has a built-in default for exporting links. If you are happy with
8972 this default, there is no need to define an export function for the link
8973 type. For a simple example of an export function, see `org-bbdb.el'."
8974 (add-to-list 'org-link-types type t)
8975 (org-make-link-regexps)
8976 (if (assoc type org-link-protocols)
8977 (setcdr (assoc type org-link-protocols) (list follow export))
8978 (push (list type follow export) org-link-protocols)))
8980 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8981 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8983 ;;;###autoload
8984 (defun org-store-link (arg)
8985 "\\<org-mode-map>Store an org-link to the current location.
8986 This link is added to `org-stored-links' and can later be inserted
8987 into an org-buffer with \\[org-insert-link].
8989 For some link types, a prefix arg is interpreted.
8990 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8991 For file links, arg negates `org-context-in-file-links'.
8993 A double prefix arg force skipping storing functions that are not
8994 part of Org's core."
8995 (interactive "P")
8996 (org-load-modules-maybe)
8997 (setq org-store-link-plist nil) ; reset
8998 (org-with-limited-levels
8999 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9000 (cond
9001 ((and (not (equal arg '(16)))
9002 (setq sfuns
9003 (delq
9004 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9005 org-store-link-functions))
9006 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9007 (or (and (cdr sfuns)
9008 (funcall (intern
9009 (completing-read "Which function for creating the link? "
9010 sfunsn t (car sfunsn)))))
9011 (funcall (caar sfuns)))
9012 (setq link (plist-get org-store-link-plist :link)
9013 desc (or (plist-get org-store-link-plist :description) link))))
9014 ((org-src-edit-buffer-p)
9015 (let (label gc)
9016 (while (or (not label)
9017 (save-excursion
9018 (save-restriction
9019 (widen)
9020 (goto-char (point-min))
9021 (re-search-forward
9022 (regexp-quote (format org-coderef-label-format label))
9023 nil t))))
9024 (when label (message "Label exists already") (sit-for 2))
9025 (setq label (read-string "Code line label: " label)))
9026 (end-of-line 1)
9027 (setq link (format org-coderef-label-format label))
9028 (setq gc (- 79 (length link)))
9029 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9030 (insert link)
9031 (setq link (concat "(" label ")") desc nil)))
9033 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9034 ;; We are in the agenda, link to referenced location
9035 (let ((m (or (get-text-property (point) 'org-hd-marker)
9036 (get-text-property (point) 'org-marker))))
9037 (when m
9038 (org-with-point-at m
9039 (setq agenda-link
9040 (if (org-called-interactively-p 'any)
9041 (call-interactively 'org-store-link)
9042 (org-store-link nil)))))))
9044 ((eq major-mode 'calendar-mode)
9045 (let ((cd (calendar-cursor-to-date)))
9046 (setq link
9047 (format-time-string
9048 (car org-time-stamp-formats)
9049 (apply 'encode-time
9050 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9051 nil nil nil))))
9052 (org-store-link-props :type "calendar" :date cd)))
9054 ((eq major-mode 'help-mode)
9055 (setq link (concat "help:" (save-excursion
9056 (goto-char (point-min))
9057 (looking-at "^[^ ]+")
9058 (match-string 0))))
9059 (org-store-link-props :type "help"))
9061 ((eq major-mode 'w3-mode)
9062 (setq cpltxt (if (and (buffer-name)
9063 (not (string-match "Untitled" (buffer-name))))
9064 (buffer-name)
9065 (url-view-url t))
9066 link (url-view-url t))
9067 (org-store-link-props :type "w3" :url (url-view-url t)))
9069 ((setq search (run-hook-with-args-until-success
9070 'org-create-file-search-functions))
9071 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9072 "::" search))
9073 (setq cpltxt (or description link)))
9075 ((eq major-mode 'image-mode)
9076 (setq cpltxt (concat "file:"
9077 (abbreviate-file-name buffer-file-name))
9078 link cpltxt)
9079 (org-store-link-props :type "image" :file buffer-file-name))
9081 ((eq major-mode 'dired-mode)
9082 ;; link to the file in the current line
9083 (let ((file (dired-get-filename nil t)))
9084 (setq file (if file
9085 (abbreviate-file-name
9086 (expand-file-name (dired-get-filename nil t)))
9087 ;; otherwise, no file so use current directory.
9088 default-directory))
9089 (setq cpltxt (concat "file:" file)
9090 link cpltxt)))
9092 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9093 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9094 (cond
9095 ((org-in-regexp "<<\\(.*?\\)>>")
9096 (setq cpltxt
9097 (concat "file:"
9098 (abbreviate-file-name
9099 (buffer-file-name (buffer-base-buffer)))
9100 "::" (match-string 1))
9101 link cpltxt))
9102 ((and (featurep 'org-id)
9103 (or (eq org-id-link-to-org-use-id t)
9104 (and (org-called-interactively-p 'any)
9105 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9106 (and (eq org-id-link-to-org-use-id
9107 'create-if-interactive-and-no-custom-id)
9108 (not custom-id))))
9109 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9110 ;; We can make a link using the ID.
9111 (setq link (condition-case nil
9112 (prog1 (org-id-store-link)
9113 (setq desc (plist-get org-store-link-plist :description)))
9114 (error
9115 ;; probably before first headline, link to file only
9116 (concat "file:"
9117 (abbreviate-file-name
9118 (buffer-file-name (buffer-base-buffer))))))))
9120 ;; Just link to current headline
9121 (setq cpltxt (concat "file:"
9122 (abbreviate-file-name
9123 (buffer-file-name (buffer-base-buffer)))))
9124 ;; Add a context search string
9125 (when (org-xor org-context-in-file-links arg)
9126 (let* ((ee (org-element-at-point))
9127 (et (org-element-type ee))
9128 (ev (plist-get (cadr ee) :value)))
9129 (setq txt (cond
9130 ((org-at-heading-p) nil)
9131 ((eq et 'keyword) ev)
9132 ((org-region-active-p)
9133 (buffer-substring (region-beginning) (region-end)))))
9134 (when (or (null txt) (string-match "\\S-" txt))
9135 (setq cpltxt
9136 (concat cpltxt "::"
9137 (condition-case nil
9138 (org-make-org-heading-search-string txt)
9139 (error "")))
9140 desc (or (and (eq et 'keyword) ev)
9141 (nth 4 (ignore-errors (org-heading-components)))
9142 "NONE")))))
9143 (if (string-match "::\\'" cpltxt)
9144 (setq cpltxt (substring cpltxt 0 -2)))
9145 (setq link cpltxt))))
9147 ((buffer-file-name (buffer-base-buffer))
9148 ;; Just link to this file here.
9149 (setq cpltxt (concat "file:"
9150 (abbreviate-file-name
9151 (buffer-file-name (buffer-base-buffer)))))
9152 ;; Add a context string
9153 (when (org-xor org-context-in-file-links arg)
9154 (setq txt (if (org-region-active-p)
9155 (buffer-substring (region-beginning) (region-end))
9156 (buffer-substring (point-at-bol) (point-at-eol))))
9157 ;; Only use search option if there is some text.
9158 (when (string-match "\\S-" txt)
9159 (setq cpltxt
9160 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9161 desc "NONE")))
9162 (setq link cpltxt))
9164 ((org-called-interactively-p 'interactive)
9165 (user-error "No method for storing a link from this buffer"))
9167 (t (setq link nil)))
9169 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9170 (setq link (or link cpltxt)
9171 desc (or desc cpltxt))
9172 (cond ((equal desc "NONE") (setq desc nil))
9173 ((string-match org-bracket-link-regexp desc)
9174 (setq desc (replace-regexp-in-string
9175 org-bracket-link-regexp
9176 (concat "\\3" (if (equal (length (match-string 0 desc))
9177 (length desc)) "*" "")) desc))))
9179 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9180 (progn
9181 (setq org-stored-links
9182 (cons (list link desc) org-stored-links))
9183 (message "Stored: %s" (or desc link))
9184 (when custom-id
9185 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9186 "::#" custom-id))
9187 (setq org-stored-links
9188 (cons (list link desc) org-stored-links))))
9189 (or agenda-link (and link (org-make-link-string link desc)))))))
9191 (defun org-store-link-props (&rest plist)
9192 "Store link properties, extract names and addresses."
9193 (let (x adr)
9194 (when (setq x (plist-get plist :from))
9195 (setq adr (mail-extract-address-components x))
9196 (setq plist (plist-put plist :fromname (car adr)))
9197 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9198 (when (setq x (plist-get plist :to))
9199 (setq adr (mail-extract-address-components x))
9200 (setq plist (plist-put plist :toname (car adr)))
9201 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9202 (let ((from (plist-get plist :from))
9203 (to (plist-get plist :to)))
9204 (when (and from to org-from-is-user-regexp)
9205 (setq plist
9206 (plist-put plist :fromto
9207 (if (string-match org-from-is-user-regexp from)
9208 (concat "to %t")
9209 (concat "from %f"))))))
9210 (setq org-store-link-plist plist))
9212 (defun org-add-link-props (&rest plist)
9213 "Add these properties to the link property list."
9214 (let (key value)
9215 (while plist
9216 (setq key (pop plist) value (pop plist))
9217 (setq org-store-link-plist
9218 (plist-put org-store-link-plist key value)))))
9220 (defun org-email-link-description (&optional fmt)
9221 "Return the description part of an email link.
9222 This takes information from `org-store-link-plist' and formats it
9223 according to FMT (default from `org-email-link-description-format')."
9224 (setq fmt (or fmt org-email-link-description-format))
9225 (let* ((p org-store-link-plist)
9226 (to (plist-get p :toaddress))
9227 (from (plist-get p :fromaddress))
9228 (table
9229 (list
9230 (cons "%c" (plist-get p :fromto))
9231 (cons "%F" (plist-get p :from))
9232 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9233 (cons "%T" (plist-get p :to))
9234 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9235 (cons "%s" (plist-get p :subject))
9236 (cons "%d" (plist-get p :date))
9237 (cons "%m" (plist-get p :message-id)))))
9238 (when (string-match "%c" fmt)
9239 ;; Check if the user wrote this message
9240 (if (and org-from-is-user-regexp from to
9241 (save-match-data (string-match org-from-is-user-regexp from)))
9242 (setq fmt (replace-match "to %t" t t fmt))
9243 (setq fmt (replace-match "from %f" t t fmt))))
9244 (org-replace-escapes fmt table)))
9246 (defun org-make-org-heading-search-string (&optional string)
9247 "Make search string for the current headline or STRING."
9248 (let ((s (or string
9249 (and (derived-mode-p 'org-mode)
9250 (save-excursion
9251 (org-back-to-heading t)
9252 (plist-get (cadr (org-element-at-point))
9253 :raw-value)))))
9254 (lines org-context-in-file-links))
9255 (or string (setq s (concat "*" s))) ; Add * for headlines
9256 (when (and string (integerp lines) (> lines 0))
9257 (let ((slines (org-split-string s "\n")))
9258 (when (< lines (length slines))
9259 (setq s (mapconcat
9260 'identity
9261 (reverse (nthcdr (- (length slines) lines)
9262 (reverse slines))) "\n")))))
9263 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9265 (defun org-make-link-string (link &optional description)
9266 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9267 (unless (string-match "\\S-" link)
9268 (error "Empty link"))
9269 (when (and description
9270 (stringp description)
9271 (not (string-match "\\S-" description)))
9272 (setq description nil))
9273 (when (stringp description)
9274 ;; Remove brackets from the description, they are fatal.
9275 (while (string-match "\\[" description)
9276 (setq description (replace-match "{" t t description)))
9277 (while (string-match "\\]" description)
9278 (setq description (replace-match "}" t t description))))
9279 (when (equal link description)
9280 ;; No description needed, it is identical
9281 (setq description nil))
9282 (when (and (not description)
9283 (not (string-match (org-image-file-name-regexp) link))
9284 (not (equal link (org-link-escape link))))
9285 (setq description (org-extract-attributes link)))
9286 (setq link
9287 (cond ((string-match (org-image-file-name-regexp) link) link)
9288 ((string-match org-link-types-re link)
9289 (concat (match-string 1 link)
9290 (org-link-escape (substring link (match-end 1)))))
9291 (t (org-link-escape link))))
9292 (concat "[[" link "]"
9293 (if description (concat "[" description "]") "")
9294 "]"))
9296 (defconst org-link-escape-chars
9297 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9298 "List of characters that should be escaped in link.
9299 This is the list that is used for internal purposes.")
9301 (defconst org-link-escape-chars-browser
9302 '(?\ )
9303 "List of escapes for characters that are problematic in links.
9304 This is the list that is used before handing over to the browser.")
9306 (defun org-link-escape (text &optional table merge)
9307 "Return percent escaped representation of TEXT.
9308 TEXT is a string with the text to escape.
9309 Optional argument TABLE is a list with characters that should be
9310 escaped. When nil, `org-link-escape-chars' is used.
9311 If optional argument MERGE is set, merge TABLE into
9312 `org-link-escape-chars'."
9313 (cond
9314 ((and table merge)
9315 (mapc (lambda (defchr)
9316 (unless (member defchr table)
9317 (setq table (cons defchr table)))) org-link-escape-chars))
9318 ((null table)
9319 (setq table org-link-escape-chars)))
9320 (mapconcat
9321 (lambda (char)
9322 (if (or (member char table)
9323 (and (or (< char 32) (= char 37) (> char 126))
9324 org-url-hexify-p))
9325 (mapconcat (lambda (sequence-element)
9326 (format "%%%.2X" sequence-element))
9327 (or (encode-coding-char char 'utf-8)
9328 (error "Unable to percent escape character: %s"
9329 (char-to-string char))) "")
9330 (char-to-string char))) text ""))
9332 (defun org-link-unescape (str)
9333 "Unhex hexified Unicode strings as returned from the JavaScript function
9334 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9335 (unless (and (null str) (string= "" str))
9336 (let ((pos 0) (case-fold-search t) unhexed)
9337 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9338 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9339 (setq str (replace-match unhexed t t str))
9340 (setq pos (+ pos (length unhexed))))))
9341 str)
9343 (defun org-link-unescape-compound (hex)
9344 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9345 Note: this function also decodes single byte encodings like
9346 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9347 (save-match-data
9348 (let* ((bytes (cdr (split-string hex "%")))
9349 (ret "")
9350 (eat 0)
9351 (sum 0))
9352 (while bytes
9353 (let* ((val (string-to-number (pop bytes) 16))
9354 (shift-xor
9355 (if (= 0 eat)
9356 (cond
9357 ((>= val 252) (cons 6 252))
9358 ((>= val 248) (cons 5 248))
9359 ((>= val 240) (cons 4 240))
9360 ((>= val 224) (cons 3 224))
9361 ((>= val 192) (cons 2 192))
9362 (t (cons 0 0)))
9363 (cons 6 128))))
9364 (if (>= val 192) (setq eat (car shift-xor)))
9365 (setq val (logxor val (cdr shift-xor)))
9366 (setq sum (+ (lsh sum (car shift-xor)) val))
9367 (if (> eat 0) (setq eat (- eat 1)))
9368 (cond
9369 ((= 0 eat) ;multi byte
9370 (setq ret (concat ret (org-char-to-string sum)))
9371 (setq sum 0))
9372 ((not bytes) ; single byte(s)
9373 (setq ret (org-link-unescape-single-byte-sequence hex))))
9374 )) ;; end (while bytes
9375 ret )))
9377 (defun org-link-unescape-single-byte-sequence (hex)
9378 "Unhexify hex-encoded single byte character sequences."
9379 (mapconcat (lambda (byte)
9380 (char-to-string (string-to-number byte 16)))
9381 (cdr (split-string hex "%")) ""))
9383 (defun org-xor (a b)
9384 "Exclusive or."
9385 (if a (not b) b))
9387 (defun org-fixup-message-id-for-http (s)
9388 "Replace special characters in a message id, so it can be used in an http query."
9389 (when (string-match "%" s)
9390 (setq s (mapconcat (lambda (c)
9391 (if (eq c ?%)
9392 "%25"
9393 (char-to-string c)))
9394 s "")))
9395 (while (string-match "<" s)
9396 (setq s (replace-match "%3C" t t s)))
9397 (while (string-match ">" s)
9398 (setq s (replace-match "%3E" t t s)))
9399 (while (string-match "@" s)
9400 (setq s (replace-match "%40" t t s)))
9403 (defun org-link-prettify (link)
9404 "Return a human-readable representation of LINK.
9405 The car of LINK must be a raw link the cdr of LINK must be either
9406 a link description or nil."
9407 (let ((desc (or (cadr link) "<no description>")))
9408 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9409 "<" (car link) ">")))
9411 ;;;###autoload
9412 (defun org-insert-link-global ()
9413 "Insert a link like Org-mode does.
9414 This command can be called in any mode to insert a link in Org-mode syntax."
9415 (interactive)
9416 (org-load-modules-maybe)
9417 (org-run-like-in-org-mode 'org-insert-link))
9419 (defun org-insert-all-links (&optional keep)
9420 "Insert all links in `org-stored-links'."
9421 (interactive "P")
9422 (let ((links (copy-sequence org-stored-links)) l)
9423 (while (setq l (if keep (pop links) (pop org-stored-links)))
9424 (insert "- ")
9425 (org-insert-link nil (car l) (cadr l))
9426 (insert "\n"))))
9428 (defun org-link-fontify-links-to-this-file ()
9429 "Fontify links to the current file in `org-stored-links'."
9430 (let ((f (buffer-file-name)) a b)
9431 (setq a (mapcar (lambda(l)
9432 (let ((ll (car l)))
9433 (when (and (string-match "^file:\\(.+\\)::" ll)
9434 (equal f (expand-file-name (match-string 1 ll))))
9435 ll)))
9436 org-stored-links))
9437 (when (featurep 'org-id)
9438 (setq b (mapcar (lambda(l)
9439 (let ((ll (car l)))
9440 (when (and (string-match "^id:\\(.+\\)$" ll)
9441 (equal f (expand-file-name
9442 (or (org-id-find-id-file
9443 (match-string 1 ll)) ""))))
9444 ll)))
9445 org-stored-links)))
9446 (mapcar (lambda(l)
9447 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9448 (delq nil (append a b)))))
9450 (defvar org-link-links-in-this-file nil)
9451 (defun org-insert-link (&optional complete-file link-location default-description)
9452 "Insert a link. At the prompt, enter the link.
9454 Completion can be used to insert any of the link protocol prefixes like
9455 http or ftp in use.
9457 The history can be used to select a link previously stored with
9458 `org-store-link'. When the empty string is entered (i.e. if you just
9459 press RET at the prompt), the link defaults to the most recently
9460 stored link. As SPC triggers completion in the minibuffer, you need to
9461 use M-SPC or C-q SPC to force the insertion of a space character.
9463 You will also be prompted for a description, and if one is given, it will
9464 be displayed in the buffer instead of the link.
9466 If there is already a link at point, this command will allow you to edit link
9467 and description parts.
9469 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9470 be selected using completion. The path to the file will be relative to the
9471 current directory if the file is in the current directory or a subdirectory.
9472 Otherwise, the link will be the absolute path as completed in the minibuffer
9473 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9474 option `org-link-file-path-type'.
9476 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9477 the current directory or below.
9479 With three \\[universal-argument] prefixes, negate the meaning of
9480 `org-keep-stored-link-after-insertion'.
9482 If `org-make-link-description-function' is non-nil, this function will be
9483 called with the link target, and the result will be the default
9484 link description.
9486 If the LINK-LOCATION parameter is non-nil, this value will be
9487 used as the link location instead of reading one interactively.
9489 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9490 be used as the default description."
9491 (interactive "P")
9492 (let* ((wcf (current-window-configuration))
9493 (origbuf (current-buffer))
9494 (region (if (org-region-active-p)
9495 (buffer-substring (region-beginning) (region-end))))
9496 (remove (and region (list (region-beginning) (region-end))))
9497 (desc region)
9498 tmphist ; byte-compile incorrectly complains about this
9499 (link link-location)
9500 (abbrevs org-link-abbrev-alist-local)
9501 entry file all-prefixes auto-desc)
9502 (cond
9503 (link-location) ; specified by arg, just use it.
9504 ((org-in-regexp org-bracket-link-regexp 1)
9505 ;; We do have a link at point, and we are going to edit it.
9506 (setq remove (list (match-beginning 0) (match-end 0)))
9507 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9508 (setq link (read-string "Link: "
9509 (org-link-unescape
9510 (org-match-string-no-properties 1)))))
9511 ((or (org-in-regexp org-angle-link-re)
9512 (org-in-regexp org-plain-link-re))
9513 ;; Convert to bracket link
9514 (setq remove (list (match-beginning 0) (match-end 0))
9515 link (read-string "Link: "
9516 (org-remove-angle-brackets (match-string 0)))))
9517 ((member complete-file '((4) (16)))
9518 ;; Completing read for file names.
9519 (setq link (org-file-complete-link complete-file)))
9521 ;; Read link, with completion for stored links.
9522 (org-link-fontify-links-to-this-file)
9523 (org-switch-to-buffer-other-window "*Org Links*")
9524 (with-current-buffer "*Org Links*"
9525 (erase-buffer)
9526 (insert "Insert a link.
9527 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9528 (when org-stored-links
9529 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9530 (insert (mapconcat 'org-link-prettify
9531 (reverse org-stored-links) "\n")))
9532 (goto-char (point-min)))
9533 (let ((cw (selected-window)))
9534 (select-window (get-buffer-window "*Org Links*" 'visible))
9535 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9536 (unless (pos-visible-in-window-p (point-max))
9537 (org-fit-window-to-buffer))
9538 (and (window-live-p cw) (select-window cw)))
9539 ;; Fake a link history, containing the stored links.
9540 (setq tmphist (append (mapcar 'car org-stored-links)
9541 org-insert-link-history))
9542 (setq all-prefixes (append (mapcar 'car abbrevs)
9543 (mapcar 'car org-link-abbrev-alist)
9544 org-link-types))
9545 (unwind-protect
9546 (progn
9547 (setq link
9548 (org-completing-read
9549 "Link: "
9550 (append
9551 (mapcar (lambda (x) (concat x ":"))
9552 all-prefixes)
9553 (mapcar 'car org-stored-links))
9554 nil nil nil
9555 'tmphist
9556 (caar org-stored-links)))
9557 (if (not (string-match "\\S-" link))
9558 (error "No link selected"))
9559 (mapc (lambda(l)
9560 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9561 org-stored-links)
9562 (if (or (member link all-prefixes)
9563 (and (equal ":" (substring link -1))
9564 (member (substring link 0 -1) all-prefixes)
9565 (setq link (substring link 0 -1))))
9566 (setq link (with-current-buffer origbuf
9567 (org-link-try-special-completion link)))))
9568 (set-window-configuration wcf)
9569 (kill-buffer "*Org Links*"))
9570 (setq entry (assoc link org-stored-links))
9571 (or entry (push link org-insert-link-history))
9572 (setq desc (or desc (nth 1 entry)))))
9574 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9575 (not org-keep-stored-link-after-insertion))
9576 (setq org-stored-links (delq (assoc link org-stored-links)
9577 org-stored-links)))
9579 (if (string-match org-plain-link-re link)
9580 ;; URL-like link, normalize the use of angular brackets.
9581 (setq link (org-remove-angle-brackets link)))
9583 ;; Check if we are linking to the current file with a search
9584 ;; option If yes, simplify the link by using only the search
9585 ;; option.
9586 (when (and buffer-file-name
9587 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9588 (let* ((path (match-string 1 link))
9589 (case-fold-search nil)
9590 (search (match-string 2 link)))
9591 (save-match-data
9592 (if (equal (file-truename buffer-file-name) (file-truename path))
9593 ;; We are linking to this same file, with a search option
9594 (setq link search)))))
9596 ;; Check if we can/should use a relative path. If yes, simplify the link
9597 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9598 (let* ((type (match-string 1 link))
9599 (path (match-string 2 link))
9600 (origpath path)
9601 (case-fold-search nil))
9602 (cond
9603 ((or (eq org-link-file-path-type 'absolute)
9604 (equal complete-file '(16)))
9605 (setq path (abbreviate-file-name (expand-file-name path))))
9606 ((eq org-link-file-path-type 'noabbrev)
9607 (setq path (expand-file-name path)))
9608 ((eq org-link-file-path-type 'relative)
9609 (setq path (file-relative-name path)))
9611 (save-match-data
9612 (if (string-match (concat "^" (regexp-quote
9613 (expand-file-name
9614 (file-name-as-directory
9615 default-directory))))
9616 (expand-file-name path))
9617 ;; We are linking a file with relative path name.
9618 (setq path (substring (expand-file-name path)
9619 (match-end 0)))
9620 (setq path (abbreviate-file-name (expand-file-name path)))))))
9621 (setq link (concat type path))
9622 (if (equal desc origpath)
9623 (setq desc path))))
9625 (if org-make-link-description-function
9626 (setq desc
9627 (or (condition-case nil
9628 (funcall org-make-link-description-function link desc)
9629 (error (progn (message "Can't get link description from `%s'"
9630 (symbol-name org-make-link-description-function))
9631 (sit-for 2) nil)))
9632 (read-string "Description: " default-description)))
9633 (if default-description (setq desc default-description)
9634 (setq desc (or (and auto-desc desc)
9635 (read-string "Description: " desc)))))
9637 (unless (string-match "\\S-" desc) (setq desc nil))
9638 (if remove (apply 'delete-region remove))
9639 (insert (org-make-link-string link desc))))
9641 (defun org-link-try-special-completion (type)
9642 "If there is completion support for link type TYPE, offer it."
9643 (let ((fun (intern (concat "org-" type "-complete-link"))))
9644 (if (functionp fun)
9645 (funcall fun)
9646 (read-string "Link (no completion support): " (concat type ":")))))
9648 (defun org-file-complete-link (&optional arg)
9649 "Create a file link using completion."
9650 (let (file link)
9651 (setq file (org-iread-file-name "File: "))
9652 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9653 (pwd1 (file-name-as-directory (abbreviate-file-name
9654 (expand-file-name ".")))))
9655 (cond
9656 ((equal arg '(16))
9657 (setq link (concat
9658 "file:"
9659 (abbreviate-file-name (expand-file-name file)))))
9660 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9661 (setq link (concat "file:" (match-string 1 file))))
9662 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9663 (expand-file-name file))
9664 (setq link (concat
9665 "file:" (match-string 1 (expand-file-name file)))))
9666 (t (setq link (concat "file:" file)))))
9667 link))
9669 (defun org-iread-file-name (&rest args)
9670 "Read-file-name using `ido-mode' speedup if available.
9671 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9672 See `read-file-name' for a description of parameters."
9673 (org-without-partial-completion
9674 (if (and org-completion-use-ido
9675 (fboundp 'ido-read-file-name)
9676 (boundp 'ido-mode) ido-mode
9677 (listp (second args)))
9678 (let ((ido-enter-matching-directory nil))
9679 (apply 'ido-read-file-name args))
9680 (apply 'read-file-name args))))
9682 (defun org-completing-read (&rest args)
9683 "Completing-read with SPACE being a normal character."
9684 (let ((enable-recursive-minibuffers t)
9685 (minibuffer-local-completion-map
9686 (copy-keymap minibuffer-local-completion-map)))
9687 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9688 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9689 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9690 (apply 'org-icompleting-read args)))
9692 (defun org-completing-read-no-i (&rest args)
9693 (let (org-completion-use-ido org-completion-use-iswitchb)
9694 (apply 'org-completing-read args)))
9696 (defun org-iswitchb-completing-read (prompt choices &rest args)
9697 "Use iswitch as a completing-read replacement to choose from choices.
9698 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9699 from."
9700 (let* ((iswitchb-use-virtual-buffers nil)
9701 (iswitchb-make-buflist-hook
9702 (lambda ()
9703 (setq iswitchb-temp-buflist choices))))
9704 (iswitchb-read-buffer prompt)))
9706 (defun org-icompleting-read (&rest args)
9707 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9708 (org-without-partial-completion
9709 (if (and org-completion-use-ido
9710 (fboundp 'ido-completing-read)
9711 (boundp 'ido-mode) ido-mode
9712 (listp (second args)))
9713 (let ((ido-enter-matching-directory nil))
9714 (apply 'ido-completing-read (concat (car args))
9715 (if (consp (car (nth 1 args)))
9716 (mapcar 'car (nth 1 args))
9717 (nth 1 args))
9718 (cddr args)))
9719 (if (and org-completion-use-iswitchb
9720 (boundp 'iswitchb-mode) iswitchb-mode
9721 (listp (second args)))
9722 (apply 'org-iswitchb-completing-read (concat (car args))
9723 (if (consp (car (nth 1 args)))
9724 (mapcar 'car (nth 1 args))
9725 (nth 1 args))
9726 (cddr args))
9727 (apply 'completing-read args)))))
9729 (defun org-extract-attributes (s)
9730 "Extract the attributes cookie from a string and set as text property."
9731 (let (a attr (start 0) key value)
9732 (save-match-data
9733 (when (string-match "{{\\([^}]+\\)}}$" s)
9734 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9735 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9736 (setq key (match-string 1 a) value (match-string 2 a)
9737 start (match-end 0)
9738 attr (plist-put attr (intern key) value))))
9739 (org-add-props s nil 'org-attr attr))
9742 (defun org-extract-attributes-from-string (tag)
9743 (let (key value attr)
9744 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9745 (setq key (match-string 1 tag) value (match-string 2 tag)
9746 tag (replace-match "" t t tag)
9747 attr (plist-put attr (intern key) value)))
9748 (cons tag attr)))
9750 (defun org-attributes-to-string (plist)
9751 "Format a property list into an HTML attribute list."
9752 (let ((s "") key value)
9753 (while plist
9754 (setq key (pop plist) value (pop plist))
9755 (and value
9756 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9759 ;;; Opening/following a link
9761 (defvar org-link-search-failed nil)
9763 (defvar org-open-link-functions nil
9764 "Hook for functions finding a plain text link.
9765 These functions must take a single argument, the link content.
9766 They will be called for links that look like [[link text][description]]
9767 when LINK TEXT does not have a protocol like \"http:\" and does not look
9768 like a filename (e.g. \"./blue.png\").
9770 These functions will be called *before* Org attempts to resolve the
9771 link by doing text searches in the current buffer - so if you want a
9772 link \"[[target]]\" to still find \"<<target>>\", your function should
9773 handle this as a special case.
9775 When the function does handle the link, it must return a non-nil value.
9776 If it decides that it is not responsible for this link, it must return
9777 nil to indicate that that Org-mode can continue with other options
9778 like exact and fuzzy text search.")
9780 (defun org-next-link ()
9781 "Move forward to the next link.
9782 If the link is in hidden text, expose it."
9783 (interactive)
9784 (when (and org-link-search-failed (eq this-command last-command))
9785 (goto-char (point-min))
9786 (message "Link search wrapped back to beginning of buffer"))
9787 (setq org-link-search-failed nil)
9788 (let* ((pos (point))
9789 (ct (org-context))
9790 (a (assoc :link ct)))
9791 (if a (goto-char (nth 2 a)))
9792 (if (re-search-forward org-any-link-re nil t)
9793 (progn
9794 (goto-char (match-beginning 0))
9795 (if (outline-invisible-p) (org-show-context)))
9796 (goto-char pos)
9797 (setq org-link-search-failed t)
9798 (error "No further link found"))))
9800 (defun org-previous-link ()
9801 "Move backward to the previous link.
9802 If the link is in hidden text, expose it."
9803 (interactive)
9804 (when (and org-link-search-failed (eq this-command last-command))
9805 (goto-char (point-max))
9806 (message "Link search wrapped back to end of buffer"))
9807 (setq org-link-search-failed nil)
9808 (let* ((pos (point))
9809 (ct (org-context))
9810 (a (assoc :link ct)))
9811 (if a (goto-char (nth 1 a)))
9812 (if (re-search-backward org-any-link-re nil t)
9813 (progn
9814 (goto-char (match-beginning 0))
9815 (if (outline-invisible-p) (org-show-context)))
9816 (goto-char pos)
9817 (setq org-link-search-failed t)
9818 (error "No further link found"))))
9820 (defun org-translate-link (s)
9821 "Translate a link string if a translation function has been defined."
9822 (if (and org-link-translation-function
9823 (fboundp org-link-translation-function)
9824 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9825 (progn
9826 (setq s (funcall org-link-translation-function
9827 (match-string 1 s) (match-string 2 s)))
9828 (concat (car s) ":" (cdr s)))
9831 (defun org-translate-link-from-planner (type path)
9832 "Translate a link from Emacs Planner syntax so that Org can follow it.
9833 This is still an experimental function, your mileage may vary."
9834 (cond
9835 ((member type '("http" "https" "news" "ftp"))
9836 ;; standard Internet links are the same.
9837 nil)
9838 ((and (equal type "irc") (string-match "^//" path))
9839 ;; Planner has two / at the beginning of an irc link, we have 1.
9840 ;; We should have zero, actually....
9841 (setq path (substring path 1)))
9842 ((and (equal type "lisp") (string-match "^/" path))
9843 ;; Planner has a slash, we do not.
9844 (setq type "elisp" path (substring path 1)))
9845 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9846 ;; A typical message link. Planner has the id after the final slash,
9847 ;; we separate it with a hash mark
9848 (setq path (concat (match-string 1 path) "#"
9849 (org-remove-angle-brackets (match-string 2 path)))))
9851 (cons type path))
9853 (defun org-find-file-at-mouse (ev)
9854 "Open file link or URL at mouse."
9855 (interactive "e")
9856 (mouse-set-point ev)
9857 (org-open-at-point 'in-emacs))
9859 (defun org-open-at-mouse (ev)
9860 "Open file link or URL at mouse.
9861 See the docstring of `org-open-file' for details."
9862 (interactive "e")
9863 (mouse-set-point ev)
9864 (if (eq major-mode 'org-agenda-mode)
9865 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9866 (org-open-at-point))
9868 (defvar org-window-config-before-follow-link nil
9869 "The window configuration before following a link.
9870 This is saved in case the need arises to restore it.")
9872 (defvar org-open-link-marker (make-marker)
9873 "Marker pointing to the location where `org-open-at-point; was called.")
9875 ;;;###autoload
9876 (defun org-open-at-point-global ()
9877 "Follow a link like Org-mode does.
9878 This command can be called in any mode to follow a link that has
9879 Org-mode syntax."
9880 (interactive)
9881 (org-run-like-in-org-mode 'org-open-at-point))
9883 ;;;###autoload
9884 (defun org-open-link-from-string (s &optional arg reference-buffer)
9885 "Open a link in the string S, as if it was in Org-mode."
9886 (interactive "sLink: \nP")
9887 (let ((reference-buffer (or reference-buffer (current-buffer))))
9888 (with-temp-buffer
9889 (let ((org-inhibit-startup (not reference-buffer)))
9890 (org-mode)
9891 (insert s)
9892 (goto-char (point-min))
9893 (when reference-buffer
9894 (setq org-link-abbrev-alist-local
9895 (with-current-buffer reference-buffer
9896 org-link-abbrev-alist-local)))
9897 (org-open-at-point arg reference-buffer)))))
9899 (defvar org-open-at-point-functions nil
9900 "Hook that is run when following a link at point.
9902 Functions in this hook must return t if they identify and follow
9903 a link at point. If they don't find anything interesting at point,
9904 they must return nil.")
9906 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9907 (defun org-open-at-point (&optional arg reference-buffer)
9908 "Open link at or after point.
9909 If there is no link at point, this function will search forward up to
9910 the end of the current line.
9911 Normally, files will be opened by an appropriate application. If the
9912 optional prefix argument ARG is non-nil, Emacs will visit the file.
9913 With a double prefix argument, try to open outside of Emacs, in the
9914 application the system uses for this file type."
9915 (interactive "P")
9916 ;; if in a code block, then open the block's results
9917 (unless (call-interactively #'org-babel-open-src-block-result)
9918 (org-load-modules-maybe)
9919 (move-marker org-open-link-marker (point))
9920 (setq org-window-config-before-follow-link (current-window-configuration))
9921 (org-remove-occur-highlights nil nil t)
9922 (cond
9923 ((and (org-at-heading-p)
9924 (not (org-at-timestamp-p t))
9925 (not (org-in-regexp
9926 (concat org-plain-link-re "\\|"
9927 org-bracket-link-regexp "\\|"
9928 org-angle-link-re "\\|"
9929 "[ \t]:[^ \t\n]+:[ \t]*$")))
9930 (not (get-text-property (point) 'org-linked-text)))
9931 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9932 (lk0 (car lkall))
9933 (lk (if (stringp lk0) (list lk0) lk0))
9934 (lkend (cdr lkall)))
9935 (mapcar (lambda(l)
9936 (search-forward l nil lkend)
9937 (goto-char (match-beginning 0))
9938 (org-open-at-point))
9939 lk))
9940 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9941 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9942 ((and (org-at-timestamp-p t)
9943 (not (org-in-regexp org-bracket-link-regexp)))
9944 (org-follow-timestamp-link))
9945 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9946 (not (org-in-regexp org-any-link-re)))
9947 (org-footnote-action))
9949 (let (type path link line search (pos (point)))
9950 (catch 'match
9951 (save-excursion
9952 (skip-chars-forward "^]\n\r")
9953 (when (org-in-regexp org-bracket-link-regexp 1)
9954 (setq link (org-extract-attributes
9955 (org-link-unescape (org-match-string-no-properties 1))))
9956 (while (string-match " *\n *" link)
9957 (setq link (replace-match " " t t link)))
9958 (setq link (org-link-expand-abbrev link))
9959 (cond
9960 ((or (file-name-absolute-p link)
9961 (string-match "^\\.\\.?/" link))
9962 (setq type "file" path link))
9963 ((string-match org-link-re-with-space3 link)
9964 (setq type (match-string 1 link) path (match-string 2 link)))
9965 ((string-match "^help:+\\(.+\\)" link)
9966 (setq type "help" path (match-string 1 link)))
9967 (t (setq type "thisfile" path link)))
9968 (throw 'match t)))
9970 (when (get-text-property (point) 'org-linked-text)
9971 (setq type "thisfile"
9972 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9973 (1+ (point)) (point))
9974 path (buffer-substring
9975 (or (previous-single-property-change pos 'org-linked-text)
9976 (point-min))
9977 (or (next-single-property-change pos 'org-linked-text)
9978 (point-max))))
9979 (throw 'match t))
9981 (save-excursion
9982 (when (or (org-in-regexp org-angle-link-re)
9983 (let ((match (org-in-regexp org-plain-link-re)))
9984 ;; Check a plain link is not within a bracket link
9985 (and match
9986 (save-excursion
9987 (progn
9988 (goto-char (car match))
9989 (not (org-in-regexp org-bracket-link-regexp))))))
9990 (let ((line_ending (save-excursion (end-of-line) (point))))
9991 ;; We are in a line before a plain or bracket link
9992 (or (re-search-forward org-plain-link-re line_ending t)
9993 (re-search-forward org-bracket-link-regexp line_ending t))))
9994 (setq type (match-string 1)
9995 path (org-link-unescape (match-string 2)))
9996 (throw 'match t)))
9997 (save-excursion
9998 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9999 (setq type "tags"
10000 path (match-string 1))
10001 (while (string-match ":" path)
10002 (setq path (replace-match "+" t t path)))
10003 (throw 'match t)))
10004 (when (org-in-regexp "<\\([^><\n]+\\)>")
10005 (setq type "tree-match"
10006 path (match-string 1))
10007 (throw 'match t)))
10008 (unless path
10009 (user-error "No link found"))
10011 ;; switch back to reference buffer
10012 ;; needed when if called in a temporary buffer through
10013 ;; org-open-link-from-string
10014 (with-current-buffer (or reference-buffer (current-buffer))
10016 ;; Remove any trailing spaces in path
10017 (if (string-match " +\\'" path)
10018 (setq path (replace-match "" t t path)))
10019 (if (and org-link-translation-function
10020 (fboundp org-link-translation-function))
10021 ;; Check if we need to translate the link
10022 (let ((tmp (funcall org-link-translation-function type path)))
10023 (setq type (car tmp) path (cdr tmp))))
10025 (cond
10027 ((assoc type org-link-protocols)
10028 (funcall (nth 1 (assoc type org-link-protocols)) path))
10030 ((equal type "help")
10031 (let ((f-or-v (intern path)))
10032 (cond ((fboundp f-or-v)
10033 (describe-function f-or-v))
10034 ((boundp f-or-v)
10035 (describe-variable f-or-v))
10036 (t (error "Not a known function or variable")))))
10038 ((equal type "mailto")
10039 (let ((cmd (car org-link-mailto-program))
10040 (args (cdr org-link-mailto-program)) args1
10041 (address path) (subject "") a)
10042 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10043 (setq address (match-string 1 path)
10044 subject (org-link-escape (match-string 2 path))))
10045 (while args
10046 (cond
10047 ((not (stringp (car args))) (push (pop args) args1))
10048 (t (setq a (pop args))
10049 (if (string-match "%a" a)
10050 (setq a (replace-match address t t a)))
10051 (if (string-match "%s" a)
10052 (setq a (replace-match subject t t a)))
10053 (push a args1))))
10054 (apply cmd (nreverse args1))))
10056 ((member type '("http" "https" "ftp" "news"))
10057 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10058 (org-link-escape
10059 path org-link-escape-chars-browser)
10060 path))))
10062 ((string= type "doi")
10063 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10064 (org-link-escape
10065 path org-link-escape-chars-browser)
10066 path))))
10068 ((member type '("message"))
10069 (browse-url (concat type ":" path)))
10071 ((string= type "tags")
10072 (org-tags-view arg path))
10074 ((string= type "tree-match")
10075 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10077 ((string= type "file")
10078 (if (string-match "::\\([0-9]+\\)\\'" path)
10079 (setq line (string-to-number (match-string 1 path))
10080 path (substring path 0 (match-beginning 0)))
10081 (if (string-match "::\\(.+\\)\\'" path)
10082 (setq search (match-string 1 path)
10083 path (substring path 0 (match-beginning 0)))))
10084 (if (string-match "[*?{]" (file-name-nondirectory path))
10085 (dired path)
10086 (org-open-file path arg line search)))
10088 ((string= type "shell")
10089 (let ((buf (generate-new-buffer "*Org Shell Output"))
10090 (cmd path))
10091 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10092 (string-match org-confirm-shell-link-not-regexp cmd))
10093 (not org-confirm-shell-link-function)
10094 (funcall org-confirm-shell-link-function
10095 (format "Execute \"%s\" in shell? "
10096 (org-add-props cmd nil
10097 'face 'org-warning))))
10098 (progn
10099 (message "Executing %s" cmd)
10100 (shell-command cmd buf)
10101 (if (featurep 'midnight)
10102 (setq clean-buffer-list-kill-buffer-names
10103 (cons buf clean-buffer-list-kill-buffer-names))))
10104 (error "Abort"))))
10106 ((string= type "elisp")
10107 (let ((cmd path))
10108 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10109 (string-match org-confirm-elisp-link-not-regexp cmd))
10110 (not org-confirm-elisp-link-function)
10111 (funcall org-confirm-elisp-link-function
10112 (format "Execute \"%s\" as elisp? "
10113 (org-add-props cmd nil
10114 'face 'org-warning))))
10115 (message "%s => %s" cmd
10116 (if (equal (string-to-char cmd) ?\()
10117 (eval (read cmd))
10118 (call-interactively (read cmd))))
10119 (error "Abort"))))
10121 ((and (string= type "thisfile")
10122 (run-hook-with-args-until-success
10123 'org-open-link-functions path)))
10125 ((string= type "thisfile")
10126 (if arg
10127 (switch-to-buffer-other-window
10128 (org-get-buffer-for-internal-link (current-buffer)))
10129 (org-mark-ring-push))
10130 (let ((cmd `(org-link-search
10131 ,path
10132 ,(cond ((equal arg '(4)) ''occur)
10133 ((equal arg '(16)) ''org-occur))
10134 ,pos)))
10135 (condition-case nil (let ((org-link-search-inhibit-query t))
10136 (eval cmd))
10137 (error (progn (widen) (eval cmd))))))
10139 (t (browse-url-at-point)))))))
10140 (move-marker org-open-link-marker nil)
10141 (run-hook-with-args 'org-follow-link-hook)))
10143 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10144 "Offer links in the current entry and return the selected link.
10145 If there is only one link, return it.
10146 If NTH is an integer, return the NTH link found.
10147 If ZERO is a string, check also this string for a link, and if
10148 there is one, return it."
10149 (with-current-buffer buffer
10150 (save-excursion
10151 (save-restriction
10152 (widen)
10153 (goto-char marker)
10154 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10155 "\\(" org-angle-link-re "\\)\\|"
10156 "\\(" org-plain-link-re "\\)"))
10157 (cnt ?0)
10158 (in-emacs (if (integerp nth) nil nth))
10159 have-zero end links link c)
10160 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10161 (push (match-string 0 zero) links)
10162 (setq cnt (1- cnt) have-zero t))
10163 (save-excursion
10164 (org-back-to-heading t)
10165 (setq end (save-excursion (outline-next-heading) (point)))
10166 (while (re-search-forward re end t)
10167 (push (match-string 0) links))
10168 (setq links (org-uniquify (reverse links))))
10169 (cond
10170 ((null links)
10171 (message "No links"))
10172 ((equal (length links) 1)
10173 (setq link (car links)))
10174 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10175 (setq link (nth (if have-zero nth (1- nth)) links)))
10176 (t ; we have to select a link
10177 (save-excursion
10178 (save-window-excursion
10179 (delete-other-windows)
10180 (with-output-to-temp-buffer "*Select Link*"
10181 (mapc (lambda (l)
10182 (if (not (string-match org-bracket-link-regexp l))
10183 (princ (format "[%c] %s\n" (incf cnt)
10184 (org-remove-angle-brackets l)))
10185 (if (match-end 3)
10186 (princ (format "[%c] %s (%s)\n" (incf cnt)
10187 (match-string 3 l) (match-string 1 l)))
10188 (princ (format "[%c] %s\n" (incf cnt)
10189 (match-string 1 l))))))
10190 links))
10191 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10192 (message "Select link to open, RET to open all:")
10193 (setq c (read-char-exclusive))
10194 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10195 (when (equal c ?q) (error "Abort"))
10196 (if (equal c ?\C-m)
10197 (setq link links)
10198 (setq nth (- c ?0))
10199 (if have-zero (setq nth (1+ nth)))
10200 (unless (and (integerp nth) (>= (length links) nth))
10201 (error "Invalid link selection"))
10202 (setq link (nth (1- nth) links)))))
10203 (cons link end))))))
10205 ;; Add special file links that specify the way of opening
10207 (org-add-link-type "file+sys" 'org-open-file-with-system)
10208 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10209 (defun org-open-file-with-system (path)
10210 "Open file at PATH using the system way of opening it."
10211 (org-open-file path 'system))
10212 (defun org-open-file-with-emacs (path)
10213 "Open file at PATH in Emacs."
10214 (org-open-file path 'emacs))
10217 ;;; File search
10219 (defvar org-create-file-search-functions nil
10220 "List of functions to construct the right search string for a file link.
10221 These functions are called in turn with point at the location to
10222 which the link should point.
10224 A function in the hook should first test if it would like to
10225 handle this file type, for example by checking the `major-mode'
10226 or the file extension. If it decides not to handle this file, it
10227 should just return nil to give other functions a chance. If it
10228 does handle the file, it must return the search string to be used
10229 when following the link. The search string will be part of the
10230 file link, given after a double colon, and `org-open-at-point'
10231 will automatically search for it. If special measures must be
10232 taken to make the search successful, another function should be
10233 added to the companion hook `org-execute-file-search-functions',
10234 which see.
10236 A function in this hook may also use `setq' to set the variable
10237 `description' to provide a suggestion for the descriptive text to
10238 be used for this link when it gets inserted into an Org-mode
10239 buffer with \\[org-insert-link].")
10241 (defvar org-execute-file-search-functions nil
10242 "List of functions to execute a file search triggered by a link.
10244 Functions added to this hook must accept a single argument, the
10245 search string that was part of the file link, the part after the
10246 double colon. The function must first check if it would like to
10247 handle this search, for example by checking the `major-mode' or
10248 the file extension. If it decides not to handle this search, it
10249 should just return nil to give other functions a chance. If it
10250 does handle the search, it must return a non-nil value to keep
10251 other functions from trying.
10253 Each function can access the current prefix argument through the
10254 variable `current-prefix-argument'. Note that a single prefix is
10255 used to force opening a link in Emacs, so it may be good to only
10256 use a numeric or double prefix to guide the search function.
10258 In case this is needed, a function in this hook can also restore
10259 the window configuration before `org-open-at-point' was called using:
10261 (set-window-configuration org-window-config-before-follow-link)")
10263 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10264 (defun org-link-search (s &optional type avoid-pos stealth)
10265 "Search for a link search option.
10266 If S is surrounded by forward slashes, it is interpreted as a
10267 regular expression. In org-mode files, this will create an `org-occur'
10268 sparse tree. In ordinary files, `occur' will be used to list matches.
10269 If the current buffer is in `dired-mode', grep will be used to search
10270 in all files. If AVOID-POS is given, ignore matches near that position.
10272 When optional argument STEALTH is non-nil, do not modify
10273 visibility around point, thus ignoring
10274 `org-show-hierarchy-above', `org-show-following-heading' and
10275 `org-show-siblings' variables."
10276 (let ((case-fold-search t)
10277 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10278 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10279 (append '(("") (" ") ("\t") ("\n"))
10280 org-emphasis-alist)
10281 "\\|") "\\)"))
10282 (pos (point))
10283 (pre nil) (post nil)
10284 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10285 (cond
10286 ;; First check if there are any special search functions
10287 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10288 ;; Now try the builtin stuff
10289 ((and (equal (string-to-char s0) ?#)
10290 (> (length s0) 1)
10291 (save-excursion
10292 (goto-char (point-min))
10293 (and
10294 (re-search-forward
10295 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10296 (setq type 'dedicated
10297 pos (match-beginning 0))))
10298 ;; There is an exact target for this
10299 (goto-char pos)
10300 (org-back-to-heading t)))
10301 ((save-excursion
10302 (goto-char (point-min))
10303 (and
10304 (re-search-forward
10305 (concat "<<" (regexp-quote s0) ">>") nil t)
10306 (setq type 'dedicated
10307 pos (match-beginning 0))))
10308 ;; There is an exact target for this
10309 (goto-char pos))
10310 ((save-excursion
10311 (goto-char (point-min))
10312 (and
10313 (re-search-forward
10314 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10315 (setq type 'dedicated pos (match-beginning 0))))
10316 ;; Found an invisible target.
10317 (goto-char pos))
10318 ((save-excursion
10319 (goto-char (point-min))
10320 (and
10321 (re-search-forward
10322 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10323 (setq type 'dedicated pos (match-beginning 0))))
10324 ;; Found an element with a matching #+name affiliated keyword.
10325 (goto-char pos))
10326 ((and (string-match "^(\\(.*\\))$" s0)
10327 (save-excursion
10328 (goto-char (point-min))
10329 (and
10330 (re-search-forward
10331 (concat "[^[]" (regexp-quote
10332 (format org-coderef-label-format
10333 (match-string 1 s0))))
10334 nil t)
10335 (setq type 'dedicated
10336 pos (1+ (match-beginning 0))))))
10337 ;; There is a coderef target for this
10338 (goto-char pos))
10339 ((string-match "^/\\(.*\\)/$" s)
10340 ;; A regular expression
10341 (cond
10342 ((derived-mode-p 'org-mode)
10343 (org-occur (match-string 1 s)))
10344 ;;((eq major-mode 'dired-mode)
10345 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10346 (t (org-do-occur (match-string 1 s)))))
10347 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10348 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10349 (goto-char (point-min))
10350 (cond
10351 ((let (case-fold-search)
10352 (re-search-forward (format org-complex-heading-regexp-format
10353 (regexp-quote s))
10354 nil t))
10355 ;; OK, found a match
10356 (setq type 'dedicated)
10357 (goto-char (match-beginning 0)))
10358 ((and (not org-link-search-inhibit-query)
10359 (eq org-link-search-must-match-exact-headline 'query-to-create)
10360 (y-or-n-p "No match - create this as a new heading? "))
10361 (goto-char (point-max))
10362 (or (bolp) (newline))
10363 (insert "* " s "\n")
10364 (beginning-of-line 0))
10366 (goto-char pos)
10367 (error "No match"))))
10369 ;; A normal search string
10370 (when (equal (string-to-char s) ?*)
10371 ;; Anchor on headlines, post may include tags.
10372 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10373 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10374 s (substring s 1)))
10375 (remove-text-properties
10376 0 (length s)
10377 '(face nil mouse-face nil keymap nil fontified nil) s)
10378 ;; Make a series of regular expressions to find a match
10379 (setq words (org-split-string s "[ \n\r\t]+")
10381 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10382 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10383 "\\)" markers)
10384 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10385 re2a (concat "[ \t\r\n]" re2a_)
10386 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10387 re4 (concat "[^a-zA-Z_]" re4_)
10389 re1 (concat pre re2 post)
10390 re3 (concat pre (if pre re4_ re4) post)
10391 re5 (concat pre ".*" re4)
10392 re2 (concat pre re2)
10393 re2a (concat pre (if pre re2a_ re2a))
10394 re4 (concat pre (if pre re4_ re4))
10395 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10396 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10397 re5 "\\)"
10399 (cond
10400 ((eq type 'org-occur) (org-occur reall))
10401 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10402 (t (goto-char (point-min))
10403 (setq type 'fuzzy)
10404 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10405 (org-search-not-self 1 re1 nil t)
10406 (org-search-not-self 1 re2 nil t)
10407 (org-search-not-self 1 re2a nil t)
10408 (org-search-not-self 1 re3 nil t)
10409 (org-search-not-self 1 re4 nil t)
10410 (org-search-not-self 1 re5 nil t)
10412 (goto-char (match-beginning 1))
10413 (goto-char pos)
10414 (error "No match"))))))
10415 (and (derived-mode-p 'org-mode)
10416 (not stealth)
10417 (org-show-context 'link-search))
10418 type))
10420 (defun org-search-not-self (group &rest args)
10421 "Execute `re-search-forward', but only accept matches that do not
10422 enclose the position of `org-open-link-marker'."
10423 (let ((m org-open-link-marker))
10424 (catch 'exit
10425 (while (apply 're-search-forward args)
10426 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10427 (goto-char (match-end group))
10428 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10429 (> (match-beginning 0) (marker-position m))
10430 (< (match-end 0) (marker-position m)))
10431 (save-match-data
10432 (or (not (org-in-regexp
10433 org-bracket-link-analytic-regexp 1))
10434 (not (match-end 4)) ; no description
10435 (and (<= (match-beginning 4) (point))
10436 (>= (match-end 4) (point))))))
10437 (throw 'exit (point))))))))
10439 (defun org-get-buffer-for-internal-link (buffer)
10440 "Return a buffer to be used for displaying the link target of internal links."
10441 (cond
10442 ((not org-display-internal-link-with-indirect-buffer)
10443 buffer)
10444 ((string-match "(Clone)$" (buffer-name buffer))
10445 (message "Buffer is already a clone, not making another one")
10446 ;; we also do not modify visibility in this case
10447 buffer)
10448 (t ; make a new indirect buffer for displaying the link
10449 (let* ((bn (buffer-name buffer))
10450 (ibn (concat bn "(Clone)"))
10451 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10452 (with-current-buffer ib (org-overview))
10453 ib))))
10455 (defun org-do-occur (regexp &optional cleanup)
10456 "Call the Emacs command `occur'.
10457 If CLEANUP is non-nil, remove the printout of the regular expression
10458 in the *Occur* buffer. This is useful if the regex is long and not useful
10459 to read."
10460 (occur regexp)
10461 (when cleanup
10462 (let ((cwin (selected-window)) win beg end)
10463 (when (setq win (get-buffer-window "*Occur*"))
10464 (select-window win))
10465 (goto-char (point-min))
10466 (when (re-search-forward "match[a-z]+" nil t)
10467 (setq beg (match-end 0))
10468 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10469 (setq end (1- (match-beginning 0)))))
10470 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10471 (goto-char (point-min))
10472 (select-window cwin))))
10474 ;;; The mark ring for links jumps
10476 (defvar org-mark-ring nil
10477 "Mark ring for positions before jumps in Org-mode.")
10478 (defvar org-mark-ring-last-goto nil
10479 "Last position in the mark ring used to go back.")
10480 ;; Fill and close the ring
10481 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10482 (loop for i from 1 to org-mark-ring-length do
10483 (push (make-marker) org-mark-ring))
10484 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10485 org-mark-ring)
10487 (defun org-mark-ring-push (&optional pos buffer)
10488 "Put the current position or POS into the mark ring and rotate it."
10489 (interactive)
10490 (setq pos (or pos (point)))
10491 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10492 (move-marker (car org-mark-ring)
10493 (or pos (point))
10494 (or buffer (current-buffer)))
10495 (message "%s"
10496 (substitute-command-keys
10497 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10499 (defun org-mark-ring-goto (&optional n)
10500 "Jump to the previous position in the mark ring.
10501 With prefix arg N, jump back that many stored positions. When
10502 called several times in succession, walk through the entire ring.
10503 Org-mode commands jumping to a different position in the current file,
10504 or to another Org-mode file, automatically push the old position
10505 onto the ring."
10506 (interactive "p")
10507 (let (p m)
10508 (if (eq last-command this-command)
10509 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10510 (setq p org-mark-ring))
10511 (setq org-mark-ring-last-goto p)
10512 (setq m (car p))
10513 (org-pop-to-buffer-same-window (marker-buffer m))
10514 (goto-char m)
10515 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10517 (defun org-remove-angle-brackets (s)
10518 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10519 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10521 (defun org-add-angle-brackets (s)
10522 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10523 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10525 (defun org-remove-double-quotes (s)
10526 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10527 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10530 ;;; Following specific links
10532 (defun org-follow-timestamp-link ()
10533 "Open an agenda view for the time-stamp date/range at point."
10534 (cond
10535 ((org-at-date-range-p t)
10536 (let ((org-agenda-start-on-weekday)
10537 (t1 (match-string 1))
10538 (t2 (match-string 2)) tt1 tt2)
10539 (setq tt1 (time-to-days (org-time-string-to-time t1))
10540 tt2 (time-to-days (org-time-string-to-time t2)))
10541 (let ((org-agenda-buffer-tmp-name
10542 (format "*Org Agenda(a:%s)"
10543 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10544 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10545 ((org-at-timestamp-p t)
10546 (let ((org-agenda-buffer-tmp-name
10547 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10548 (org-agenda-list nil (time-to-days (org-time-string-to-time
10549 (substring (match-string 1) 0 10)))
10550 1)))
10551 (t (error "This should not happen"))))
10554 ;;; Following file links
10555 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10556 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10557 (declare-function mailcap-mime-info
10558 "mailcap" (string &optional request no-decode))
10559 (defvar org-wait nil)
10560 (defun org-open-file (path &optional in-emacs line search)
10561 "Open the file at PATH.
10562 First, this expands any special file name abbreviations. Then the
10563 configuration variable `org-file-apps' is checked if it contains an
10564 entry for this file type, and if yes, the corresponding command is launched.
10566 If no application is found, Emacs simply visits the file.
10568 With optional prefix argument IN-EMACS, Emacs will visit the file.
10569 With a double \\[universal-argument] \\[universal-argument] \
10570 prefix arg, Org tries to avoid opening in Emacs
10571 and to use an external application to visit the file.
10573 Optional LINE specifies a line to go to, optional SEARCH a string
10574 to search for. If LINE or SEARCH is given, the file will be
10575 opened in Emacs, unless an entry from org-file-apps that makes
10576 use of groups in a regexp matches.
10578 If you want to change the way frames are used when following a
10579 link, please customize `org-link-frame-setup'.
10581 If the file does not exist, an error is thrown."
10582 (let* ((file (if (equal path "")
10583 buffer-file-name
10584 (substitute-in-file-name (expand-file-name path))))
10585 (file-apps (append org-file-apps (org-default-apps)))
10586 (apps (org-remove-if
10587 'org-file-apps-entry-match-against-dlink-p file-apps))
10588 (apps-dlink (org-remove-if-not
10589 'org-file-apps-entry-match-against-dlink-p file-apps))
10590 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10591 (dirp (if remp nil (file-directory-p file)))
10592 (file (if (and dirp org-open-directory-means-index-dot-org)
10593 (concat (file-name-as-directory file) "index.org")
10594 file))
10595 (a-m-a-p (assq 'auto-mode apps))
10596 (dfile (downcase file))
10597 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10598 (link (cond ((and (eq line nil)
10599 (eq search nil))
10600 file)
10601 (line
10602 (concat file "::" (number-to-string line)))
10603 (search
10604 (concat file "::" search))))
10605 (dlink (downcase link))
10606 (old-buffer (current-buffer))
10607 (old-pos (point))
10608 (old-mode major-mode)
10609 ext cmd link-match-data)
10610 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10611 (setq ext (match-string 1 dfile))
10612 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10613 (setq ext (match-string 1 dfile))))
10614 (cond
10615 ((member in-emacs '((16) system))
10616 (setq cmd (cdr (assoc 'system apps))))
10617 (in-emacs (setq cmd 'emacs))
10619 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10620 (and dirp (cdr (assoc 'directory apps)))
10621 ; first, try matching against apps-dlink
10622 ; if we get a match here, store the match data for later
10623 (let ((match (assoc-default dlink apps-dlink
10624 'string-match)))
10625 (if match
10626 (progn (setq link-match-data (match-data))
10627 match)
10628 (progn (setq in-emacs (or in-emacs line search))
10629 nil))) ; if we have no match in apps-dlink,
10630 ; always open the file in emacs if line or search
10631 ; is given (for backwards compatibility)
10632 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10633 'string-match)
10634 (cdr (assoc ext apps))
10635 (cdr (assoc t apps))))))
10636 (when (eq cmd 'system)
10637 (setq cmd (cdr (assoc 'system apps))))
10638 (when (eq cmd 'default)
10639 (setq cmd (cdr (assoc t apps))))
10640 (when (eq cmd 'mailcap)
10641 (require 'mailcap)
10642 (mailcap-parse-mailcaps)
10643 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10644 (command (mailcap-mime-info mime-type)))
10645 (if (stringp command)
10646 (setq cmd command)
10647 (setq cmd 'emacs))))
10648 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10649 (not (file-exists-p file))
10650 (not org-open-non-existing-files))
10651 (error "No such file: %s" file))
10652 (cond
10653 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10654 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10655 (while (string-match "['\"]%s['\"]" cmd)
10656 (setq cmd (replace-match "%s" t t cmd)))
10657 (while (string-match "%s" cmd)
10658 (setq cmd (replace-match
10659 (save-match-data
10660 (shell-quote-argument
10661 (convert-standard-filename file)))
10662 t t cmd)))
10664 ;; Replace "%1", "%2" etc. in command with group matches from regex
10665 (save-match-data
10666 (let ((match-index 1)
10667 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10668 (set-match-data link-match-data)
10669 (while (<= match-index number-of-groups)
10670 (let ((regex (concat "%" (number-to-string match-index)))
10671 (replace-with (match-string match-index dlink)))
10672 (while (string-match regex cmd)
10673 (setq cmd (replace-match replace-with t t cmd))))
10674 (setq match-index (+ match-index 1)))))
10676 (save-window-excursion
10677 (message "Running %s...done" cmd)
10678 (start-process-shell-command cmd nil cmd)
10679 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10680 ((or (stringp cmd)
10681 (eq cmd 'emacs))
10682 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10683 (widen)
10684 (if line (org-goto-line line)
10685 (if search (org-link-search search))))
10686 ((consp cmd)
10687 (let ((file (convert-standard-filename file)))
10688 (save-match-data
10689 (set-match-data link-match-data)
10690 (eval cmd))))
10691 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10692 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10693 (or (not (equal old-buffer (current-buffer)))
10694 (not (equal old-pos (point))))
10695 (org-mark-ring-push old-pos old-buffer))))
10697 (defun org-file-apps-entry-match-against-dlink-p (entry)
10698 "This function returns non-nil if `entry' uses a regular
10699 expression which should be matched against the whole link by
10700 org-open-file.
10702 It assumes that is the case when the entry uses a regular
10703 expression which has at least one grouping construct and the
10704 action is either a lisp form or a command string containing
10705 '%1', i.e. using at least one subexpression match as a
10706 parameter."
10707 (let ((selector (car entry))
10708 (action (cdr entry)))
10709 (if (stringp selector)
10710 (and (> (regexp-opt-depth selector) 0)
10711 (or (and (stringp action)
10712 (string-match "%[0-9]" action))
10713 (consp action)))
10714 nil)))
10716 (defun org-default-apps ()
10717 "Return the default applications for this operating system."
10718 (cond
10719 ((eq system-type 'darwin)
10720 org-file-apps-defaults-macosx)
10721 ((eq system-type 'windows-nt)
10722 org-file-apps-defaults-windowsnt)
10723 (t org-file-apps-defaults-gnu)))
10725 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10726 "Convert extensions to regular expressions in the cars of LIST.
10727 Also, weed out any non-string entries, because the return value is used
10728 only for regexp matching.
10729 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10730 point to the symbol `emacs', indicating that the file should
10731 be opened in Emacs."
10732 (append
10733 (delq nil
10734 (mapcar (lambda (x)
10735 (if (not (stringp (car x)))
10737 (if (string-match "\\W" (car x))
10739 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10740 list))
10741 (if add-auto-mode
10742 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10744 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10745 (defun org-file-remote-p (file)
10746 "Test whether FILE specifies a location on a remote system.
10747 Return non-nil if the location is indeed remote.
10749 For example, the filename \"/user@host:/foo\" specifies a location
10750 on the system \"/user@host:\"."
10751 (cond ((fboundp 'file-remote-p)
10752 (file-remote-p file))
10753 ((fboundp 'tramp-handle-file-remote-p)
10754 (tramp-handle-file-remote-p file))
10755 ((and (boundp 'ange-ftp-name-format)
10756 (string-match (car ange-ftp-name-format) file))
10757 t)))
10760 ;;;; Refiling
10762 (defun org-get-org-file ()
10763 "Read a filename, with default directory `org-directory'."
10764 (let ((default (or org-default-notes-file remember-data-file)))
10765 (read-file-name (format "File name [%s]: " default)
10766 (file-name-as-directory org-directory)
10767 default)))
10769 (defun org-notes-order-reversed-p ()
10770 "Check if the current file should receive notes in reversed order."
10771 (cond
10772 ((not org-reverse-note-order) nil)
10773 ((eq t org-reverse-note-order) t)
10774 ((not (listp org-reverse-note-order)) nil)
10775 (t (catch 'exit
10776 (let ((all org-reverse-note-order)
10777 entry)
10778 (while (setq entry (pop all))
10779 (if (string-match (car entry) buffer-file-name)
10780 (throw 'exit (cdr entry))))
10781 nil)))))
10783 (defvar org-refile-target-table nil
10784 "The list of refile targets, created by `org-refile'.")
10786 (defvar org-agenda-new-buffers nil
10787 "Buffers created to visit agenda files.")
10789 (defvar org-refile-cache nil
10790 "Cache for refile targets.")
10792 (defvar org-refile-markers nil
10793 "All the markers used for caching refile locations.")
10795 (defun org-refile-marker (pos)
10796 "Get a new refile marker, but only if caching is in use."
10797 (if (not org-refile-use-cache)
10799 (let ((m (make-marker)))
10800 (move-marker m pos)
10801 (push m org-refile-markers)
10802 m)))
10804 (defun org-refile-cache-clear ()
10805 "Clear the refile cache and disable all the markers."
10806 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10807 (setq org-refile-markers nil)
10808 (setq org-refile-cache nil)
10809 (message "Refile cache has been cleared"))
10811 (defun org-refile-cache-check-set (set)
10812 "Check if all the markers in the cache still have live buffers."
10813 (let (marker)
10814 (catch 'exit
10815 (while (and set (setq marker (nth 3 (pop set))))
10816 ;; if org-refile-use-outline-path is 'file, marker may be nil
10817 (when (and marker (null (marker-buffer marker)))
10818 (message "not found") (sit-for 3)
10819 (throw 'exit nil)))
10820 t)))
10822 (defun org-refile-cache-put (set &rest identifiers)
10823 "Push the refile targets SET into the cache, under IDENTIFIERS."
10824 (let* ((key (sha1 (prin1-to-string identifiers)))
10825 (entry (assoc key org-refile-cache)))
10826 (if entry
10827 (setcdr entry set)
10828 (push (cons key set) org-refile-cache))))
10830 (defun org-refile-cache-get (&rest identifiers)
10831 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10832 (cond
10833 ((not org-refile-cache) nil)
10834 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10836 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10837 org-refile-cache))))
10838 (and set (org-refile-cache-check-set set) set)))))
10840 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10841 "Produce a table with refile targets."
10842 (let ((case-fold-search nil)
10843 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10844 (entries (or org-refile-targets '((nil . (:level . 1)))))
10845 targets tgs txt re files f desc descre fast-path-p level pos0)
10846 (message "Getting targets...")
10847 (with-current-buffer (or default-buffer (current-buffer))
10848 (while (setq entry (pop entries))
10849 (setq files (car entry) desc (cdr entry))
10850 (setq fast-path-p nil)
10851 (cond
10852 ((null files) (setq files (list (current-buffer))))
10853 ((eq files 'org-agenda-files)
10854 (setq files (org-agenda-files 'unrestricted)))
10855 ((and (symbolp files) (fboundp files))
10856 (setq files (funcall files)))
10857 ((and (symbolp files) (boundp files))
10858 (setq files (symbol-value files))))
10859 (if (stringp files) (setq files (list files)))
10860 (cond
10861 ((eq (car desc) :tag)
10862 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10863 ((eq (car desc) :todo)
10864 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10865 ((eq (car desc) :regexp)
10866 (setq descre (cdr desc)))
10867 ((eq (car desc) :level)
10868 (setq descre (concat "^\\*\\{" (number-to-string
10869 (if org-odd-levels-only
10870 (1- (* 2 (cdr desc)))
10871 (cdr desc)))
10872 "\\}[ \t]")))
10873 ((eq (car desc) :maxlevel)
10874 (setq fast-path-p t)
10875 (setq descre (concat "^\\*\\{1," (number-to-string
10876 (if org-odd-levels-only
10877 (1- (* 2 (cdr desc)))
10878 (cdr desc)))
10879 "\\}[ \t]")))
10880 (t (error "Bad refiling target description %s" desc)))
10881 (while (setq f (pop files))
10882 (with-current-buffer
10883 (if (bufferp f) f (org-get-agenda-file-buffer f))
10885 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10886 (progn
10887 (if (bufferp f) (setq f (buffer-file-name
10888 (buffer-base-buffer f))))
10889 (setq f (and f (expand-file-name f)))
10890 (if (eq org-refile-use-outline-path 'file)
10891 (push (list (file-name-nondirectory f) f nil nil) tgs))
10892 (save-excursion
10893 (save-restriction
10894 (widen)
10895 (goto-char (point-min))
10896 (while (re-search-forward descre nil t)
10897 (goto-char (setq pos0 (point-at-bol)))
10898 (catch 'next
10899 (when org-refile-target-verify-function
10900 (save-match-data
10901 (or (funcall org-refile-target-verify-function)
10902 (throw 'next t))))
10903 (when (and (looking-at org-complex-heading-regexp)
10904 (not (member (match-string 4) excluded-entries))
10905 (match-string 4))
10906 (setq level (org-reduced-level
10907 (- (match-end 1) (match-beginning 1)))
10908 txt (org-link-display-format (match-string 4))
10909 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10910 re (format org-complex-heading-regexp-format
10911 (regexp-quote (match-string 4))))
10912 (when org-refile-use-outline-path
10913 (setq txt (mapconcat
10914 'org-protect-slash
10915 (append
10916 (if (eq org-refile-use-outline-path
10917 'file)
10918 (list (file-name-nondirectory
10919 (buffer-file-name
10920 (buffer-base-buffer))))
10921 (if (eq org-refile-use-outline-path
10922 'full-file-path)
10923 (list (buffer-file-name
10924 (buffer-base-buffer)))))
10925 (org-get-outline-path fast-path-p
10926 level txt)
10927 (list txt))
10928 "/")))
10929 (push (list txt f re (org-refile-marker (point)))
10930 tgs)))
10931 (when (= (point) pos0)
10932 ;; verification function has not moved point
10933 (goto-char (point-at-eol))))))))
10934 (when org-refile-use-cache
10935 (org-refile-cache-put tgs (buffer-file-name) descre))
10936 (setq targets (append tgs targets))
10937 ))))
10938 (message "Getting targets...done")
10939 (nreverse targets)))
10941 (defun org-protect-slash (s)
10942 (while (string-match "/" s)
10943 (setq s (replace-match "\\" t t s)))
10946 (defvar org-olpa (make-vector 20 nil))
10948 (defun org-get-outline-path (&optional fastp level heading)
10949 "Return the outline path to the current entry, as a list.
10951 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10952 routine which makes outline path derivations for an entire file,
10953 avoiding backtracing. Refile target collection makes use of that."
10954 (if fastp
10955 (progn
10956 (if (> level 19)
10957 (error "Outline path failure, more than 19 levels"))
10958 (loop for i from level upto 19 do
10959 (aset org-olpa i nil))
10960 (prog1
10961 (delq nil (append org-olpa nil))
10962 (aset org-olpa level heading)))
10963 (let (rtn case-fold-search)
10964 (save-excursion
10965 (save-restriction
10966 (widen)
10967 (while (org-up-heading-safe)
10968 (when (looking-at org-complex-heading-regexp)
10969 (push (org-match-string-no-properties 4) rtn)))
10970 rtn)))))
10972 (defun org-format-outline-path (path &optional width prefix separator)
10973 "Format the outline path PATH for display.
10974 WIDTH is the maximum number of characters that is available.
10975 PREFIX is a prefix to be included in the returned string,
10976 such as the file name.
10977 SEPARATOR is inserted between the different parts of the path,
10978 the default is \"/\"."
10979 (setq width (or width 79))
10980 (if prefix (setq width (- width (length prefix))))
10981 (if (not path)
10982 (or prefix "")
10983 (let* ((nsteps (length path))
10984 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10985 (maxwidth (if (<= total-width width)
10986 10000 ;; everything fits
10987 ;; we need to shorten the level headings
10988 (/ (- width nsteps) nsteps)))
10989 (org-odd-levels-only nil)
10990 (n 0)
10991 (total (1+ (length prefix))))
10992 (setq maxwidth (max maxwidth 10))
10993 (concat prefix
10994 (if prefix (or separator "/"))
10995 (mapconcat
10996 (lambda (h)
10997 (setq n (1+ n))
10998 (if (and (= n nsteps) (< maxwidth 10000))
10999 (setq maxwidth (- total-width total)))
11000 (if (< (length h) maxwidth)
11001 (progn (setq total (+ total (length h) 1)) h)
11002 (setq h (substring h 0 (- maxwidth 2))
11003 total (+ total maxwidth 1))
11004 (if (string-match "[ \t]+\\'" h)
11005 (setq h (substring h 0 (match-beginning 0))))
11006 (setq h (concat h "..")))
11007 (org-add-props h nil 'face
11008 (nth (% (1- n) org-n-level-faces)
11009 org-level-faces))
11011 path (or separator "/"))))))
11013 (defun org-display-outline-path (&optional file current separator just-return-string)
11014 "Display the current outline path in the echo area.
11016 If FILE is non-nil, prepend the output with the file name.
11017 If CURRENT is non-nil, append the current heading to the output.
11018 SEPARATOR is passed through to `org-format-outline-path'. It separates
11019 the different parts of the path and defaults to \"/\".
11020 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11021 (interactive "P")
11022 (let* (case-fold-search
11023 message-log-max ; Don't populate the *Messages* buffer
11024 (bfn (buffer-file-name (buffer-base-buffer)))
11025 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11026 res)
11027 (if current (setq path (append path
11028 (save-excursion
11029 (org-back-to-heading t)
11030 (if (looking-at org-complex-heading-regexp)
11031 (list (match-string 4)))))))
11032 (setq res
11033 (org-format-outline-path
11034 path
11035 (1- (frame-width))
11036 (and file bfn (concat (file-name-nondirectory bfn) separator))
11037 separator))
11038 (if just-return-string
11039 (org-no-properties res)
11040 (message "%s" res))))
11042 (defvar org-refile-history nil
11043 "History for refiling operations.")
11045 (defvar org-after-refile-insert-hook nil
11046 "Hook run after `org-refile' has inserted its stuff at the new location.
11047 Note that this is still *before* the stuff will be removed from
11048 the *old* location.")
11050 (defvar org-capture-last-stored-marker)
11051 (defvar org-refile-keep nil
11052 "Non-nil means `org-refile' will copy instead of refile.")
11054 (defun org-copy ()
11055 "Like `org-refile', but copy."
11056 (interactive)
11057 (let ((org-refile-keep t))
11058 (funcall 'org-refile nil nil nil "Copy")))
11060 (defun org-refile (&optional goto default-buffer rfloc msg)
11061 "Move the entry or entries at point to another heading.
11062 The list of target headings is compiled using the information in
11063 `org-refile-targets', which see.
11065 At the target location, the entry is filed as a subitem of the target
11066 heading. Depending on `org-reverse-note-order', the new subitem will
11067 either be the first or the last subitem.
11069 If there is an active region, all entries in that region will be moved.
11070 However, the region must fulfill the requirement that the first heading
11071 is the first one sets the top-level of the moved text - at most siblings
11072 below it are allowed.
11074 With prefix arg GOTO, the command will only visit the target location
11075 and not actually move anything.
11077 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11078 go to the location where the last refiling operation has put the subtree.
11079 With a prefix argument of `2', refile to the running clock.
11081 RFLOC can be a refile location obtained in a different way.
11083 MSG is a string to replace \"Refile\" in the default prompt with
11084 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11086 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11088 If you are using target caching (see `org-refile-use-cache'),
11089 you have to clear the target cache in order to find new targets.
11090 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11091 prefix argument (`C-u C-u C-u C-c C-w')."
11093 (interactive "P")
11094 (if (member goto '(0 (64)))
11095 (org-refile-cache-clear)
11096 (let* ((actionmsg (or msg "Refile"))
11097 (cbuf (current-buffer))
11098 (regionp (org-region-active-p))
11099 (region-start (and regionp (region-beginning)))
11100 (region-end (and regionp (region-end)))
11101 (region-length (and regionp (- region-end region-start)))
11102 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11103 pos it nbuf file re level reversed)
11104 (setq last-command nil)
11105 (when regionp
11106 (goto-char region-start)
11107 (or (bolp) (goto-char (point-at-bol)))
11108 (setq region-start (point))
11109 (unless (or (org-kill-is-subtree-p
11110 (buffer-substring region-start region-end))
11111 (prog1 org-refile-active-region-within-subtree
11112 (org-toggle-heading)))
11113 (error "The region is not a (sequence of) subtree(s)")))
11114 (if (equal goto '(16))
11115 (org-refile-goto-last-stored)
11116 (when (or
11117 (and (equal goto 2)
11118 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11119 (prog1
11120 (setq it (list (or org-clock-heading "running clock")
11121 (buffer-file-name
11122 (marker-buffer org-clock-hd-marker))
11124 (marker-position org-clock-hd-marker)))
11125 (setq goto nil)))
11126 (setq it (or rfloc
11127 (let (heading-text)
11128 (save-excursion
11129 (unless goto
11130 (org-back-to-heading t)
11131 (setq heading-text
11132 (nth 4 (org-heading-components))))
11134 (org-refile-get-location
11135 (cond (goto "Goto")
11136 (regionp (concat actionmsg " region to"))
11137 (t (concat actionmsg " subtree \""
11138 heading-text "\" to")))
11139 default-buffer
11140 (and (not (equal '(4) goto))
11141 org-refile-allow-creating-parent-nodes)
11142 goto))))))
11143 (setq file (nth 1 it)
11144 re (nth 2 it)
11145 pos (nth 3 it))
11146 (if (and (not goto)
11148 (equal (buffer-file-name) file)
11149 (if regionp
11150 (and (>= pos region-start)
11151 (<= pos region-end))
11152 (and (>= pos (point))
11153 (< pos (save-excursion
11154 (org-end-of-subtree t t))))))
11155 (error "Cannot refile to position inside the tree or region"))
11157 (setq nbuf (or (find-buffer-visiting file)
11158 (find-file-noselect file)))
11159 (if goto
11160 (progn
11161 (org-pop-to-buffer-same-window nbuf)
11162 (goto-char pos)
11163 (org-show-context 'org-goto))
11164 (if regionp
11165 (progn
11166 (org-kill-new (buffer-substring region-start region-end))
11167 (org-save-markers-in-region region-start region-end))
11168 (org-copy-subtree 1 nil t))
11169 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11170 (find-file-noselect file)))
11171 (setq reversed (org-notes-order-reversed-p))
11172 (save-excursion
11173 (save-restriction
11174 (widen)
11175 (if pos
11176 (progn
11177 (goto-char pos)
11178 (looking-at org-outline-regexp)
11179 (setq level (org-get-valid-level (funcall outline-level) 1))
11180 (goto-char
11181 (if reversed
11182 (or (outline-next-heading) (point-max))
11183 (or (save-excursion (org-get-next-sibling))
11184 (org-end-of-subtree t t)
11185 (point-max)))))
11186 (setq level 1)
11187 (if (not reversed)
11188 (goto-char (point-max))
11189 (goto-char (point-min))
11190 (or (outline-next-heading) (goto-char (point-max)))))
11191 (if (not (bolp)) (newline))
11192 (org-paste-subtree level)
11193 (when org-log-refile
11194 (org-add-log-setup 'refile nil nil 'findpos
11195 org-log-refile)
11196 (unless (eq org-log-refile 'note)
11197 (save-excursion (org-add-log-note))))
11198 (and org-auto-align-tags
11199 (let ((org-loop-over-headlines-in-active-region nil))
11200 (org-set-tags nil t)))
11201 (with-demoted-errors
11202 (bookmark-set "org-refile-last-stored"))
11203 ;; If we are refiling for capture, make sure that the
11204 ;; last-capture pointers point here
11205 (when (org-bound-and-true-p org-refile-for-capture)
11206 (with-demoted-errors
11207 (bookmark-set "org-capture-last-stored-marker"))
11208 (move-marker org-capture-last-stored-marker (point)))
11209 (if (fboundp 'deactivate-mark) (deactivate-mark))
11210 (run-hooks 'org-after-refile-insert-hook))))
11211 (unless org-refile-keep
11212 (if regionp
11213 (delete-region (point) (+ (point) region-length))
11214 (org-cut-subtree)))
11215 (when (featurep 'org-inlinetask)
11216 (org-inlinetask-remove-END-maybe))
11217 (setq org-markers-to-move nil)
11218 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11220 (defun org-refile-goto-last-stored ()
11221 "Go to the location where the last refile was stored."
11222 (interactive)
11223 (bookmark-jump "org-refile-last-stored")
11224 (message "This is the location of the last refile"))
11226 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11227 no-exclude)
11228 "Prompt the user for a refile location, using PROMPT.
11229 PROMPT should not be suffixed with a colon and a space, because
11230 this function appends the default value from
11231 `org-refile-history' automatically, if that is not empty.
11232 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11233 this is used for the GOTO interface."
11234 (let ((org-refile-targets org-refile-targets)
11235 (org-refile-use-outline-path org-refile-use-outline-path)
11236 excluded-entries)
11237 (when (and (derived-mode-p 'org-mode)
11238 (not org-refile-use-cache)
11239 (not no-exclude))
11240 (org-map-tree
11241 (lambda()
11242 (setq excluded-entries
11243 (append excluded-entries (list (org-get-heading t t)))))))
11244 (setq org-refile-target-table
11245 (org-refile-get-targets default-buffer excluded-entries)))
11246 (unless org-refile-target-table
11247 (error "No refile targets"))
11248 (let* ((cbuf (current-buffer))
11249 (partial-completion-mode nil)
11250 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11251 (cfunc (if (and org-refile-use-outline-path
11252 org-outline-path-complete-in-steps)
11253 'org-olpath-completing-read
11254 'org-icompleting-read))
11255 (extra (if org-refile-use-outline-path "/" ""))
11256 (cbnex (concat (buffer-name) extra))
11257 (filename (and cfn (expand-file-name cfn)))
11258 (tbl (mapcar
11259 (lambda (x)
11260 (if (and (not (member org-refile-use-outline-path
11261 '(file full-file-path)))
11262 (not (equal filename (nth 1 x))))
11263 (cons (concat (car x) extra " ("
11264 (file-name-nondirectory (nth 1 x)) ")")
11265 (cdr x))
11266 (cons (concat (car x) extra) (cdr x))))
11267 org-refile-target-table))
11268 (completion-ignore-case t)
11269 cdef
11270 (prompt (concat prompt
11271 (or (and (car org-refile-history)
11272 (concat " (default " (car org-refile-history) ")"))
11273 (and (assoc cbnex tbl) (setq cdef cbnex)
11274 (concat " (default " cbnex ")"))) ": "))
11275 pa answ parent-target child parent old-hist)
11276 (setq old-hist org-refile-history)
11277 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11278 nil 'org-refile-history (or cdef (car org-refile-history))))
11279 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11280 (org-refile-check-position pa)
11281 (if pa
11282 (progn
11283 (when (or (not org-refile-history)
11284 (not (eq old-hist org-refile-history))
11285 (not (equal (car pa) (car org-refile-history))))
11286 (setq org-refile-history
11287 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11288 org-refile-history
11289 (cdr org-refile-history))))
11290 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11291 (pop org-refile-history)))
11293 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11294 (progn
11295 (setq parent (match-string 1 answ)
11296 child (match-string 2 answ))
11297 (setq parent-target (or (assoc parent tbl)
11298 (assoc (concat parent "/") tbl)))
11299 (when (and parent-target
11300 (or (eq new-nodes t)
11301 (and (eq new-nodes 'confirm)
11302 (y-or-n-p (format "Create new node \"%s\"? "
11303 child)))))
11304 (org-refile-new-child parent-target child)))
11305 (error "Invalid target location")))))
11307 (declare-function org-string-nw-p "org-macs" (s))
11308 (defun org-refile-check-position (refile-pointer)
11309 "Check if the refile pointer matches the headline to which it points."
11310 (let* ((file (nth 1 refile-pointer))
11311 (re (nth 2 refile-pointer))
11312 (pos (nth 3 refile-pointer))
11313 buffer)
11314 (if (and (not (markerp pos)) (not file))
11315 (error "Please save the buffer to a file before refiling")
11316 (when (org-string-nw-p re)
11317 (setq buffer (if (markerp pos)
11318 (marker-buffer pos)
11319 (or (find-buffer-visiting file)
11320 (find-file-noselect file))))
11321 (with-current-buffer buffer
11322 (save-excursion
11323 (save-restriction
11324 (widen)
11325 (goto-char pos)
11326 (beginning-of-line 1)
11327 (unless (org-looking-at-p re)
11328 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11330 (defun org-refile-new-child (parent-target child)
11331 "Use refile target PARENT-TARGET to add new CHILD below it."
11332 (unless parent-target
11333 (error "Cannot find parent for new node"))
11334 (let ((file (nth 1 parent-target))
11335 (pos (nth 3 parent-target))
11336 level)
11337 (with-current-buffer (or (find-buffer-visiting file)
11338 (find-file-noselect file))
11339 (save-excursion
11340 (save-restriction
11341 (widen)
11342 (if pos
11343 (goto-char pos)
11344 (goto-char (point-max))
11345 (if (not (bolp)) (newline)))
11346 (when (looking-at org-outline-regexp)
11347 (setq level (funcall outline-level))
11348 (org-end-of-subtree t t))
11349 (org-back-over-empty-lines)
11350 (insert "\n" (make-string
11351 (if pos (org-get-valid-level level 1) 1) ?*)
11352 " " child "\n")
11353 (beginning-of-line 0)
11354 (list (concat (car parent-target) "/" child) file "" (point)))))))
11356 (defun org-olpath-completing-read (prompt collection &rest args)
11357 "Read an outline path like a file name."
11358 (let ((thetable collection)
11359 (org-completion-use-ido nil) ; does not work with ido.
11360 (org-completion-use-iswitchb nil)) ; or iswitchb
11361 (apply
11362 'org-icompleting-read prompt
11363 (lambda (string predicate &optional flag)
11364 (let (rtn r f (l (length string)))
11365 (cond
11366 ((eq flag nil)
11367 ;; try completion
11368 (try-completion string thetable))
11369 ((eq flag t)
11370 ;; all-completions
11371 (setq rtn (all-completions string thetable predicate))
11372 (mapcar
11373 (lambda (x)
11374 (setq r (substring x l))
11375 (if (string-match " ([^)]*)$" x)
11376 (setq f (match-string 0 x))
11377 (setq f ""))
11378 (if (string-match "/" r)
11379 (concat string (substring r 0 (match-end 0)) f)
11381 rtn))
11382 ((eq flag 'lambda)
11383 ;; exact match?
11384 (assoc string thetable)))))
11385 args)))
11387 ;;;; Dynamic blocks
11389 (defun org-find-dblock (name)
11390 "Find the first dynamic block with name NAME in the buffer.
11391 If not found, stay at current position and return nil."
11392 (let ((case-fold-search t) pos)
11393 (save-excursion
11394 (goto-char (point-min))
11395 (setq pos (and (re-search-forward
11396 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11397 (match-beginning 0))))
11398 (if pos (goto-char pos))
11399 pos))
11401 (defconst org-dblock-start-re
11402 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11403 "Matches the start line of a dynamic block, with parameters.")
11405 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11406 "Matches the end of a dynamic block.")
11408 (defun org-create-dblock (plist)
11409 "Create a dynamic block section, with parameters taken from PLIST.
11410 PLIST must contain a :name entry which is used as name of the block."
11411 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11412 (end-of-line 1)
11413 (newline))
11414 (let ((col (current-column))
11415 (name (plist-get plist :name)))
11416 (insert "#+BEGIN: " name)
11417 (while plist
11418 (if (eq (car plist) :name)
11419 (setq plist (cddr plist))
11420 (insert " " (prin1-to-string (pop plist)))))
11421 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11422 (beginning-of-line -2)))
11424 (defun org-prepare-dblock ()
11425 "Prepare dynamic block for refresh.
11426 This empties the block, puts the cursor at the insert position and returns
11427 the property list including an extra property :name with the block name."
11428 (unless (looking-at org-dblock-start-re)
11429 (error "Not at a dynamic block"))
11430 (let* ((begdel (1+ (match-end 0)))
11431 (name (org-no-properties (match-string 1)))
11432 (params (append (list :name name)
11433 (read (concat "(" (match-string 3) ")")))))
11434 (save-excursion
11435 (beginning-of-line 1)
11436 (skip-chars-forward " \t")
11437 (setq params (plist-put params :indentation-column (current-column))))
11438 (unless (re-search-forward org-dblock-end-re nil t)
11439 (error "Dynamic block not terminated"))
11440 (setq params
11441 (append params
11442 (list :content (buffer-substring
11443 begdel (match-beginning 0)))))
11444 (delete-region begdel (match-beginning 0))
11445 (goto-char begdel)
11446 (open-line 1)
11447 params))
11449 (defun org-map-dblocks (&optional command)
11450 "Apply COMMAND to all dynamic blocks in the current buffer.
11451 If COMMAND is not given, use `org-update-dblock'."
11452 (let ((cmd (or command 'org-update-dblock)))
11453 (save-excursion
11454 (goto-char (point-min))
11455 (while (re-search-forward org-dblock-start-re nil t)
11456 (goto-char (match-beginning 0))
11457 (save-excursion
11458 (condition-case nil
11459 (funcall cmd)
11460 (error (message "Error during update of dynamic block"))))
11461 (unless (re-search-forward org-dblock-end-re nil t)
11462 (error "Dynamic block not terminated"))))))
11464 (defun org-dblock-update (&optional arg)
11465 "User command for updating dynamic blocks.
11466 Update the dynamic block at point. With prefix ARG, update all dynamic
11467 blocks in the buffer."
11468 (interactive "P")
11469 (if arg
11470 (org-update-all-dblocks)
11471 (or (looking-at org-dblock-start-re)
11472 (org-beginning-of-dblock))
11473 (org-update-dblock)))
11475 (defun org-update-dblock ()
11476 "Update the dynamic block at point.
11477 This means to empty the block, parse for parameters and then call
11478 the correct writing function."
11479 (interactive)
11480 (save-window-excursion
11481 (let* ((pos (point))
11482 (line (org-current-line))
11483 (params (org-prepare-dblock))
11484 (name (plist-get params :name))
11485 (indent (plist-get params :indentation-column))
11486 (cmd (intern (concat "org-dblock-write:" name))))
11487 (message "Updating dynamic block `%s' at line %d..." name line)
11488 (funcall cmd params)
11489 (message "Updating dynamic block `%s' at line %d...done" name line)
11490 (goto-char pos)
11491 (when (and indent (> indent 0))
11492 (setq indent (make-string indent ?\ ))
11493 (save-excursion
11494 (org-beginning-of-dblock)
11495 (forward-line 1)
11496 (while (not (looking-at org-dblock-end-re))
11497 (insert indent)
11498 (beginning-of-line 2))
11499 (when (looking-at org-dblock-end-re)
11500 (and (looking-at "[ \t]+")
11501 (replace-match ""))
11502 (insert indent)))))))
11504 (defun org-beginning-of-dblock ()
11505 "Find the beginning of the dynamic block at point.
11506 Error if there is no such block at point."
11507 (let ((pos (point))
11508 beg)
11509 (end-of-line 1)
11510 (if (and (re-search-backward org-dblock-start-re nil t)
11511 (setq beg (match-beginning 0))
11512 (re-search-forward org-dblock-end-re nil t)
11513 (> (match-end 0) pos))
11514 (goto-char beg)
11515 (goto-char pos)
11516 (error "Not in a dynamic block"))))
11518 (defun org-update-all-dblocks ()
11519 "Update all dynamic blocks in the buffer.
11520 This function can be used in a hook."
11521 (interactive)
11522 (when (derived-mode-p 'org-mode)
11523 (org-map-dblocks 'org-update-dblock)))
11526 ;;;; Completion
11528 (defun org-get-export-keywords ()
11529 "Return a list of all currently understood export keywords.
11530 Export keywords include options, block names, attributes and
11531 keywords relative to each registered export back-end."
11532 (delq nil
11533 (let (keywords)
11534 (mapc
11535 (lambda (back-end)
11536 (let ((props (cdr back-end)))
11537 ;; Back-end name (for keywords, like #+LATEX:)
11538 (push (upcase (symbol-name (car back-end))) keywords)
11539 ;; Back-end options.
11540 (mapc (lambda (option) (push (cadr option) keywords))
11541 (plist-get (cdr back-end) :options-alist))))
11542 (org-bound-and-true-p org-export-registered-backends))
11543 keywords)))
11545 (defconst org-options-keywords
11546 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE"
11547 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11548 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY"
11549 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11550 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS" "EXCLUDE_TAGS" "INFOJS_OPT"))
11552 (defcustom org-structure-template-alist
11553 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11554 "<src lang=\"?\">\n\n</src>")
11555 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11556 "<example>\n?\n</example>")
11557 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11558 "<quote>\n?\n</quote>")
11559 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11560 "<verse>\n?\n</verse>")
11561 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11562 "<verbatim>\n?\n</verbatim>")
11563 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11564 "<center>\n?\n</center>")
11565 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11566 "<literal style=\"latex\">\n?\n</literal>")
11567 ("L" "#+LaTeX: "
11568 "<literal style=\"latex\">?</literal>")
11569 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11570 "<literal style=\"html\">\n?\n</literal>")
11571 ("H" "#+HTML: "
11572 "<literal style=\"html\">?</literal>")
11573 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11574 ("A" "#+ASCII: ")
11575 ("i" "#+INDEX: ?"
11576 "#+INDEX: ?")
11577 ("I" "#+INCLUDE: %file ?"
11578 "<include file=%file markup=\"?\">"))
11579 "Structure completion elements.
11580 This is a list of abbreviation keys and values. The value gets inserted
11581 if you type `<' followed by the key and then press the completion key,
11582 usually `M-TAB'. %file will be replaced by a file name after prompting
11583 for the file using completion. The cursor will be placed at the position
11584 of the `?` in the template.
11585 There are two templates for each key, the first uses the original Org syntax,
11586 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11587 the default when the /org-mtags.el/ module has been loaded. See also the
11588 variable `org-mtags-prefer-muse-templates'."
11589 :group 'org-completion
11590 :type '(repeat
11591 (string :tag "Key")
11592 (string :tag "Template")
11593 (string :tag "Muse Template")))
11595 (defun org-try-structure-completion ()
11596 "Try to complete a structure template before point.
11597 This looks for strings like \"<e\" on an otherwise empty line and
11598 expands them."
11599 (let ((l (buffer-substring (point-at-bol) (point)))
11601 (when (and (looking-at "[ \t]*$")
11602 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11603 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11604 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11605 (match-beginning 1)) a)
11606 t)))
11608 (defun org-complete-expand-structure-template (start cell)
11609 "Expand a structure template."
11610 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11611 (rpl (nth (if musep 2 1) cell))
11612 (ind ""))
11613 (delete-region start (point))
11614 (when (string-match "\\`#\\+" rpl)
11615 (cond
11616 ((bolp))
11617 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11618 (setq ind (buffer-substring (point-at-bol) (point))))
11619 (t (newline))))
11620 (setq start (point))
11621 (if (string-match "%file" rpl)
11622 (setq rpl (replace-match
11623 (concat
11624 "\""
11625 (save-match-data
11626 (abbreviate-file-name (read-file-name "Include file: ")))
11627 "\"")
11628 t t rpl)))
11629 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11630 (concat "\n" ind)))
11631 (insert rpl)
11632 (if (re-search-backward "\\?" start t) (delete-char 1))))
11634 ;;;; TODO, DEADLINE, Comments
11636 (defun org-toggle-comment ()
11637 "Change the COMMENT state of an entry."
11638 (interactive)
11639 (save-excursion
11640 (org-back-to-heading)
11641 (let (case-fold-search)
11642 (cond
11643 ((looking-at (format org-heading-keyword-regexp-format
11644 org-comment-string))
11645 (goto-char (match-end 1))
11646 (looking-at (concat " +" org-comment-string))
11647 (replace-match "" t t)
11648 (when (eolp) (insert " ")))
11649 ((looking-at org-outline-regexp)
11650 (goto-char (match-end 0))
11651 (insert org-comment-string " "))))))
11653 (defvar org-last-todo-state-is-todo nil
11654 "This is non-nil when the last TODO state change led to a TODO state.
11655 If the last change removed the TODO tag or switched to DONE, then
11656 this is nil.")
11658 (defvar org-setting-tags nil) ; dynamically skipped
11660 (defvar org-todo-setup-filter-hook nil
11661 "Hook for functions that pre-filter todo specs.
11662 Each function takes a todo spec and returns either nil or the spec
11663 transformed into canonical form." )
11665 (defvar org-todo-get-default-hook nil
11666 "Hook for functions that get a default item for todo.
11667 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11668 nil or a string to be used for the todo mark." )
11670 (defvar org-agenda-headline-snapshot-before-repeat)
11672 (defun org-current-effective-time ()
11673 "Return current time adjusted for `org-extend-today-until' variable."
11674 (let* ((ct (org-current-time))
11675 (dct (decode-time ct))
11676 (ct1
11677 (cond
11678 (org-use-last-clock-out-time-as-effective-time
11679 (or (org-clock-get-last-clock-out-time) ct))
11680 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11681 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11682 (t ct))))
11683 ct1))
11685 (defun org-todo-yesterday (&optional arg)
11686 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11687 (interactive "P")
11688 (if (eq major-mode 'org-agenda-mode)
11689 (apply 'org-agenda-todo-yesterday arg)
11690 (let* ((hour (third (decode-time
11691 (org-current-time))))
11692 (org-extend-today-until (1+ hour)))
11693 (org-todo arg))))
11695 (defvar org-block-entry-blocking ""
11696 "First entry preventing the TODO state change.")
11698 (defun org-todo (&optional arg)
11699 "Change the TODO state of an item.
11700 The state of an item is given by a keyword at the start of the heading,
11701 like
11702 *** TODO Write paper
11703 *** DONE Call mom
11705 The different keywords are specified in the variable `org-todo-keywords'.
11706 By default the available states are \"TODO\" and \"DONE\".
11707 So for this example: when the item starts with TODO, it is changed to DONE.
11708 When it starts with DONE, the DONE is removed. And when neither TODO nor
11709 DONE are present, add TODO at the beginning of the heading.
11711 With \\[universal-argument] prefix arg, use completion to determine the new \
11712 state.
11713 With numeric prefix arg, switch to that state.
11714 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11715 keywords (nextset).
11716 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11717 With a numeric prefix arg of 0, inhibit note taking for the change.
11719 For calling through lisp, arg is also interpreted in the following way:
11720 'none -> empty state
11721 \"\"(empty string) -> switch to empty state
11722 'done -> switch to DONE
11723 'nextset -> switch to the next set of keywords
11724 'previousset -> switch to the previous set of keywords
11725 \"WAITING\" -> switch to the specified keyword, but only if it
11726 really is a member of `org-todo-keywords'."
11727 (interactive "P")
11728 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11729 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11730 'region-start-level 'region))
11731 org-loop-over-headlines-in-active-region)
11732 (org-map-entries
11733 `(org-todo ,arg)
11734 org-loop-over-headlines-in-active-region
11735 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11736 (if (equal arg '(16)) (setq arg 'nextset))
11737 (let ((org-blocker-hook org-blocker-hook)
11738 commentp
11739 case-fold-search)
11740 (when (equal arg '(64))
11741 (setq arg nil org-blocker-hook nil))
11742 (when (and org-blocker-hook
11743 (or org-inhibit-blocking
11744 (org-entry-get nil "NOBLOCKING")))
11745 (setq org-blocker-hook nil))
11746 (save-excursion
11747 (catch 'exit
11748 (org-back-to-heading t)
11749 (when (looking-at (concat "^\\*+ " org-comment-string))
11750 (org-toggle-comment)
11751 (setq commentp t))
11752 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11753 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11754 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11755 (let* ((match-data (match-data))
11756 (startpos (point-at-bol))
11757 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11758 (org-log-done org-log-done)
11759 (org-log-repeat org-log-repeat)
11760 (org-todo-log-states org-todo-log-states)
11761 (org-inhibit-logging
11762 (if (equal arg 0)
11763 (progn (setq arg nil) 'note) org-inhibit-logging))
11764 (this (match-string 1))
11765 (hl-pos (match-beginning 0))
11766 (head (org-get-todo-sequence-head this))
11767 (ass (assoc head org-todo-kwd-alist))
11768 (interpret (nth 1 ass))
11769 (done-word (nth 3 ass))
11770 (final-done-word (nth 4 ass))
11771 (org-last-state (or this ""))
11772 (completion-ignore-case t)
11773 (member (member this org-todo-keywords-1))
11774 (tail (cdr member))
11775 (org-state (cond
11776 ((and org-todo-key-trigger
11777 (or (and (equal arg '(4))
11778 (eq org-use-fast-todo-selection 'prefix))
11779 (and (not arg) org-use-fast-todo-selection
11780 (not (eq org-use-fast-todo-selection
11781 'prefix)))))
11782 ;; Use fast selection
11783 (org-fast-todo-selection))
11784 ((and (equal arg '(4))
11785 (or (not org-use-fast-todo-selection)
11786 (not org-todo-key-trigger)))
11787 ;; Read a state with completion
11788 (org-icompleting-read
11789 "State: " (mapcar (lambda(x) (list x))
11790 org-todo-keywords-1)
11791 nil t))
11792 ((eq arg 'right)
11793 (if this
11794 (if tail (car tail) nil)
11795 (car org-todo-keywords-1)))
11796 ((eq arg 'left)
11797 (if (equal member org-todo-keywords-1)
11799 (if this
11800 (nth (- (length org-todo-keywords-1)
11801 (length tail) 2)
11802 org-todo-keywords-1)
11803 (org-last org-todo-keywords-1))))
11804 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11805 (setq arg nil))) ; hack to fall back to cycling
11806 (arg
11807 ;; user or caller requests a specific state
11808 (cond
11809 ((equal arg "") nil)
11810 ((eq arg 'none) nil)
11811 ((eq arg 'done) (or done-word (car org-done-keywords)))
11812 ((eq arg 'nextset)
11813 (or (car (cdr (member head org-todo-heads)))
11814 (car org-todo-heads)))
11815 ((eq arg 'previousset)
11816 (let ((org-todo-heads (reverse org-todo-heads)))
11817 (or (car (cdr (member head org-todo-heads)))
11818 (car org-todo-heads))))
11819 ((car (member arg org-todo-keywords-1)))
11820 ((stringp arg)
11821 (error "State `%s' not valid in this file" arg))
11822 ((nth (1- (prefix-numeric-value arg))
11823 org-todo-keywords-1))))
11824 ((null member) (or head (car org-todo-keywords-1)))
11825 ((equal this final-done-word) nil) ;; -> make empty
11826 ((null tail) nil) ;; -> first entry
11827 ((memq interpret '(type priority))
11828 (if (eq this-command last-command)
11829 (car tail)
11830 (if (> (length tail) 0)
11831 (or done-word (car org-done-keywords))
11832 nil)))
11834 (car tail))))
11835 (org-state (or
11836 (run-hook-with-args-until-success
11837 'org-todo-get-default-hook org-state org-last-state)
11838 org-state))
11839 (next (if org-state (concat " " org-state " ") " "))
11840 (change-plist (list :type 'todo-state-change :from this :to org-state
11841 :position startpos))
11842 dolog now-done-p)
11843 (when org-blocker-hook
11844 (setq org-last-todo-state-is-todo
11845 (not (member this org-done-keywords)))
11846 (unless (save-excursion
11847 (save-match-data
11848 (org-with-wide-buffer
11849 (run-hook-with-args-until-failure
11850 'org-blocker-hook change-plist))))
11851 (if (org-called-interactively-p 'interactive)
11852 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11853 this org-state org-block-entry-blocking)
11854 ;; fail silently
11855 (message "TODO state change from %s to %s blocked (by \"%s\")"
11856 this org-state org-block-entry-blocking)
11857 (throw 'exit nil))))
11858 (store-match-data match-data)
11859 (replace-match next t t)
11860 (unless (pos-visible-in-window-p hl-pos)
11861 (message "TODO state changed to %s" (org-trim next)))
11862 (unless head
11863 (setq head (org-get-todo-sequence-head org-state)
11864 ass (assoc head org-todo-kwd-alist)
11865 interpret (nth 1 ass)
11866 done-word (nth 3 ass)
11867 final-done-word (nth 4 ass)))
11868 (when (memq arg '(nextset previousset))
11869 (message "Keyword-Set %d/%d: %s"
11870 (- (length org-todo-sets) -1
11871 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11872 (length org-todo-sets)
11873 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11874 (setq org-last-todo-state-is-todo
11875 (not (member org-state org-done-keywords)))
11876 (setq now-done-p (and (member org-state org-done-keywords)
11877 (not (member this org-done-keywords))))
11878 (and logging (org-local-logging logging))
11879 (when (and (or org-todo-log-states org-log-done)
11880 (not (eq org-inhibit-logging t))
11881 (not (memq arg '(nextset previousset))))
11882 ;; we need to look at recording a time and note
11883 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11884 (nth 2 (assoc this org-todo-log-states))))
11885 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11886 (setq dolog 'time))
11887 (when (and org-state
11888 (member org-state org-not-done-keywords)
11889 (not (member this org-not-done-keywords)))
11890 ;; This is now a todo state and was not one before
11891 ;; If there was a CLOSED time stamp, get rid of it.
11892 (org-add-planning-info nil nil 'closed))
11893 (when (and now-done-p org-log-done)
11894 ;; It is now done, and it was not done before
11895 (org-add-planning-info 'closed (org-current-effective-time))
11896 (if (and (not dolog) (eq 'note org-log-done))
11897 (org-add-log-setup 'done org-state this 'findpos 'note)))
11898 (when (and org-state dolog)
11899 ;; This is a non-nil state, and we need to log it
11900 (org-add-log-setup 'state org-state this 'findpos dolog)))
11901 ;; Fixup tag positioning
11902 (org-todo-trigger-tag-changes org-state)
11903 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11904 (when org-provide-todo-statistics
11905 (org-update-parent-todo-statistics))
11906 (run-hooks 'org-after-todo-state-change-hook)
11907 (if (and arg (not (member org-state org-done-keywords)))
11908 (setq head (org-get-todo-sequence-head org-state)))
11909 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11910 ;; Do we need to trigger a repeat?
11911 (when now-done-p
11912 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11913 ;; This is for the agenda, take a snapshot of the headline.
11914 (save-match-data
11915 (setq org-agenda-headline-snapshot-before-repeat
11916 (org-get-heading))))
11917 (org-auto-repeat-maybe org-state))
11918 ;; Fixup cursor location if close to the keyword
11919 (if (and (outline-on-heading-p)
11920 (not (bolp))
11921 (save-excursion (beginning-of-line 1)
11922 (looking-at org-todo-line-regexp))
11923 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11924 (progn
11925 (goto-char (or (match-end 2) (match-end 1)))
11926 (and (looking-at " ") (just-one-space))))
11927 (when org-trigger-hook
11928 (save-excursion
11929 (run-hook-with-args 'org-trigger-hook change-plist)))
11930 (when commentp (org-toggle-comment))))))))
11932 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11933 "Block turning an entry into a TODO, using the hierarchy.
11934 This checks whether the current task should be blocked from state
11935 changes. Such blocking occurs when:
11937 1. The task has children which are not all in a completed state.
11939 2. A task has a parent with the property :ORDERED:, and there
11940 are siblings prior to the current task with incomplete
11941 status.
11943 3. The parent of the task is blocked because it has siblings that should
11944 be done first, or is child of a block grandparent TODO entry."
11946 (if (not org-enforce-todo-dependencies)
11947 t ; if locally turned off don't block
11948 (catch 'dont-block
11949 ;; If this is not a todo state change, or if this entry is already DONE,
11950 ;; do not block
11951 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11952 (member (plist-get change-plist :from)
11953 (cons 'done org-done-keywords))
11954 (member (plist-get change-plist :to)
11955 (cons 'todo org-not-done-keywords))
11956 (not (plist-get change-plist :to)))
11957 (throw 'dont-block t))
11958 ;; If this task has children, and any are undone, it's blocked
11959 (save-excursion
11960 (org-back-to-heading t)
11961 (let ((this-level (funcall outline-level)))
11962 (outline-next-heading)
11963 (let ((child-level (funcall outline-level)))
11964 (while (and (not (eobp))
11965 (> child-level this-level))
11966 ;; this todo has children, check whether they are all
11967 ;; completed
11968 (if (and (not (org-entry-is-done-p))
11969 (org-entry-is-todo-p))
11970 (progn (setq org-block-entry-blocking (org-get-heading))
11971 (throw 'dont-block nil)))
11972 (outline-next-heading)
11973 (setq child-level (funcall outline-level))))))
11974 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11975 ;; any previous siblings are undone, it's blocked
11976 (save-excursion
11977 (org-back-to-heading t)
11978 (let* ((pos (point))
11979 (parent-pos (and (org-up-heading-safe) (point))))
11980 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11981 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11982 (forward-line 1)
11983 (re-search-forward org-not-done-heading-regexp pos t))
11984 (setq org-block-entry-blocking (match-string 0))
11985 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11986 ;; Search further up the hierarchy, to see if an ancestor is blocked
11987 (while t
11988 (goto-char parent-pos)
11989 (if (not (looking-at org-not-done-heading-regexp))
11990 (throw 'dont-block t)) ; do not block, parent is not a TODO
11991 (setq pos (point))
11992 (setq parent-pos (and (org-up-heading-safe) (point)))
11993 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11994 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11995 (forward-line 1)
11996 (re-search-forward org-not-done-heading-regexp pos t)
11997 (setq org-block-entry-blocking (org-get-heading)))
11998 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12000 (defcustom org-track-ordered-property-with-tag nil
12001 "Should the ORDERED property also be shown as a tag?
12002 The ORDERED property decides if an entry should require subtasks to be
12003 completed in sequence. Since a property is not very visible, setting
12004 this option means that toggling the ORDERED property with the command
12005 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12006 not relevant for the behavior, but it makes things more visible.
12008 Note that toggling the tag with tags commands will not change the property
12009 and therefore not influence behavior!
12011 This can be t, meaning the tag ORDERED should be used, It can also be a
12012 string to select a different tag for this task."
12013 :group 'org-todo
12014 :type '(choice
12015 (const :tag "No tracking" nil)
12016 (const :tag "Track with ORDERED tag" t)
12017 (string :tag "Use other tag")))
12019 (defun org-toggle-ordered-property ()
12020 "Toggle the ORDERED property of the current entry.
12021 For better visibility, you can track the value of this property with a tag.
12022 See variable `org-track-ordered-property-with-tag'."
12023 (interactive)
12024 (let* ((t1 org-track-ordered-property-with-tag)
12025 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12026 (save-excursion
12027 (org-back-to-heading)
12028 (if (org-entry-get nil "ORDERED")
12029 (progn
12030 (org-delete-property "ORDERED")
12031 (and tag (org-toggle-tag tag 'off))
12032 (message "Subtasks can be completed in arbitrary order"))
12033 (org-entry-put nil "ORDERED" "t")
12034 (and tag (org-toggle-tag tag 'on))
12035 (message "Subtasks must be completed in sequence")))))
12037 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12038 (defun org-block-todo-from-checkboxes (change-plist)
12039 "Block turning an entry into a TODO, using checkboxes.
12040 This checks whether the current task should be blocked from state
12041 changes because there are unchecked boxes in this entry."
12042 (if (not org-enforce-todo-checkbox-dependencies)
12043 t ; if locally turned off don't block
12044 (catch 'dont-block
12045 ;; If this is not a todo state change, or if this entry is already DONE,
12046 ;; do not block
12047 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12048 (member (plist-get change-plist :from)
12049 (cons 'done org-done-keywords))
12050 (member (plist-get change-plist :to)
12051 (cons 'todo org-not-done-keywords))
12052 (not (plist-get change-plist :to)))
12053 (throw 'dont-block t))
12054 ;; If this task has checkboxes that are not checked, it's blocked
12055 (save-excursion
12056 (org-back-to-heading t)
12057 (let ((beg (point)) end)
12058 (outline-next-heading)
12059 (setq end (point))
12060 (goto-char beg)
12061 (if (org-list-search-forward
12062 (concat (org-item-beginning-re)
12063 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12064 "\\[[- ]\\]")
12065 end t)
12066 (progn
12067 (if (boundp 'org-blocked-by-checkboxes)
12068 (setq org-blocked-by-checkboxes t))
12069 (throw 'dont-block nil)))))
12070 t))) ; do not block
12072 (defun org-entry-blocked-p ()
12073 "Is the current entry blocked?"
12074 (org-with-buffer-modified-unmodified
12075 (if (org-entry-get nil "NOBLOCKING")
12076 nil ;; Never block this entry
12077 (not
12078 (run-hook-with-args-until-failure
12079 'org-blocker-hook
12080 (list :type 'todo-state-change
12081 :position (point)
12082 :from 'todo
12083 :to 'done))))))
12085 (defun org-update-statistics-cookies (all)
12086 "Update the statistics cookie, either from TODO or from checkboxes.
12087 This should be called with the cursor in a line with a statistics cookie."
12088 (interactive "P")
12089 (if all
12090 (progn
12091 (org-update-checkbox-count 'all)
12092 (org-map-entries 'org-update-parent-todo-statistics))
12093 (if (not (org-at-heading-p))
12094 (org-update-checkbox-count)
12095 (let ((pos (point-marker))
12096 end l1 l2)
12097 (ignore-errors (org-back-to-heading t))
12098 (if (not (org-at-heading-p))
12099 (org-update-checkbox-count)
12100 (setq l1 (org-outline-level))
12101 (setq end (save-excursion
12102 (outline-next-heading)
12103 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12104 (point)))
12105 (if (and (save-excursion
12106 (re-search-forward
12107 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12108 (not (save-excursion (re-search-forward
12109 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12110 (org-update-checkbox-count)
12111 (if (and l2 (> l2 l1))
12112 (progn
12113 (goto-char end)
12114 (org-update-parent-todo-statistics))
12115 (goto-char pos)
12116 (beginning-of-line 1)
12117 (while (re-search-forward
12118 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12119 (point-at-eol) t)
12120 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12121 (goto-char pos)
12122 (move-marker pos nil)))))
12124 (defvar org-entry-property-inherited-from) ;; defined below
12125 (defun org-update-parent-todo-statistics ()
12126 "Update any statistics cookie in the parent of the current headline.
12127 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12128 the entire subtree and this will travel up the hierarchy and update
12129 statistics everywhere."
12130 (let* ((prop (save-excursion (org-up-heading-safe)
12131 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12132 (recursive (or (not org-hierarchical-todo-statistics)
12133 (and prop (string-match "\\<recursive\\>" prop))))
12134 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12136 (first t)
12137 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12138 level ltoggle l1 new ndel
12139 (cnt-all 0) (cnt-done 0) is-percent kwd
12140 checkbox-beg ov ovs ove cookie-present)
12141 (catch 'exit
12142 (save-excursion
12143 (beginning-of-line 1)
12144 (setq ltoggle (funcall outline-level))
12145 ;; Three situations are to consider:
12147 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12148 ;; to the top-level ancestor on the headline;
12150 ;; 2. If parent has "recursive" property, repeat up to the
12151 ;; headline setting that property, taking inheritance into
12152 ;; account;
12154 ;; 3. Else, move up to direct parent and proceed only once.
12155 (while (and (setq level (org-up-heading-safe))
12156 (or recursive first)
12157 (>= (point) lim))
12158 (setq first nil cookie-present nil)
12159 (unless (and level
12160 (not (string-match
12161 "\\<checkbox\\>"
12162 (downcase (or (org-entry-get nil "COOKIE_DATA")
12163 "")))))
12164 (throw 'exit nil))
12165 (while (re-search-forward box-re (point-at-eol) t)
12166 (setq cnt-all 0 cnt-done 0 cookie-present t)
12167 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12168 (save-match-data
12169 (unless (outline-next-heading) (throw 'exit nil))
12170 (while (and (looking-at org-complex-heading-regexp)
12171 (> (setq l1 (length (match-string 1))) level))
12172 (setq kwd (and (or recursive (= l1 ltoggle))
12173 (match-string 2)))
12174 (if (or (eq org-provide-todo-statistics 'all-headlines)
12175 (and (listp org-provide-todo-statistics)
12176 (or (member kwd org-provide-todo-statistics)
12177 (member kwd org-done-keywords))))
12178 (setq cnt-all (1+ cnt-all))
12179 (if (eq org-provide-todo-statistics t)
12180 (and kwd (setq cnt-all (1+ cnt-all)))))
12181 (and (member kwd org-done-keywords)
12182 (setq cnt-done (1+ cnt-done)))
12183 (outline-next-heading)))
12184 (setq new
12185 (if is-percent
12186 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12187 (format "[%d/%d]" cnt-done cnt-all))
12188 ndel (- (match-end 0) checkbox-beg))
12189 ;; handle overlays when updating cookie from column view
12190 (when (setq ov (car (overlays-at checkbox-beg)))
12191 (setq ovs (overlay-start ov) ove (overlay-end ov))
12192 (delete-overlay ov))
12193 (goto-char checkbox-beg)
12194 (insert new)
12195 (delete-region (point) (+ (point) ndel))
12196 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12197 (when ov (move-overlay ov ovs ove)))
12198 (when cookie-present
12199 (run-hook-with-args 'org-after-todo-statistics-hook
12200 cnt-done (- cnt-all cnt-done))))))
12201 (run-hooks 'org-todo-statistics-hook)))
12203 (defvar org-after-todo-statistics-hook nil
12204 "Hook that is called after a TODO statistics cookie has been updated.
12205 Each function is called with two arguments: the number of not-done entries
12206 and the number of done entries.
12208 For example, the following function, when added to this hook, will switch
12209 an entry to DONE when all children are done, and back to TODO when new
12210 entries are set to a TODO status. Note that this hook is only called
12211 when there is a statistics cookie in the headline!
12213 (defun org-summary-todo (n-done n-not-done)
12214 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12215 (let (org-log-done org-log-states) ; turn off logging
12216 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12219 (defvar org-todo-statistics-hook nil
12220 "Hook that is run whenever Org thinks TODO statistics should be updated.
12221 This hook runs even if there is no statistics cookie present, in which case
12222 `org-after-todo-statistics-hook' would not run.")
12224 (defun org-todo-trigger-tag-changes (state)
12225 "Apply the changes defined in `org-todo-state-tags-triggers'."
12226 (let ((l org-todo-state-tags-triggers)
12227 changes)
12228 (when (or (not state) (equal state ""))
12229 (setq changes (append changes (cdr (assoc "" l)))))
12230 (when (and (stringp state) (> (length state) 0))
12231 (setq changes (append changes (cdr (assoc state l)))))
12232 (when (member state org-not-done-keywords)
12233 (setq changes (append changes (cdr (assoc 'todo l)))))
12234 (when (member state org-done-keywords)
12235 (setq changes (append changes (cdr (assoc 'done l)))))
12236 (dolist (c changes)
12237 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12239 (defun org-local-logging (value)
12240 "Get logging settings from a property VALUE."
12241 (let* (words w a)
12242 ;; directly set the variables, they are already local.
12243 (setq org-log-done nil
12244 org-log-repeat nil
12245 org-todo-log-states nil)
12246 (setq words (org-split-string value))
12247 (while (setq w (pop words))
12248 (cond
12249 ((setq a (assoc w org-startup-options))
12250 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12251 (set (nth 1 a) (nth 2 a))))
12252 ((setq a (org-extract-log-state-settings w))
12253 (and (member (car a) org-todo-keywords-1)
12254 (push a org-todo-log-states)))))))
12256 (defun org-get-todo-sequence-head (kwd)
12257 "Return the head of the TODO sequence to which KWD belongs.
12258 If KWD is not set, check if there is a text property remembering the
12259 right sequence."
12260 (let (p)
12261 (cond
12262 ((not kwd)
12263 (or (get-text-property (point-at-bol) 'org-todo-head)
12264 (progn
12265 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12266 nil (point-at-eol)))
12267 (get-text-property p 'org-todo-head))))
12268 ((not (member kwd org-todo-keywords-1))
12269 (car org-todo-keywords-1))
12270 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12272 (defun org-fast-todo-selection ()
12273 "Fast TODO keyword selection with single keys.
12274 Returns the new TODO keyword, or nil if no state change should occur."
12275 (let* ((fulltable org-todo-key-alist)
12276 (done-keywords org-done-keywords) ;; needed for the faces.
12277 (maxlen (apply 'max (mapcar
12278 (lambda (x)
12279 (if (stringp (car x)) (string-width (car x)) 0))
12280 fulltable)))
12281 (expert nil)
12282 (fwidth (+ maxlen 3 1 3))
12283 (ncol (/ (- (window-width) 4) fwidth))
12284 tg cnt e c tbl
12285 groups ingroup)
12286 (save-excursion
12287 (save-window-excursion
12288 (if expert
12289 (set-buffer (get-buffer-create " *Org todo*"))
12290 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12291 (erase-buffer)
12292 (org-set-local 'org-done-keywords done-keywords)
12293 (setq tbl fulltable cnt 0)
12294 (while (setq e (pop tbl))
12295 (cond
12296 ((equal e '(:startgroup))
12297 (push '() groups) (setq ingroup t)
12298 (when (not (= cnt 0))
12299 (setq cnt 0)
12300 (insert "\n"))
12301 (insert "{ "))
12302 ((equal e '(:endgroup))
12303 (setq ingroup nil cnt 0)
12304 (insert "}\n"))
12305 ((equal e '(:newline))
12306 (when (not (= cnt 0))
12307 (setq cnt 0)
12308 (insert "\n")
12309 (setq e (car tbl))
12310 (while (equal (car tbl) '(:newline))
12311 (insert "\n")
12312 (setq tbl (cdr tbl)))))
12314 (setq tg (car e) c (cdr e))
12315 (if ingroup (push tg (car groups)))
12316 (setq tg (org-add-props tg nil 'face
12317 (org-get-todo-face tg)))
12318 (if (and (= cnt 0) (not ingroup)) (insert " "))
12319 (insert "[" c "] " tg (make-string
12320 (- fwidth 4 (length tg)) ?\ ))
12321 (when (= (setq cnt (1+ cnt)) ncol)
12322 (insert "\n")
12323 (if ingroup (insert " "))
12324 (setq cnt 0)))))
12325 (insert "\n")
12326 (goto-char (point-min))
12327 (if (not expert) (org-fit-window-to-buffer))
12328 (message "[a-z..]:Set [SPC]:clear")
12329 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12330 (cond
12331 ((or (= c ?\C-g)
12332 (and (= c ?q) (not (rassoc c fulltable))))
12333 (setq quit-flag t))
12334 ((= c ?\ ) nil)
12335 ((setq e (rassoc c fulltable) tg (car e))
12337 (t (setq quit-flag t)))))))
12339 (defun org-entry-is-todo-p ()
12340 (member (org-get-todo-state) org-not-done-keywords))
12342 (defun org-entry-is-done-p ()
12343 (member (org-get-todo-state) org-done-keywords))
12345 (defun org-get-todo-state ()
12346 (save-excursion
12347 (org-back-to-heading t)
12348 (and (looking-at org-todo-line-regexp)
12349 (match-end 2)
12350 (match-string 2))))
12352 (defun org-at-date-range-p (&optional inactive-ok)
12353 "Is the cursor inside a date range?"
12354 (interactive)
12355 (save-excursion
12356 (catch 'exit
12357 (let ((pos (point)))
12358 (skip-chars-backward "^[<\r\n")
12359 (skip-chars-backward "<[")
12360 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12361 (>= (match-end 0) pos)
12362 (throw 'exit t))
12363 (skip-chars-backward "^<[\r\n")
12364 (skip-chars-backward "<[")
12365 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12366 (>= (match-end 0) pos)
12367 (throw 'exit t)))
12368 nil)))
12370 (defun org-get-repeat (&optional tagline)
12371 "Check if there is a deadline/schedule with repeater in this entry."
12372 (save-match-data
12373 (save-excursion
12374 (org-back-to-heading t)
12375 (and (re-search-forward (if tagline
12376 (concat tagline "\\s-*" org-repeat-re)
12377 org-repeat-re)
12378 (org-entry-end-position) t)
12379 (match-string-no-properties 1)))))
12381 (defvar org-last-changed-timestamp)
12382 (defvar org-last-inserted-timestamp)
12383 (defvar org-log-post-message)
12384 (defvar org-log-note-purpose)
12385 (defvar org-log-note-how)
12386 (defvar org-log-note-extra)
12387 (defun org-auto-repeat-maybe (done-word)
12388 "Check if the current headline contains a repeated deadline/schedule.
12389 If yes, set TODO state back to what it was and change the base date
12390 of repeating deadline/scheduled time stamps to new date.
12391 This function is run automatically after each state change to a DONE state."
12392 ;; last-state is dynamically scoped into this function
12393 (let* ((repeat (org-get-repeat))
12394 (aa (assoc org-last-state org-todo-kwd-alist))
12395 (interpret (nth 1 aa))
12396 (head (nth 2 aa))
12397 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12398 (msg "Entry repeats: ")
12399 (org-log-done nil)
12400 (org-todo-log-states nil)
12401 re type n what ts time to-state)
12402 (when repeat
12403 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12404 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12405 org-todo-repeat-to-state))
12406 (unless (and to-state (member to-state org-todo-keywords-1))
12407 (setq to-state (if (eq interpret 'type) org-last-state head)))
12408 (org-todo to-state)
12409 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12410 (org-entry-put nil "LAST_REPEAT" (format-time-string
12411 (org-time-stamp-format t t))))
12412 (when org-log-repeat
12413 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12414 (memq 'org-add-log-note post-command-hook))
12415 ;; OK, we are already setup for some record
12416 (if (eq org-log-repeat 'note)
12417 ;; make sure we take a note, not only a time stamp
12418 (setq org-log-note-how 'note))
12419 ;; Set up for taking a record
12420 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12421 org-last-state
12422 'findpos org-log-repeat)))
12423 (org-back-to-heading t)
12424 (org-add-planning-info nil nil 'closed)
12425 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12426 org-deadline-time-regexp "\\)\\|\\("
12427 org-ts-regexp "\\)"))
12428 (while (re-search-forward
12429 re (save-excursion (outline-next-heading) (point)) t)
12430 (setq type (if (match-end 1) org-scheduled-string
12431 (if (match-end 3) org-deadline-string "Plain:"))
12432 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12433 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12434 (setq n (string-to-number (match-string 2 ts))
12435 what (match-string 3 ts))
12436 (if (equal what "w") (setq n (* n 7) what "d"))
12437 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12438 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12439 ;; Preparation, see if we need to modify the start date for the change
12440 (when (match-end 1)
12441 (setq time (save-match-data (org-time-string-to-time ts)))
12442 (cond
12443 ((equal (match-string 1 ts) ".")
12444 ;; Shift starting date to today
12445 (org-timestamp-change
12446 (- (org-today) (time-to-days time))
12447 'day))
12448 ((equal (match-string 1 ts) "+")
12449 (let ((nshiftmax 10) (nshift 0))
12450 (while (or (= nshift 0)
12451 (<= (time-to-days time)
12452 (time-to-days (current-time))))
12453 (when (= (incf nshift) nshiftmax)
12454 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12455 (error "Abort")))
12456 (org-timestamp-change n (cdr (assoc what whata)))
12457 (org-at-timestamp-p t)
12458 (setq ts (match-string 1))
12459 (setq time (save-match-data (org-time-string-to-time ts)))))
12460 (org-timestamp-change (- n) (cdr (assoc what whata)))
12461 ;; rematch, so that we have everything in place for the real shift
12462 (org-at-timestamp-p t)
12463 (setq ts (match-string 1))
12464 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12465 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12466 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12467 (setq org-log-post-message msg)
12468 (message "%s" msg))))
12470 (defun org-show-todo-tree (arg)
12471 "Make a compact tree which shows all headlines marked with TODO.
12472 The tree will show the lines where the regexp matches, and all higher
12473 headlines above the match.
12474 With a \\[universal-argument] prefix, prompt for a regexp to match.
12475 With a numeric prefix N, construct a sparse tree for the Nth element
12476 of `org-todo-keywords-1'."
12477 (interactive "P")
12478 (let ((case-fold-search nil)
12479 (kwd-re
12480 (cond ((null arg) org-not-done-regexp)
12481 ((equal arg '(4))
12482 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12483 (mapcar 'list org-todo-keywords-1))))
12484 (concat "\\("
12485 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12486 "\\)\\>")))
12487 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12488 (regexp-quote (nth (1- (prefix-numeric-value arg))
12489 org-todo-keywords-1)))
12490 (t (error "Invalid prefix argument: %s" arg)))))
12491 (message "%d TODO entries found"
12492 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12494 (defun org-deadline (&optional arg time)
12495 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12496 With one universal prefix argument, remove any deadline from the item.
12497 With two universal prefix arguments, prompt for a warning delay.
12498 With argument TIME, set the deadline at the corresponding date. TIME
12499 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12500 (interactive "P")
12501 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12502 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12503 'region-start-level 'region))
12504 org-loop-over-headlines-in-active-region)
12505 (org-map-entries
12506 `(org-deadline ',arg ,time)
12507 org-loop-over-headlines-in-active-region
12508 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12509 (let* ((old-date (org-entry-get nil "DEADLINE"))
12510 (repeater (and old-date
12511 (string-match
12512 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12513 old-date)
12514 (match-string 1 old-date))))
12515 (cond
12516 ((equal arg '(4))
12517 (when (and old-date org-log-redeadline)
12518 (org-add-log-setup 'deldeadline nil old-date 'findpos
12519 org-log-redeadline))
12520 (org-remove-timestamp-with-keyword org-deadline-string)
12521 (message "Item no longer has a deadline."))
12522 ((equal arg '(16))
12523 (save-excursion
12524 (if (re-search-forward
12525 org-deadline-time-regexp
12526 (save-excursion (outline-next-heading) (point)) t)
12527 (let* ((rpl0 (match-string 1))
12528 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12529 (replace-match
12530 (concat org-deadline-string
12531 " <" rpl
12532 (format " -%dd" (abs
12533 (- (time-to-days
12534 (save-match-data
12535 (org-read-date nil t nil "Warn starting from")))
12536 (time-to-days nil))))
12537 ">") t t))
12538 (user-error "No deadline information to update"))))
12540 (org-add-planning-info 'deadline time 'closed)
12541 (when (and old-date org-log-redeadline
12542 (not (equal old-date
12543 (substring org-last-inserted-timestamp 1 -1))))
12544 (org-add-log-setup 'redeadline nil old-date 'findpos
12545 org-log-redeadline))
12546 (when repeater
12547 (save-excursion
12548 (org-back-to-heading t)
12549 (when (re-search-forward (concat org-deadline-string " "
12550 org-last-inserted-timestamp)
12551 (save-excursion
12552 (outline-next-heading) (point)) t)
12553 (goto-char (1- (match-end 0)))
12554 (insert " " repeater)
12555 (setq org-last-inserted-timestamp
12556 (concat (substring org-last-inserted-timestamp 0 -1)
12557 " " repeater
12558 (substring org-last-inserted-timestamp -1))))))
12559 (message "Deadline on %s" org-last-inserted-timestamp))))))
12561 (defun org-schedule (&optional arg time)
12562 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12563 With one universal prefix argument, remove any scheduling date from the item.
12564 With two universal prefix arguments, prompt for a delay cookie.
12565 With argument TIME, scheduled at the corresponding date. TIME can
12566 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12567 (interactive "P")
12568 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12569 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12570 'region-start-level 'region))
12571 org-loop-over-headlines-in-active-region)
12572 (org-map-entries
12573 `(org-schedule ',arg ,time)
12574 org-loop-over-headlines-in-active-region
12575 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12576 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12577 (repeater (and old-date
12578 (string-match
12579 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12580 old-date)
12581 (match-string 1 old-date))))
12582 (cond
12583 ((equal arg '(4))
12584 (progn
12585 (when (and old-date org-log-reschedule)
12586 (org-add-log-setup 'delschedule nil old-date 'findpos
12587 org-log-reschedule))
12588 (org-remove-timestamp-with-keyword org-scheduled-string)
12589 (message "Item is no longer scheduled.")))
12590 ((equal arg '(16))
12591 (save-excursion
12592 (if (re-search-forward
12593 org-scheduled-time-regexp
12594 (save-excursion (outline-next-heading) (point)) t)
12595 (let* ((rpl0 (match-string 1))
12596 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12597 (replace-match
12598 (concat org-scheduled-string
12599 " <" rpl
12600 (format " -%dd" (abs
12601 (- (time-to-days
12602 (save-match-data
12603 (org-read-date nil t nil "Delay until")))
12604 (time-to-days nil))))
12605 ">") t t))
12606 (user-error "No scheduled information to update"))))
12608 (org-add-planning-info 'scheduled time 'closed)
12609 (when (and old-date org-log-reschedule
12610 (not (equal old-date
12611 (substring org-last-inserted-timestamp 1 -1))))
12612 (org-add-log-setup 'reschedule nil old-date 'findpos
12613 org-log-reschedule))
12614 (when repeater
12615 (save-excursion
12616 (org-back-to-heading t)
12617 (when (re-search-forward (concat org-scheduled-string " "
12618 org-last-inserted-timestamp)
12619 (save-excursion
12620 (outline-next-heading) (point)) t)
12621 (goto-char (1- (match-end 0)))
12622 (insert " " repeater)
12623 (setq org-last-inserted-timestamp
12624 (concat (substring org-last-inserted-timestamp 0 -1)
12625 " " repeater
12626 (substring org-last-inserted-timestamp -1))))))
12627 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12629 (defun org-get-scheduled-time (pom &optional inherit)
12630 "Get the scheduled time as a time tuple, of a format suitable
12631 for calling org-schedule with, or if there is no scheduling,
12632 returns nil."
12633 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12634 (when time
12635 (apply 'encode-time (org-parse-time-string time)))))
12637 (defun org-get-deadline-time (pom &optional inherit)
12638 "Get the deadline as a time tuple, of a format suitable for
12639 calling org-deadline with, or if there is no scheduling, returns
12640 nil."
12641 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12642 (when time
12643 (apply 'encode-time (org-parse-time-string time)))))
12645 (defun org-remove-timestamp-with-keyword (keyword)
12646 "Remove all time stamps with KEYWORD in the current entry."
12647 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12648 beg)
12649 (save-excursion
12650 (org-back-to-heading t)
12651 (setq beg (point))
12652 (outline-next-heading)
12653 (while (re-search-backward re beg t)
12654 (replace-match "")
12655 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12656 (equal (char-before) ?\ ))
12657 (backward-delete-char 1)
12658 (if (string-match "^[ \t]*$" (buffer-substring
12659 (point-at-bol) (point-at-eol)))
12660 (delete-region (point-at-bol)
12661 (min (point-max) (1+ (point-at-eol))))))))))
12663 (defun org-add-planning-info (what &optional time &rest remove)
12664 "Insert new timestamp with keyword in the line directly after the headline.
12665 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12666 If non is given, the user is prompted for a date.
12667 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12668 be removed."
12669 (interactive)
12670 (let (org-time-was-given org-end-time-was-given ts
12671 end default-time default-input)
12673 (catch 'exit
12674 (when (and (memq what '(scheduled deadline))
12675 (or (not time)
12676 (and (stringp time)
12677 (string-match "^[-+]+[0-9]" time))))
12678 ;; Try to get a default date/time from existing timestamp
12679 (save-excursion
12680 (org-back-to-heading t)
12681 (setq end (save-excursion (outline-next-heading) (point)))
12682 (when (re-search-forward (if (eq what 'scheduled)
12683 org-scheduled-time-regexp
12684 org-deadline-time-regexp)
12685 end t)
12686 (setq ts (match-string 1)
12687 default-time
12688 (apply 'encode-time (org-parse-time-string ts))
12689 default-input (and ts (org-get-compact-tod ts))))))
12690 (when what
12691 (setq time
12692 (if (stringp time)
12693 ;; This is a string (relative or absolute), set proper date
12694 (apply 'encode-time
12695 (org-read-date-analyze
12696 time default-time (decode-time default-time)))
12697 ;; If necessary, get the time from the user
12698 (or time (org-read-date nil 'to-time nil nil
12699 default-time default-input)))))
12701 (when (and org-insert-labeled-timestamps-at-point
12702 (member what '(scheduled deadline)))
12703 (insert
12704 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12705 (org-insert-time-stamp time org-time-was-given
12706 nil nil nil (list org-end-time-was-given))
12707 (setq what nil))
12708 (save-excursion
12709 (save-restriction
12710 (let (col list elt ts buffer-invisibility-spec)
12711 (org-back-to-heading t)
12712 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12713 (goto-char (match-end 1))
12714 (setq col (current-column))
12715 (goto-char (match-end 0))
12716 (if (eobp) (insert "\n") (forward-char 1))
12717 (when (and (not what)
12718 (not (looking-at
12719 (concat "[ \t]*"
12720 org-keyword-time-not-clock-regexp))))
12721 ;; Nothing to add, nothing to remove...... :-)
12722 (throw 'exit nil))
12723 (if (and (not (looking-at org-outline-regexp))
12724 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12725 "[^\r\n]*"))
12726 (not (equal (match-string 1) org-clock-string)))
12727 (narrow-to-region (match-beginning 0) (match-end 0))
12728 (insert-before-markers "\n")
12729 (backward-char 1)
12730 (narrow-to-region (point) (point))
12731 (and org-adapt-indentation (org-indent-to-column col)))
12732 ;; Check if we have to remove something.
12733 (setq list (cons what remove))
12734 (while list
12735 (setq elt (pop list))
12736 (when (or (and (eq elt 'scheduled)
12737 (re-search-forward org-scheduled-time-regexp nil t))
12738 (and (eq elt 'deadline)
12739 (re-search-forward org-deadline-time-regexp nil t))
12740 (and (eq elt 'closed)
12741 (re-search-forward org-closed-time-regexp nil t)))
12742 (replace-match "")
12743 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12744 (and (looking-at "[ \t]+") (replace-match ""))
12745 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12746 (when what
12747 (insert
12748 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12749 (cond ((eq what 'scheduled) org-scheduled-string)
12750 ((eq what 'deadline) org-deadline-string)
12751 ((eq what 'closed) org-closed-string))
12752 " ")
12753 (setq ts (org-insert-time-stamp
12754 time
12755 (or org-time-was-given
12756 (and (eq what 'closed) org-log-done-with-time))
12757 (eq what 'closed)
12758 nil nil (list org-end-time-was-given)))
12759 (insert
12760 (if (not (or (bolp) (eq (char-before) ?\ )
12761 (memq (char-after) '(32 10))
12762 (eobp))) " " ""))
12763 (end-of-line 1))
12764 (goto-char (point-min))
12765 (widen)
12766 (if (and (looking-at "[ \t]*\n")
12767 (equal (char-before) ?\n))
12768 (delete-region (1- (point)) (point-at-eol)))
12769 ts))))))
12771 (defvar org-log-note-marker (make-marker))
12772 (defvar org-log-note-purpose nil)
12773 (defvar org-log-note-state nil)
12774 (defvar org-log-note-previous-state nil)
12775 (defvar org-log-note-how nil)
12776 (defvar org-log-note-extra nil)
12777 (defvar org-log-note-window-configuration nil)
12778 (defvar org-log-note-return-to (make-marker))
12779 (defvar org-log-note-effective-time nil
12780 "Remembered current time so that dynamically scoped
12781 `org-extend-today-until' affects tha timestamps in state change
12782 log")
12784 (defvar org-log-post-message nil
12785 "Message to be displayed after a log note has been stored.
12786 The auto-repeater uses this.")
12788 (defun org-add-note ()
12789 "Add a note to the current entry.
12790 This is done in the same way as adding a state change note."
12791 (interactive)
12792 (org-add-log-setup 'note nil nil 'findpos nil))
12794 (defvar org-property-end-re)
12795 (defun org-add-log-setup (&optional purpose state prev-state
12796 findpos how extra)
12797 "Set up the post command hook to take a note.
12798 If this is about to TODO state change, the new state is expected in STATE.
12799 When FINDPOS is non-nil, find the correct position for the note in
12800 the current entry. If not, assume that it can be inserted at point.
12801 HOW is an indicator what kind of note should be created.
12802 EXTRA is additional text that will be inserted into the notes buffer."
12803 (let* ((org-log-into-drawer (org-log-into-drawer))
12804 (drawer (cond ((stringp org-log-into-drawer)
12805 org-log-into-drawer)
12806 (org-log-into-drawer "LOGBOOK"))))
12807 (save-restriction
12808 (save-excursion
12809 (when findpos
12810 (org-back-to-heading t)
12811 (narrow-to-region (point) (save-excursion
12812 (outline-next-heading) (point)))
12813 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12814 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12815 "[^\r\n]*\\)?"))
12816 (goto-char (match-end 0))
12817 (cond
12818 (drawer
12819 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12820 nil t)
12821 (progn
12822 (goto-char (match-end 0))
12823 (or org-log-states-order-reversed
12824 (and (re-search-forward org-property-end-re nil t)
12825 (goto-char (1- (match-beginning 0))))))
12826 (insert "\n:" drawer ":\n:END:")
12827 (beginning-of-line 0)
12828 (org-indent-line)
12829 (beginning-of-line 2)
12830 (org-indent-line)
12831 (end-of-line 0)))
12832 ((and org-log-state-notes-insert-after-drawers
12833 (save-excursion
12834 (forward-line) (looking-at org-drawer-regexp)))
12835 (forward-line)
12836 (while (looking-at org-drawer-regexp)
12837 (goto-char (match-end 0))
12838 (re-search-forward org-property-end-re (point-max) t)
12839 (forward-line))
12840 (forward-line -1)))
12841 (unless org-log-states-order-reversed
12842 (and (= (char-after) ?\n) (forward-char 1))
12843 (org-skip-over-state-notes)
12844 (skip-chars-backward " \t\n\r")))
12845 (move-marker org-log-note-marker (point))
12846 (setq org-log-note-purpose purpose
12847 org-log-note-state state
12848 org-log-note-previous-state prev-state
12849 org-log-note-how how
12850 org-log-note-extra extra
12851 org-log-note-effective-time (org-current-effective-time))
12852 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12854 (defun org-skip-over-state-notes ()
12855 "Skip past the list of State notes in an entry."
12856 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12857 (when (ignore-errors (goto-char (org-in-item-p)))
12858 (let* ((struct (org-list-struct))
12859 (prevs (org-list-prevs-alist struct)))
12860 (while (looking-at "[ \t]*- State")
12861 (goto-char (or (org-list-get-next-item (point) struct prevs)
12862 (org-list-get-item-end (point) struct)))))))
12864 (defun org-add-log-note (&optional purpose)
12865 "Pop up a window for taking a note, and add this note later at point."
12866 (remove-hook 'post-command-hook 'org-add-log-note)
12867 (setq org-log-note-window-configuration (current-window-configuration))
12868 (delete-other-windows)
12869 (move-marker org-log-note-return-to (point))
12870 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12871 (goto-char org-log-note-marker)
12872 (org-switch-to-buffer-other-window "*Org Note*")
12873 (erase-buffer)
12874 (if (memq org-log-note-how '(time state))
12875 (let (current-prefix-arg) (org-store-log-note))
12876 (let ((org-inhibit-startup t)) (org-mode))
12877 (insert (format "# Insert note for %s.
12878 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12879 (cond
12880 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12881 ((eq org-log-note-purpose 'done) "closed todo item")
12882 ((eq org-log-note-purpose 'state)
12883 (format "state change from \"%s\" to \"%s\""
12884 (or org-log-note-previous-state "")
12885 (or org-log-note-state "")))
12886 ((eq org-log-note-purpose 'reschedule)
12887 "rescheduling")
12888 ((eq org-log-note-purpose 'delschedule)
12889 "no longer scheduled")
12890 ((eq org-log-note-purpose 'redeadline)
12891 "changing deadline")
12892 ((eq org-log-note-purpose 'deldeadline)
12893 "removing deadline")
12894 ((eq org-log-note-purpose 'refile)
12895 "refiling")
12896 ((eq org-log-note-purpose 'note)
12897 "this entry")
12898 (t (error "This should not happen")))))
12899 (if org-log-note-extra (insert org-log-note-extra))
12900 (org-set-local 'org-finish-function 'org-store-log-note)
12901 (run-hooks 'org-log-buffer-setup-hook)))
12903 (defvar org-note-abort nil) ; dynamically scoped
12904 (defun org-store-log-note ()
12905 "Finish taking a log note, and insert it to where it belongs."
12906 (let ((txt (buffer-string)))
12907 (kill-buffer (current-buffer))
12908 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12909 lines ind bul)
12910 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12911 (setq txt (replace-match "" t t txt)))
12912 (if (string-match "\\s-+\\'" txt)
12913 (setq txt (replace-match "" t t txt)))
12914 (setq lines (org-split-string txt "\n"))
12915 (when (and note (string-match "\\S-" note))
12916 (setq note
12917 (org-replace-escapes
12918 note
12919 (list (cons "%u" (user-login-name))
12920 (cons "%U" user-full-name)
12921 (cons "%t" (format-time-string
12922 (org-time-stamp-format 'long 'inactive)
12923 org-log-note-effective-time))
12924 (cons "%T" (format-time-string
12925 (org-time-stamp-format 'long nil)
12926 org-log-note-effective-time))
12927 (cons "%d" (format-time-string
12928 (org-time-stamp-format nil 'inactive)
12929 org-log-note-effective-time))
12930 (cons "%D" (format-time-string
12931 (org-time-stamp-format nil nil)
12932 org-log-note-effective-time))
12933 (cons "%s" (if org-log-note-state
12934 (concat "\"" org-log-note-state "\"")
12935 ""))
12936 (cons "%S" (if org-log-note-previous-state
12937 (concat "\"" org-log-note-previous-state "\"")
12938 "\"\"")))))
12939 (if lines (setq note (concat note " \\\\")))
12940 (push note lines))
12941 (when (or current-prefix-arg org-note-abort)
12942 (when org-log-into-drawer
12943 (org-remove-empty-drawer-at
12944 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12945 org-log-note-marker))
12946 (setq lines nil))
12947 (when lines
12948 (with-current-buffer (marker-buffer org-log-note-marker)
12949 (save-excursion
12950 (goto-char org-log-note-marker)
12951 (move-marker org-log-note-marker nil)
12952 (end-of-line 1)
12953 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12954 (setq ind (save-excursion
12955 (if (ignore-errors (goto-char (org-in-item-p)))
12956 (let ((struct (org-list-struct)))
12957 (org-list-get-ind
12958 (org-list-get-top-point struct) struct))
12959 (skip-chars-backward " \r\t\n")
12960 (cond
12961 ((and (org-at-heading-p)
12962 org-adapt-indentation)
12963 (1+ (org-current-level)))
12964 ((org-at-heading-p) 0)
12965 (t (org-get-indentation))))))
12966 (setq bul (org-list-bullet-string "-"))
12967 (org-indent-line-to ind)
12968 (insert bul (pop lines))
12969 (let ((ind-body (+ (length bul) ind)))
12970 (while lines
12971 (insert "\n")
12972 (org-indent-line-to ind-body)
12973 (insert (pop lines))))
12974 (message "Note stored")
12975 (org-back-to-heading t)
12976 (org-cycle-hide-drawers 'children))))))
12977 (set-window-configuration org-log-note-window-configuration)
12978 (with-current-buffer (marker-buffer org-log-note-return-to)
12979 (goto-char org-log-note-return-to))
12980 (move-marker org-log-note-return-to nil)
12981 (and org-log-post-message (message "%s" org-log-post-message)))
12983 (defun org-remove-empty-drawer-at (drawer pos)
12984 "Remove an empty drawer DRAWER at position POS.
12985 POS may also be a marker."
12986 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12987 (save-excursion
12988 (save-restriction
12989 (widen)
12990 (goto-char pos)
12991 (if (org-in-regexp
12992 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12993 (replace-match ""))))))
12995 (defvar org-ts-type nil)
12996 (defun org-sparse-tree (&optional arg type)
12997 "Create a sparse tree, prompt for the details.
12998 This command can create sparse trees. You first need to select the type
12999 of match used to create the tree:
13001 t Show all TODO entries.
13002 T Show entries with a specific TODO keyword.
13003 m Show entries selected by a tags/property match.
13004 p Enter a property name and its value (both with completion on existing
13005 names/values) and show entries with that property.
13006 r Show entries matching a regular expression (`/' can be used as well).
13007 b Show deadlines and scheduled items before a date.
13008 a Show deadlines and scheduled items after a date.
13009 d Show deadlines due within `org-deadline-warning-days'.
13010 D Show deadlines and scheduled items between a date range."
13011 (interactive "P")
13012 (let (ans kwd value ts-type)
13013 (setq type (or type org-sparse-tree-default-date-type))
13014 (setq org-ts-type type)
13015 (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"
13016 (cond ((eq type 'all) "all timestamps")
13017 ((eq type 'scheduled) "only scheduled")
13018 ((eq type 'deadline) "only deadline")
13019 ((eq type 'active) "only active timestamps")
13020 ((eq type 'inactive) "only inactive timestamps")
13021 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13022 (t "scheduled/deadline")))
13023 (setq ans (read-char-exclusive))
13024 (cond
13025 ((equal ans ?c)
13026 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13027 ((equal ans ?d)
13028 (call-interactively 'org-check-deadlines))
13029 ((equal ans ?b)
13030 (call-interactively 'org-check-before-date))
13031 ((equal ans ?a)
13032 (call-interactively 'org-check-after-date))
13033 ((equal ans ?D)
13034 (call-interactively 'org-check-dates-range))
13035 ((equal ans ?t)
13036 (call-interactively 'org-show-todo-tree))
13037 ((equal ans ?T)
13038 (org-show-todo-tree '(4)))
13039 ((member ans '(?T ?m))
13040 (call-interactively 'org-match-sparse-tree))
13041 ((member ans '(?p ?P))
13042 (setq kwd (org-icompleting-read "Property: "
13043 (mapcar 'list (org-buffer-property-keys))))
13044 (setq value (org-icompleting-read "Value: "
13045 (mapcar 'list (org-property-values kwd))))
13046 (unless (string-match "\\`{.*}\\'" value)
13047 (setq value (concat "\"" value "\"")))
13048 (org-match-sparse-tree arg (concat kwd "=" value)))
13049 ((member ans '(?r ?R ?/))
13050 (call-interactively 'org-occur))
13051 (t (error "No such sparse tree command \"%c\"" ans)))))
13053 (defvar org-occur-highlights nil
13054 "List of overlays used for occur matches.")
13055 (make-variable-buffer-local 'org-occur-highlights)
13056 (defvar org-occur-parameters nil
13057 "Parameters of the active org-occur calls.
13058 This is a list, each call to org-occur pushes as cons cell,
13059 containing the regular expression and the callback, onto the list.
13060 The list can contain several entries if `org-occur' has been called
13061 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13062 will only contain one set of parameters. When the highlights are
13063 removed (for example with `C-c C-c', or with the next edit (depending
13064 on `org-remove-highlights-with-change'), this variable is emptied
13065 as well.")
13066 (make-variable-buffer-local 'org-occur-parameters)
13068 (defun org-occur (regexp &optional keep-previous callback)
13069 "Make a compact tree which shows all matches of REGEXP.
13070 The tree will show the lines where the regexp matches, and all higher
13071 headlines above the match. It will also show the heading after the match,
13072 to make sure editing the matching entry is easy.
13073 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13074 call to `org-occur' will be kept, to allow stacking of calls to this
13075 command.
13076 If CALLBACK is non-nil, it is a function which is called to confirm
13077 that the match should indeed be shown."
13078 (interactive "sRegexp: \nP")
13079 (when (equal regexp "")
13080 (error "Regexp cannot be empty"))
13081 (unless keep-previous
13082 (org-remove-occur-highlights nil nil t))
13083 (push (cons regexp callback) org-occur-parameters)
13084 (let ((cnt 0))
13085 (save-excursion
13086 (goto-char (point-min))
13087 (if (or (not keep-previous) ; do not want to keep
13088 (not org-occur-highlights)) ; no previous matches
13089 ;; hide everything
13090 (org-overview))
13091 (while (re-search-forward regexp nil t)
13092 (when (or (not callback)
13093 (save-match-data (funcall callback)))
13094 (setq cnt (1+ cnt))
13095 (when org-highlight-sparse-tree-matches
13096 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13097 (org-show-context 'occur-tree))))
13098 (when org-remove-highlights-with-change
13099 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13100 nil 'local))
13101 (unless org-sparse-tree-open-archived-trees
13102 (org-hide-archived-subtrees (point-min) (point-max)))
13103 (run-hooks 'org-occur-hook)
13104 (if (org-called-interactively-p 'interactive)
13105 (message "%d match(es) for regexp %s" cnt regexp))
13106 cnt))
13108 (defun org-occur-next-match (&optional n reset)
13109 "Function for `next-error-function' to find sparse tree matches.
13110 N is the number of matches to move, when negative move backwards.
13111 RESET is entirely ignored - this function always goes back to the
13112 starting point when no match is found."
13113 (let* ((limit (if (< n 0) (point-min) (point-max)))
13114 (search-func (if (< n 0)
13115 'previous-single-char-property-change
13116 'next-single-char-property-change))
13117 (n (abs n))
13118 (pos (point))
13120 (catch 'exit
13121 (while (setq p1 (funcall search-func (point) 'org-type))
13122 (when (equal p1 limit)
13123 (goto-char pos)
13124 (error "No more matches"))
13125 (when (equal (get-char-property p1 'org-type) 'org-occur)
13126 (setq n (1- n))
13127 (when (= n 0)
13128 (goto-char p1)
13129 (throw 'exit (point))))
13130 (goto-char p1))
13131 (goto-char p1)
13132 (error "No more matches"))))
13134 (defun org-show-context (&optional key)
13135 "Make sure point and context are visible.
13136 How much context is shown depends upon the variables
13137 `org-show-hierarchy-above', `org-show-following-heading',
13138 `org-show-entry-below' and `org-show-siblings'."
13139 (let ((heading-p (org-at-heading-p t))
13140 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13141 (following-p (org-get-alist-option org-show-following-heading key))
13142 (entry-p (org-get-alist-option org-show-entry-below key))
13143 (siblings-p (org-get-alist-option org-show-siblings key)))
13144 (catch 'exit
13145 ;; Show heading or entry text
13146 (if (and heading-p (not entry-p))
13147 (org-flag-heading nil) ; only show the heading
13148 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13149 (org-show-hidden-entry))) ; show entire entry
13150 (when following-p
13151 ;; Show next sibling, or heading below text
13152 (save-excursion
13153 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13154 (org-flag-heading nil))))
13155 (when siblings-p (org-show-siblings))
13156 (when hierarchy-p
13157 ;; show all higher headings, possibly with siblings
13158 (save-excursion
13159 (while (and (condition-case nil
13160 (progn (org-up-heading-all 1) t)
13161 (error nil))
13162 (not (bobp)))
13163 (org-flag-heading nil)
13164 (when siblings-p (org-show-siblings))))))))
13166 (defvar org-reveal-start-hook nil
13167 "Hook run before revealing a location.")
13169 (defun org-reveal (&optional siblings)
13170 "Show current entry, hierarchy above it, and the following headline.
13171 This can be used to show a consistent set of context around locations
13172 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13173 not t for the search context.
13175 With optional argument SIBLINGS, on each level of the hierarchy all
13176 siblings are shown. This repairs the tree structure to what it would
13177 look like when opened with hierarchical calls to `org-cycle'.
13178 With double optional argument \\[universal-argument] \\[universal-argument], \
13179 go to the parent and show the
13180 entire tree."
13181 (interactive "P")
13182 (run-hooks 'org-reveal-start-hook)
13183 (let ((org-show-hierarchy-above t)
13184 (org-show-following-heading t)
13185 (org-show-siblings (if siblings t org-show-siblings)))
13186 (org-show-context nil))
13187 (when (equal siblings '(16))
13188 (save-excursion
13189 (when (org-up-heading-safe)
13190 (org-show-subtree)
13191 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13193 (defun org-highlight-new-match (beg end)
13194 "Highlight from BEG to END and mark the highlight is an occur headline."
13195 (let ((ov (make-overlay beg end)))
13196 (overlay-put ov 'face 'secondary-selection)
13197 (overlay-put ov 'org-type 'org-occur)
13198 (push ov org-occur-highlights)))
13200 (defun org-remove-occur-highlights (&optional beg end noremove)
13201 "Remove the occur highlights from the buffer.
13202 BEG and END are ignored. If NOREMOVE is nil, remove this function
13203 from the `before-change-functions' in the current buffer."
13204 (interactive)
13205 (unless org-inhibit-highlight-removal
13206 (mapc 'delete-overlay org-occur-highlights)
13207 (setq org-occur-highlights nil)
13208 (setq org-occur-parameters nil)
13209 (unless noremove
13210 (remove-hook 'before-change-functions
13211 'org-remove-occur-highlights 'local))))
13213 ;;;; Priorities
13215 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13216 "Regular expression matching the priority indicator.")
13218 (defvar org-remove-priority-next-time nil)
13220 (defun org-priority-up ()
13221 "Increase the priority of the current item."
13222 (interactive)
13223 (org-priority 'up))
13225 (defun org-priority-down ()
13226 "Decrease the priority of the current item."
13227 (interactive)
13228 (org-priority 'down))
13230 (defun org-priority (&optional action show)
13231 "Change the priority of an item.
13232 ACTION can be `set', `up', `down', or a character."
13233 (interactive "P")
13234 (if (equal action '(4))
13235 (org-show-priority)
13236 (unless org-enable-priority-commands
13237 (error "Priority commands are disabled"))
13238 (setq action (or action 'set))
13239 (let (current new news have remove)
13240 (save-excursion
13241 (org-back-to-heading t)
13242 (if (looking-at org-priority-regexp)
13243 (setq current (string-to-char (match-string 2))
13244 have t))
13245 (cond
13246 ((eq action 'remove)
13247 (setq remove t new ?\ ))
13248 ((or (eq action 'set)
13249 (if (featurep 'xemacs) (characterp action) (integerp action)))
13250 (if (not (eq action 'set))
13251 (setq new action)
13252 (message "Priority %c-%c, SPC to remove: "
13253 org-highest-priority org-lowest-priority)
13254 (save-match-data
13255 (setq new (read-char-exclusive))))
13256 (if (and (= (upcase org-highest-priority) org-highest-priority)
13257 (= (upcase org-lowest-priority) org-lowest-priority))
13258 (setq new (upcase new)))
13259 (cond ((equal new ?\ ) (setq remove t))
13260 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13261 (error "Priority must be between `%c' and `%c'"
13262 org-highest-priority org-lowest-priority))))
13263 ((eq action 'up)
13264 (setq new (if have
13265 (1- current) ; normal cycling
13266 ;; last priority was empty
13267 (if (eq last-command this-command)
13268 org-lowest-priority ; wrap around empty to lowest
13269 ;; default
13270 (if org-priority-start-cycle-with-default
13271 org-default-priority
13272 (1- org-default-priority))))))
13273 ((eq action 'down)
13274 (setq new (if have
13275 (1+ current) ; normal cycling
13276 ;; last priority was empty
13277 (if (eq last-command this-command)
13278 org-highest-priority ; wrap around empty to highest
13279 ;; default
13280 (if org-priority-start-cycle-with-default
13281 org-default-priority
13282 (1+ org-default-priority))))))
13283 (t (error "Invalid action")))
13284 (if (or (< (upcase new) org-highest-priority)
13285 (> (upcase new) org-lowest-priority))
13286 (if (and (memq action '(up down))
13287 (not have) (not (eq last-command this-command)))
13288 ;; `new' is from default priority
13289 (error
13290 "The default can not be set, see `org-default-priority' why")
13291 ;; normal cycling: `new' is beyond highest/lowest priority
13292 ;; and is wrapped around to the empty priority
13293 (setq remove t)))
13294 (setq news (format "%c" new))
13295 (if have
13296 (if remove
13297 (replace-match "" t t nil 1)
13298 (replace-match news t t nil 2))
13299 (if remove
13300 (error "No priority cookie found in line")
13301 (let ((case-fold-search nil))
13302 (looking-at org-todo-line-regexp))
13303 (if (match-end 2)
13304 (progn
13305 (goto-char (match-end 2))
13306 (insert " [#" news "]"))
13307 (goto-char (match-beginning 3))
13308 (insert "[#" news "] "))))
13309 (org-preserve-lc (org-set-tags nil 'align)))
13310 (if remove
13311 (message "Priority removed")
13312 (message "Priority of current item set to %s" news)))))
13314 (defun org-show-priority ()
13315 "Show the priority of the current item.
13316 This priority is composed of the main priority given with the [#A] cookies,
13317 and by additional input from the age of a schedules or deadline entry."
13318 (interactive)
13319 (let ((pri (if (eq major-mode 'org-agenda-mode)
13320 (org-get-at-bol 'priority)
13321 (save-excursion
13322 (save-match-data
13323 (beginning-of-line)
13324 (and (looking-at org-heading-regexp)
13325 (org-get-priority (match-string 0))))))))
13326 (message "Priority is %d" (if pri pri -1000))))
13328 (defun org-get-priority (s)
13329 "Find priority cookie and return priority."
13330 (save-match-data
13331 (if (functionp org-get-priority-function)
13332 (funcall org-get-priority-function)
13333 (if (not (string-match org-priority-regexp s))
13334 (* 1000 (- org-lowest-priority org-default-priority))
13335 (* 1000 (- org-lowest-priority
13336 (string-to-char (match-string 2 s))))))))
13338 ;;;; Tags
13340 (defvar org-agenda-archives-mode)
13341 (defvar org-map-continue-from nil
13342 "Position from where mapping should continue.
13343 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13345 (defvar org-scanner-tags nil
13346 "The current tag list while the tags scanner is running.")
13347 (defvar org-trust-scanner-tags nil
13348 "Should `org-get-tags-at' use the tags for the scanner.
13349 This is for internal dynamical scoping only.
13350 When this is non-nil, the function `org-get-tags-at' will return the value
13351 of `org-scanner-tags' instead of building the list by itself. This
13352 can lead to large speed-ups when the tags scanner is used in a file with
13353 many entries, and when the list of tags is retrieved, for example to
13354 obtain a list of properties. Building the tags list for each entry in such
13355 a file becomes an N^2 operation - but with this variable set, it scales
13356 as N.")
13358 (defun org-scan-tags (action matcher todo-only &optional start-level)
13359 "Scan headline tags with inheritance and produce output ACTION.
13361 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13362 or `agenda' to produce an entry list for an agenda view. It can also be
13363 a Lisp form or a function that should be called at each matched headline, in
13364 this case the return value is a list of all return values from these calls.
13366 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13367 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13368 only lines with a not-done TODO keyword are included in the output.
13369 This should be the same variable that was scoped into
13370 and set by `org-make-tags-matcher' when it constructed MATCHER.
13372 START-LEVEL can be a string with asterisks, reducing the scope to
13373 headlines matching this string."
13374 (require 'org-agenda)
13375 (let* ((re (concat "^"
13376 (if start-level
13377 ;; Get the correct level to match
13378 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13379 org-outline-regexp)
13380 " *\\(\\<\\("
13381 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13382 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13383 (props (list 'face 'default
13384 'done-face 'org-agenda-done
13385 'undone-face 'default
13386 'mouse-face 'highlight
13387 'org-not-done-regexp org-not-done-regexp
13388 'org-todo-regexp org-todo-regexp
13389 'org-complex-heading-regexp org-complex-heading-regexp
13390 'help-echo
13391 (format "mouse-2 or RET jump to org file %s"
13392 (abbreviate-file-name
13393 (or (buffer-file-name (buffer-base-buffer))
13394 (buffer-name (buffer-base-buffer)))))))
13395 (case-fold-search nil)
13396 (org-map-continue-from nil)
13397 lspos tags tags-list
13398 (tags-alist (list (cons 0 org-file-tags)))
13399 (llast 0) rtn rtn1 level category i txt
13400 todo marker entry priority)
13401 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13402 (setq action (list 'lambda nil action)))
13403 (save-excursion
13404 (goto-char (point-min))
13405 (when (eq action 'sparse-tree)
13406 (org-overview)
13407 (org-remove-occur-highlights))
13408 (while (re-search-forward re nil t)
13409 (setq org-map-continue-from nil)
13410 (catch :skip
13411 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13412 tags (if (match-end 4) (org-match-string-no-properties 4)))
13413 (goto-char (setq lspos (match-beginning 0)))
13414 (setq level (org-reduced-level (org-outline-level))
13415 category (org-get-category))
13416 (setq i llast llast level)
13417 ;; remove tag lists from same and sublevels
13418 (while (>= i level)
13419 (when (setq entry (assoc i tags-alist))
13420 (setq tags-alist (delete entry tags-alist)))
13421 (setq i (1- i)))
13422 ;; add the next tags
13423 (when tags
13424 (setq tags (org-split-string tags ":")
13425 tags-alist
13426 (cons (cons level tags) tags-alist)))
13427 ;; compile tags for current headline
13428 (setq tags-list
13429 (if org-use-tag-inheritance
13430 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13431 tags)
13432 org-scanner-tags tags-list)
13433 (when org-use-tag-inheritance
13434 (setcdr (car tags-alist)
13435 (mapcar (lambda (x)
13436 (setq x (copy-sequence x))
13437 (org-add-prop-inherited x))
13438 (cdar tags-alist))))
13439 (when (and tags org-use-tag-inheritance
13440 (or (not (eq t org-use-tag-inheritance))
13441 org-tags-exclude-from-inheritance))
13442 ;; selective inheritance, remove uninherited ones
13443 (setcdr (car tags-alist)
13444 (org-remove-uninherited-tags (cdar tags-alist))))
13445 (when (and
13447 ;; eval matcher only when the todo condition is OK
13448 (and (or (not todo-only) (member todo org-not-done-keywords))
13449 (let ((case-fold-search t) (org-trust-scanner-tags t))
13450 (eval matcher)))
13452 ;; Call the skipper, but return t if it does not skip,
13453 ;; so that the `and' form continues evaluating
13454 (progn
13455 (unless (eq action 'sparse-tree) (org-agenda-skip))
13458 ;; Check if timestamps are deselecting this entry
13459 (or (not todo-only)
13460 (and (member todo org-not-done-keywords)
13461 (or (not org-agenda-tags-todo-honor-ignore-options)
13462 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13464 ;; select this headline
13465 (cond
13466 ((eq action 'sparse-tree)
13467 (and org-highlight-sparse-tree-matches
13468 (org-get-heading) (match-end 0)
13469 (org-highlight-new-match
13470 (match-beginning 1) (match-end 1)))
13471 (org-show-context 'tags-tree))
13472 ((eq action 'agenda)
13473 (setq txt (org-agenda-format-item
13475 (concat
13476 (if (eq org-tags-match-list-sublevels 'indented)
13477 (make-string (1- level) ?.) "")
13478 (org-get-heading))
13479 level category
13480 tags-list)
13481 priority (org-get-priority txt))
13482 (goto-char lspos)
13483 (setq marker (org-agenda-new-marker))
13484 (org-add-props txt props
13485 'org-marker marker 'org-hd-marker marker 'org-category category
13486 'todo-state todo
13487 'priority priority 'type "tagsmatch")
13488 (push txt rtn))
13489 ((functionp action)
13490 (setq org-map-continue-from nil)
13491 (save-excursion
13492 (setq rtn1 (funcall action))
13493 (push rtn1 rtn)))
13494 (t (error "Invalid action")))
13496 ;; if we are to skip sublevels, jump to end of subtree
13497 (unless org-tags-match-list-sublevels
13498 (org-end-of-subtree t)
13499 (backward-char 1))))
13500 ;; Get the correct position from where to continue
13501 (if org-map-continue-from
13502 (goto-char org-map-continue-from)
13503 (and (= (point) lspos) (end-of-line 1)))))
13504 (when (and (eq action 'sparse-tree)
13505 (not org-sparse-tree-open-archived-trees))
13506 (org-hide-archived-subtrees (point-min) (point-max)))
13507 (nreverse rtn)))
13509 (defun org-remove-uninherited-tags (tags)
13510 "Remove all tags that are not inherited from the list TAGS."
13511 (cond
13512 ((eq org-use-tag-inheritance t)
13513 (if org-tags-exclude-from-inheritance
13514 (org-delete-all org-tags-exclude-from-inheritance tags)
13515 tags))
13516 ((not org-use-tag-inheritance) nil)
13517 ((stringp org-use-tag-inheritance)
13518 (delq nil (mapcar
13519 (lambda (x)
13520 (if (and (string-match org-use-tag-inheritance x)
13521 (not (member x org-tags-exclude-from-inheritance)))
13522 x nil))
13523 tags)))
13524 ((listp org-use-tag-inheritance)
13525 (delq nil (mapcar
13526 (lambda (x)
13527 (if (member x org-use-tag-inheritance) x nil))
13528 tags)))))
13530 (defun org-match-sparse-tree (&optional todo-only match)
13531 "Create a sparse tree according to tags string MATCH.
13532 MATCH can contain positive and negative selection of tags, like
13533 \"+WORK+URGENT-WITHBOSS\".
13534 If optional argument TODO-ONLY is non-nil, only select lines that are
13535 also TODO lines."
13536 (interactive "P")
13537 (org-agenda-prepare-buffers (list (current-buffer)))
13538 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13540 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13542 (defvar org-cached-props nil)
13543 (defun org-cached-entry-get (pom property)
13544 (if (or (eq t org-use-property-inheritance)
13545 (and (stringp org-use-property-inheritance)
13546 (string-match org-use-property-inheritance property))
13547 (and (listp org-use-property-inheritance)
13548 (member property org-use-property-inheritance)))
13549 ;; Caching is not possible, check it directly
13550 (org-entry-get pom property 'inherit)
13551 ;; Get all properties, so that we can do complicated checks easily
13552 (cdr (assoc property (or org-cached-props
13553 (setq org-cached-props
13554 (org-entry-properties pom)))))))
13556 (defun org-global-tags-completion-table (&optional files)
13557 "Return the list of all tags in all agenda buffer/files.
13558 Optional FILES argument is a list of files which can be used
13559 instead of the agenda files."
13560 (save-excursion
13561 (org-uniquify
13562 (delq nil
13563 (apply 'append
13564 (mapcar
13565 (lambda (file)
13566 (set-buffer (find-file-noselect file))
13567 (append (org-get-buffer-tags)
13568 (mapcar (lambda (x) (if (stringp (car-safe x))
13569 (list (car-safe x)) nil))
13570 org-tag-alist)))
13571 (if (and files (car files))
13572 files
13573 (org-agenda-files))))))))
13575 (defun org-make-tags-matcher (match)
13576 "Create the TAGS/TODO matcher form for the selection string MATCH.
13578 The variable `todo-only' is scoped dynamically into this function.
13579 It will be set to t if the matcher restricts matching to TODO entries,
13580 otherwise will not be touched.
13582 Returns a cons of the selection string MATCH and the constructed
13583 lisp form implementing the matcher. The matcher is to be evaluated
13584 at an Org entry, with point on the headline, and returns t if the
13585 entry matches the selection string MATCH. The returned lisp form
13586 references two variables with information about the entry, which
13587 must be bound around the form's evaluation: todo, the TODO keyword
13588 at the entry (or nil of none); and tags-list, the list of all tags
13589 at the entry including inherited ones. Additionally, the category
13590 of the entry (if any) must be specified as the text property
13591 'org-category on the headline.
13593 See also `org-scan-tags'.
13595 (declare (special todo-only))
13596 (unless (boundp 'todo-only)
13597 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13598 (unless match
13599 ;; Get a new match request, with completion
13600 (let ((org-last-tags-completion-table
13601 (org-global-tags-completion-table)))
13602 (setq match (org-completing-read-no-i
13603 "Match: " 'org-tags-completion-function nil nil nil
13604 'org-tags-history))))
13606 ;; Parse the string and create a lisp form
13607 (let ((match0 match)
13608 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13609 minus tag mm
13610 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13611 orterms term orlist re-p str-p level-p level-op time-p
13612 prop-p pn pv po gv rest)
13613 (if (string-match "/+" match)
13614 ;; match contains also a todo-matching request
13615 (progn
13616 (setq tagsmatch (substring match 0 (match-beginning 0))
13617 todomatch (substring match (match-end 0)))
13618 (if (string-match "^!" todomatch)
13619 (setq todo-only t todomatch (substring todomatch 1)))
13620 (if (string-match "^\\s-*$" todomatch)
13621 (setq todomatch nil)))
13622 ;; only matching tags
13623 (setq tagsmatch match todomatch nil))
13625 ;; Make the tags matcher
13626 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13627 (setq tagsmatcher t)
13628 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13629 (while (setq term (pop orterms))
13630 (while (and (equal (substring term -1) "\\") orterms)
13631 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13632 (while (string-match re term)
13633 (setq rest (substring term (match-end 0))
13634 minus (and (match-end 1)
13635 (equal (match-string 1 term) "-"))
13636 tag (save-match-data (replace-regexp-in-string
13637 "\\\\-" "-"
13638 (match-string 2 term)))
13639 re-p (equal (string-to-char tag) ?{)
13640 level-p (match-end 4)
13641 prop-p (match-end 5)
13642 mm (cond
13643 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13644 (level-p
13645 (setq level-op (org-op-to-function (match-string 3 term)))
13646 `(,level-op level ,(string-to-number
13647 (match-string 4 term))))
13648 (prop-p
13649 (setq pn (match-string 5 term)
13650 po (match-string 6 term)
13651 pv (match-string 7 term)
13652 re-p (equal (string-to-char pv) ?{)
13653 str-p (equal (string-to-char pv) ?\")
13654 time-p (save-match-data
13655 (string-match "^\"[[<].*[]>]\"$" pv))
13656 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13657 (if time-p (setq pv (org-matcher-time pv)))
13658 (setq po (org-op-to-function po (if time-p 'time str-p)))
13659 (cond
13660 ((equal pn "CATEGORY")
13661 (setq gv '(get-text-property (point) 'org-category)))
13662 ((equal pn "TODO")
13663 (setq gv 'todo))
13665 (setq gv `(org-cached-entry-get nil ,pn))))
13666 (if re-p
13667 (if (eq po 'org<>)
13668 `(not (string-match ,pv (or ,gv "")))
13669 `(string-match ,pv (or ,gv "")))
13670 (if str-p
13671 `(,po (or ,gv "") ,pv)
13672 `(,po (string-to-number (or ,gv ""))
13673 ,(string-to-number pv) ))))
13674 (t `(member ,tag tags-list)))
13675 mm (if minus (list 'not mm) mm)
13676 term rest)
13677 (push mm tagsmatcher))
13678 (push (if (> (length tagsmatcher) 1)
13679 (cons 'and tagsmatcher)
13680 (car tagsmatcher))
13681 orlist)
13682 (setq tagsmatcher nil))
13683 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13684 (setq tagsmatcher
13685 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13686 ;; Make the todo matcher
13687 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13688 (setq todomatcher t)
13689 (setq orterms (org-split-string todomatch "|") orlist nil)
13690 (while (setq term (pop orterms))
13691 (while (string-match re term)
13692 (setq minus (and (match-end 1)
13693 (equal (match-string 1 term) "-"))
13694 kwd (match-string 2 term)
13695 re-p (equal (string-to-char kwd) ?{)
13696 term (substring term (match-end 0))
13697 mm (if re-p
13698 `(string-match ,(substring kwd 1 -1) todo)
13699 (list 'equal 'todo kwd))
13700 mm (if minus (list 'not mm) mm))
13701 (push mm todomatcher))
13702 (push (if (> (length todomatcher) 1)
13703 (cons 'and todomatcher)
13704 (car todomatcher))
13705 orlist)
13706 (setq todomatcher nil))
13707 (setq todomatcher (if (> (length orlist) 1)
13708 (cons 'or orlist) (car orlist))))
13710 ;; Return the string and lisp forms of the matcher
13711 (setq matcher (if todomatcher
13712 (list 'and tagsmatcher todomatcher)
13713 tagsmatcher))
13714 (when todo-only
13715 (setq matcher (list 'and '(member todo org-not-done-keywords)
13716 matcher)))
13717 (cons match0 matcher)))
13719 (defun org-op-to-function (op &optional stringp)
13720 "Turn an operator into the appropriate function."
13721 (setq op
13722 (cond
13723 ((equal op "<" ) '(< string< org-time<))
13724 ((equal op ">" ) '(> org-string> org-time>))
13725 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13726 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13727 ((member op '("=" "==")) '(= string= org-time=))
13728 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13729 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13731 (defun org<> (a b) (not (= a b)))
13732 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13733 (defun org-string>= (a b) (not (string< a b)))
13734 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13735 (defun org-string<> (a b) (not (string= a b)))
13736 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13737 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13738 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13739 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13740 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13741 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13742 (defun org-2ft (s)
13743 "Convert S to a floating point time.
13744 If S is already a number, just return it. If it is a string, parse
13745 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13746 (cond
13747 ((numberp s) s)
13748 ((stringp s)
13749 (condition-case nil
13750 (float-time (apply 'encode-time (org-parse-time-string s)))
13751 (error 0.)))
13752 (t 0.)))
13754 (defun org-time-today ()
13755 "Time in seconds today at 0:00.
13756 Returns the float number of seconds since the beginning of the
13757 epoch to the beginning of today (00:00)."
13758 (float-time (apply 'encode-time
13759 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13761 (defun org-matcher-time (s)
13762 "Interpret a time comparison value."
13763 (save-match-data
13764 (cond
13765 ((string= s "<now>") (float-time))
13766 ((string= s "<today>") (org-time-today))
13767 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13768 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13769 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13770 (+ (org-time-today)
13771 (* (string-to-number (match-string 1 s))
13772 (cdr (assoc (match-string 2 s)
13773 '(("d" . 86400.0) ("w" . 604800.0)
13774 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13775 (t (org-2ft s)))))
13777 (defun org-match-any-p (re list)
13778 "Does re match any element of list?"
13779 (setq list (mapcar (lambda (x) (string-match re x)) list))
13780 (delq nil list))
13782 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13783 (defvar org-tags-overlay (make-overlay 1 1))
13784 (org-detach-overlay org-tags-overlay)
13786 (defun org-get-local-tags-at (&optional pos)
13787 "Get a list of tags defined in the current headline."
13788 (org-get-tags-at pos 'local))
13790 (defun org-get-local-tags ()
13791 "Get a list of tags defined in the current headline."
13792 (org-get-tags-at nil 'local))
13794 (defun org-get-tags-at (&optional pos local)
13795 "Get a list of all headline tags applicable at POS.
13796 POS defaults to point. If tags are inherited, the list contains
13797 the targets in the same sequence as the headlines appear, i.e.
13798 the tags of the current headline come last.
13799 When LOCAL is non-nil, only return tags from the current headline,
13800 ignore inherited ones."
13801 (interactive)
13802 (if (and org-trust-scanner-tags
13803 (or (not pos) (equal pos (point)))
13804 (not local))
13805 org-scanner-tags
13806 (let (tags ltags lastpos parent)
13807 (save-excursion
13808 (save-restriction
13809 (widen)
13810 (goto-char (or pos (point)))
13811 (save-match-data
13812 (catch 'done
13813 (condition-case nil
13814 (progn
13815 (org-back-to-heading t)
13816 (while (not (equal lastpos (point)))
13817 (setq lastpos (point))
13818 (when (looking-at
13819 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13820 (setq ltags (org-split-string
13821 (org-match-string-no-properties 1) ":"))
13822 (when parent
13823 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13824 (setq tags (append
13825 (if parent
13826 (org-remove-uninherited-tags ltags)
13827 ltags)
13828 tags)))
13829 (or org-use-tag-inheritance (throw 'done t))
13830 (if local (throw 'done t))
13831 (or (org-up-heading-safe) (error nil))
13832 (setq parent t)))
13833 (error nil)))))
13834 (if local
13835 tags
13836 (reverse (delete-dups
13837 (reverse (append
13838 (org-remove-uninherited-tags
13839 org-file-tags) tags)))))))))
13841 (defun org-add-prop-inherited (s)
13842 (add-text-properties 0 (length s) '(inherited t) s)
13845 (defun org-toggle-tag (tag &optional onoff)
13846 "Toggle the tag TAG for the current line.
13847 If ONOFF is `on' or `off', don't toggle but set to this state."
13848 (let (res current)
13849 (save-excursion
13850 (org-back-to-heading t)
13851 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13852 (point-at-eol) t)
13853 (progn
13854 (setq current (match-string 1))
13855 (replace-match ""))
13856 (setq current ""))
13857 (setq current (nreverse (org-split-string current ":")))
13858 (cond
13859 ((eq onoff 'on)
13860 (setq res t)
13861 (or (member tag current) (push tag current)))
13862 ((eq onoff 'off)
13863 (or (not (member tag current)) (setq current (delete tag current))))
13864 (t (if (member tag current)
13865 (setq current (delete tag current))
13866 (setq res t)
13867 (push tag current))))
13868 (end-of-line 1)
13869 (if current
13870 (progn
13871 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13872 (org-set-tags nil t))
13873 (delete-horizontal-space))
13874 (run-hooks 'org-after-tags-change-hook))
13875 res))
13877 (defun org-align-tags-here (to-col)
13878 ;; Assumes that this is a headline
13879 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13880 (beginning-of-line 1)
13881 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13882 (< pos (match-beginning 2)))
13883 (progn
13884 (setq tags-l (- (match-end 2) (match-beginning 2)))
13885 (goto-char (match-beginning 1))
13886 (insert " ")
13887 (delete-region (point) (1+ (match-beginning 2)))
13888 (setq ncol (max (current-column)
13889 (1+ col)
13890 (if (> to-col 0)
13891 to-col
13892 (- (abs to-col) tags-l))))
13893 (setq p (point))
13894 (insert (make-string (- ncol (current-column)) ?\ ))
13895 (setq ncol (current-column))
13896 (when indent-tabs-mode (tabify p (point-at-eol)))
13897 (org-move-to-column (min ncol col) t))
13898 (goto-char pos))))
13900 (defun org-set-tags-command (&optional arg just-align)
13901 "Call the set-tags command for the current entry."
13902 (interactive "P")
13903 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13904 (org-set-tags arg just-align)
13905 (save-excursion
13906 (org-back-to-heading t)
13907 (org-set-tags arg just-align))))
13909 (defun org-set-tags-to (data)
13910 "Set the tags of the current entry to DATA, replacing the current tags.
13911 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13912 If DATA is nil or the empty string, any tags will be removed."
13913 (interactive "sTags: ")
13914 (setq data
13915 (cond
13916 ((eq data nil) "")
13917 ((equal data "") "")
13918 ((stringp data)
13919 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13920 ":"))
13921 ((listp data)
13922 (concat ":" (mapconcat 'identity data ":") ":"))))
13923 (when data
13924 (save-excursion
13925 (org-back-to-heading t)
13926 (when (looking-at org-complex-heading-regexp)
13927 (if (match-end 5)
13928 (progn
13929 (goto-char (match-beginning 5))
13930 (insert data)
13931 (delete-region (point) (point-at-eol))
13932 (org-set-tags nil 'align))
13933 (goto-char (point-at-eol))
13934 (insert " " data)
13935 (org-set-tags nil 'align)))
13936 (beginning-of-line 1)
13937 (if (looking-at ".*?\\([ \t]+\\)$")
13938 (delete-region (match-beginning 1) (match-end 1))))))
13940 (defun org-align-all-tags ()
13941 "Align the tags i all headings."
13942 (interactive)
13943 (save-excursion
13944 (or (ignore-errors (org-back-to-heading t))
13945 (outline-next-heading))
13946 (if (org-at-heading-p)
13947 (org-set-tags t)
13948 (message "No headings"))))
13950 (defvar org-indent-indentation-per-level)
13951 (defun org-set-tags (&optional arg just-align)
13952 "Set the tags for the current headline.
13953 With prefix ARG, realign all tags in headings in the current buffer."
13954 (interactive "P")
13955 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13956 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13957 'region-start-level 'region))
13958 org-loop-over-headlines-in-active-region)
13959 (org-map-entries
13960 ;; We don't use ARG and JUST-ALIGN here these args are not
13961 ;; useful when looping over headlines
13962 `(org-set-tags)
13963 org-loop-over-headlines-in-active-region
13964 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13965 (let* ((re org-outline-regexp-bol)
13966 (current (unless arg (org-get-tags-string)))
13967 (col (current-column))
13968 (org-setting-tags t)
13969 table current-tags inherited-tags ; computed below when needed
13970 tags p0 c0 c1 rpl di tc level)
13971 (if arg
13972 (save-excursion
13973 (goto-char (point-min))
13974 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13975 (while (re-search-forward re nil t)
13976 (org-set-tags nil t)
13977 (end-of-line 1)))
13978 (message "All tags realigned to column %d" org-tags-column))
13979 (if just-align
13980 (setq tags current)
13981 ;; Get a new set of tags from the user
13982 (save-excursion
13983 (setq table (append org-tag-persistent-alist
13984 (or org-tag-alist (org-get-buffer-tags))
13985 (and
13986 org-complete-tags-always-offer-all-agenda-tags
13987 (org-global-tags-completion-table
13988 (org-agenda-files))))
13989 org-last-tags-completion-table table
13990 current-tags (org-split-string current ":")
13991 inherited-tags (nreverse
13992 (nthcdr (length current-tags)
13993 (nreverse (org-get-tags-at))))
13994 tags
13995 (if (or (eq t org-use-fast-tag-selection)
13996 (and org-use-fast-tag-selection
13997 (delq nil (mapcar 'cdr table))))
13998 (org-fast-tag-selection
13999 current-tags inherited-tags table
14000 (if org-fast-tag-selection-include-todo
14001 org-todo-key-alist))
14002 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14003 (org-trim
14004 (org-icompleting-read "Tags: "
14005 'org-tags-completion-function
14006 nil nil current 'org-tags-history))))))
14007 (while (string-match "[-+&]+" tags)
14008 ;; No boolean logic, just a list
14009 (setq tags (replace-match ":" t t tags))))
14011 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14013 (if org-tags-sort-function
14014 (setq tags (mapconcat 'identity
14015 (sort (org-split-string
14016 tags (org-re "[^[:alnum:]_@#%]+"))
14017 org-tags-sort-function) ":")))
14019 (if (string-match "\\`[\t ]*\\'" tags)
14020 (setq tags "")
14021 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14022 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14024 ;; Insert new tags at the correct column
14025 (beginning-of-line 1)
14026 (setq level (or (and (looking-at org-outline-regexp)
14027 (- (match-end 0) (point) 1))
14029 (cond
14030 ((and (equal current "") (equal tags "")))
14031 ((re-search-forward
14032 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14033 (point-at-eol) t)
14034 (if (equal tags "")
14035 (setq rpl "")
14036 (goto-char (match-beginning 0))
14037 (setq c0 (current-column)
14038 ;; compute offset for the case of org-indent-mode active
14039 di (if org-indent-mode
14040 (* (1- org-indent-indentation-per-level) (1- level))
14042 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14043 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14044 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14045 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14046 (replace-match rpl t t)
14047 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14048 tags)
14049 (t (error "Tags alignment failed")))
14050 (org-move-to-column col)
14051 (unless just-align
14052 (run-hooks 'org-after-tags-change-hook))))))
14054 (defun org-change-tag-in-region (beg end tag off)
14055 "Add or remove TAG for each entry in the region.
14056 This works in the agenda, and also in an org-mode buffer."
14057 (interactive
14058 (list (region-beginning) (region-end)
14059 (let ((org-last-tags-completion-table
14060 (if (derived-mode-p 'org-mode)
14061 (org-get-buffer-tags)
14062 (org-global-tags-completion-table))))
14063 (org-icompleting-read
14064 "Tag: " 'org-tags-completion-function nil nil nil
14065 'org-tags-history))
14066 (progn
14067 (message "[s]et or [r]emove? ")
14068 (equal (read-char-exclusive) ?r))))
14069 (if (fboundp 'deactivate-mark) (deactivate-mark))
14070 (let ((agendap (equal major-mode 'org-agenda-mode))
14071 l1 l2 m buf pos newhead (cnt 0))
14072 (goto-char end)
14073 (setq l2 (1- (org-current-line)))
14074 (goto-char beg)
14075 (setq l1 (org-current-line))
14076 (loop for l from l1 to l2 do
14077 (org-goto-line l)
14078 (setq m (get-text-property (point) 'org-hd-marker))
14079 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14080 (and agendap m))
14081 (setq buf (if agendap (marker-buffer m) (current-buffer))
14082 pos (if agendap m (point)))
14083 (with-current-buffer buf
14084 (save-excursion
14085 (save-restriction
14086 (goto-char pos)
14087 (setq cnt (1+ cnt))
14088 (org-toggle-tag tag (if off 'off 'on))
14089 (setq newhead (org-get-heading)))))
14090 (and agendap (org-agenda-change-all-lines newhead m))))
14091 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14093 (defun org-tags-completion-function (string predicate &optional flag)
14094 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14095 (confirm (lambda (x) (stringp (car x)))))
14096 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14097 (setq s1 (match-string 1 string)
14098 s2 (match-string 2 string))
14099 (setq s1 "" s2 string))
14100 (cond
14101 ((eq flag nil)
14102 ;; try completion
14103 (setq rtn (try-completion s2 ctable confirm))
14104 (if (stringp rtn)
14105 (setq rtn
14106 (concat s1 s2 (substring rtn (length s2))
14107 (if (and org-add-colon-after-tag-completion
14108 (assoc rtn ctable))
14109 ":" ""))))
14110 rtn)
14111 ((eq flag t)
14112 ;; all-completions
14113 (all-completions s2 ctable confirm)
14115 ((eq flag 'lambda)
14116 ;; exact match?
14117 (assoc s2 ctable)))
14120 (defun org-fast-tag-insert (kwd tags face &optional end)
14121 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14122 (insert (format "%-12s" (concat kwd ":"))
14123 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14124 (or end "")))
14126 (defun org-fast-tag-show-exit (flag)
14127 (save-excursion
14128 (org-goto-line 3)
14129 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14130 (replace-match ""))
14131 (when flag
14132 (end-of-line 1)
14133 (org-move-to-column (- (window-width) 19) t)
14134 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14136 (defun org-set-current-tags-overlay (current prefix)
14137 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14138 (if (featurep 'xemacs)
14139 (org-overlay-display org-tags-overlay (concat prefix s)
14140 'secondary-selection)
14141 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14142 (org-overlay-display org-tags-overlay (concat prefix s)))))
14144 (defvar org-last-tag-selection-key nil)
14145 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14146 "Fast tag selection with single keys.
14147 CURRENT is the current list of tags in the headline, INHERITED is the
14148 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14149 possibly with grouping information. TODO-TABLE is a similar table with
14150 TODO keywords, should these have keys assigned to them.
14151 If the keys are nil, a-z are automatically assigned.
14152 Returns the new tags string, or nil to not change the current settings."
14153 (let* ((fulltable (append table todo-table))
14154 (maxlen (apply 'max (mapcar
14155 (lambda (x)
14156 (if (stringp (car x)) (string-width (car x)) 0))
14157 fulltable)))
14158 (buf (current-buffer))
14159 (expert (eq org-fast-tag-selection-single-key 'expert))
14160 (buffer-tags nil)
14161 (fwidth (+ maxlen 3 1 3))
14162 (ncol (/ (- (window-width) 4) fwidth))
14163 (i-face 'org-done)
14164 (c-face 'org-todo)
14165 tg cnt e c char c1 c2 ntable tbl rtn
14166 ov-start ov-end ov-prefix
14167 (exit-after-next org-fast-tag-selection-single-key)
14168 (done-keywords org-done-keywords)
14169 groups ingroup)
14170 (save-excursion
14171 (beginning-of-line 1)
14172 (if (looking-at
14173 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14174 (setq ov-start (match-beginning 1)
14175 ov-end (match-end 1)
14176 ov-prefix "")
14177 (setq ov-start (1- (point-at-eol))
14178 ov-end (1+ ov-start))
14179 (skip-chars-forward "^\n\r")
14180 (setq ov-prefix
14181 (concat
14182 (buffer-substring (1- (point)) (point))
14183 (if (> (current-column) org-tags-column)
14185 (make-string (- org-tags-column (current-column)) ?\ ))))))
14186 (move-overlay org-tags-overlay ov-start ov-end)
14187 (save-window-excursion
14188 (if expert
14189 (set-buffer (get-buffer-create " *Org tags*"))
14190 (delete-other-windows)
14191 (split-window-vertically)
14192 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14193 (erase-buffer)
14194 (org-set-local 'org-done-keywords done-keywords)
14195 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14196 (org-fast-tag-insert "Current" current c-face "\n\n")
14197 (org-fast-tag-show-exit exit-after-next)
14198 (org-set-current-tags-overlay current ov-prefix)
14199 (setq tbl fulltable char ?a cnt 0)
14200 (while (setq e (pop tbl))
14201 (cond
14202 ((equal (car e) :startgroup)
14203 (push '() groups) (setq ingroup t)
14204 (when (not (= cnt 0))
14205 (setq cnt 0)
14206 (insert "\n"))
14207 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14208 ((equal (car e) :endgroup)
14209 (setq ingroup nil cnt 0)
14210 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14211 ((equal e '(:newline))
14212 (when (not (= cnt 0))
14213 (setq cnt 0)
14214 (insert "\n")
14215 (setq e (car tbl))
14216 (while (equal (car tbl) '(:newline))
14217 (insert "\n")
14218 (setq tbl (cdr tbl)))))
14220 (setq tg (copy-sequence (car e)) c2 nil)
14221 (if (cdr e)
14222 (setq c (cdr e))
14223 ;; automatically assign a character.
14224 (setq c1 (string-to-char
14225 (downcase (substring
14226 tg (if (= (string-to-char tg) ?@) 1 0)))))
14227 (if (or (rassoc c1 ntable) (rassoc c1 table))
14228 (while (or (rassoc char ntable) (rassoc char table))
14229 (setq char (1+ char)))
14230 (setq c2 c1))
14231 (setq c (or c2 char)))
14232 (if ingroup (push tg (car groups)))
14233 (setq tg (org-add-props tg nil 'face
14234 (cond
14235 ((not (assoc tg table))
14236 (org-get-todo-face tg))
14237 ((member tg current) c-face)
14238 ((member tg inherited) i-face))))
14239 (if (and (= cnt 0) (not ingroup)) (insert " "))
14240 (insert "[" c "] " tg (make-string
14241 (- fwidth 4 (length tg)) ?\ ))
14242 (push (cons tg c) ntable)
14243 (when (= (setq cnt (1+ cnt)) ncol)
14244 (insert "\n")
14245 (if ingroup (insert " "))
14246 (setq cnt 0)))))
14247 (setq ntable (nreverse ntable))
14248 (insert "\n")
14249 (goto-char (point-min))
14250 (if (not expert) (org-fit-window-to-buffer))
14251 (setq rtn
14252 (catch 'exit
14253 (while t
14254 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14255 (if (not groups) "no " "")
14256 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14257 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14258 (setq org-last-tag-selection-key c)
14259 (cond
14260 ((= c ?\r) (throw 'exit t))
14261 ((= c ?!)
14262 (setq groups (not groups))
14263 (goto-char (point-min))
14264 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14265 ((= c ?\C-c)
14266 (if (not expert)
14267 (org-fast-tag-show-exit
14268 (setq exit-after-next (not exit-after-next)))
14269 (setq expert nil)
14270 (delete-other-windows)
14271 (set-window-buffer (split-window-vertically) " *Org tags*")
14272 (org-switch-to-buffer-other-window " *Org tags*")
14273 (org-fit-window-to-buffer)))
14274 ((or (= c ?\C-g)
14275 (and (= c ?q) (not (rassoc c ntable))))
14276 (org-detach-overlay org-tags-overlay)
14277 (setq quit-flag t))
14278 ((= c ?\ )
14279 (setq current nil)
14280 (if exit-after-next (setq exit-after-next 'now)))
14281 ((= c ?\t)
14282 (condition-case nil
14283 (setq tg (org-icompleting-read
14284 "Tag: "
14285 (or buffer-tags
14286 (with-current-buffer buf
14287 (org-get-buffer-tags)))))
14288 (quit (setq tg "")))
14289 (when (string-match "\\S-" tg)
14290 (add-to-list 'buffer-tags (list tg))
14291 (if (member tg current)
14292 (setq current (delete tg current))
14293 (push tg current)))
14294 (if exit-after-next (setq exit-after-next 'now)))
14295 ((setq e (rassoc c todo-table) tg (car e))
14296 (with-current-buffer buf
14297 (save-excursion (org-todo tg)))
14298 (if exit-after-next (setq exit-after-next 'now)))
14299 ((setq e (rassoc c ntable) tg (car e))
14300 (if (member tg current)
14301 (setq current (delete tg current))
14302 (loop for g in groups do
14303 (if (member tg g)
14304 (mapc (lambda (x)
14305 (setq current (delete x current)))
14306 g)))
14307 (push tg current))
14308 (if exit-after-next (setq exit-after-next 'now))))
14310 ;; Create a sorted list
14311 (setq current
14312 (sort current
14313 (lambda (a b)
14314 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14315 (if (eq exit-after-next 'now) (throw 'exit t))
14316 (goto-char (point-min))
14317 (beginning-of-line 2)
14318 (delete-region (point) (point-at-eol))
14319 (org-fast-tag-insert "Current" current c-face)
14320 (org-set-current-tags-overlay current ov-prefix)
14321 (while (re-search-forward
14322 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14323 (setq tg (match-string 1))
14324 (add-text-properties
14325 (match-beginning 1) (match-end 1)
14326 (list 'face
14327 (cond
14328 ((member tg current) c-face)
14329 ((member tg inherited) i-face)
14330 (t (get-text-property (match-beginning 1) 'face))))))
14331 (goto-char (point-min)))))
14332 (org-detach-overlay org-tags-overlay)
14333 (if rtn
14334 (mapconcat 'identity current ":")
14335 nil))))
14337 (defun org-get-tags-string ()
14338 "Get the TAGS string in the current headline."
14339 (unless (org-at-heading-p t)
14340 (error "Not on a heading"))
14341 (save-excursion
14342 (beginning-of-line 1)
14343 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14344 (org-match-string-no-properties 1)
14345 "")))
14347 (defun org-get-tags ()
14348 "Get the list of tags specified in the current headline."
14349 (org-split-string (org-get-tags-string) ":"))
14351 (defun org-get-buffer-tags ()
14352 "Get a table of all tags used in the buffer, for completion."
14353 (let (tags)
14354 (save-excursion
14355 (goto-char (point-min))
14356 (while (re-search-forward
14357 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14358 (when (equal (char-after (point-at-bol 0)) ?*)
14359 (mapc (lambda (x) (add-to-list 'tags x))
14360 (org-split-string (org-match-string-no-properties 1) ":")))))
14361 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14362 (mapcar 'list tags)))
14364 ;;;; The mapping API
14366 (defun org-map-entries (func &optional match scope &rest skip)
14367 "Call FUNC at each headline selected by MATCH in SCOPE.
14369 FUNC is a function or a lisp form. The function will be called without
14370 arguments, with the cursor positioned at the beginning of the headline.
14371 The return values of all calls to the function will be collected and
14372 returned as a list.
14374 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14375 does not need to preserve point. After evaluation, the cursor will be
14376 moved to the end of the line (presumably of the headline of the
14377 processed entry) and search continues from there. Under some
14378 circumstances, this may not produce the wanted results. For example,
14379 if you have removed (e.g. archived) the current (sub)tree it could
14380 mean that the next entry will be skipped entirely. In such cases, you
14381 can specify the position from where search should continue by making
14382 FUNC set the variable `org-map-continue-from' to the desired buffer
14383 position.
14385 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14386 Only headlines that are matched by this query will be considered during
14387 the iteration. When MATCH is nil or t, all headlines will be
14388 visited by the iteration.
14390 SCOPE determines the scope of this command. It can be any of:
14392 nil The current buffer, respecting the restriction if any
14393 tree The subtree started with the entry at point
14394 region The entries within the active region, if any
14395 region-start-level
14396 The entries within the active region, but only those at
14397 the same level than the first one.
14398 file The current buffer, without restriction
14399 file-with-archives
14400 The current buffer, and any archives associated with it
14401 agenda All agenda files
14402 agenda-with-archives
14403 All agenda files with any archive files associated with them
14404 \(file1 file2 ...)
14405 If this is a list, all files in the list will be scanned
14407 The remaining args are treated as settings for the skipping facilities of
14408 the scanner. The following items can be given here:
14410 archive skip trees with the archive tag.
14411 comment skip trees with the COMMENT keyword
14412 function or Emacs Lisp form:
14413 will be used as value for `org-agenda-skip-function', so whenever
14414 the function returns t, FUNC will not be called for that
14415 entry and search will continue from the point where the
14416 function leaves it.
14418 If your function needs to retrieve the tags including inherited tags
14419 at the *current* entry, you can use the value of the variable
14420 `org-scanner-tags' which will be much faster than getting the value
14421 with `org-get-tags-at'. If your function gets properties with
14422 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14423 to t around the call to `org-entry-properties' to get the same speedup.
14424 Note that if your function moves around to retrieve tags and properties at
14425 a *different* entry, you cannot use these techniques."
14426 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14427 (not (org-region-active-p)))
14428 (let* ((org-agenda-archives-mode nil) ; just to make sure
14429 (org-agenda-skip-archived-trees (memq 'archive skip))
14430 (org-agenda-skip-comment-trees (memq 'comment skip))
14431 (org-agenda-skip-function
14432 (car (org-delete-all '(comment archive) skip)))
14433 (org-tags-match-list-sublevels t)
14434 (start-level (eq scope 'region-start-level))
14435 matcher file res
14436 org-todo-keywords-for-agenda
14437 org-done-keywords-for-agenda
14438 org-todo-keyword-alist-for-agenda
14439 org-drawers-for-agenda
14440 org-tag-alist-for-agenda
14441 todo-only)
14443 (cond
14444 ((eq match t) (setq matcher t))
14445 ((eq match nil) (setq matcher t))
14446 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14448 (save-excursion
14449 (save-restriction
14450 (cond ((eq scope 'tree)
14451 (org-back-to-heading t)
14452 (org-narrow-to-subtree)
14453 (setq scope nil))
14454 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14455 (org-region-active-p))
14456 ;; If needed, set start-level to a string like "2"
14457 (when start-level
14458 (save-excursion
14459 (goto-char (region-beginning))
14460 (unless (org-at-heading-p) (outline-next-heading))
14461 (setq start-level (org-current-level))))
14462 (narrow-to-region (region-beginning)
14463 (save-excursion
14464 (goto-char (region-end))
14465 (unless (and (bolp) (org-at-heading-p))
14466 (outline-next-heading))
14467 (point)))
14468 (setq scope nil)))
14470 (if (not scope)
14471 (progn
14472 (org-agenda-prepare-buffers
14473 (list (buffer-file-name (current-buffer))))
14474 (setq res (org-scan-tags func matcher todo-only start-level)))
14475 ;; Get the right scope
14476 (cond
14477 ((and scope (listp scope) (symbolp (car scope)))
14478 (setq scope (eval scope)))
14479 ((eq scope 'agenda)
14480 (setq scope (org-agenda-files t)))
14481 ((eq scope 'agenda-with-archives)
14482 (setq scope (org-agenda-files t))
14483 (setq scope (org-add-archive-files scope)))
14484 ((eq scope 'file)
14485 (setq scope (list (buffer-file-name))))
14486 ((eq scope 'file-with-archives)
14487 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14488 (org-agenda-prepare-buffers scope)
14489 (while (setq file (pop scope))
14490 (with-current-buffer (org-find-base-buffer-visiting file)
14491 (save-excursion
14492 (save-restriction
14493 (widen)
14494 (goto-char (point-min))
14495 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14496 res)))
14498 ;;;; Properties
14500 ;;; Setting and retrieving properties
14502 (defconst org-special-properties
14503 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14504 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14505 "The special properties valid in Org-mode.
14507 These are properties that are not defined in the property drawer,
14508 but in some other way.")
14510 (defconst org-default-properties
14511 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14512 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14513 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14514 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14515 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14516 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14517 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14518 "Some properties that are used by Org-mode for various purposes.
14519 Being in this list makes sure that they are offered for completion.")
14521 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14522 "Regular expression matching the first line of a property drawer.")
14524 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14525 "Regular expression matching the last line of a property drawer.")
14527 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14528 "Regular expression matching the first line of a property drawer.")
14530 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14531 "Regular expression matching the first line of a property drawer.")
14533 (defconst org-property-drawer-re
14534 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14535 org-property-end-re "\\)\n?")
14536 "Matches an entire property drawer.")
14538 (defconst org-clock-drawer-re
14539 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14540 org-property-end-re "\\)\n?")
14541 "Matches an entire clock drawer.")
14543 (defsubst org-re-property (property)
14544 "Return a regexp matching a PROPERTY line.
14545 Match group 1 will be set to the value."
14546 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14548 (defsubst org-re-property-keyword (property)
14549 "Return a regexp matching a PROPERTY line, possibly with no
14550 value for the property."
14551 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14553 (defun org-property-action ()
14554 "Do an action on properties."
14555 (interactive)
14556 (let (c)
14557 (org-at-property-p)
14558 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14559 (setq c (read-char-exclusive))
14560 (cond
14561 ((equal c ?s)
14562 (call-interactively 'org-set-property))
14563 ((equal c ?d)
14564 (call-interactively 'org-delete-property))
14565 ((equal c ?D)
14566 (call-interactively 'org-delete-property-globally))
14567 ((equal c ?c)
14568 (call-interactively 'org-compute-property-at-point))
14569 (t (error "No such property action %c" c)))))
14571 (defun org-inc-effort ()
14572 "Increment the value of the effort property in the current entry."
14573 (interactive)
14574 (org-set-effort nil t))
14576 (defun org-set-effort (&optional value increment)
14577 "Set the effort property of the current entry.
14578 With numerical prefix arg, use the nth allowed value, 0 stands for the
14579 10th allowed value.
14581 When INCREMENT is non-nil, set the property to the next allowed value."
14582 (interactive "P")
14583 (if (equal value 0) (setq value 10))
14584 (let* ((completion-ignore-case t)
14585 (prop org-effort-property)
14586 (cur (org-entry-get nil prop))
14587 (allowed (org-property-get-allowed-values nil prop 'table))
14588 (existing (mapcar 'list (org-property-values prop)))
14590 (val (cond
14591 ((stringp value) value)
14592 ((and allowed (integerp value))
14593 (or (car (nth (1- value) allowed))
14594 (car (org-last allowed))))
14595 ((and allowed increment)
14596 (or (caadr (member (list cur) allowed))
14597 (error "Allowed effort values are not set")))
14598 (allowed
14599 (message "Select 1-9,0, [RET%s]: %s"
14600 (if cur (concat "=" cur) "")
14601 (mapconcat 'car allowed " "))
14602 (setq rpl (read-char-exclusive))
14603 (if (equal rpl ?\r)
14605 (setq rpl (- rpl ?0))
14606 (if (equal rpl 0) (setq rpl 10))
14607 (if (and (> rpl 0) (<= rpl (length allowed)))
14608 (car (nth (1- rpl) allowed))
14609 (org-completing-read "Effort: " allowed nil))))
14611 (let (org-completion-use-ido org-completion-use-iswitchb)
14612 (org-completing-read
14613 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14614 (concat "[" cur "]") "")
14615 ": ")
14616 existing nil nil "" nil cur))))))
14617 (unless (equal (org-entry-get nil prop) val)
14618 (org-entry-put nil prop val))
14619 (save-excursion
14620 (org-back-to-heading t)
14621 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14622 (message "%s is now %s" prop val)))
14624 (defun org-at-property-p ()
14625 "Is cursor inside a property drawer?"
14626 (save-excursion
14627 (beginning-of-line 1)
14628 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14629 (save-match-data ;; Used by calling procedures
14630 (let ((p (point))
14631 (range (unless (org-before-first-heading-p)
14632 (org-get-property-block))))
14633 (and range (<= (car range) p) (< p (cdr range))))))))
14635 (defun org-get-property-block (&optional beg end force)
14636 "Return the (beg . end) range of the body of the property drawer.
14637 BEG and END are the beginning and end of the current subtree, or of
14638 the part before the first headline. If they are not given, they will
14639 be found. If the drawer does not exist and FORCE is non-nil, create
14640 the drawer."
14641 (catch 'exit
14642 (save-excursion
14643 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14644 (progn (org-back-to-heading t) (point))))
14645 (end (or end (and (not (outline-next-heading)) (point-max))
14646 (point))))
14647 (goto-char beg)
14648 (if (re-search-forward org-property-start-re end t)
14649 (setq beg (1+ (match-end 0)))
14650 (if force
14651 (save-excursion
14652 (org-insert-property-drawer)
14653 (setq end (progn (outline-next-heading) (point))))
14654 (throw 'exit nil))
14655 (goto-char beg)
14656 (if (re-search-forward org-property-start-re end t)
14657 (setq beg (1+ (match-end 0)))))
14658 (if (re-search-forward org-property-end-re end t)
14659 (setq end (match-beginning 0))
14660 (or force (throw 'exit nil))
14661 (goto-char beg)
14662 (setq end beg)
14663 (org-indent-line)
14664 (insert ":END:\n"))
14665 (cons beg end)))))
14667 (defun org-entry-properties (&optional pom which specific)
14668 "Get all properties of the entry at point-or-marker POM.
14669 This includes the TODO keyword, the tags, time strings for deadline,
14670 scheduled, and clocking, and any additional properties defined in the
14671 entry. The return value is an alist, keys may occur multiple times
14672 if the property key was used several times.
14673 POM may also be nil, in which case the current entry is used.
14674 If WHICH is nil or `all', get all properties. If WHICH is
14675 `special' or `standard', only get that subclass. If WHICH
14676 is a string only get exactly this property. SPECIFIC can be a string, the
14677 specific property we are interested in. Specifying it can speed
14678 things up because then unnecessary parsing is avoided."
14679 (setq which (or which 'all))
14680 (org-with-point-at pom
14681 (let ((clockstr (substring org-clock-string 0 -1))
14682 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14683 (case-fold-search nil)
14684 beg end range props sum-props key key1 value string clocksum clocksumt)
14685 (save-excursion
14686 (when (condition-case nil
14687 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14688 (error nil))
14689 (setq beg (point))
14690 (setq sum-props (get-text-property (point) 'org-summaries))
14691 (setq clocksum (get-text-property (point) :org-clock-minutes)
14692 clocksumt (get-text-property (point) :org-clock-minutes-today))
14693 (outline-next-heading)
14694 (setq end (point))
14695 (when (memq which '(all special))
14696 ;; Get the special properties, like TODO and tags
14697 (goto-char beg)
14698 (when (and (or (not specific) (string= specific "TODO"))
14699 (looking-at org-todo-line-regexp) (match-end 2))
14700 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14701 (when (and (or (not specific) (string= specific "PRIORITY"))
14702 (looking-at org-priority-regexp))
14703 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14704 (when (or (not specific) (string= specific "FILE"))
14705 (push (cons "FILE" buffer-file-name) props))
14706 (when (and (or (not specific) (string= specific "TAGS"))
14707 (setq value (org-get-tags-string))
14708 (string-match "\\S-" value))
14709 (push (cons "TAGS" value) props))
14710 (when (and (or (not specific) (string= specific "ALLTAGS"))
14711 (setq value (org-get-tags-at)))
14712 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14713 ":"))
14714 props))
14715 (when (or (not specific) (string= specific "BLOCKED"))
14716 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14717 (when (or (not specific)
14718 (member specific
14719 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14720 "TIMESTAMP" "TIMESTAMP_IA")))
14721 (catch 'match
14722 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14723 (setq key (if (match-end 1)
14724 (substring (org-match-string-no-properties 1)
14725 0 -1))
14726 string (if (equal key clockstr)
14727 (org-trim
14728 (buffer-substring-no-properties
14729 (match-beginning 3) (goto-char
14730 (point-at-eol))))
14731 (substring (org-match-string-no-properties 3)
14732 1 -1)))
14733 ;; Get the correct property name from the key. This is
14734 ;; necessary if the user has configured time keywords.
14735 (setq key1 (concat key ":"))
14736 (cond
14737 ((not key)
14738 (setq key
14739 (if (= (char-after (match-beginning 3)) ?\[)
14740 "TIMESTAMP_IA" "TIMESTAMP")))
14741 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14742 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14743 ((equal key1 org-closed-string) (setq key "CLOSED"))
14744 ((equal key1 org-clock-string) (setq key "CLOCK")))
14745 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14746 (progn
14747 (push (cons key string) props)
14748 ;; no need to search further if match is found
14749 (throw 'match t))
14750 (when (or (equal key "CLOCK") (not (assoc key props)))
14751 (push (cons key string) props)))))))
14753 (when (memq which '(all standard))
14754 ;; Get the standard properties, like :PROP: ...
14755 (setq range (org-get-property-block beg end))
14756 (when range
14757 (goto-char (car range))
14758 (while (re-search-forward
14759 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14760 (cdr range) t)
14761 (setq key (org-match-string-no-properties 1)
14762 value (org-trim (or (org-match-string-no-properties 2) "")))
14763 (unless (member key excluded)
14764 (push (cons key (or value "")) props)))))
14765 (if clocksum
14766 (push (cons "CLOCKSUM"
14767 (org-columns-number-to-string (/ (float clocksum) 60.)
14768 'add_times))
14769 props))
14770 (if clocksumt
14771 (push (cons "CLOCKSUM_T"
14772 (org-columns-number-to-string (/ (float clocksumt) 60.)
14773 'add_times))
14774 props))
14775 (unless (assoc "CATEGORY" props)
14776 (push (cons "CATEGORY" (org-get-category)) props))
14777 (append sum-props (nreverse props)))))))
14779 (defun org-entry-get (pom property &optional inherit literal-nil)
14780 "Get value of PROPERTY for entry or content at point-or-marker POM.
14781 If INHERIT is non-nil and the entry does not have the property,
14782 then also check higher levels of the hierarchy.
14783 If INHERIT is the symbol `selective', use inheritance only if the setting
14784 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14785 If the property is present but empty, the return value is the empty string.
14786 If the property is not present at all, nil is returned.
14788 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14789 do not interpret it as the list atom nil. This is used for inheritance
14790 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14791 (org-with-point-at pom
14792 (if (and inherit (if (eq inherit 'selective)
14793 (org-property-inherit-p property)
14795 (org-entry-get-with-inheritance property literal-nil)
14796 (if (member property org-special-properties)
14797 ;; We need a special property. Use `org-entry-properties' to
14798 ;; retrieve it, but specify the wanted property
14799 (cdr (assoc property (org-entry-properties nil 'special property)))
14800 (let ((range (org-get-property-block)))
14801 (when (and range (not (eq (car range) (cdr range))))
14802 (let* ((props (list (or (assoc property org-file-properties)
14803 (assoc property org-global-properties)
14804 (assoc property org-global-properties-fixed))))
14805 (ap (lambda (key)
14806 (when (re-search-forward
14807 (org-re-property key) (cdr range) t)
14808 (setq props
14809 (org-update-property-plist
14811 (if (match-end 1)
14812 (org-match-string-no-properties 1) "")
14813 props)))))
14814 val)
14815 (goto-char (car range))
14816 (funcall ap property)
14817 (goto-char (car range))
14818 (while (funcall ap (concat property "+")))
14819 (setq val (cdr (assoc property props)))
14820 (when val (if literal-nil val (org-not-nil val))))))))))
14822 (defun org-property-or-variable-value (var &optional inherit)
14823 "Check if there is a property fixing the value of VAR.
14824 If yes, return this value. If not, return the current value of the variable."
14825 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14826 (if (and prop (stringp prop) (string-match "\\S-" prop))
14827 (read prop)
14828 (symbol-value var))))
14830 (defun org-entry-delete (pom property)
14831 "Delete the property PROPERTY from entry at point-or-marker POM."
14832 (org-with-point-at pom
14833 (if (member property org-special-properties)
14834 nil ; cannot delete these properties.
14835 (let ((range (org-get-property-block)))
14836 (if (and range
14837 (goto-char (car range))
14838 (re-search-forward
14839 (org-re-property property)
14840 (cdr range) t))
14841 (progn
14842 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14844 nil)))))
14846 ;; Multi-values properties are properties that contain multiple values
14847 ;; These values are assumed to be single words, separated by whitespace.
14848 (defun org-entry-add-to-multivalued-property (pom property value)
14849 "Add VALUE to 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 (unless (member value values)
14854 (setq values (cons value values))
14855 (org-entry-put pom property
14856 (mapconcat 'identity values " ")))))
14858 (defun org-entry-remove-from-multivalued-property (pom property value)
14859 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14860 (let* ((old (org-entry-get pom property))
14861 (values (and old (org-split-string old "[ \t]"))))
14862 (setq value (org-entry-protect-space value))
14863 (when (member value values)
14864 (setq values (delete value values))
14865 (org-entry-put pom property
14866 (mapconcat 'identity values " ")))))
14868 (defun org-entry-member-in-multivalued-property (pom property value)
14869 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14870 (let* ((old (org-entry-get pom property))
14871 (values (and old (org-split-string old "[ \t]"))))
14872 (setq value (org-entry-protect-space value))
14873 (member value values)))
14875 (defun org-entry-get-multivalued-property (pom property)
14876 "Return a list of values in a multivalued property."
14877 (let* ((value (org-entry-get pom property))
14878 (values (and value (org-split-string value "[ \t]"))))
14879 (mapcar 'org-entry-restore-space values)))
14881 (defun org-entry-put-multivalued-property (pom property &rest values)
14882 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14883 VALUES should be a list of strings. Spaces will be protected."
14884 (org-entry-put pom property
14885 (mapconcat 'org-entry-protect-space values " "))
14886 (let* ((value (org-entry-get pom property))
14887 (values (and value (org-split-string value "[ \t]"))))
14888 (mapcar 'org-entry-restore-space values)))
14890 (defun org-entry-protect-space (s)
14891 "Protect spaces and newline in string S."
14892 (while (string-match " " s)
14893 (setq s (replace-match "%20" t t s)))
14894 (while (string-match "\n" s)
14895 (setq s (replace-match "%0A" t t s)))
14898 (defun org-entry-restore-space (s)
14899 "Restore spaces and newline in string S."
14900 (while (string-match "%20" s)
14901 (setq s (replace-match " " t t s)))
14902 (while (string-match "%0A" s)
14903 (setq s (replace-match "\n" t t s)))
14906 (defvar org-entry-property-inherited-from (make-marker)
14907 "Marker pointing to the entry from where a property was inherited.
14908 Each call to `org-entry-get-with-inheritance' will set this marker to the
14909 location of the entry where the inheritance search matched. If there was
14910 no match, the marker will point nowhere.
14911 Note that also `org-entry-get' calls this function, if the INHERIT flag
14912 is set.")
14914 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14915 "Get PROPERTY of entry or content at point, search higher levels if needed.
14916 The search will stop at the first ancestor which has the property defined.
14917 If the value found is \"nil\", return nil to show that the property
14918 should be considered as undefined (this is the meaning of nil here).
14919 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14920 (move-marker org-entry-property-inherited-from nil)
14921 (let (tmp)
14922 (save-excursion
14923 (save-restriction
14924 (widen)
14925 (catch 'ex
14926 (while t
14927 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14928 (or (ignore-errors (org-back-to-heading t))
14929 (goto-char (point-min)))
14930 (move-marker org-entry-property-inherited-from (point))
14931 (throw 'ex tmp))
14932 (or (ignore-errors (org-up-heading-safe))
14933 (throw 'ex nil))))))
14934 (setq tmp (or tmp
14935 (cdr (assoc property org-file-properties))
14936 (cdr (assoc property org-global-properties))
14937 (cdr (assoc property org-global-properties-fixed))))
14938 (if literal-nil tmp (org-not-nil tmp))))
14940 (defvar org-property-changed-functions nil
14941 "Hook called when the value of a property has changed.
14942 Each hook function should accept two arguments, the name of the property
14943 and the new value.")
14945 (defun org-entry-put (pom property value)
14946 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14947 (org-with-point-at pom
14948 (org-back-to-heading t)
14949 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14950 range)
14951 (cond
14952 ((equal property "TODO")
14953 (when (and (stringp value) (string-match "\\S-" value)
14954 (not (member value org-todo-keywords-1)))
14955 (error "\"%s\" is not a valid TODO state" value))
14956 (if (or (not value)
14957 (not (string-match "\\S-" value)))
14958 (setq value 'none))
14959 (org-todo value)
14960 (org-set-tags nil 'align))
14961 ((equal property "PRIORITY")
14962 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14963 (string-to-char value) ?\ ))
14964 (org-set-tags nil 'align))
14965 ((equal property "CLOCKSUM")
14966 (if (not (re-search-forward
14967 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14968 (error "Cannot find a clock log")
14969 (goto-char (- (match-end 1) 2))
14970 (cond
14971 ((eq value 'earlier) (org-timestamp-down))
14972 ((eq value 'later) (org-timestamp-up)))
14973 (org-clock-sum-current-item)))
14974 ((equal property "SCHEDULED")
14975 (if (re-search-forward org-scheduled-time-regexp end t)
14976 (cond
14977 ((eq value 'earlier) (org-timestamp-change -1 'day))
14978 ((eq value 'later) (org-timestamp-change 1 'day))
14979 (t (call-interactively 'org-schedule)))
14980 (call-interactively 'org-schedule)))
14981 ((equal property "DEADLINE")
14982 (if (re-search-forward org-deadline-time-regexp end t)
14983 (cond
14984 ((eq value 'earlier) (org-timestamp-change -1 'day))
14985 ((eq value 'later) (org-timestamp-change 1 'day))
14986 (t (call-interactively 'org-deadline)))
14987 (call-interactively 'org-deadline)))
14988 ((member property org-special-properties)
14989 (error "The %s property can not yet be set with `org-entry-put'"
14990 property))
14991 (t ; a non-special property
14992 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14993 (setq range (org-get-property-block beg end 'force))
14994 (goto-char (car range))
14995 (if (re-search-forward
14996 (org-re-property-keyword property) (cdr range) t)
14997 (progn
14998 (delete-region (match-beginning 0) (match-end 0))
14999 (goto-char (match-beginning 0)))
15000 (goto-char (cdr range))
15001 (insert "\n")
15002 (backward-char 1)
15003 (org-indent-line))
15004 (insert ":" property ":")
15005 (and value (insert " " value))
15006 (org-indent-line)))))
15007 (run-hook-with-args 'org-property-changed-functions property value)))
15009 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15010 "Get all property keys in the current buffer.
15011 With INCLUDE-SPECIALS, also list the special properties that reflect things
15012 like tags and TODO state.
15013 With INCLUDE-DEFAULTS, also include properties that has special meaning
15014 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15015 and others.
15016 With INCLUDE-COLUMNS, also include property names given in COLUMN
15017 formats in the current buffer."
15018 (let (rtn range cfmt s p)
15019 (save-excursion
15020 (save-restriction
15021 (widen)
15022 (goto-char (point-min))
15023 (while (re-search-forward org-property-start-re nil t)
15024 (setq range (org-get-property-block))
15025 (goto-char (car range))
15026 (while (re-search-forward
15027 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15028 (cdr range) t)
15029 (add-to-list 'rtn (org-match-string-no-properties 1)))
15030 (outline-next-heading))))
15032 (when include-specials
15033 (setq rtn (append org-special-properties rtn)))
15035 (when include-defaults
15036 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15037 (add-to-list 'rtn org-effort-property))
15039 (when include-columns
15040 (save-excursion
15041 (save-restriction
15042 (widen)
15043 (goto-char (point-min))
15044 (while (re-search-forward
15045 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15046 nil t)
15047 (setq cfmt (match-string 2) s 0)
15048 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15049 cfmt s)
15050 (setq s (match-end 0)
15051 p (match-string 1 cfmt))
15052 (unless (or (equal p "ITEM")
15053 (member p org-special-properties))
15054 (add-to-list 'rtn (match-string 1 cfmt))))))))
15056 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15058 (defun org-property-values (key)
15059 "Return a list of all values of property KEY in the current buffer."
15060 (save-excursion
15061 (save-restriction
15062 (widen)
15063 (goto-char (point-min))
15064 (let ((re (org-re-property key))
15065 values)
15066 (while (re-search-forward re nil t)
15067 (add-to-list 'values (org-trim (match-string 1))))
15068 (delete "" values)))))
15070 (defun org-insert-property-drawer ()
15071 "Insert a property drawer into the current entry."
15072 (org-back-to-heading t)
15073 (looking-at org-outline-regexp)
15074 (let ((indent (if org-adapt-indentation
15075 (- (match-end 0) (match-beginning 0))
15077 (beg (point))
15078 (re (concat "^[ \t]*" org-keyword-time-regexp))
15079 end hiddenp)
15080 (outline-next-heading)
15081 (setq end (point))
15082 (goto-char beg)
15083 (while (re-search-forward re end t))
15084 (setq hiddenp (outline-invisible-p))
15085 (end-of-line 1)
15086 (and (equal (char-after) ?\n) (forward-char 1))
15087 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15088 (if (member (match-string 1) '("CLOCK:" ":END:"))
15089 ;; just skip this line
15090 (beginning-of-line 2)
15091 ;; Drawer start, find the end
15092 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15093 (beginning-of-line 1)))
15094 (org-skip-over-state-notes)
15095 (skip-chars-backward " \t\n\r")
15096 (if (eq (char-before) ?*) (forward-char 1))
15097 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15098 (beginning-of-line 0)
15099 (org-indent-to-column indent)
15100 (beginning-of-line 2)
15101 (org-indent-to-column indent)
15102 (beginning-of-line 0)
15103 (if hiddenp
15104 (save-excursion
15105 (org-back-to-heading t)
15106 (hide-entry))
15107 (org-flag-drawer t))))
15109 (defun org-insert-drawer (&optional arg drawer)
15110 "Insert a drawer at point.
15112 Optional argument DRAWER, when non-nil, is a string representing
15113 drawer's name. Otherwise, the user is prompted for a name.
15115 If a region is active, insert the drawer around that region
15116 instead.
15118 Point is left between drawer's boundaries."
15119 (interactive "P")
15120 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15121 "LOGBOOK"))
15122 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15123 ;; internally by Org. They are meant to be inserted
15124 ;; automatically.
15125 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15126 ;; Remove system drawers from list. Note: For some reason,
15127 ;; `org-completing-read' ignores the predicate while
15128 ;; `completing-read' handles it fine.
15129 (drawer (if arg "PROPERTIES"
15130 (or drawer
15131 (completing-read
15132 "Drawer: " org-drawers
15133 (lambda (d) (not (member d system-drawers))))))))
15134 (cond
15135 ;; With C-u, fall back on `org-insert-property-drawer'
15136 (arg (org-insert-property-drawer))
15137 ;; With an active region, insert a drawer at point.
15138 ((not (org-region-active-p))
15139 (progn
15140 (unless (bolp) (insert "\n"))
15141 (insert (format ":%s:\n\n:END:\n" drawer))
15142 (forward-line -2)))
15143 ;; Otherwise, insert the drawer at point
15145 (let ((rbeg (region-beginning))
15146 (rend (copy-marker (region-end))))
15147 (unwind-protect
15148 (progn
15149 (goto-char rbeg)
15150 (beginning-of-line)
15151 (when (save-excursion
15152 (re-search-forward org-outline-regexp-bol rend t))
15153 (error "Drawers cannot contain headlines"))
15154 ;; Position point at the beginning of the first
15155 ;; non-blank line in region. Insert drawer's opening
15156 ;; there, then indent it.
15157 (org-skip-whitespace)
15158 (beginning-of-line)
15159 (insert ":" drawer ":\n")
15160 (forward-line -1)
15161 (indent-for-tab-command)
15162 ;; Move point to the beginning of the first blank line
15163 ;; after the last non-blank line in region. Insert
15164 ;; drawer's closing, then indent it.
15165 (goto-char rend)
15166 (skip-chars-backward " \r\t\n")
15167 (insert "\n:END:")
15168 (deactivate-mark t)
15169 (indent-for-tab-command)
15170 (unless (eolp) (insert "\n")))
15171 ;; Clear marker, whatever the outcome of insertion is.
15172 (set-marker rend nil)))))))
15174 (defvar org-property-set-functions-alist nil
15175 "Property set function alist.
15176 Each entry should have the following format:
15178 (PROPERTY . READ-FUNCTION)
15180 The read function will be called with the same argument as
15181 `org-completing-read'.")
15183 (defun org-set-property-function (property)
15184 "Get the function that should be used to set PROPERTY.
15185 This is computed according to `org-property-set-functions-alist'."
15186 (or (cdr (assoc property org-property-set-functions-alist))
15187 'org-completing-read))
15189 (defun org-read-property-value (property)
15190 "Read PROPERTY value from user."
15191 (let* ((completion-ignore-case t)
15192 (allowed (org-property-get-allowed-values nil property 'table))
15193 (cur (org-entry-get nil property))
15194 (prompt (concat property " value"
15195 (if (and cur (string-match "\\S-" cur))
15196 (concat " [" cur "]") "") ": "))
15197 (set-function (org-set-property-function property))
15198 (val (if allowed
15199 (funcall set-function prompt allowed nil
15200 (not (get-text-property 0 'org-unrestricted
15201 (caar allowed))))
15202 (let (org-completion-use-ido org-completion-use-iswitchb)
15203 (funcall set-function prompt
15204 (mapcar 'list (org-property-values property))
15205 nil nil "" nil cur)))))
15206 (if (equal val "")
15208 val)))
15210 (defvar org-last-set-property nil)
15211 (defvar org-last-set-property-value nil)
15212 (defun org-read-property-name ()
15213 "Read a property name."
15214 (let* ((completion-ignore-case t)
15215 (keys (org-buffer-property-keys nil t t))
15216 (default-prop (or (save-excursion
15217 (save-match-data
15218 (beginning-of-line)
15219 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15220 (null (string= (match-string 1) "END"))
15221 (match-string 1))))
15222 org-last-set-property))
15223 (property (org-icompleting-read
15224 (concat "Property"
15225 (if default-prop (concat " [" default-prop "]") "")
15226 ": ")
15227 (mapcar 'list keys)
15228 nil nil nil nil
15229 default-prop)))
15230 (if (member property keys)
15231 property
15232 (or (cdr (assoc (downcase property)
15233 (mapcar (lambda (x) (cons (downcase x) x))
15234 keys)))
15235 property))))
15237 (defun org-set-property-and-value (use-last)
15238 "Allow to set [PROPERTY]: [value] direction from prompt.
15239 When use-default, don't even ask, just use the last
15240 \"[PROPERTY]: [value]\" string from the history."
15241 (interactive "P")
15242 (let* ((completion-ignore-case t)
15243 (pv (or (and use-last org-last-set-property-value)
15244 (org-completing-read
15245 "Enter a \"[Property]: [value]\" pair: "
15246 nil nil nil nil nil
15247 org-last-set-property-value)))
15248 prop val)
15249 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15250 (setq prop (match-string 1 pv)
15251 val (match-string 2 pv))
15252 (org-set-property prop val))))
15254 (defun org-set-property (property value)
15255 "In the current entry, set PROPERTY to VALUE.
15256 When called interactively, this will prompt for a property name, offering
15257 completion on existing and default properties. And then it will prompt
15258 for a value, offering completion either on allowed values (via an inherited
15259 xxx_ALL property) or on existing values in other instances of this property
15260 in the current file."
15261 (interactive (list nil nil))
15262 (let* ((property (or property (org-read-property-name)))
15263 (value (or value (org-read-property-value property)))
15264 (fn (cdr (assoc property org-properties-postprocess-alist))))
15265 (setq org-last-set-property property)
15266 (setq org-last-set-property-value (concat property ": " value))
15267 ;; Possibly postprocess the inserted value:
15268 (when fn (setq value (funcall fn value)))
15269 (unless (equal (org-entry-get nil property) value)
15270 (org-entry-put nil property value))))
15272 (defun org-delete-property (property)
15273 "In the current entry, delete PROPERTY."
15274 (interactive
15275 (let* ((completion-ignore-case t)
15276 (prop (org-icompleting-read "Property: "
15277 (org-entry-properties nil 'standard))))
15278 (list prop)))
15279 (message "Property %s %s" property
15280 (if (org-entry-delete nil property)
15281 "deleted"
15282 "was not present in the entry")))
15284 (defun org-delete-property-globally (property)
15285 "Remove PROPERTY globally, from all entries."
15286 (interactive
15287 (let* ((completion-ignore-case t)
15288 (prop (org-icompleting-read
15289 "Globally remove property: "
15290 (mapcar 'list (org-buffer-property-keys)))))
15291 (list prop)))
15292 (save-excursion
15293 (save-restriction
15294 (widen)
15295 (goto-char (point-min))
15296 (let ((cnt 0))
15297 (while (re-search-forward
15298 (org-re-property property)
15299 nil t)
15300 (setq cnt (1+ cnt))
15301 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15302 (message "Property \"%s\" removed from %d entries" property cnt)))))
15304 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15306 (defun org-compute-property-at-point ()
15307 "Compute the property at point.
15308 This looks for an enclosing column format, extracts the operator and
15309 then applies it to the property in the column format's scope."
15310 (interactive)
15311 (unless (org-at-property-p)
15312 (error "Not at a property"))
15313 (let ((prop (org-match-string-no-properties 2)))
15314 (org-columns-get-format-and-top-level)
15315 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15316 (error "No operator defined for property %s" prop))
15317 (org-columns-compute prop)))
15319 (defvar org-property-allowed-value-functions nil
15320 "Hook for functions supplying allowed values for a specific property.
15321 The functions must take a single argument, the name of the property, and
15322 return a flat list of allowed values. If \":ETC\" is one of
15323 the values, this means that these values are intended as defaults for
15324 completion, but that other values should be allowed too.
15325 The functions must return nil if they are not responsible for this
15326 property.")
15328 (defun org-property-get-allowed-values (pom property &optional table)
15329 "Get allowed values for the property PROPERTY.
15330 When TABLE is non-nil, return an alist that can directly be used for
15331 completion."
15332 (let (vals)
15333 (cond
15334 ((equal property "TODO")
15335 (setq vals (org-with-point-at pom
15336 (append org-todo-keywords-1 '("")))))
15337 ((equal property "PRIORITY")
15338 (let ((n org-lowest-priority))
15339 (while (>= n org-highest-priority)
15340 (push (char-to-string n) vals)
15341 (setq n (1- n)))))
15342 ((member property org-special-properties))
15343 ((setq vals (run-hook-with-args-until-success
15344 'org-property-allowed-value-functions property)))
15346 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15347 (when (and vals (string-match "\\S-" vals))
15348 (setq vals (car (read-from-string (concat "(" vals ")"))))
15349 (setq vals (mapcar (lambda (x)
15350 (cond ((stringp x) x)
15351 ((numberp x) (number-to-string x))
15352 ((symbolp x) (symbol-name x))
15353 (t "???")))
15354 vals)))))
15355 (when (member ":ETC" vals)
15356 (setq vals (remove ":ETC" vals))
15357 (org-add-props (car vals) '(org-unrestricted t)))
15358 (if table (mapcar 'list vals) vals)))
15360 (defun org-property-previous-allowed-value (&optional previous)
15361 "Switch to the next allowed value for this property."
15362 (interactive)
15363 (org-property-next-allowed-value t))
15365 (defun org-property-next-allowed-value (&optional previous)
15366 "Switch to the next allowed value for this property."
15367 (interactive)
15368 (unless (org-at-property-p)
15369 (error "Not at a property"))
15370 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15371 (key (match-string 2))
15372 (value (match-string 3))
15373 (allowed (or (org-property-get-allowed-values (point) key)
15374 (and (member value '("[ ]" "[-]" "[X]"))
15375 '("[ ]" "[X]"))))
15376 nval)
15377 (unless allowed
15378 (error "Allowed values for this property have not been defined"))
15379 (if previous (setq allowed (reverse allowed)))
15380 (if (member value allowed)
15381 (setq nval (car (cdr (member value allowed)))))
15382 (setq nval (or nval (car allowed)))
15383 (if (equal nval value)
15384 (error "Only one allowed value for this property"))
15385 (org-at-property-p)
15386 (replace-match (concat " :" key ": " nval) t t)
15387 (org-indent-line)
15388 (beginning-of-line 1)
15389 (skip-chars-forward " \t")
15390 (when (equal prop org-effort-property)
15391 (save-excursion
15392 (org-back-to-heading t)
15393 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15394 (run-hook-with-args 'org-property-changed-functions key nval)))
15396 (defun org-find-olp (path &optional this-buffer)
15397 "Return a marker pointing to the entry at outline path OLP.
15398 If anything goes wrong, throw an error.
15399 You can wrap this call to catch the error like this:
15401 (condition-case msg
15402 (org-mobile-locate-entry (match-string 4))
15403 (error (nth 1 msg)))
15405 The return value will then be either a string with the error message,
15406 or a marker if everything is OK.
15408 If THIS-BUFFER is set, the outline path does not contain a file,
15409 only headings."
15410 (let* ((file (if this-buffer buffer-file-name (pop path)))
15411 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15412 (level 1)
15413 (lmin 1)
15414 (lmax 1)
15415 limit re end found pos heading cnt flevel)
15416 (unless buffer (error "File not found :%s" file))
15417 (with-current-buffer buffer
15418 (save-excursion
15419 (save-restriction
15420 (widen)
15421 (setq limit (point-max))
15422 (goto-char (point-min))
15423 (while (setq heading (pop path))
15424 (setq re (format org-complex-heading-regexp-format
15425 (regexp-quote heading)))
15426 (setq cnt 0 pos (point))
15427 (while (re-search-forward re end t)
15428 (setq level (- (match-end 1) (match-beginning 1)))
15429 (if (and (>= level lmin) (<= level lmax))
15430 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15431 (when (= cnt 0) (error "Heading not found on level %d: %s"
15432 lmax heading))
15433 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15434 lmax heading))
15435 (goto-char found)
15436 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15437 (setq end (save-excursion (org-end-of-subtree t t))))
15438 (when (org-at-heading-p)
15439 (point-marker)))))))
15441 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15442 "Find node HEADING in BUFFER.
15443 Return a marker to the heading if it was found, or nil if not.
15444 If POS-ONLY is set, return just the position instead of a marker.
15446 The heading text must match exact, but it may have a TODO keyword,
15447 a priority cookie and tags in the standard locations."
15448 (with-current-buffer (or buffer (current-buffer))
15449 (save-excursion
15450 (save-restriction
15451 (widen)
15452 (goto-char (point-min))
15453 (let (case-fold-search)
15454 (if (re-search-forward
15455 (format org-complex-heading-regexp-format
15456 (regexp-quote heading)) nil t)
15457 (if pos-only
15458 (match-beginning 0)
15459 (move-marker (make-marker) (match-beginning 0)))))))))
15461 (defun org-find-exact-heading-in-directory (heading &optional dir)
15462 "Find Org node headline HEADING in all .org files in directory DIR.
15463 When the target headline is found, return a marker to this location."
15464 (let ((files (directory-files (or dir default-directory)
15465 nil "\\`[^.#].*\\.org\\'"))
15466 file visiting m buffer)
15467 (catch 'found
15468 (while (setq file (pop files))
15469 (message "trying %s" file)
15470 (setq visiting (org-find-base-buffer-visiting file))
15471 (setq buffer (or visiting (find-file-noselect file)))
15472 (setq m (org-find-exact-headline-in-buffer
15473 heading buffer))
15474 (when (and (not m) (not visiting)) (kill-buffer buffer))
15475 (and m (throw 'found m))))))
15477 (defun org-find-entry-with-id (ident)
15478 "Locate the entry that contains the ID property with exact value IDENT.
15479 IDENT can be a string, a symbol or a number, this function will search for
15480 the string representation of it.
15481 Return the position where this entry starts, or nil if there is no such entry."
15482 (interactive "sID: ")
15483 (let ((id (cond
15484 ((stringp ident) ident)
15485 ((symbol-name ident) (symbol-name ident))
15486 ((numberp ident) (number-to-string ident))
15487 (t (error "IDENT %s must be a string, symbol or number" ident))))
15488 (case-fold-search nil))
15489 (save-excursion
15490 (save-restriction
15491 (widen)
15492 (goto-char (point-min))
15493 (when (re-search-forward
15494 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15495 nil t)
15496 (org-back-to-heading t)
15497 (point))))))
15499 ;;;; Timestamps
15501 (defvar org-last-changed-timestamp nil)
15502 (defvar org-last-inserted-timestamp nil
15503 "The last time stamp inserted with `org-insert-time-stamp'.")
15504 (defvar org-time-was-given) ; dynamically scoped parameter
15505 (defvar org-end-time-was-given) ; dynamically scoped parameter
15506 (defvar org-ts-what) ; dynamically scoped parameter
15508 (defun org-time-stamp (arg &optional inactive)
15509 "Prompt for a date/time and insert a time stamp.
15510 If the user specifies a time like HH:MM or if this command is
15511 called with at least one prefix argument, the time stamp contains
15512 the date and the time. Otherwise, only the date is be included.
15514 All parts of a date not specified by the user is filled in from
15515 the current date/time. So if you just press return without
15516 typing anything, the time stamp will represent the current
15517 date/time.
15519 If there is already a timestamp at the cursor, it will be
15520 modified.
15522 With two universal prefix arguments, insert an active timestamp
15523 with the current time without prompting the user."
15524 (interactive "P")
15525 (let* ((ts nil)
15526 (default-time
15527 ;; Default time is either today, or, when entering a range,
15528 ;; the range start.
15529 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15530 (save-excursion
15531 (re-search-backward
15532 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15533 (- (point) 20) t)))
15534 (apply 'encode-time (org-parse-time-string (match-string 1)))
15535 (current-time)))
15536 (default-input (and ts (org-get-compact-tod ts)))
15537 (repeater (save-excursion
15538 (save-match-data
15539 (beginning-of-line)
15540 (when (re-search-forward
15541 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15542 (save-excursion (progn (end-of-line) (point))) t)
15543 (match-string 0)))))
15544 org-time-was-given org-end-time-was-given time)
15545 (cond
15546 ((and (org-at-timestamp-p t)
15547 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15548 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15549 (insert "--")
15550 (setq time (let ((this-command this-command))
15551 (org-read-date arg 'totime nil nil
15552 default-time default-input inactive)))
15553 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15554 ((org-at-timestamp-p t)
15555 (setq time (let ((this-command this-command))
15556 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15557 (when (org-at-timestamp-p t) ; just to get the match data
15558 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15559 (replace-match "")
15560 (setq org-last-changed-timestamp
15561 (org-insert-time-stamp
15562 time (or org-time-was-given arg)
15563 inactive nil nil (list org-end-time-was-given)))
15564 (when repeater (goto-char (1- (point))) (insert " " repeater)
15565 (setq org-last-changed-timestamp
15566 (concat (substring org-last-inserted-timestamp 0 -1)
15567 " " repeater ">"))))
15568 (message "Timestamp updated"))
15569 ((equal arg '(16))
15570 (org-insert-time-stamp (current-time) t))
15572 (setq time (let ((this-command this-command))
15573 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15574 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15575 nil nil (list org-end-time-was-given))))))
15577 ;; FIXME: can we use this for something else, like computing time differences?
15578 (defun org-get-compact-tod (s)
15579 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15580 (let* ((t1 (match-string 1 s))
15581 (h1 (string-to-number (match-string 2 s)))
15582 (m1 (string-to-number (match-string 3 s)))
15583 (t2 (and (match-end 4) (match-string 5 s)))
15584 (h2 (and t2 (string-to-number (match-string 6 s))))
15585 (m2 (and t2 (string-to-number (match-string 7 s))))
15586 dh dm)
15587 (if (not t2)
15589 (setq dh (- h2 h1) dm (- m2 m1))
15590 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15591 (concat t1 "+" (number-to-string dh)
15592 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15594 (defun org-time-stamp-inactive (&optional arg)
15595 "Insert an inactive time stamp.
15596 An inactive time stamp is enclosed in square brackets instead of angle
15597 brackets. It is inactive in the sense that it does not trigger agenda entries,
15598 does not link to the calendar and cannot be changed with the S-cursor keys.
15599 So these are more for recording a certain time/date."
15600 (interactive "P")
15601 (org-time-stamp arg 'inactive))
15603 (defvar org-date-ovl (make-overlay 1 1))
15604 (overlay-put org-date-ovl 'face 'org-date-selected)
15605 (org-detach-overlay org-date-ovl)
15607 (defvar org-ans1) ; dynamically scoped parameter
15608 (defvar org-ans2) ; dynamically scoped parameter
15610 (defvar org-plain-time-of-day-regexp) ; defined below
15612 (defvar org-overriding-default-time nil) ; dynamically scoped
15613 (defvar org-read-date-overlay nil)
15614 (defvar org-dcst nil) ; dynamically scoped
15615 (defvar org-read-date-history nil)
15616 (defvar org-read-date-final-answer nil)
15617 (defvar org-read-date-analyze-futurep nil)
15618 (defvar org-read-date-analyze-forced-year nil)
15619 (defvar org-read-date-inactive)
15621 (defvar org-read-date-minibuffer-local-map
15622 (let ((map (make-sparse-keymap)))
15623 (set-keymap-parent map minibuffer-local-map)
15624 (org-defkey map (kbd ".")
15625 (lambda () (interactive)
15626 (org-eval-in-calendar '(calendar-goto-today))))
15627 (org-defkey map [(meta shift left)]
15628 (lambda () (interactive)
15629 (org-eval-in-calendar '(calendar-backward-month 1))))
15630 (org-defkey map [(meta shift right)]
15631 (lambda () (interactive)
15632 (org-eval-in-calendar '(calendar-forward-month 1))))
15633 (org-defkey map [(meta shift up)]
15634 (lambda () (interactive)
15635 (org-eval-in-calendar '(calendar-backward-year 1))))
15636 (org-defkey map [(meta shift down)]
15637 (lambda () (interactive)
15638 (org-eval-in-calendar '(calendar-forward-year 1))))
15639 (org-defkey map [?\e (shift left)]
15640 (lambda () (interactive)
15641 (org-eval-in-calendar '(calendar-backward-month 1))))
15642 (org-defkey map [?\e (shift right)]
15643 (lambda () (interactive)
15644 (org-eval-in-calendar '(calendar-forward-month 1))))
15645 (org-defkey map [?\e (shift up)]
15646 (lambda () (interactive)
15647 (org-eval-in-calendar '(calendar-backward-year 1))))
15648 (org-defkey map [?\e (shift down)]
15649 (lambda () (interactive)
15650 (org-eval-in-calendar '(calendar-forward-year 1))))
15651 (org-defkey map [(shift up)]
15652 (lambda () (interactive)
15653 (org-eval-in-calendar '(calendar-backward-week 1))))
15654 (org-defkey map [(shift down)]
15655 (lambda () (interactive)
15656 (org-eval-in-calendar '(calendar-forward-week 1))))
15657 (org-defkey map [(shift left)]
15658 (lambda () (interactive)
15659 (org-eval-in-calendar '(calendar-backward-day 1))))
15660 (org-defkey map [(shift right)]
15661 (lambda () (interactive)
15662 (org-eval-in-calendar '(calendar-forward-day 1))))
15663 (org-defkey map "!"
15664 (lambda () (interactive)
15665 (org-eval-in-calendar '(diary-view-entries))
15666 (message "")))
15667 (org-defkey map ">"
15668 (lambda () (interactive)
15669 (org-eval-in-calendar '(scroll-calendar-left 1))))
15670 (org-defkey map "<"
15671 (lambda () (interactive)
15672 (org-eval-in-calendar '(scroll-calendar-right 1))))
15673 (org-defkey map "\C-v"
15674 (lambda () (interactive)
15675 (org-eval-in-calendar
15676 '(calendar-scroll-left-three-months 1))))
15677 (org-defkey map "\M-v"
15678 (lambda () (interactive)
15679 (org-eval-in-calendar
15680 '(calendar-scroll-right-three-months 1))))
15681 map)
15682 "Keymap for minibuffer commands when using `org-read-date'.")
15684 (defun org-read-date (&optional org-with-time to-time from-string prompt
15685 default-time default-input inactive)
15686 "Read a date, possibly a time, and make things smooth for the user.
15687 The prompt will suggest to enter an ISO date, but you can also enter anything
15688 which will at least partially be understood by `parse-time-string'.
15689 Unrecognized parts of the date will default to the current day, month, year,
15690 hour and minute. If this command is called to replace a timestamp at point,
15691 or to enter the second timestamp of a range, the default time is taken
15692 from the existing stamp. Furthermore, the command prefers the future,
15693 so if you are giving a date where the year is not given, and the day-month
15694 combination is already past in the current year, it will assume you
15695 mean next year. For details, see the manual. A few examples:
15697 3-2-5 --> 2003-02-05
15698 feb 15 --> currentyear-02-15
15699 2/15 --> currentyear-02-15
15700 sep 12 9 --> 2009-09-12
15701 12:45 --> today 12:45
15702 22 sept 0:34 --> currentyear-09-22 0:34
15703 12 --> currentyear-currentmonth-12
15704 Fri --> nearest Friday (today or later)
15705 etc.
15707 Furthermore you can specify a relative date by giving, as the *first* thing
15708 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15709 change in days weeks, months, years.
15710 With a single plus or minus, the date is relative to today. With a double
15711 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15712 +4d --> four days from today
15713 +4 --> same as above
15714 +2w --> two weeks from today
15715 ++5 --> five days from default date
15717 The function understands only English month and weekday abbreviations.
15719 While prompting, a calendar is popped up - you can also select the
15720 date with the mouse (button 1). The calendar shows a period of three
15721 months. To scroll it to other months, use the keys `>' and `<'.
15722 If you don't like the calendar, turn it off with
15723 \(setq org-read-date-popup-calendar nil)
15725 With optional argument TO-TIME, the date will immediately be converted
15726 to an internal time.
15727 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15728 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15729 still enter a time, and this function will inform the calling routine
15730 about this change. The calling routine may then choose to change the
15731 format used to insert the time stamp into the buffer to include the time.
15732 With optional argument FROM-STRING, read from this string instead from
15733 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15734 the time/date that is used for everything that is not specified by the
15735 user."
15736 (require 'parse-time)
15737 (let* ((org-time-stamp-rounding-minutes
15738 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15739 (org-dcst org-display-custom-times)
15740 (ct (org-current-time))
15741 (org-def (or org-overriding-default-time default-time ct))
15742 (org-defdecode (decode-time org-def))
15743 (dummy (progn
15744 (when (< (nth 2 org-defdecode) org-extend-today-until)
15745 (setcar (nthcdr 2 org-defdecode) -1)
15746 (setcar (nthcdr 1 org-defdecode) 59)
15747 (setq org-def (apply 'encode-time org-defdecode)
15748 org-defdecode (decode-time org-def)))))
15749 (mouse-autoselect-window nil) ; Don't let the mouse jump
15750 (calendar-frame-setup nil)
15751 (calendar-setup nil)
15752 (calendar-move-hook nil)
15753 (calendar-view-diary-initially-flag nil)
15754 (calendar-view-holidays-initially-flag nil)
15755 (timestr (format-time-string
15756 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15757 (prompt (concat (if prompt (concat prompt " ") "")
15758 (format "Date+time [%s]: " timestr)))
15759 ans (org-ans0 "") org-ans1 org-ans2 final)
15761 (cond
15762 (from-string (setq ans from-string))
15763 (org-read-date-popup-calendar
15764 (save-excursion
15765 (save-window-excursion
15766 (calendar)
15767 (org-eval-in-calendar '(setq cursor-type nil) t)
15768 (unwind-protect
15769 (progn
15770 (calendar-forward-day (- (time-to-days org-def)
15771 (calendar-absolute-from-gregorian
15772 (calendar-current-date))))
15773 (org-eval-in-calendar nil t)
15774 (let* ((old-map (current-local-map))
15775 (map (copy-keymap calendar-mode-map))
15776 (minibuffer-local-map
15777 (copy-keymap org-read-date-minibuffer-local-map)))
15778 (org-defkey map (kbd "RET") 'org-calendar-select)
15779 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15780 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15781 (unwind-protect
15782 (progn
15783 (use-local-map map)
15784 (setq org-read-date-inactive inactive)
15785 (add-hook 'post-command-hook 'org-read-date-display)
15786 (setq org-ans0 (read-string prompt default-input
15787 'org-read-date-history nil))
15788 ;; org-ans0: from prompt
15789 ;; org-ans1: from mouse click
15790 ;; org-ans2: from calendar motion
15791 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15792 (remove-hook 'post-command-hook 'org-read-date-display)
15793 (use-local-map old-map)
15794 (when org-read-date-overlay
15795 (delete-overlay org-read-date-overlay)
15796 (setq org-read-date-overlay nil)))))
15797 (bury-buffer "*Calendar*")))))
15799 (t ; Naked prompt only
15800 (unwind-protect
15801 (setq ans (read-string prompt default-input
15802 'org-read-date-history timestr))
15803 (when org-read-date-overlay
15804 (delete-overlay org-read-date-overlay)
15805 (setq org-read-date-overlay nil)))))
15807 (setq final (org-read-date-analyze ans org-def org-defdecode))
15809 (when org-read-date-analyze-forced-year
15810 (message "Year was forced into %s"
15811 (if org-read-date-force-compatible-dates
15812 "compatible range (1970-2037)"
15813 "range representable on this machine"))
15814 (ding))
15816 ;; One round trip to get rid of 34th of August and stuff like that....
15817 (setq final (decode-time (apply 'encode-time final)))
15819 (setq org-read-date-final-answer ans)
15821 (if to-time
15822 (apply 'encode-time final)
15823 (if (and (boundp 'org-time-was-given) org-time-was-given)
15824 (format "%04d-%02d-%02d %02d:%02d"
15825 (nth 5 final) (nth 4 final) (nth 3 final)
15826 (nth 2 final) (nth 1 final))
15827 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15829 (defvar org-def)
15830 (defvar org-defdecode)
15831 (defvar org-with-time)
15832 (defun org-read-date-display ()
15833 "Display the current date prompt interpretation in the minibuffer."
15834 (when org-read-date-display-live
15835 (when org-read-date-overlay
15836 (delete-overlay org-read-date-overlay))
15837 (when (minibufferp (current-buffer))
15838 (save-excursion
15839 (end-of-line 1)
15840 (while (not (equal (buffer-substring
15841 (max (point-min) (- (point) 4)) (point))
15842 " "))
15843 (insert " ")))
15844 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15845 " " (or org-ans1 org-ans2)))
15846 (org-end-time-was-given nil)
15847 (f (org-read-date-analyze ans org-def org-defdecode))
15848 (fmts (if org-dcst
15849 org-time-stamp-custom-formats
15850 org-time-stamp-formats))
15851 (fmt (if (or org-with-time
15852 (and (boundp 'org-time-was-given) org-time-was-given))
15853 (cdr fmts)
15854 (car fmts)))
15855 (txt (format-time-string fmt (apply 'encode-time f)))
15856 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15857 (txt (concat "=> " txt)))
15858 (when (and org-end-time-was-given
15859 (string-match org-plain-time-of-day-regexp txt))
15860 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15861 org-end-time-was-given
15862 (substring txt (match-end 0)))))
15863 (when org-read-date-analyze-futurep
15864 (setq txt (concat txt " (=>F)")))
15865 (setq org-read-date-overlay
15866 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15867 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15869 (defun org-read-date-analyze (ans org-def org-defdecode)
15870 "Analyze the combined answer of the date prompt."
15871 ;; FIXME: cleanup and comment
15872 (let ((nowdecode (decode-time (current-time)))
15873 delta deltan deltaw deltadef year month day
15874 hour minute second wday pm h2 m2 tl wday1
15875 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15876 (setq org-read-date-analyze-futurep nil
15877 org-read-date-analyze-forced-year nil)
15878 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15879 (setq ans "+0"))
15881 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15882 (setq ans (replace-match "" t t ans)
15883 deltan (car delta)
15884 deltaw (nth 1 delta)
15885 deltadef (nth 2 delta)))
15887 ;; Check if there is an iso week date in there. If yes, store the
15888 ;; info and postpone interpreting it until the rest of the parsing
15889 ;; is done.
15890 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15891 (setq iso-year (if (match-end 1)
15892 (org-small-year-to-year
15893 (string-to-number (match-string 1 ans))))
15894 iso-weekday (if (match-end 3)
15895 (string-to-number (match-string 3 ans)))
15896 iso-week (string-to-number (match-string 2 ans)))
15897 (setq ans (replace-match "" t t ans)))
15899 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15900 (when (string-match
15901 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15902 (setq year (if (match-end 2)
15903 (string-to-number (match-string 2 ans))
15904 (progn (setq kill-year t)
15905 (string-to-number (format-time-string "%Y"))))
15906 month (string-to-number (match-string 3 ans))
15907 day (string-to-number (match-string 4 ans)))
15908 (if (< year 100) (setq year (+ 2000 year)))
15909 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15910 t nil ans)))
15912 ;; Help matching dotted european dates
15913 (when (string-match
15914 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15915 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15916 (setq kill-year t)
15917 (string-to-number (format-time-string "%Y")))
15918 day (string-to-number (match-string 1 ans))
15919 month (string-to-number (match-string 2 ans))
15920 ans (replace-match (format "%04d-%02d-%02d" year month day)
15921 t nil ans)))
15923 ;; Help matching american dates, like 5/30 or 5/30/7
15924 (when (string-match
15925 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15926 (setq year (if (match-end 4)
15927 (string-to-number (match-string 4 ans))
15928 (progn (setq kill-year t)
15929 (string-to-number (format-time-string "%Y"))))
15930 month (string-to-number (match-string 1 ans))
15931 day (string-to-number (match-string 2 ans)))
15932 (if (< year 100) (setq year (+ 2000 year)))
15933 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15934 t nil ans)))
15935 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15936 ;; If there is a time with am/pm, and *no* time without it, we convert
15937 ;; so that matching will be successful.
15938 (loop for i from 1 to 2 do ; twice, for end time as well
15939 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15940 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15941 (setq hour (string-to-number (match-string 1 ans))
15942 minute (if (match-end 3)
15943 (string-to-number (match-string 3 ans))
15945 pm (equal ?p
15946 (string-to-char (downcase (match-string 4 ans)))))
15947 (if (and (= hour 12) (not pm))
15948 (setq hour 0)
15949 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15950 (setq ans (replace-match (format "%02d:%02d" hour minute)
15951 t t ans))))
15953 ;; Check if a time range is given as a duration
15954 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15955 (setq hour (string-to-number (match-string 1 ans))
15956 h2 (+ hour (string-to-number (match-string 3 ans)))
15957 minute (string-to-number (match-string 2 ans))
15958 m2 (+ minute (if (match-end 5) (string-to-number
15959 (match-string 5 ans))0)))
15960 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15961 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15962 t t ans)))
15964 ;; Check if there is a time range
15965 (when (boundp 'org-end-time-was-given)
15966 (setq org-time-was-given nil)
15967 (when (and (string-match org-plain-time-of-day-regexp ans)
15968 (match-end 8))
15969 (setq org-end-time-was-given (match-string 8 ans))
15970 (setq ans (concat (substring ans 0 (match-beginning 7))
15971 (substring ans (match-end 7))))))
15973 (setq tl (parse-time-string ans)
15974 day (or (nth 3 tl) (nth 3 org-defdecode))
15975 month (or (nth 4 tl)
15976 (if (and org-read-date-prefer-future
15977 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15978 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15979 (nth 4 org-defdecode)))
15980 year (or (and (not kill-year) (nth 5 tl))
15981 (if (and org-read-date-prefer-future
15982 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15983 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15984 (nth 5 org-defdecode)))
15985 hour (or (nth 2 tl) (nth 2 org-defdecode))
15986 minute (or (nth 1 tl) (nth 1 org-defdecode))
15987 second (or (nth 0 tl) 0)
15988 wday (nth 6 tl))
15990 (when (and (eq org-read-date-prefer-future 'time)
15991 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15992 (equal day (nth 3 nowdecode))
15993 (equal month (nth 4 nowdecode))
15994 (equal year (nth 5 nowdecode))
15995 (nth 2 tl)
15996 (or (< (nth 2 tl) (nth 2 nowdecode))
15997 (and (= (nth 2 tl) (nth 2 nowdecode))
15998 (nth 1 tl)
15999 (< (nth 1 tl) (nth 1 nowdecode)))))
16000 (setq day (1+ day)
16001 futurep t))
16003 ;; Special date definitions below
16004 (cond
16005 (iso-week
16006 ;; There was an iso week
16007 (require 'cal-iso)
16008 (setq futurep nil)
16009 (setq year (or iso-year year)
16010 day (or iso-weekday wday 1)
16011 wday nil ; to make sure that the trigger below does not match
16012 iso-date (calendar-gregorian-from-absolute
16013 (calendar-absolute-from-iso
16014 (list iso-week day year))))
16015 ; FIXME: Should we also push ISO weeks into the future?
16016 ; (when (and org-read-date-prefer-future
16017 ; (not iso-year)
16018 ; (< (calendar-absolute-from-gregorian iso-date)
16019 ; (time-to-days (current-time))))
16020 ; (setq year (1+ year)
16021 ; iso-date (calendar-gregorian-from-absolute
16022 ; (calendar-absolute-from-iso
16023 ; (list iso-week day year)))))
16024 (setq month (car iso-date)
16025 year (nth 2 iso-date)
16026 day (nth 1 iso-date)))
16027 (deltan
16028 (setq futurep nil)
16029 (unless deltadef
16030 (let ((now (decode-time (current-time))))
16031 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16032 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16033 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16034 ((equal deltaw "m") (setq month (+ month deltan)))
16035 ((equal deltaw "y") (setq year (+ year deltan)))))
16036 ((and wday (not (nth 3 tl)))
16037 ;; Weekday was given, but no day, so pick that day in the week
16038 ;; on or after the derived date.
16039 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16040 (unless (equal wday wday1)
16041 (setq day (+ day (% (- wday wday1 -7) 7))))))
16042 (if (and (boundp 'org-time-was-given)
16043 (nth 2 tl))
16044 (setq org-time-was-given t))
16045 (if (< year 100) (setq year (+ 2000 year)))
16046 ;; Check of the date is representable
16047 (if org-read-date-force-compatible-dates
16048 (progn
16049 (if (< year 1970)
16050 (setq year 1970 org-read-date-analyze-forced-year t))
16051 (if (> year 2037)
16052 (setq year 2037 org-read-date-analyze-forced-year t)))
16053 (condition-case nil
16054 (ignore (encode-time second minute hour day month year))
16055 (error
16056 (setq year (nth 5 org-defdecode))
16057 (setq org-read-date-analyze-forced-year t))))
16058 (setq org-read-date-analyze-futurep futurep)
16059 (list second minute hour day month year)))
16061 (defvar parse-time-weekdays)
16062 (defun org-read-date-get-relative (s today default)
16063 "Check string S for special relative date string.
16064 TODAY and DEFAULT are internal times, for today and for a default.
16065 Return shift list (N what def-flag)
16066 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16067 N is the number of WHATs to shift.
16068 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16069 the DEFAULT date rather than TODAY."
16070 (require 'parse-time)
16071 (when (and
16072 (string-match
16073 (concat
16074 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16075 "\\([0-9]+\\)?"
16076 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16077 "\\([ \t]\\|$\\)") s)
16078 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16079 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16080 (string-to-char (substring (match-string 1 s) -1))
16081 ?+))
16082 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16083 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16084 (what (if (match-end 3) (match-string 3 s) "d"))
16085 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16086 (date (if rel default today))
16087 (wday (nth 6 (decode-time date)))
16088 delta)
16089 (if wday1
16090 (progn
16091 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16092 (if (= dir ?-) (setq delta (- delta 7)))
16093 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16094 (list delta "d" rel))
16095 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16097 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16098 "Turn a user-specified date into the internal representation.
16099 The internal representation needed by the calendar is (month day year).
16100 This is a wrapper to handle the brain-dead convention in calendar that
16101 user function argument order change dependent on argument order."
16102 (if (boundp 'calendar-date-style)
16103 (cond
16104 ((eq calendar-date-style 'american)
16105 (list arg1 arg2 arg3))
16106 ((eq calendar-date-style 'european)
16107 (list arg2 arg1 arg3))
16108 ((eq calendar-date-style 'iso)
16109 (list arg2 arg3 arg1)))
16110 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16111 (if (org-bound-and-true-p european-calendar-style)
16112 (list arg2 arg1 arg3)
16113 (list arg1 arg2 arg3)))))
16115 (defun org-eval-in-calendar (form &optional keepdate)
16116 "Eval FORM in the calendar window and return to current window.
16117 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16118 otherwise stick to the current value of `org-ans2'."
16119 (let ((sf (selected-frame))
16120 (sw (selected-window)))
16121 (select-window (get-buffer-window "*Calendar*" t))
16122 (eval form)
16123 (when (and (not keepdate) (calendar-cursor-to-date))
16124 (let* ((date (calendar-cursor-to-date))
16125 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16126 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16127 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16128 (select-window sw)
16129 (org-select-frame-set-input-focus sf)))
16131 (defun org-calendar-select ()
16132 "Return to `org-read-date' with the date currently selected.
16133 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16134 (interactive)
16135 (when (calendar-cursor-to-date)
16136 (let* ((date (calendar-cursor-to-date))
16137 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16138 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16139 (if (active-minibuffer-window) (exit-minibuffer))))
16141 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16142 "Insert a date stamp for the date given by the internal TIME.
16143 WITH-HM means use the stamp format that includes the time of the day.
16144 INACTIVE means use square brackets instead of angular ones, so that the
16145 stamp will not contribute to the agenda.
16146 PRE and POST are optional strings to be inserted before and after the
16147 stamp.
16148 The command returns the inserted time stamp."
16149 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16150 stamp)
16151 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16152 (insert-before-markers (or pre ""))
16153 (when (listp extra)
16154 (setq extra (car extra))
16155 (if (and (stringp extra)
16156 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16157 (setq extra (format "-%02d:%02d"
16158 (string-to-number (match-string 1 extra))
16159 (string-to-number (match-string 2 extra))))
16160 (setq extra nil)))
16161 (when extra
16162 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16163 (insert-before-markers (setq stamp (format-time-string fmt time)))
16164 (insert-before-markers (or post ""))
16165 (setq org-last-inserted-timestamp stamp)))
16167 (defun org-toggle-time-stamp-overlays ()
16168 "Toggle the use of custom time stamp formats."
16169 (interactive)
16170 (setq org-display-custom-times (not org-display-custom-times))
16171 (unless org-display-custom-times
16172 (let ((p (point-min)) (bmp (buffer-modified-p)))
16173 (while (setq p (next-single-property-change p 'display))
16174 (if (and (get-text-property p 'display)
16175 (eq (get-text-property p 'face) 'org-date))
16176 (remove-text-properties
16177 p (setq p (next-single-property-change p 'display))
16178 '(display t))))
16179 (set-buffer-modified-p bmp)))
16180 (if (featurep 'xemacs)
16181 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16182 (org-restart-font-lock)
16183 (setq org-table-may-need-update t)
16184 (if org-display-custom-times
16185 (message "Time stamps are overlaid with custom format")
16186 (message "Time stamp overlays removed")))
16188 (defun org-display-custom-time (beg end)
16189 "Overlay modified time stamp format over timestamp between BEG and END."
16190 (let* ((ts (buffer-substring beg end))
16191 t1 w1 with-hm tf time str w2 (off 0))
16192 (save-match-data
16193 (setq t1 (org-parse-time-string ts t))
16194 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16195 (setq off (- (match-end 0) (match-beginning 0)))))
16196 (setq end (- end off))
16197 (setq w1 (- end beg)
16198 with-hm (and (nth 1 t1) (nth 2 t1))
16199 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16200 time (org-fix-decoded-time t1)
16201 str (org-add-props
16202 (format-time-string
16203 (substring tf 1 -1) (apply 'encode-time time))
16204 nil 'mouse-face 'highlight)
16205 w2 (length str))
16206 (if (not (= w2 w1))
16207 (add-text-properties (1+ beg) (+ 2 beg)
16208 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16209 (if (featurep 'xemacs)
16210 (progn
16211 (put-text-property beg end 'invisible t)
16212 (put-text-property beg end 'end-glyph (make-glyph str)))
16213 (put-text-property beg end 'display str))))
16215 (defun org-translate-time (string)
16216 "Translate all timestamps in STRING to custom format.
16217 But do this only if the variable `org-display-custom-times' is set."
16218 (when org-display-custom-times
16219 (save-match-data
16220 (let* ((start 0)
16221 (re org-ts-regexp-both)
16222 t1 with-hm inactive tf time str beg end)
16223 (while (setq start (string-match re string start))
16224 (setq beg (match-beginning 0)
16225 end (match-end 0)
16226 t1 (save-match-data
16227 (org-parse-time-string (substring string beg end) t))
16228 with-hm (and (nth 1 t1) (nth 2 t1))
16229 inactive (equal (substring string beg (1+ beg)) "[")
16230 tf (funcall (if with-hm 'cdr 'car)
16231 org-time-stamp-custom-formats)
16232 time (org-fix-decoded-time t1)
16233 str (format-time-string
16234 (concat
16235 (if inactive "[" "<") (substring tf 1 -1)
16236 (if inactive "]" ">"))
16237 (apply 'encode-time time))
16238 string (replace-match str t t string)
16239 start (+ start (length str)))))))
16240 string)
16242 (defun org-fix-decoded-time (time)
16243 "Set 0 instead of nil for the first 6 elements of time.
16244 Don't touch the rest."
16245 (let ((n 0))
16246 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16248 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16250 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16251 "Difference between TIMESTAMP-STRING and now in days.
16252 If SECONDS is non-nil, return the difference in seconds."
16253 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16254 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16255 (funcall fdiff (current-time)))))
16257 (defun org-deadline-close (timestamp-string &optional ndays)
16258 "Is the time in TIMESTAMP-STRING close to the current date?"
16259 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16260 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16261 (not (org-entry-is-done-p))))
16263 (defun org-get-wdays (ts &optional delay zero-delay)
16264 "Get the deadline lead time appropriate for timestring TS.
16265 When DELAY is non-nil, get the delay time for scheduled items
16266 instead of the deadline lead time. When ZERO-DELAY is non-nil
16267 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16268 don't try to find the delay cookie in the scheduled timestamp."
16269 (let ((tv (if delay org-scheduled-delay-days
16270 org-deadline-warning-days)))
16271 (cond
16272 ((or (and delay (< tv 0))
16273 (and delay zero-delay (<= tv 0))
16274 (and (not delay) (<= tv 0)))
16275 ;; Enforce this value no matter what
16276 (- tv))
16277 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16278 ;; lead time is specified.
16279 (floor (* (string-to-number (match-string 1 ts))
16280 (cdr (assoc (match-string 2 ts)
16281 '(("d" . 1) ("w" . 7)
16282 ("m" . 30.4) ("y" . 365.25)
16283 ("h" . 0.041667)))))))
16284 ;; go for the default.
16285 (t tv))))
16287 (defun org-calendar-select-mouse (ev)
16288 "Return to `org-read-date' with the date currently selected.
16289 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16290 (interactive "e")
16291 (mouse-set-point ev)
16292 (when (calendar-cursor-to-date)
16293 (let* ((date (calendar-cursor-to-date))
16294 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16295 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16296 (if (active-minibuffer-window) (exit-minibuffer))))
16298 (defun org-check-deadlines (ndays)
16299 "Check if there are any deadlines due or past due.
16300 A deadline is considered due if it happens within `org-deadline-warning-days'
16301 days from today's date. If the deadline appears in an entry marked DONE,
16302 it is not shown. The prefix arg NDAYS can be used to test that many
16303 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16304 (interactive "P")
16305 (let* ((org-warn-days
16306 (cond
16307 ((equal ndays '(4)) 100000)
16308 (ndays (prefix-numeric-value ndays))
16309 (t (abs org-deadline-warning-days))))
16310 (case-fold-search nil)
16311 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16312 (callback
16313 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16315 (message "%d deadlines past-due or due within %d days"
16316 (org-occur regexp nil callback)
16317 org-warn-days)))
16319 (defsubst org-re-timestamp (type)
16320 "Return a regexp for timestamp TYPE.
16321 Allowed values for TYPE are:
16323 all: all timestamps
16324 active: only active timestamps (<...>)
16325 inactive: only inactive timestamps ([...])
16326 scheduled: only scheduled timestamps
16327 deadline: only deadline timestamps
16329 When TYPE is nil, fall back on returning a regexp that matches
16330 both scheduled and deadline timestamps."
16331 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16332 ((eq type 'active) org-ts-regexp)
16333 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16334 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16335 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16336 ((eq type 'scheduled-or-deadline)
16337 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16339 (defun org-check-before-date (date)
16340 "Check if there are deadlines or scheduled entries before DATE."
16341 (interactive (list (org-read-date)))
16342 (let ((case-fold-search nil)
16343 (regexp (org-re-timestamp org-ts-type))
16344 (callback
16345 (lambda () (time-less-p
16346 (org-time-string-to-time (match-string 1))
16347 (org-time-string-to-time date)))))
16348 (message "%d entries before %s"
16349 (org-occur regexp nil callback) date)))
16351 (defun org-check-after-date (date)
16352 "Check if there are deadlines or scheduled entries after DATE."
16353 (interactive (list (org-read-date)))
16354 (let ((case-fold-search nil)
16355 (regexp (org-re-timestamp org-ts-type))
16356 (callback
16357 (lambda () (not
16358 (time-less-p
16359 (org-time-string-to-time (match-string 1))
16360 (org-time-string-to-time date))))))
16361 (message "%d entries after %s"
16362 (org-occur regexp nil callback) date)))
16364 (defun org-check-dates-range (start-date end-date)
16365 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16366 (interactive (list (org-read-date nil nil nil "Range starts")
16367 (org-read-date nil nil nil "Range end")))
16368 (let ((case-fold-search nil)
16369 (regexp (org-re-timestamp org-ts-type))
16370 (callback
16371 (lambda ()
16372 (let ((match (match-string 1)))
16373 (and
16374 (not (time-less-p
16375 (org-time-string-to-time match)
16376 (org-time-string-to-time start-date)))
16377 (time-less-p
16378 (org-time-string-to-time match)
16379 (org-time-string-to-time end-date)))))))
16380 (message "%d entries between %s and %s"
16381 (org-occur regexp nil callback) start-date end-date)))
16383 (defun org-evaluate-time-range (&optional to-buffer)
16384 "Evaluate a time range by computing the difference between start and end.
16385 Normally the result is just printed in the echo area, but with prefix arg
16386 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16387 If the time range is actually in a table, the result is inserted into the
16388 next column.
16389 For time difference computation, a year is assumed to be exactly 365
16390 days in order to avoid rounding problems."
16391 (interactive "P")
16393 (org-clock-update-time-maybe)
16394 (save-excursion
16395 (unless (org-at-date-range-p t)
16396 (goto-char (point-at-bol))
16397 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16398 (if (not (org-at-date-range-p t))
16399 (error "Not at a time-stamp range, and none found in current line")))
16400 (let* ((ts1 (match-string 1))
16401 (ts2 (match-string 2))
16402 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16403 (match-end (match-end 0))
16404 (time1 (org-time-string-to-time ts1))
16405 (time2 (org-time-string-to-time ts2))
16406 (t1 (org-float-time time1))
16407 (t2 (org-float-time time2))
16408 (diff (abs (- t2 t1)))
16409 (negative (< (- t2 t1) 0))
16410 ;; (ys (floor (* 365 24 60 60)))
16411 (ds (* 24 60 60))
16412 (hs (* 60 60))
16413 (fy "%dy %dd %02d:%02d")
16414 (fy1 "%dy %dd")
16415 (fd "%dd %02d:%02d")
16416 (fd1 "%dd")
16417 (fh "%02d:%02d")
16418 y d h m align)
16419 (if havetime
16420 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16422 d (floor (/ diff ds)) diff (mod diff ds)
16423 h (floor (/ diff hs)) diff (mod diff hs)
16424 m (floor (/ diff 60)))
16425 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16427 d (floor (+ (/ diff ds) 0.5))
16428 h 0 m 0))
16429 (if (not to-buffer)
16430 (message "%s" (org-make-tdiff-string y d h m))
16431 (if (org-at-table-p)
16432 (progn
16433 (goto-char match-end)
16434 (setq align t)
16435 (and (looking-at " *|") (goto-char (match-end 0))))
16436 (goto-char match-end))
16437 (if (looking-at
16438 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16439 (replace-match ""))
16440 (if negative (insert " -"))
16441 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16442 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16443 (insert " " (format fh h m))))
16444 (if align (org-table-align))
16445 (message "Time difference inserted")))))
16447 (defun org-make-tdiff-string (y d h m)
16448 (let ((fmt "")
16449 (l nil))
16450 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16451 l (push y l)))
16452 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16453 l (push d l)))
16454 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16455 l (push h l)))
16456 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16457 l (push m l)))
16458 (apply 'format fmt (nreverse l))))
16460 (defun org-time-string-to-time (s &optional buffer pos)
16461 "Convert a timestamp string into internal time."
16462 (condition-case errdata
16463 (apply 'encode-time (org-parse-time-string s))
16464 (error (error "Bad timestamp `%s'%s\nError was: %s"
16465 s (if (not (and buffer pos))
16467 (format " at %d in buffer `%s'" pos buffer))
16468 (cdr errdata)))))
16470 (defun org-time-string-to-seconds (s)
16471 "Convert a timestamp string to a number of seconds."
16472 (org-float-time (org-time-string-to-time s)))
16474 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16475 "Convert a time stamp to an absolute day number.
16476 If there is a specifier for a cyclic time stamp, get the closest
16477 date to DAYNR.
16478 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16479 The variable date is bound by the calendar when this is called."
16480 (cond
16481 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16482 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16483 daynr
16484 (+ daynr 1000)))
16485 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16486 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16487 (time-to-days (current-time))) (match-string 0 s)
16488 prefer show-all))
16489 (t (time-to-days
16490 (condition-case errdata
16491 (apply 'encode-time (org-parse-time-string s))
16492 (error (error "Bad timestamp `%s'%s\nError was: %s"
16493 s (if (not (and buffer pos))
16495 (format " at %d in buffer `%s'" pos buffer))
16496 (cdr errdata))))))))
16498 (defun org-days-to-iso-week (days)
16499 "Return the iso week number."
16500 (require 'cal-iso)
16501 (car (calendar-iso-from-absolute days)))
16503 (defun org-small-year-to-year (year)
16504 "Convert 2-digit years into 4-digit years.
16505 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16506 The year 2000 cannot be abbreviated. Any year larger than 99
16507 is returned unchanged."
16508 (if (< year 38)
16509 (setq year (+ 2000 year))
16510 (if (< year 100)
16511 (setq year (+ 1900 year))))
16512 year)
16514 (defun org-time-from-absolute (d)
16515 "Return the time corresponding to date D.
16516 D may be an absolute day number, or a calendar-type list (month day year)."
16517 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16518 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16520 (defun org-calendar-holiday ()
16521 "List of holidays, for Diary display in Org-mode."
16522 (require 'holidays)
16523 (let ((hl (funcall
16524 (if (fboundp 'calendar-check-holidays)
16525 'calendar-check-holidays 'check-calendar-holidays) date)))
16526 (if hl (mapconcat 'identity hl "; "))))
16528 (defun org-diary-sexp-entry (sexp entry date)
16529 "Process a SEXP diary ENTRY for DATE."
16530 (require 'diary-lib)
16531 (let ((result (if calendar-debug-sexp
16532 (let ((stack-trace-on-error t))
16533 (eval (car (read-from-string sexp))))
16534 (condition-case nil
16535 (eval (car (read-from-string sexp)))
16536 (error
16537 (beep)
16538 (message "Bad sexp at line %d in %s: %s"
16539 (org-current-line)
16540 (buffer-file-name) sexp)
16541 (sleep-for 2))))))
16542 (cond ((stringp result) (split-string result "; "))
16543 ((and (consp result)
16544 (not (consp (cdr result)))
16545 (stringp (cdr result))) (cdr result))
16546 ((and (consp result)
16547 (stringp (car result))) result)
16548 (result entry))))
16550 (defun org-diary-to-ical-string (frombuf)
16551 "Get iCalendar entries from diary entries in buffer FROMBUF.
16552 This uses the icalendar.el library."
16553 (let* ((tmpdir (if (featurep 'xemacs)
16554 (temp-directory)
16555 temporary-file-directory))
16556 (tmpfile (make-temp-name
16557 (expand-file-name "orgics" tmpdir)))
16558 buf rtn b e)
16559 (with-current-buffer frombuf
16560 (icalendar-export-region (point-min) (point-max) tmpfile)
16561 (setq buf (find-buffer-visiting tmpfile))
16562 (set-buffer buf)
16563 (goto-char (point-min))
16564 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16565 (setq b (match-beginning 0)))
16566 (goto-char (point-max))
16567 (if (re-search-backward "^END:VEVENT" nil t)
16568 (setq e (match-end 0)))
16569 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16570 (kill-buffer buf)
16571 (delete-file tmpfile)
16572 rtn))
16574 (defun org-closest-date (start current change prefer show-all)
16575 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16576 When PREFER is `past', return a date that is either CURRENT or past.
16577 When PREFER is `future', return a date that is either CURRENT or future.
16578 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16579 ;; Make the proper lists from the dates
16580 (catch 'exit
16581 (let ((a1 '(("h" . hour)
16582 ("d" . day)
16583 ("w" . week)
16584 ("m" . month)
16585 ("y" . year)))
16586 (shour (nth 2 (org-parse-time-string start)))
16587 dn dw sday cday n1 n2 n0
16588 d m y y1 y2 date1 date2 nmonths nm ny m2)
16590 (setq start (org-date-to-gregorian start)
16591 current (org-date-to-gregorian
16592 (if show-all
16593 current
16594 (time-to-days (current-time))))
16595 sday (calendar-absolute-from-gregorian start)
16596 cday (calendar-absolute-from-gregorian current))
16598 (if (<= cday sday) (throw 'exit sday))
16600 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16601 (setq dn (string-to-number (match-string 1 change))
16602 dw (cdr (assoc (match-string 2 change) a1)))
16603 (error "Invalid change specifier: %s" change))
16604 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16605 (cond
16606 ((eq dw 'hour)
16607 (let ((missing-hours
16608 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16609 dn)))
16610 (setq n1 (if (zerop missing-hours) cday
16611 (- cday (1+ (floor (/ missing-hours 24)))))
16612 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16613 ((eq dw 'day)
16614 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16615 n2 (+ n1 dn)))
16616 ((eq dw 'year)
16617 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16618 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16619 (setq date1 (list m d y1)
16620 n1 (calendar-absolute-from-gregorian date1)
16621 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16622 n2 (calendar-absolute-from-gregorian date2)))
16623 ((eq dw 'month)
16624 ;; approx number of month between the two dates
16625 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16626 ;; How often does dn fit in there?
16627 (setq d (nth 1 start) m (car start) y (nth 2 start)
16628 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16629 m (+ m nm)
16630 ny (floor (/ m 12))
16631 y (+ y ny)
16632 m (- m (* ny 12)))
16633 (while (> m 12) (setq m (- m 12) y (1+ y)))
16634 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16635 (setq m2 (+ m dn) y2 y)
16636 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16637 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16638 (while (<= n2 cday)
16639 (setq n1 n2 m m2 y y2)
16640 (setq m2 (+ m dn) y2 y)
16641 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16642 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16643 ;; Make sure n1 is the earlier date
16644 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16645 (if show-all
16646 (cond
16647 ((eq prefer 'past) (if (= cday n2) n2 n1))
16648 ((eq prefer 'future) (if (= cday n1) n1 n2))
16649 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16650 (cond
16651 ((eq prefer 'past) (if (= cday n2) n2 n1))
16652 ((eq prefer 'future) (if (= cday n1) n1 n2))
16653 (t (if (= cday n1) n1 n2)))))))
16655 (defun org-date-to-gregorian (date)
16656 "Turn any specification of DATE into a Gregorian date for the calendar."
16657 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16658 ((and (listp date) (= (length date) 3)) date)
16659 ((stringp date)
16660 (setq date (org-parse-time-string date))
16661 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16662 ((listp date)
16663 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16665 (defun org-parse-time-string (s &optional nodefault)
16666 "Parse the standard Org-mode time string.
16667 This should be a lot faster than the normal `parse-time-string'.
16668 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16669 hour and minute fields will be nil if not given."
16670 (cond ((string-match org-ts-regexp0 s)
16671 (list 0
16672 (if (or (match-beginning 8) (not nodefault))
16673 (string-to-number (or (match-string 8 s) "0")))
16674 (if (or (match-beginning 7) (not nodefault))
16675 (string-to-number (or (match-string 7 s) "0")))
16676 (string-to-number (match-string 4 s))
16677 (string-to-number (match-string 3 s))
16678 (string-to-number (match-string 2 s))
16679 nil nil nil))
16680 ((string-match "^<[^>]+>$" s)
16681 (decode-time (seconds-to-time (org-matcher-time s))))
16682 (t (error "Not a standard Org-mode time string: %s" s))))
16684 (defun org-timestamp-up (&optional arg)
16685 "Increase the date item at the cursor by one.
16686 If the cursor is on the year, change the year. If it is on the month,
16687 the day or the time, change that.
16688 With prefix ARG, change by that many units."
16689 (interactive "p")
16690 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16692 (defun org-timestamp-down (&optional arg)
16693 "Decrease the date item at the cursor by one.
16694 If the cursor is on the year, change the year. If it is on the month,
16695 the day or the time, change that.
16696 With prefix ARG, change by that many units."
16697 (interactive "p")
16698 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16700 (defun org-timestamp-up-day (&optional arg)
16701 "Increase the date in the time stamp by one day.
16702 With prefix ARG, change that many days."
16703 (interactive "p")
16704 (if (and (not (org-at-timestamp-p t))
16705 (org-at-heading-p))
16706 (org-todo 'up)
16707 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16709 (defun org-timestamp-down-day (&optional arg)
16710 "Decrease the date in the time stamp by one day.
16711 With prefix ARG, change that many days."
16712 (interactive "p")
16713 (if (and (not (org-at-timestamp-p t))
16714 (org-at-heading-p))
16715 (org-todo 'down)
16716 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16718 (defun org-at-timestamp-p (&optional inactive-ok)
16719 "Determine if the cursor is in or at a timestamp."
16720 (interactive)
16721 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16722 (pos (point))
16723 (ans (or (looking-at tsr)
16724 (save-excursion
16725 (skip-chars-backward "^[<\n\r\t")
16726 (if (> (point) (point-min)) (backward-char 1))
16727 (and (looking-at tsr)
16728 (> (- (match-end 0) pos) -1))))))
16729 (and ans
16730 (boundp 'org-ts-what)
16731 (setq org-ts-what
16732 (cond
16733 ((= pos (match-beginning 0)) 'bracket)
16734 ;; Point is considered to be "on the bracket" whether
16735 ;; it's really on it or right after it.
16736 ((= pos (1- (match-end 0))) 'bracket)
16737 ((= pos (match-end 0)) 'after)
16738 ((org-pos-in-match-range pos 2) 'year)
16739 ((org-pos-in-match-range pos 3) 'month)
16740 ((org-pos-in-match-range pos 7) 'hour)
16741 ((org-pos-in-match-range pos 8) 'minute)
16742 ((or (org-pos-in-match-range pos 4)
16743 (org-pos-in-match-range pos 5)) 'day)
16744 ((and (> pos (or (match-end 8) (match-end 5)))
16745 (< pos (match-end 0)))
16746 (- pos (or (match-end 8) (match-end 5))))
16747 (t 'day))))
16748 ans))
16750 (defun org-toggle-timestamp-type ()
16751 "Toggle the type (<active> or [inactive]) of a time stamp."
16752 (interactive)
16753 (when (org-at-timestamp-p t)
16754 (let ((beg (match-beginning 0)) (end (match-end 0))
16755 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16756 (save-excursion
16757 (goto-char beg)
16758 (while (re-search-forward "[][<>]" end t)
16759 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16760 t t)))
16761 (message "Timestamp is now %sactive"
16762 (if (equal (char-after beg) ?<) "" "in")))))
16764 (defvar org-clock-history) ; defined in org-clock.el
16765 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16766 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16767 "Change the date in the time stamp at point.
16768 The date will be changed by N times WHAT. WHAT can be `day', `month',
16769 `year', `minute', `second'. If WHAT is not given, the cursor position
16770 in the timestamp determines what will be changed.
16771 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
16772 (let ((origin (point)) origin-cat
16773 with-hm inactive
16774 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16775 org-ts-what
16776 extra rem
16777 ts time time0 fixnext clrgx)
16778 (if (not (org-at-timestamp-p t))
16779 (error "Not at a timestamp"))
16780 (if (and (not what) (eq org-ts-what 'bracket))
16781 (org-toggle-timestamp-type)
16782 ;; Point isn't on brackets. Remember the part of the time-stamp
16783 ;; the point was in. Indeed, size of time-stamps may change,
16784 ;; but point must be kept in the same category nonetheless.
16785 (setq origin-cat org-ts-what)
16786 (if (and (not what) (not (eq org-ts-what 'day))
16787 org-display-custom-times
16788 (get-text-property (point) 'display)
16789 (not (get-text-property (1- (point)) 'display)))
16790 (setq org-ts-what 'day))
16791 (setq org-ts-what (or what org-ts-what)
16792 inactive (= (char-after (match-beginning 0)) ?\[)
16793 ts (match-string 0))
16794 (replace-match "")
16795 (when (string-match
16796 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16798 (setq extra (match-string 1 ts))
16799 (if suppress-tmp-delay
16800 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
16801 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16802 (setq with-hm t))
16803 (setq time0 (org-parse-time-string ts))
16804 (when (and updown
16805 (eq org-ts-what 'minute)
16806 (not current-prefix-arg))
16807 ;; This looks like s-up and s-down. Change by one rounding step.
16808 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16809 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16810 (setcar (cdr time0) (+ (nth 1 time0)
16811 (if (> n 0) (- rem) (- dm rem))))))
16812 (setq time
16813 (encode-time (or (car time0) 0)
16814 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16815 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16816 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16817 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16818 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16819 (nthcdr 6 time0)))
16820 (when (and (member org-ts-what '(hour minute))
16821 extra
16822 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16823 (setq extra (org-modify-ts-extra
16824 extra
16825 (if (eq org-ts-what 'hour) 2 5)
16826 n dm)))
16827 (when (integerp org-ts-what)
16828 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16829 (if (eq what 'calendar)
16830 (let ((cal-date (org-get-date-from-calendar)))
16831 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16832 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16833 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16834 (setcar time0 (or (car time0) 0))
16835 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16836 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16837 (setq time (apply 'encode-time time0))))
16838 ;; Insert the new time-stamp, and ensure point stays in the same
16839 ;; category as before (i.e. not after the last position in that
16840 ;; category).
16841 (let ((pos (point)))
16842 ;; Stay before inserted string. `save-excursion' is of no use.
16843 (setq org-last-changed-timestamp
16844 (org-insert-time-stamp time with-hm inactive nil nil extra))
16845 (goto-char pos))
16846 (save-match-data
16847 (looking-at org-ts-regexp3)
16848 (goto-char (cond
16849 ;; `day' category ends before `hour' if any, or at
16850 ;; the end of the day name.
16851 ((eq origin-cat 'day)
16852 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16853 ((eq origin-cat 'hour) (min (match-end 7) origin))
16854 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16855 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16856 ;; `year' and `month' have both fixed size: point
16857 ;; couldn't have moved into another part.
16858 (t origin))))
16859 ;; Update clock if on a CLOCK line.
16860 (org-clock-update-time-maybe)
16861 ;; Maybe adjust the closest clock in `org-clock-history'
16862 (when org-clock-adjust-closest
16863 (if (not (and (org-at-clock-log-p)
16864 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16865 org-clock-history))))))
16866 (message "No clock to adjust")
16867 (cond ((save-excursion ; fix previous clock?
16868 (re-search-backward org-ts-regexp0 nil t)
16869 (org-looking-back (concat org-clock-string " \\[")))
16870 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16871 ((save-excursion ; fix next clock?
16872 (re-search-backward org-ts-regexp0 nil t)
16873 (looking-at (concat org-ts-regexp0 "\\] =>")))
16874 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16875 (save-window-excursion
16876 ;; Find closest clock to point, adjust the previous/next one in history
16877 (let* ((p (save-excursion (org-back-to-heading t)))
16878 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16879 (clfixnth
16880 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16881 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16882 (if (not clfixpos)
16883 (message "No clock to adjust")
16884 (save-excursion
16885 (org-goto-marker-or-bmk clfixpos)
16886 (org-show-subtree)
16887 (when (re-search-forward clrgx nil t)
16888 (goto-char (match-beginning 1))
16889 (let (org-clock-adjust-closest)
16890 (org-timestamp-change n org-ts-what updown))
16891 (message "Clock adjusted in %s for heading: %s"
16892 (file-name-nondirectory (buffer-file-name))
16893 (org-get-heading t t)))))))))
16894 ;; Try to recenter the calendar window, if any.
16895 (if (and org-calendar-follow-timestamp-change
16896 (get-buffer-window "*Calendar*" t)
16897 (memq org-ts-what '(day month year)))
16898 (org-recenter-calendar (time-to-days time))))))
16900 (defun org-modify-ts-extra (s pos n dm)
16901 "Change the different parts of the lead-time and repeat fields in timestamp."
16902 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16903 ng h m new rem)
16904 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16905 (cond
16906 ((or (org-pos-in-match-range pos 2)
16907 (org-pos-in-match-range pos 3))
16908 (setq m (string-to-number (match-string 3 s))
16909 h (string-to-number (match-string 2 s)))
16910 (if (org-pos-in-match-range pos 2)
16911 (setq h (+ h n))
16912 (setq n (* dm (org-no-warnings (signum n))))
16913 (when (not (= 0 (setq rem (% m dm))))
16914 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16915 (setq m (+ m n)))
16916 (if (< m 0) (setq m (+ m 60) h (1- h)))
16917 (if (> m 59) (setq m (- m 60) h (1+ h)))
16918 (setq h (min 24 (max 0 h)))
16919 (setq ng 1 new (format "-%02d:%02d" h m)))
16920 ((org-pos-in-match-range pos 6)
16921 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16922 ((org-pos-in-match-range pos 5)
16923 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16925 ((org-pos-in-match-range pos 9)
16926 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16927 ((org-pos-in-match-range pos 8)
16928 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16930 (when ng
16931 (setq s (concat
16932 (substring s 0 (match-beginning ng))
16934 (substring s (match-end ng))))))
16937 (defun org-recenter-calendar (date)
16938 "If the calendar is visible, recenter it to DATE."
16939 (let ((cwin (get-buffer-window "*Calendar*" t)))
16940 (when cwin
16941 (let ((calendar-move-hook nil))
16942 (with-selected-window cwin
16943 (calendar-goto-date (if (listp date) date
16944 (calendar-gregorian-from-absolute date))))))))
16946 (defun org-goto-calendar (&optional arg)
16947 "Go to the Emacs calendar at the current date.
16948 If there is a time stamp in the current line, go to that date.
16949 A prefix ARG can be used to force the current date."
16950 (interactive "P")
16951 (let ((tsr org-ts-regexp) diff
16952 (calendar-move-hook nil)
16953 (calendar-view-holidays-initially-flag nil)
16954 (calendar-view-diary-initially-flag nil))
16955 (if (or (org-at-timestamp-p)
16956 (save-excursion
16957 (beginning-of-line 1)
16958 (looking-at (concat ".*" tsr))))
16959 (let ((d1 (time-to-days (current-time)))
16960 (d2 (time-to-days
16961 (org-time-string-to-time (match-string 1)))))
16962 (setq diff (- d2 d1))))
16963 (calendar)
16964 (calendar-goto-today)
16965 (if (and diff (not arg)) (calendar-forward-day diff))))
16967 (defun org-get-date-from-calendar ()
16968 "Return a list (month day year) of date at point in calendar."
16969 (with-current-buffer "*Calendar*"
16970 (save-match-data
16971 (calendar-cursor-to-date))))
16973 (defun org-date-from-calendar ()
16974 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16975 If there is already a time stamp at the cursor position, update it."
16976 (interactive)
16977 (if (org-at-timestamp-p t)
16978 (org-timestamp-change 0 'calendar)
16979 (let ((cal-date (org-get-date-from-calendar)))
16980 (org-insert-time-stamp
16981 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16983 (defcustom org-effort-durations
16984 `(("h" . 60)
16985 ("d" . ,(* 60 8))
16986 ("w" . ,(* 60 8 5))
16987 ("m" . ,(* 60 8 5 4))
16988 ("y" . ,(* 60 8 5 40)))
16989 "Conversion factor to minutes for an effort modifier.
16991 Each entry has the form (MODIFIER . MINUTES).
16993 In an effort string, a number followed by MODIFIER is multiplied
16994 by the specified number of MINUTES to obtain an effort in
16995 minutes.
16997 For example, if the value of this variable is ((\"hours\" . 60)), then an
16998 effort string \"2hours\" is equivalent to 120 minutes."
16999 :group 'org-agenda
17000 :version "24.1"
17001 :type '(alist :key-type (string :tag "Modifier")
17002 :value-type (number :tag "Minutes")))
17004 (defun org-minutes-to-clocksum-string (m)
17005 "Format number of minutes as a clocksum string.
17006 The format is determined by `org-time-clocksum-format',
17007 `org-time-clocksum-use-fractional' and
17008 `org-time-clocksum-fractional-format' and
17009 `org-time-clocksum-use-effort-durations'."
17010 (let ((clocksum "") h d w mo y fmt n)
17011 (setq h (if org-time-clocksum-use-effort-durations
17012 (cdr (assoc "h" org-effort-durations)) 60)
17013 d (if org-time-clocksum-use-effort-durations
17014 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17015 w (if org-time-clocksum-use-effort-durations
17016 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17017 mo (if org-time-clocksum-use-effort-durations
17018 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17019 y (if org-time-clocksum-use-effort-durations
17020 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17021 ;; fractional format
17022 (if org-time-clocksum-use-fractional
17023 (cond
17024 ;; single format string
17025 ((stringp org-time-clocksum-fractional-format)
17026 (format org-time-clocksum-fractional-format (/ m (float h))))
17027 ;; choice of fractional formats for different time units
17028 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17029 (> (/ (truncate m) (* y d h)) 0))
17030 (format fmt (/ m (* y d (float h)))))
17031 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17032 (> (/ (truncate m) (* mo d h)) 0))
17033 (format fmt (/ m (* mo d (float h)))))
17034 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17035 (> (/ (truncate m) (* w d h)) 0))
17036 (format fmt (/ m (* w d (float h)))))
17037 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17038 (> (/ (truncate m) (* d h)) 0))
17039 (format fmt (/ m (* d (float h)))))
17040 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17041 (> (/ (truncate m) h) 0))
17042 (format fmt (/ m (float h))))
17043 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17044 (format fmt m))
17045 ;; fall back to smallest time unit with a format
17046 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17047 (format fmt (/ m (float h))))
17048 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17049 (format fmt (/ m (* d (float h)))))
17050 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17051 (format fmt (/ m (* w d (float h)))))
17052 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17053 (format fmt (/ m (* mo d (float h)))))
17054 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17055 (format fmt (/ m (* y d (float h))))))
17056 ;; standard (non-fractional) format, with single format string
17057 (if (stringp org-time-clocksum-format)
17058 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17059 ;; separate formats components
17060 (and (setq fmt (plist-get org-time-clocksum-format :years))
17061 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17062 (plist-get org-time-clocksum-format :require-years))
17063 (setq clocksum (concat clocksum (format fmt n))
17064 m (- m (* n y d h))))
17065 (and (setq fmt (plist-get org-time-clocksum-format :months))
17066 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17067 (plist-get org-time-clocksum-format :require-months))
17068 (setq clocksum (concat clocksum (format fmt n))
17069 m (- m (* n mo d h))))
17070 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17071 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17072 (plist-get org-time-clocksum-format :require-weeks))
17073 (setq clocksum (concat clocksum (format fmt n))
17074 m (- m (* n w d h))))
17075 (and (setq fmt (plist-get org-time-clocksum-format :days))
17076 (or (> (setq n (/ (truncate m) (* d h))) 0)
17077 (plist-get org-time-clocksum-format :require-days))
17078 (setq clocksum (concat clocksum (format fmt n))
17079 m (- m (* n d h))))
17080 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17081 (or (> (setq n (/ (truncate m) h)) 0)
17082 (plist-get org-time-clocksum-format :require-hours))
17083 (setq clocksum (concat clocksum (format fmt n))
17084 m (- m (* n h))))
17085 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17086 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17087 (setq clocksum (concat clocksum (format fmt m))))
17088 ;; return formatted time duration
17089 clocksum))))
17091 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17092 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17093 "Org mode version 8.0")
17095 (defun org-hours-to-clocksum-string (n)
17096 (org-minutes-to-clocksum-string (* n 60)))
17098 (defun org-hh:mm-string-to-minutes (s)
17099 "Convert a string H:MM to a number of minutes.
17100 If the string is just a number, interpret it as minutes.
17101 In fact, the first hh:mm or number in the string will be taken,
17102 there can be extra stuff in the string.
17103 If no number is found, the return value is 0."
17104 (cond
17105 ((integerp s) s)
17106 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17107 (+ (* (string-to-number (match-string 1 s)) 60)
17108 (string-to-number (match-string 2 s))))
17109 ((string-match "\\([0-9]+\\)" s)
17110 (string-to-number (match-string 1 s)))
17111 (t 0)))
17113 (defcustom org-image-actual-width t
17114 "Should we use the actual width of images when inlining them?
17116 When set to `t', always use the image width.
17118 When set to a number, use imagemagick (when available) to set
17119 the image's width to this value.
17121 When set to a number in a list, try to get the width from the
17122 #+ATTR.* keyword if it matches a width specification like
17123 width=\"[0-9]+\", and fall back on that number if none is found.
17125 When set to nil, try to get the width from an #+ATTR.* keyword
17126 and fall back on the original width if none is found.
17128 This requires Emacs >= 24.1, build with imagemagick support."
17129 :group 'org-appearance
17130 :version "24.3"
17131 :type '(choice
17132 (const :tag "Use the image width" t)
17133 (integer :tag "Use a number of pixels")
17134 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17135 (const :tag "Use #+ATTR* or don't resize" nil)))
17137 (defcustom org-agenda-inhibit-startup t
17138 "Inhibit startup when preparing agenda buffers.
17139 When this variable is `t' (the default), the initialization of
17140 the Org agenda buffers is inhibited: e.g. the visibility state
17141 is not set, the tables are not re-aligned, etc."
17142 :type 'boolean
17143 :version "24.3"
17144 :group 'org-agenda)
17146 (defun org-duration-string-to-minutes (s &optional output-to-string)
17147 "Convert a duration string S to minutes.
17149 A bare number is interpreted as minutes, modifiers can be set by
17150 customizing `org-effort-durations' (which see).
17152 Entries containing a colon are interpreted as H:MM by
17153 `org-hh:mm-string-to-minutes'."
17154 (let ((result 0)
17155 (re (concat "\\([0-9.]+\\) *\\("
17156 (regexp-opt (mapcar 'car org-effort-durations))
17157 "\\)")))
17158 (while (string-match re s)
17159 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17160 (string-to-number (match-string 1 s))))
17161 (setq s (replace-match "" nil t s)))
17162 (setq result (floor result))
17163 (incf result (org-hh:mm-string-to-minutes s))
17164 (if output-to-string (number-to-string result) result)))
17166 ;;;; Files
17168 (defun org-save-all-org-buffers ()
17169 "Save all Org-mode buffers without user confirmation."
17170 (interactive)
17171 (message "Saving all Org-mode buffers...")
17172 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17173 (when (featurep 'org-id) (org-id-locations-save))
17174 (message "Saving all Org-mode buffers... done"))
17176 (defun org-revert-all-org-buffers ()
17177 "Revert all Org-mode buffers.
17178 Prompt for confirmation when there are unsaved changes.
17179 Be sure you know what you are doing before letting this function
17180 overwrite your changes.
17182 This function is useful in a setup where one tracks org files
17183 with a version control system, to revert on one machine after pulling
17184 changes from another. I believe the procedure must be like this:
17186 1. M-x org-save-all-org-buffers
17187 2. Pull changes from the other machine, resolve conflicts
17188 3. M-x org-revert-all-org-buffers"
17189 (interactive)
17190 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17191 (error "Abort"))
17192 (save-excursion
17193 (save-window-excursion
17194 (mapc
17195 (lambda (b)
17196 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17197 (with-current-buffer b buffer-file-name))
17198 (org-pop-to-buffer-same-window b)
17199 (revert-buffer t 'no-confirm)))
17200 (buffer-list))
17201 (when (and (featurep 'org-id) org-id-track-globally)
17202 (org-id-locations-load)))))
17204 ;;;; Agenda files
17206 ;;;###autoload
17207 (defun org-switchb (&optional arg)
17208 "Switch between Org buffers.
17209 With one prefix argument, restrict available buffers to files.
17210 With two prefix arguments, restrict available buffers to agenda files.
17212 Defaults to `iswitchb' for buffer name completion.
17213 Set `org-completion-use-ido' to make it use ido instead."
17214 (interactive "P")
17215 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17216 ((equal arg '(16)) (org-buffer-list 'agenda))
17217 (t (org-buffer-list))))
17218 (org-completion-use-iswitchb org-completion-use-iswitchb)
17219 (org-completion-use-ido org-completion-use-ido))
17220 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17221 (setq org-completion-use-iswitchb t))
17222 (org-pop-to-buffer-same-window
17223 (org-icompleting-read "Org buffer: "
17224 (mapcar 'list (mapcar 'buffer-name blist))
17225 nil t))))
17227 ;;; Define some older names previously used for this functionality
17228 ;;;###autoload
17229 (defalias 'org-ido-switchb 'org-switchb)
17230 ;;;###autoload
17231 (defalias 'org-iswitchb 'org-switchb)
17233 (defun org-buffer-list (&optional predicate exclude-tmp)
17234 "Return a list of Org buffers.
17235 PREDICATE can be `export', `files' or `agenda'.
17237 export restrict the list to Export buffers.
17238 files restrict the list to buffers visiting Org files.
17239 agenda restrict the list to buffers visiting agenda files.
17241 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17242 (let* ((bfn nil)
17243 (agenda-files (and (eq predicate 'agenda)
17244 (mapcar 'file-truename (org-agenda-files t))))
17245 (filter
17246 (cond
17247 ((eq predicate 'files)
17248 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17249 ((eq predicate 'export)
17250 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17251 ((eq predicate 'agenda)
17252 (lambda (b)
17253 (with-current-buffer b
17254 (and (derived-mode-p 'org-mode)
17255 (setq bfn (buffer-file-name b))
17256 (member (file-truename bfn) agenda-files)))))
17257 (t (lambda (b) (with-current-buffer b
17258 (or (derived-mode-p 'org-mode)
17259 (string-match "\*Org .*Export"
17260 (buffer-name b)))))))))
17261 (delq nil
17262 (mapcar
17263 (lambda(b)
17264 (if (and (funcall filter b)
17265 (or (not exclude-tmp)
17266 (not (string-match "tmp" (buffer-name b)))))
17268 nil))
17269 (buffer-list)))))
17271 (defun org-agenda-files (&optional unrestricted archives)
17272 "Get the list of agenda files.
17273 Optional UNRESTRICTED means return the full list even if a restriction
17274 is currently in place.
17275 When ARCHIVES is t, include all archive files that are really being
17276 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17277 `org-agenda-archives-mode' is t."
17278 (let ((files
17279 (cond
17280 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17281 ((stringp org-agenda-files) (org-read-agenda-file-list))
17282 ((listp org-agenda-files) org-agenda-files)
17283 (t (error "Invalid value of `org-agenda-files'")))))
17284 (setq files (apply 'append
17285 (mapcar (lambda (f)
17286 (if (file-directory-p f)
17287 (directory-files
17288 f t org-agenda-file-regexp)
17289 (list f)))
17290 files)))
17291 (when org-agenda-skip-unavailable-files
17292 (setq files (delq nil
17293 (mapcar (function
17294 (lambda (file)
17295 (and (file-readable-p file) file)))
17296 files))))
17297 (when (or (eq archives t)
17298 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17299 (setq files (org-add-archive-files files)))
17300 files))
17302 (defun org-agenda-file-p (&optional file)
17303 "Return non-nil, if FILE is an agenda file.
17304 If FILE is omitted, use the file associated with the current
17305 buffer."
17306 (member (or file (buffer-file-name))
17307 (org-agenda-files t)))
17309 (defun org-edit-agenda-file-list ()
17310 "Edit the list of agenda files.
17311 Depending on setup, this either uses customize to edit the variable
17312 `org-agenda-files', or it visits the file that is holding the list. In the
17313 latter case, the buffer is set up in a way that saving it automatically kills
17314 the buffer and restores the previous window configuration."
17315 (interactive)
17316 (if (stringp org-agenda-files)
17317 (let ((cw (current-window-configuration)))
17318 (find-file org-agenda-files)
17319 (org-set-local 'org-window-configuration cw)
17320 (org-add-hook 'after-save-hook
17321 (lambda ()
17322 (set-window-configuration
17323 (prog1 org-window-configuration
17324 (kill-buffer (current-buffer))))
17325 (org-install-agenda-files-menu)
17326 (message "New agenda file list installed"))
17327 nil 'local)
17328 (message "%s" (substitute-command-keys
17329 "Edit list and finish with \\[save-buffer]")))
17330 (customize-variable 'org-agenda-files)))
17332 (defun org-store-new-agenda-file-list (list)
17333 "Set new value for the agenda file list and save it correctly."
17334 (if (stringp org-agenda-files)
17335 (let ((fe (org-read-agenda-file-list t)) b u)
17336 (while (setq b (find-buffer-visiting org-agenda-files))
17337 (kill-buffer b))
17338 (with-temp-file org-agenda-files
17339 (insert
17340 (mapconcat
17341 (lambda (f) ;; Keep un-expanded entries.
17342 (if (setq u (assoc f fe))
17343 (cdr u)
17345 list "\n")
17346 "\n")))
17347 (let ((org-mode-hook nil) (org-inhibit-startup t)
17348 (org-insert-mode-line-in-empty-file nil))
17349 (setq org-agenda-files list)
17350 (customize-save-variable 'org-agenda-files org-agenda-files))))
17352 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17353 "Read the list of agenda files from a file.
17354 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17355 filenames, used by `org-store-new-agenda-file-list' to write back
17356 un-expanded file names."
17357 (when (file-directory-p org-agenda-files)
17358 (error "`org-agenda-files' cannot be a single directory"))
17359 (when (stringp org-agenda-files)
17360 (with-temp-buffer
17361 (insert-file-contents org-agenda-files)
17362 (mapcar
17363 (lambda (f)
17364 (let ((e (expand-file-name (substitute-in-file-name f)
17365 org-directory)))
17366 (if pair-with-expansion
17367 (cons e f)
17368 e)))
17369 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17371 ;;;###autoload
17372 (defun org-cycle-agenda-files ()
17373 "Cycle through the files in `org-agenda-files'.
17374 If the current buffer visits an agenda file, find the next one in the list.
17375 If the current buffer does not, find the first agenda file."
17376 (interactive)
17377 (let* ((fs (org-agenda-files t))
17378 (files (append fs (list (car fs))))
17379 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17380 file)
17381 (unless files (error "No agenda files"))
17382 (catch 'exit
17383 (while (setq file (pop files))
17384 (if (equal (file-truename file) tcf)
17385 (when (car files)
17386 (find-file (car files))
17387 (throw 'exit t))))
17388 (find-file (car fs)))
17389 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17391 (defun org-agenda-file-to-front (&optional to-end)
17392 "Move/add the current file to the top of the agenda file list.
17393 If the file is not present in the list, it is added to the front. If it is
17394 present, it is moved there. With optional argument TO-END, add/move to the
17395 end of the list."
17396 (interactive "P")
17397 (let ((org-agenda-skip-unavailable-files nil)
17398 (file-alist (mapcar (lambda (x)
17399 (cons (file-truename x) x))
17400 (org-agenda-files t)))
17401 (ctf (file-truename
17402 (or buffer-file-name
17403 (error "Please save the current buffer to a file"))))
17404 x had)
17405 (setq x (assoc ctf file-alist) had x)
17407 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17408 (if to-end
17409 (setq file-alist (append (delq x file-alist) (list x)))
17410 (setq file-alist (cons x (delq x file-alist))))
17411 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17412 (org-install-agenda-files-menu)
17413 (message "File %s to %s of agenda file list"
17414 (if had "moved" "added") (if to-end "end" "front"))))
17416 (defun org-remove-file (&optional file)
17417 "Remove current file from the list of files in variable `org-agenda-files'.
17418 These are the files which are being checked for agenda entries.
17419 Optional argument FILE means use this file instead of the current."
17420 (interactive)
17421 (let* ((org-agenda-skip-unavailable-files nil)
17422 (file (or file buffer-file-name
17423 (error "Current buffer does not visit a file")))
17424 (true-file (file-truename file))
17425 (afile (abbreviate-file-name file))
17426 (files (delq nil (mapcar
17427 (lambda (x)
17428 (if (equal true-file
17429 (file-truename x))
17430 nil x))
17431 (org-agenda-files t)))))
17432 (if (not (= (length files) (length (org-agenda-files t))))
17433 (progn
17434 (org-store-new-agenda-file-list files)
17435 (org-install-agenda-files-menu)
17436 (message "Removed file: %s" afile))
17437 (message "File was not in list: %s (not removed)" afile))))
17439 (defun org-file-menu-entry (file)
17440 (vector file (list 'find-file file) t))
17442 (defun org-check-agenda-file (file)
17443 "Make sure FILE exists. If not, ask user what to do."
17444 (when (not (file-exists-p file))
17445 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17446 (abbreviate-file-name file))
17447 (let ((r (downcase (read-char-exclusive))))
17448 (cond
17449 ((equal r ?r)
17450 (org-remove-file file)
17451 (throw 'nextfile t))
17452 (t (error "Abort"))))))
17454 (defun org-get-agenda-file-buffer (file)
17455 "Get a buffer visiting FILE. If the buffer needs to be created, add
17456 it to the list of buffers which might be released later."
17457 (let ((buf (org-find-base-buffer-visiting file)))
17458 (if buf
17459 buf ; just return it
17460 ;; Make a new buffer and remember it
17461 (setq buf (find-file-noselect file))
17462 (if buf (push buf org-agenda-new-buffers))
17463 buf)))
17465 (defun org-release-buffers (blist)
17466 "Release all buffers in list, asking the user for confirmation when needed.
17467 When a buffer is unmodified, it is just killed. When modified, it is saved
17468 \(if the user agrees) and then killed."
17469 (let (buf file)
17470 (while (setq buf (pop blist))
17471 (setq file (buffer-file-name buf))
17472 (when (and (buffer-modified-p buf)
17473 file
17474 (y-or-n-p (format "Save file %s? " file)))
17475 (with-current-buffer buf (save-buffer)))
17476 (kill-buffer buf))))
17478 (defun org-agenda-prepare-buffers (files)
17479 "Create buffers for all agenda files, protect archived trees and comments."
17480 (interactive)
17481 (let ((pa '(:org-archived t))
17482 (pc '(:org-comment t))
17483 (pall '(:org-archived t :org-comment t))
17484 (inhibit-read-only t)
17485 (org-inhibit-startup org-agenda-inhibit-startup)
17486 (rea (concat ":" org-archive-tag ":"))
17487 file re)
17488 (save-excursion
17489 (save-restriction
17490 (while (setq file (pop files))
17491 (catch 'nextfile
17492 (if (bufferp file)
17493 (set-buffer file)
17494 (org-check-agenda-file file)
17495 (set-buffer (org-get-agenda-file-buffer file)))
17496 (widen)
17497 (org-unmodified
17498 (org-refresh-category-properties)
17499 (org-refresh-properties org-effort-property 'org-effort)
17500 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17501 (setq org-todo-keywords-for-agenda
17502 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17503 (setq org-done-keywords-for-agenda
17504 (append org-done-keywords-for-agenda org-done-keywords))
17505 (setq org-todo-keyword-alist-for-agenda
17506 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17507 (setq org-drawers-for-agenda
17508 (append org-drawers-for-agenda org-drawers))
17509 (setq org-tag-alist-for-agenda
17510 (append org-tag-alist-for-agenda org-tag-alist))
17512 (save-excursion
17513 (remove-text-properties (point-min) (point-max) pall)
17514 (when org-agenda-skip-archived-trees
17515 (goto-char (point-min))
17516 (while (re-search-forward rea nil t)
17517 (if (org-at-heading-p t)
17518 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17519 (goto-char (point-min))
17520 (setq re (format org-heading-keyword-regexp-format
17521 org-comment-string))
17522 (while (re-search-forward re nil t)
17523 (add-text-properties
17524 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17525 (setq org-todo-keywords-for-agenda
17526 (org-uniquify org-todo-keywords-for-agenda))
17527 (setq org-todo-keyword-alist-for-agenda
17528 (org-uniquify org-todo-keyword-alist-for-agenda)
17529 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17533 ;;;; CDLaTeX minor mode
17535 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17536 "Keymap for the minor `org-cdlatex-mode'.")
17538 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17539 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17540 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17541 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17542 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17544 (defvar org-cdlatex-texmathp-advice-is-done nil
17545 "Flag remembering if we have applied the advice to texmathp already.")
17547 (define-minor-mode org-cdlatex-mode
17548 "Toggle the minor `org-cdlatex-mode'.
17549 This mode supports entering LaTeX environment and math in LaTeX fragments
17550 in Org-mode.
17551 \\{org-cdlatex-mode-map}"
17552 nil " OCDL" nil
17553 (when org-cdlatex-mode
17554 (require 'cdlatex)
17555 (run-hooks 'cdlatex-mode-hook)
17556 (cdlatex-compute-tables))
17557 (unless org-cdlatex-texmathp-advice-is-done
17558 (setq org-cdlatex-texmathp-advice-is-done t)
17559 (defadvice texmathp (around org-math-always-on activate)
17560 "Always return t in org-mode buffers.
17561 This is because we want to insert math symbols without dollars even outside
17562 the LaTeX math segments. If Orgmode thinks that point is actually inside
17563 an embedded LaTeX fragment, let texmathp do its job.
17564 \\[org-cdlatex-mode-map]"
17565 (interactive)
17566 (let (p)
17567 (cond
17568 ((not (derived-mode-p 'org-mode)) ad-do-it)
17569 ((eq this-command 'cdlatex-math-symbol)
17570 (setq ad-return-value t
17571 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17573 (let ((p (org-inside-LaTeX-fragment-p)))
17574 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17575 (setq ad-return-value t
17576 texmathp-why '("Org-mode embedded math" . 0))
17577 (if p ad-do-it)))))))))
17579 (defun turn-on-org-cdlatex ()
17580 "Unconditionally turn on `org-cdlatex-mode'."
17581 (org-cdlatex-mode 1))
17583 (defun org-try-cdlatex-tab ()
17584 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17585 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17586 - inside a LaTeX fragment, or
17587 - after the first word in a line, where an abbreviation expansion could
17588 insert a LaTeX environment."
17589 (when org-cdlatex-mode
17590 (cond
17591 ;; Before any word on the line: No expansion possible.
17592 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17593 ;; Just after first word on the line: Expand it. Make sure it
17594 ;; cannot happen on headlines, though.
17595 ((save-excursion
17596 (skip-chars-backward "a-zA-Z0-9*")
17597 (skip-chars-backward " \t")
17598 (and (bolp) (not (org-at-heading-p))))
17599 (cdlatex-tab) t)
17600 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17602 (defun org-cdlatex-underscore-caret (&optional arg)
17603 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17604 Revert to the normal definition outside of these fragments."
17605 (interactive "P")
17606 (if (org-inside-LaTeX-fragment-p)
17607 (call-interactively 'cdlatex-sub-superscript)
17608 (let (org-cdlatex-mode)
17609 (call-interactively (key-binding (vector last-input-event))))))
17611 (defun org-cdlatex-math-modify (&optional arg)
17612 "Execute `cdlatex-math-modify' in LaTeX fragments.
17613 Revert to the normal definition outside of these fragments."
17614 (interactive "P")
17615 (if (org-inside-LaTeX-fragment-p)
17616 (call-interactively 'cdlatex-math-modify)
17617 (let (org-cdlatex-mode)
17618 (call-interactively (key-binding (vector last-input-event))))))
17622 ;;;; LaTeX fragments
17624 (defvar org-latex-regexps
17625 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17626 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17627 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17628 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17629 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17630 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17631 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17632 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17633 "Regular expressions for matching embedded LaTeX.")
17635 (defun org-inside-LaTeX-fragment-p ()
17636 "Test if point is inside a LaTeX fragment.
17637 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17638 sequence appearing also before point.
17639 Even though the matchers for math are configurable, this function assumes
17640 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17641 delimiters are skipped when they have been removed by customization.
17642 The return value is nil, or a cons cell with the delimiter and the
17643 position of this delimiter.
17645 This function does a reasonably good job, but can locally be fooled by
17646 for example currency specifications. For example it will assume being in
17647 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17648 fragments that are properly closed, but during editing, we have to live
17649 with the uncertainty caused by missing closing delimiters. This function
17650 looks only before point, not after."
17651 (catch 'exit
17652 (let ((pos (point))
17653 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17654 (lim (progn
17655 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17656 (point)))
17657 dd-on str (start 0) m re)
17658 (goto-char pos)
17659 (when dodollar
17660 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17661 re (nth 1 (assoc "$" org-latex-regexps)))
17662 (while (string-match re str start)
17663 (cond
17664 ((= (match-end 0) (length str))
17665 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17666 ((= (match-end 0) (- (length str) 5))
17667 (throw 'exit nil))
17668 (t (setq start (match-end 0))))))
17669 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17670 (goto-char pos)
17671 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17672 (and (match-beginning 2) (throw 'exit nil))
17673 ;; count $$
17674 (while (re-search-backward "\\$\\$" lim t)
17675 (setq dd-on (not dd-on)))
17676 (goto-char pos)
17677 (if dd-on (cons "$$" m))))))
17679 (defun org-inside-latex-macro-p ()
17680 "Is point inside a LaTeX macro or its arguments?"
17681 (save-match-data
17682 (org-in-regexp
17683 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17685 (defvar org-latex-fragment-image-overlays nil
17686 "List of overlays carrying the images of latex fragments.")
17687 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17689 (defun org-remove-latex-fragment-image-overlays ()
17690 "Remove all overlays with LaTeX fragment images in current buffer."
17691 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17692 (setq org-latex-fragment-image-overlays nil))
17694 (defun org-preview-latex-fragment (&optional subtree)
17695 "Preview the LaTeX fragment at point, or all locally or globally.
17696 If the cursor is in a LaTeX fragment, create the image and overlay
17697 it over the source code. If there is no fragment at point, display
17698 all fragments in the current text, from one headline to the next. With
17699 prefix SUBTREE, display all fragments in the current subtree. With a
17700 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17701 the cursor is before the first headline,
17702 display all fragments in the buffer.
17703 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17704 (interactive "P")
17705 (unless buffer-file-name
17706 (error "Can't preview LaTeX fragment in a non-file buffer"))
17707 (org-remove-latex-fragment-image-overlays)
17708 (save-excursion
17709 (save-restriction
17710 (let (beg end at msg)
17711 (cond
17712 ((or (equal subtree '(16))
17713 (not (save-excursion
17714 (re-search-backward org-outline-regexp-bol nil t))))
17715 (setq beg (point-min) end (point-max)
17716 msg "Creating images for buffer...%s"))
17717 ((equal subtree '(4))
17718 (org-back-to-heading)
17719 (setq beg (point) end (org-end-of-subtree t)
17720 msg "Creating images for subtree...%s"))
17722 (if (setq at (org-inside-LaTeX-fragment-p))
17723 (goto-char (max (point-min) (- (cdr at) 2)))
17724 (org-back-to-heading))
17725 (setq beg (point) end (progn (outline-next-heading) (point))
17726 msg (if at "Creating image...%s"
17727 "Creating images for entry...%s"))))
17728 (message msg "")
17729 (narrow-to-region beg end)
17730 (goto-char beg)
17731 (org-format-latex
17732 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17733 (file-name-nondirectory
17734 buffer-file-name)))
17735 default-directory 'overlays msg at 'forbuffer
17736 org-latex-create-formula-image-program)
17737 (message msg "done. Use `C-c C-c' to remove images.")))))
17739 (defun org-format-latex (prefix &optional dir overlays msg at
17740 forbuffer processing-type)
17741 "Replace LaTeX fragments with links to an image, and produce images.
17742 Some of the options can be changed using the variable
17743 `org-format-latex-options'."
17744 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17745 (let* ((prefixnodir (file-name-nondirectory prefix))
17746 (absprefix (expand-file-name prefix dir))
17747 (todir (file-name-directory absprefix))
17748 (opt org-format-latex-options)
17749 (optnew org-format-latex-options)
17750 (matchers (plist-get opt :matchers))
17751 (re-list org-latex-regexps)
17752 (cnt 0) txt hash link beg end re e checkdir
17753 string
17754 m n block-type block linkfile movefile ov)
17755 ;; Check the different regular expressions
17756 (while (setq e (pop re-list))
17757 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17758 block (if block-type "\n\n" ""))
17759 (when (member m matchers)
17760 (goto-char (point-min))
17761 (while (re-search-forward re nil t)
17762 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17763 (or (not overlays)
17764 (not (eq (get-char-property (match-beginning n)
17765 'org-overlay-type)
17766 'org-latex-overlay))))
17767 (cond
17768 ((eq processing-type 'verbatim))
17769 ((eq processing-type 'mathjax)
17770 ;; Prepare for MathJax processing.
17771 (setq string (match-string n))
17772 (when (member m '("$" "$1"))
17773 (save-excursion
17774 (delete-region (match-beginning n) (match-end n))
17775 (goto-char (match-beginning n))
17776 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17777 ((or (eq processing-type 'dvipng)
17778 (eq processing-type 'imagemagick))
17779 ;; Process to an image.
17780 (setq txt (match-string n)
17781 beg (match-beginning n) end (match-end n)
17782 cnt (1+ cnt))
17783 (let ((face (face-at-point))
17784 (fg (plist-get opt :foreground))
17785 (bg (plist-get opt :background))
17786 ;; Ensure full list is printed.
17787 print-length print-level)
17788 (when forbuffer
17789 ;; Get the colors from the face at point.
17790 (goto-char beg)
17791 (when (eq fg 'auto)
17792 (setq fg (face-attribute face :foreground nil 'default)))
17793 (when (eq bg 'auto)
17794 (setq bg (face-attribute face :background nil 'default)))
17795 (setq optnew (copy-sequence opt))
17796 (plist-put optnew :foreground fg)
17797 (plist-put optnew :background bg))
17798 (setq hash (sha1 (prin1-to-string
17799 (list org-format-latex-header
17800 org-latex-default-packages-alist
17801 org-latex-packages-alist
17802 org-format-latex-options
17803 forbuffer txt fg bg)))
17804 linkfile (format "%s_%s.png" prefix hash)
17805 movefile (format "%s_%s.png" absprefix hash)))
17806 (setq link (concat block "[[file:" linkfile "]]" block))
17807 (if msg (message msg cnt))
17808 (goto-char beg)
17809 (unless checkdir ; Ensure the directory exists.
17810 (setq checkdir t)
17811 (or (file-directory-p todir) (make-directory todir t)))
17812 (unless (file-exists-p movefile)
17813 (org-create-formula-image
17814 txt movefile optnew forbuffer processing-type))
17815 (if overlays
17816 (progn
17817 (mapc (lambda (o)
17818 (if (eq (overlay-get o 'org-overlay-type)
17819 'org-latex-overlay)
17820 (delete-overlay o)))
17821 (overlays-in beg end))
17822 (setq ov (make-overlay beg end))
17823 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17824 (if (featurep 'xemacs)
17825 (progn
17826 (overlay-put ov 'invisible t)
17827 (overlay-put
17828 ov 'end-glyph
17829 (make-glyph (vector 'png :file movefile))))
17830 (overlay-put
17831 ov 'display
17832 (list 'image :type 'png :file movefile :ascent 'center)))
17833 (push ov org-latex-fragment-image-overlays)
17834 (goto-char end))
17835 (delete-region beg end)
17836 (insert (org-add-props link
17837 (list 'org-latex-src
17838 (replace-regexp-in-string
17839 "\"" "" txt)
17840 'org-latex-src-embed-type
17841 (if block-type 'paragraph 'character))))))
17842 ((eq processing-type 'mathml)
17843 ;; Process to MathML
17844 (unless (save-match-data (org-format-latex-mathml-available-p))
17845 (error "LaTeX to MathML converter not configured"))
17846 (setq txt (match-string n)
17847 beg (match-beginning n) end (match-end n)
17848 cnt (1+ cnt))
17849 (if msg (message msg cnt))
17850 (goto-char beg)
17851 (delete-region beg end)
17852 (insert (org-format-latex-as-mathml
17853 txt block-type prefix dir)))
17855 (error "Unknown conversion type %s for latex fragments"
17856 processing-type)))))))))
17858 (defun org-create-math-formula (latex-frag &optional mathml-file)
17859 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17860 Use `org-latex-to-mathml-convert-command'. If the conversion is
17861 sucessful, return the portion between \"<math...> </math>\"
17862 elements otherwise return nil. When MATHML-FILE is specified,
17863 write the results in to that file. When invoked as an
17864 interactive command, prompt for LATEX-FRAG, with initial value
17865 set to the current active region and echo the results for user
17866 inspection."
17867 (interactive (list (let ((frag (when (org-region-active-p)
17868 (buffer-substring-no-properties
17869 (region-beginning) (region-end)))))
17870 (read-string "LaTeX Fragment: " frag nil frag))))
17871 (unless latex-frag (error "Invalid latex-frag"))
17872 (let* ((tmp-in-file (file-relative-name
17873 (make-temp-name (expand-file-name "ltxmathml-in"))))
17874 (ignore (write-region latex-frag nil tmp-in-file))
17875 (tmp-out-file (file-relative-name
17876 (make-temp-name (expand-file-name "ltxmathml-out"))))
17877 (cmd (format-spec
17878 org-latex-to-mathml-convert-command
17879 `((?j . ,(shell-quote-argument
17880 (expand-file-name org-latex-to-mathml-jar-file)))
17881 (?I . ,(shell-quote-argument tmp-in-file))
17882 (?o . ,(shell-quote-argument tmp-out-file)))))
17883 mathml shell-command-output)
17884 (when (org-called-interactively-p 'any)
17885 (unless (org-format-latex-mathml-available-p)
17886 (error "LaTeX to MathML converter not configured")))
17887 (message "Running %s" cmd)
17888 (setq shell-command-output (shell-command-to-string cmd))
17889 (setq mathml
17890 (when (file-readable-p tmp-out-file)
17891 (with-current-buffer (find-file-noselect tmp-out-file t)
17892 (goto-char (point-min))
17893 (when (re-search-forward
17894 (concat
17895 (regexp-quote
17896 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17897 "\\(.\\|\n\\)*"
17898 (regexp-quote "</math>")) nil t)
17899 (prog1 (match-string 0) (kill-buffer))))))
17900 (cond
17901 (mathml
17902 (setq mathml
17903 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17904 (when mathml-file
17905 (write-region mathml nil mathml-file))
17906 (when (org-called-interactively-p 'any)
17907 (message mathml)))
17908 ((message "LaTeX to MathML conversion failed")
17909 (message shell-command-output)))
17910 (delete-file tmp-in-file)
17911 (when (file-exists-p tmp-out-file)
17912 (delete-file tmp-out-file))
17913 mathml))
17915 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17916 prefix &optional dir)
17917 "Use `org-create-math-formula' but check local cache first."
17918 (let* ((absprefix (expand-file-name prefix dir))
17919 (print-length nil) (print-level nil)
17920 (formula-id (concat
17921 "formula-"
17922 (sha1
17923 (prin1-to-string
17924 (list latex-frag
17925 org-latex-to-mathml-convert-command)))))
17926 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17927 (formula-cache-dir (file-name-directory formula-cache)))
17929 (unless (file-directory-p formula-cache-dir)
17930 (make-directory formula-cache-dir t))
17932 (unless (file-exists-p formula-cache)
17933 (org-create-math-formula latex-frag formula-cache))
17935 (if (file-exists-p formula-cache)
17936 ;; Successful conversion. Return the link to MathML file.
17937 (org-add-props
17938 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17939 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17940 'org-latex-src-embed-type (if latex-frag-type
17941 'paragraph 'character)))
17942 ;; Failed conversion. Return the LaTeX fragment verbatim
17943 latex-frag)))
17945 (defun org-create-formula-image (string tofile options buffer &optional type)
17946 "Create an image from LaTeX source using dvipng or convert.
17947 This function calls either `org-create-formula-image-with-dvipng'
17948 or `org-create-formula-image-with-imagemagick' depending on the
17949 value of `org-latex-create-formula-image-program' or on the value
17950 of the optional TYPE variable.
17952 Note: ultimately these two function should be combined as they
17953 share a good deal of logic."
17954 (org-check-external-command
17955 "latex" "needed to convert LaTeX fragments to images")
17956 (funcall
17957 (case (or type org-latex-create-formula-image-program)
17958 ('dvipng
17959 (org-check-external-command
17960 "dvipng" "needed to convert LaTeX fragments to images")
17961 #'org-create-formula-image-with-dvipng)
17962 ('imagemagick
17963 (org-check-external-command
17964 "convert" "you need to install imagemagick")
17965 #'org-create-formula-image-with-imagemagick)
17966 (t (error
17967 "invalid value of `org-latex-create-formula-image-program'")))
17968 string tofile options buffer))
17970 ;; This function borrows from Ganesh Swami's latex2png.el
17971 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17972 "This calls dvipng."
17973 (let* ((tmpdir (if (featurep 'xemacs)
17974 (temp-directory)
17975 temporary-file-directory))
17976 (texfilebase (make-temp-name
17977 (expand-file-name "orgtex" tmpdir)))
17978 (texfile (concat texfilebase ".tex"))
17979 (dvifile (concat texfilebase ".dvi"))
17980 (pngfile (concat texfilebase ".png"))
17981 (fnh (if (featurep 'xemacs)
17982 (font-height (face-font 'default))
17983 (face-attribute 'default :height nil)))
17984 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17985 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17986 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17987 "Black"))
17988 (bg (or (plist-get options (if buffer :background :html-background))
17989 "Transparent")))
17990 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17991 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17992 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17993 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17994 (with-temp-file texfile
17995 (require 'ox-latex)
17996 (insert (org-latex-guess-inputenc
17997 (org-splice-latex-header
17998 org-format-latex-header
17999 org-latex-default-packages-alist
18000 org-latex-packages-alist t)))
18001 (insert "\n\\begin{document}\n" string "\n\\end{document}\n"))
18002 (let ((dir default-directory))
18003 (condition-case nil
18004 (progn
18005 (cd tmpdir)
18006 (call-process "latex" nil nil nil texfile))
18007 (error nil))
18008 (cd dir))
18009 (if (not (file-exists-p dvifile))
18010 (progn (message "Failed to create dvi file from %s" texfile) nil)
18011 (condition-case nil
18012 (if (featurep 'xemacs)
18013 (call-process "dvipng" nil nil nil
18014 "-fg" fg "-bg" bg
18015 "-T" "tight"
18016 "-o" pngfile
18017 dvifile)
18018 (call-process "dvipng" nil nil nil
18019 "-fg" fg "-bg" bg
18020 "-D" dpi
18021 ;;"-x" scale "-y" scale
18022 "-T" "tight"
18023 "-o" pngfile
18024 dvifile))
18025 (error nil))
18026 (if (not (file-exists-p pngfile))
18027 (if org-format-latex-signal-error
18028 (error "Failed to create png file from %s" texfile)
18029 (message "Failed to create png file from %s" texfile)
18030 nil)
18031 ;; Use the requested file name and clean up
18032 (copy-file pngfile tofile 'replace)
18033 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18034 (if (file-exists-p (concat texfilebase e))
18035 (delete-file (concat texfilebase e))))
18036 pngfile))))
18038 (defvar org-latex-pdf-process) ; From ox-latex.el
18039 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18040 "This calls convert, which is included into imagemagick."
18041 (let* ((tmpdir (if (featurep 'xemacs)
18042 (temp-directory)
18043 temporary-file-directory))
18044 (texfilebase (make-temp-name
18045 (expand-file-name "orgtex" tmpdir)))
18046 (texfile (concat texfilebase ".tex"))
18047 (pdffile (concat texfilebase ".pdf"))
18048 (pngfile (concat texfilebase ".png"))
18049 (fnh (if (featurep 'xemacs)
18050 (font-height (face-font 'default))
18051 (face-attribute 'default :height nil)))
18052 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18053 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18054 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18055 "black"))
18056 (bg (or (plist-get options (if buffer :background :html-background))
18057 "white")))
18058 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18059 (setq fg (org-latex-color-format fg)))
18060 (if (eq bg 'default) (setq bg (org-latex-color :background))
18061 (setq bg (org-latex-color-format
18062 (if (string= bg "Transparent") "white" bg))))
18063 (with-temp-file texfile
18064 (require 'ox-latex)
18065 (insert (org-latex-guess-inputenc
18066 (org-splice-latex-header
18067 org-format-latex-header
18068 org-latex-default-packages-alist
18069 org-latex-packages-alist t)))
18070 (insert "\n\\begin{document}\n"
18071 "\\definecolor{fg}{rgb}{" fg "}\n"
18072 "\\definecolor{bg}{rgb}{" bg "}\n"
18073 "\n\\pagecolor{bg}\n"
18074 "\n{\\color{fg}\n"
18075 string
18076 "\n}\n"
18077 "\n\\end{document}\n"))
18078 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18079 (condition-case nil
18080 (progn
18081 (cd tmpdir)
18082 (setq cmds org-latex-pdf-process)
18083 (while cmds
18084 (setq latex-frags-cmds (pop cmds))
18085 (if (listp latex-frags-cmds)
18086 (setq cmds nil)
18087 (setq latex-frags-cmds (list (car org-latex-pdf-process)))))
18088 (while latex-frags-cmds
18089 (setq cmd (pop latex-frags-cmds))
18090 (while (string-match "%b" cmd)
18091 (setq cmd (replace-match
18092 (save-match-data
18093 (shell-quote-argument texfile))
18094 t t cmd)))
18095 (while (string-match "%f" cmd)
18096 (setq cmd (replace-match
18097 (save-match-data
18098 (shell-quote-argument
18099 (file-name-nondirectory texfile)))
18100 t t cmd)))
18101 (while (string-match "%o" cmd)
18102 (setq cmd (replace-match
18103 (save-match-data
18104 (shell-quote-argument
18105 (file-name-directory texfile)))
18106 t t cmd)))
18107 (setq cmd (split-string cmd))
18108 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18109 (error nil))
18110 (cd dir))
18111 (if (not (file-exists-p pdffile))
18112 (progn (message "Failed to create pdf file from %s" texfile) nil)
18113 (condition-case nil
18114 (if (featurep 'xemacs)
18115 (call-process "convert" nil nil nil
18116 "-density" "96"
18117 "-trim"
18118 "-antialias"
18119 pdffile
18120 "-quality" "100"
18121 ;; "-sharpen" "0x1.0"
18122 pngfile)
18123 (call-process "convert" nil nil nil
18124 "-density" dpi
18125 "-trim"
18126 "-antialias"
18127 pdffile
18128 "-quality" "100"
18129 ;; "-sharpen" "0x1.0"
18130 pngfile))
18131 (error nil))
18132 (if (not (file-exists-p pngfile))
18133 (if org-format-latex-signal-error
18134 (error "Failed to create png file from %s" texfile)
18135 (message "Failed to create png file from %s" texfile)
18136 nil)
18137 ;; Use the requested file name and clean up
18138 (copy-file pngfile tofile 'replace)
18139 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18140 (if (file-exists-p (concat texfilebase e))
18141 (delete-file (concat texfilebase e))))
18142 pngfile))))
18144 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18145 "Fill a LaTeX header template TPL.
18146 In the template, the following place holders will be recognized:
18148 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18149 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18150 [PACKAGES] \\usepackage statements for PKG
18151 [NO-PACKAGES] do not include PKG
18152 [EXTRA] the string EXTRA
18153 [NO-EXTRA] do not include EXTRA
18155 For backward compatibility, if both the positive and the negative place
18156 holder is missing, the positive one (without the \"NO-\") will be
18157 assumed to be present at the end of the template.
18158 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18159 EXTRA is a string.
18160 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18161 (let (rpl (end ""))
18162 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18163 (setq rpl (if (or (match-end 1) (not def-pkg))
18164 "" (org-latex-packages-to-string def-pkg snippets-p t))
18165 tpl (replace-match rpl t t tpl))
18166 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18168 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18169 (setq rpl (if (or (match-end 1) (not pkg))
18170 "" (org-latex-packages-to-string pkg snippets-p t))
18171 tpl (replace-match rpl t t tpl))
18172 (if pkg (setq end
18173 (concat end "\n"
18174 (org-latex-packages-to-string pkg snippets-p)))))
18176 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18177 (setq rpl (if (or (match-end 1) (not extra))
18178 "" (concat extra "\n"))
18179 tpl (replace-match rpl t t tpl))
18180 (if (and extra (string-match "\\S-" extra))
18181 (setq end (concat end "\n" extra))))
18183 (if (string-match "\\S-" end)
18184 (concat tpl "\n" end)
18185 tpl)))
18187 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18188 "Turn an alist of packages into a string with the \\usepackage macros."
18189 (setq pkg (mapconcat (lambda(p)
18190 (cond
18191 ((stringp p) p)
18192 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18193 (format "%% Package %s omitted" (cadr p)))
18194 ((equal "" (car p))
18195 (format "\\usepackage{%s}" (cadr p)))
18197 (format "\\usepackage[%s]{%s}"
18198 (car p) (cadr p)))))
18200 "\n"))
18201 (if newline (concat pkg "\n") pkg))
18203 (defun org-dvipng-color (attr)
18204 "Return a RGB color specification for dvipng."
18205 (apply 'format "rgb %s %s %s"
18206 (mapcar 'org-normalize-color
18207 (if (featurep 'xemacs)
18208 (color-rgb-components
18209 (face-property 'default
18210 (cond ((eq attr :foreground) 'foreground)
18211 ((eq attr :background) 'background))))
18212 (color-values (face-attribute 'default attr nil))))))
18214 (defun org-dvipng-color-format (color-name)
18215 "Convert COLOR-NAME to a RGB color value for dvipng."
18216 (apply 'format "rgb %s %s %s"
18217 (mapcar 'org-normalize-color
18218 (color-values color-name))))
18220 (defun org-latex-color (attr)
18221 "Return a RGB color for the LaTeX color package."
18222 (apply 'format "%s,%s,%s"
18223 (mapcar 'org-normalize-color
18224 (if (featurep 'xemacs)
18225 (color-rgb-components
18226 (face-property 'default
18227 (cond ((eq attr :foreground) 'foreground)
18228 ((eq attr :background) 'background))))
18229 (color-values (face-attribute 'default attr nil))))))
18231 (defun org-latex-color-format (color-name)
18232 "Convert COLOR-NAME to a RGB color value."
18233 (apply 'format "%s,%s,%s"
18234 (mapcar 'org-normalize-color
18235 (color-values color-name))))
18237 (defun org-normalize-color (value)
18238 "Return string to be used as color value for an RGB component."
18239 (format "%g" (/ value 65535.0)))
18243 ;; Image display
18245 (defvar org-inline-image-overlays nil)
18246 (make-variable-buffer-local 'org-inline-image-overlays)
18248 (defun org-toggle-inline-images (&optional include-linked)
18249 "Toggle the display of inline images.
18250 INCLUDE-LINKED is passed to `org-display-inline-images'."
18251 (interactive "P")
18252 (if org-inline-image-overlays
18253 (progn
18254 (org-remove-inline-images)
18255 (message "Inline image display turned off"))
18256 (org-display-inline-images include-linked)
18257 (if (and (org-called-interactively-p)
18258 org-inline-image-overlays)
18259 (message "%d images displayed inline"
18260 (length org-inline-image-overlays))
18261 (message "No images to display inline"))))
18263 (defun org-redisplay-inline-images ()
18264 "Refresh the display of inline images."
18265 (interactive)
18266 (if (not org-inline-image-overlays)
18267 (org-toggle-inline-images)
18268 (org-toggle-inline-images)
18269 (org-toggle-inline-images)))
18271 (defun org-display-inline-images (&optional include-linked refresh beg end)
18272 "Display inline images.
18273 Normally only links without a description part are inlined, because this
18274 is how it will work for export. When INCLUDE-LINKED is set, also links
18275 with a description part will be inlined. This can be nice for a quick
18276 look at those images, but it does not reflect what exported files will look
18277 like.
18278 When REFRESH is set, refresh existing images between BEG and END.
18279 This will create new image displays only if necessary.
18280 BEG and END default to the buffer boundaries."
18281 (interactive "P")
18282 (unless refresh
18283 (org-remove-inline-images)
18284 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18285 (save-excursion
18286 (save-restriction
18287 (widen)
18288 (setq beg (or beg (point-min)) end (or end (point-max)))
18289 (goto-char beg)
18290 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18291 (substring (org-image-file-name-regexp) 0 -2)
18292 "\\)\\]" (if include-linked "" "\\]")))
18293 old file ov img type attrwidth width)
18294 (while (re-search-forward re end t)
18295 (setq old (get-char-property-and-overlay (match-beginning 1)
18296 'org-image-overlay)
18297 file (expand-file-name
18298 (concat (or (match-string 3) "") (match-string 4))))
18299 (when (image-type-available-p 'imagemagick)
18300 (setq attrwidth (if (or (listp org-image-actual-width)
18301 (null org-image-actual-width))
18302 (save-excursion
18303 (save-match-data
18304 (when (re-search-backward
18305 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18306 (save-excursion
18307 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18308 (string-to-number (match-string 1))))))
18309 width (cond ((eq org-image-actual-width t) nil)
18310 ((null org-image-actual-width) attrwidth)
18311 ((numberp org-image-actual-width)
18312 org-image-actual-width)
18313 ((listp org-image-actual-width)
18314 (or attrwidth (car org-image-actual-width))))
18315 type (if width 'imagemagick)))
18316 (when (file-exists-p file)
18317 (if (and (car-safe old) refresh)
18318 (image-refresh (overlay-get (cdr old) 'display))
18319 (setq img (save-match-data (create-image file type nil :width width)))
18320 (when img
18321 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18322 (overlay-put ov 'display img)
18323 (overlay-put ov 'face 'default)
18324 (overlay-put ov 'org-image-overlay t)
18325 (overlay-put ov 'modification-hooks
18326 (list 'org-display-inline-remove-overlay))
18327 (push ov org-inline-image-overlays)))))))))
18329 (define-obsolete-function-alias
18330 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18332 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18333 "Remove inline-display overlay if a corresponding region is modified."
18334 (let ((inhibit-modification-hooks t))
18335 (when (and ov after)
18336 (delete ov org-inline-image-overlays)
18337 (delete-overlay ov))))
18339 (defun org-remove-inline-images ()
18340 "Remove inline display of images."
18341 (interactive)
18342 (mapc 'delete-overlay org-inline-image-overlays)
18343 (setq org-inline-image-overlays nil))
18345 ;;;; Key bindings
18347 ;; Outline functions from `outline-mode-prefix-map'
18348 ;; that can be remapped in Org:
18349 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18350 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18351 (define-key org-mode-map [remap outline-forward-same-level]
18352 'org-forward-heading-same-level)
18353 (define-key org-mode-map [remap outline-backward-same-level]
18354 'org-backward-heading-same-level)
18355 (define-key org-mode-map [remap show-branches]
18356 'org-kill-note-or-show-branches)
18357 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18358 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18359 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18361 ;; Outline functions from `outline-mode-prefix-map' that can not
18362 ;; be remapped in Org:
18364 ;; - the column "key binding" shows whether the Outline function is still
18365 ;; available in Org mode on the same key that it has been bound to in
18366 ;; Outline mode:
18367 ;; - "overridden": key used for a different functionality in Org mode
18368 ;; - else: key still bound to the same Outline function in Org mode
18370 ;; | Outline function | key binding | Org replacement |
18371 ;; |------------------------------------+-------------+-----------------------|
18372 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18373 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18374 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18375 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18376 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18377 ;; | `show-entry' | overridden | no replacement |
18378 ;; | `show-children' | `C-c C-i' | visibility cycling |
18379 ;; | `show-branches' | `C-c C-k' | still same function |
18380 ;; | `show-subtree' | overridden | visibility cycling |
18381 ;; | `show-all' | overridden | no replacement |
18382 ;; | `hide-subtree' | overridden | visibility cycling |
18383 ;; | `hide-body' | overridden | no replacement |
18384 ;; | `hide-entry' | overridden | visibility cycling |
18385 ;; | `hide-leaves' | overridden | no replacement |
18386 ;; | `hide-sublevels' | overridden | no replacement |
18387 ;; | `hide-other' | overridden | no replacement |
18389 ;; Make `C-c C-x' a prefix key
18390 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18392 ;; TAB key with modifiers
18393 (org-defkey org-mode-map "\C-i" 'org-cycle)
18394 (org-defkey org-mode-map [(tab)] 'org-cycle)
18395 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18396 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18397 ;; The following line is necessary under Suse GNU/Linux
18398 (unless (featurep 'xemacs)
18399 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18400 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18401 (define-key org-mode-map [backtab] 'org-shifttab)
18403 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18404 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18405 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18407 ;; Cursor keys with modifiers
18408 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18409 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18410 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18411 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18413 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18414 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18415 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18416 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18418 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18419 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18420 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18421 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18423 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18424 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18425 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18426 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18428 ;; Babel keys
18429 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18430 (mapc (lambda (pair)
18431 (define-key org-babel-map (car pair) (cdr pair)))
18432 org-babel-key-bindings)
18434 ;;; Extra keys for tty access.
18435 ;; We only set them when really needed because otherwise the
18436 ;; menus don't show the simple keys
18438 (when (or org-use-extra-keys
18439 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18440 (not window-system))
18441 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18442 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18443 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18444 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18445 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18446 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18447 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18448 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18449 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18450 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18451 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18452 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18453 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18454 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18455 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18456 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18457 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18458 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18459 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18460 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18461 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18462 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18463 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18464 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18465 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18466 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18467 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18468 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18470 ;; All the other keys
18472 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18473 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18474 (if (boundp 'narrow-map)
18475 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18476 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18477 (if (boundp 'narrow-map)
18478 (org-defkey narrow-map "b" 'org-narrow-to-block)
18479 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18480 (if (boundp 'narrow-map)
18481 (org-defkey narrow-map "e" 'org-narrow-to-element)
18482 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18483 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18484 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18485 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18486 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18487 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18488 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18489 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18490 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18491 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18492 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18493 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18494 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18495 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18496 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18497 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18498 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18499 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18500 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18501 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18502 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18503 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18504 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18505 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18506 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18507 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18508 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18509 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18510 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18511 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18512 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18513 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18514 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18515 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18516 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18517 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18518 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18519 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18520 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18521 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18522 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18523 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18524 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18525 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18526 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18527 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18528 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18529 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18530 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18531 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18532 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18533 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18534 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18535 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18536 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18537 (org-defkey org-mode-map "\C-c^" 'org-sort)
18538 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18539 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18540 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18541 (org-defkey org-mode-map "\C-m" 'org-return)
18542 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18543 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18544 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18545 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18546 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18547 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18548 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18549 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18550 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18551 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18552 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18553 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18554 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18555 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18556 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18557 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18558 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18559 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18560 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18561 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18562 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18563 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18564 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18566 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18567 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18568 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18570 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18571 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18572 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18573 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18574 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18575 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18576 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18577 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18578 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18579 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18580 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18581 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18582 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18583 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18584 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18585 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18586 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18587 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18588 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18589 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18590 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18591 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18592 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18594 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18595 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18596 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18597 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18598 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18600 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18602 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18604 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18605 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18607 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18610 (when (featurep 'xemacs)
18611 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18614 (defconst org-speed-commands-default
18616 ("Outline Navigation")
18617 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18618 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18619 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18620 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18621 ("F" . org-next-block)
18622 ("B" . org-previous-block)
18623 ("u" . (org-speed-move-safe 'outline-up-heading))
18624 ("j" . org-goto)
18625 ("g" . (org-refile t))
18626 ("Outline Visibility")
18627 ("c" . org-cycle)
18628 ("C" . org-shifttab)
18629 (" " . org-display-outline-path)
18630 ("=" . org-columns)
18631 ("Outline Structure Editing")
18632 ("U" . org-shiftmetaup)
18633 ("D" . org-shiftmetadown)
18634 ("r" . org-metaright)
18635 ("l" . org-metaleft)
18636 ("R" . org-shiftmetaright)
18637 ("L" . org-shiftmetaleft)
18638 ("i" . (progn (forward-char 1) (call-interactively
18639 'org-insert-heading-respect-content)))
18640 ("^" . org-sort)
18641 ("w" . org-refile)
18642 ("a" . org-archive-subtree-default-with-confirmation)
18643 ("." . org-mark-subtree) ;; FIXME Better use @ (see C-c @) here?
18644 ("#" . org-toggle-comment)
18645 ("Clock Commands")
18646 ("I" . org-clock-in)
18647 ("O" . org-clock-out)
18648 ("Meta Data Editing")
18649 ("t" . org-todo)
18650 ("," . (org-priority))
18651 ("0" . (org-priority ?\ ))
18652 ("1" . (org-priority ?A))
18653 ("2" . (org-priority ?B))
18654 ("3" . (org-priority ?C))
18655 (":" . org-set-tags-command)
18656 ("e" . org-set-effort)
18657 ("E" . org-inc-effort)
18658 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18659 (org-entry-put (point) "APPT_WARNTIME" m)))
18660 ("Agenda Views etc")
18661 ("v" . org-agenda)
18662 ("/" . org-sparse-tree)
18663 ("Misc")
18664 ("o" . org-open-at-point)
18665 ("?" . org-speed-command-help)
18666 ("<" . (org-agenda-set-restriction-lock 'subtree))
18667 (">" . (org-agenda-remove-restriction-lock))
18669 "The default speed commands.")
18671 (defun org-print-speed-command (e)
18672 (if (> (length (car e)) 1)
18673 (progn
18674 (princ "\n")
18675 (princ (car e))
18676 (princ "\n")
18677 (princ (make-string (length (car e)) ?-))
18678 (princ "\n"))
18679 (princ (car e))
18680 (princ " ")
18681 (if (symbolp (cdr e))
18682 (princ (symbol-name (cdr e)))
18683 (prin1 (cdr e)))
18684 (princ "\n")))
18686 (defun org-speed-command-help ()
18687 "Show the available speed commands."
18688 (interactive)
18689 (if (not org-use-speed-commands)
18690 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18691 (with-output-to-temp-buffer "*Help*"
18692 (princ "User-defined Speed commands\n===========================\n")
18693 (mapc 'org-print-speed-command org-speed-commands-user)
18694 (princ "\n")
18695 (princ "Built-in Speed commands\n=======================\n")
18696 (mapc 'org-print-speed-command org-speed-commands-default))
18697 (with-current-buffer "*Help*"
18698 (setq truncate-lines t))))
18700 (defun org-speed-move-safe (cmd)
18701 "Execute CMD, but make sure that the cursor always ends up in a headline.
18702 If not, return to the original position and throw an error."
18703 (interactive)
18704 (let ((pos (point)))
18705 (call-interactively cmd)
18706 (unless (and (bolp) (org-at-heading-p))
18707 (goto-char pos)
18708 (error "Boundary reached while executing %s" cmd))))
18710 (defvar org-self-insert-command-undo-counter 0)
18712 (defvar org-table-auto-blank-field) ; defined in org-table.el
18713 (defvar org-speed-command nil)
18715 (define-obsolete-function-alias
18716 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18718 (defun org-speed-command-activate (keys)
18719 "Hook for activating single-letter speed commands.
18720 `org-speed-commands-default' specifies a minimal command set.
18721 Use `org-speed-commands-user' for further customization."
18722 (when (or (and (bolp) (looking-at org-outline-regexp))
18723 (and (functionp org-use-speed-commands)
18724 (funcall org-use-speed-commands)))
18725 (cdr (assoc keys (append org-speed-commands-user
18726 org-speed-commands-default)))))
18728 (define-obsolete-function-alias
18729 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18731 (defun org-babel-speed-command-activate (keys)
18732 "Hook for activating single-letter code block commands."
18733 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18734 (cdr (assoc keys org-babel-key-bindings))))
18736 (defcustom org-speed-command-hook
18737 '(org-speed-command-default-hook org-babel-speed-command-hook)
18738 "Hook for activating speed commands at strategic locations.
18739 Hook functions are called in sequence until a valid handler is
18740 found.
18742 Each hook takes a single argument, a user-pressed command key
18743 which is also a `self-insert-command' from the global map.
18745 Within the hook, examine the cursor position and the command key
18746 and return nil or a valid handler as appropriate. Handler could
18747 be one of an interactive command, a function, or a form.
18749 Set `org-use-speed-commands' to non-nil value to enable this
18750 hook. The default setting is `org-speed-command-activate'."
18751 :group 'org-structure
18752 :version "24.1"
18753 :type 'hook)
18755 (defun org-self-insert-command (N)
18756 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18757 If the cursor is in a table looking at whitespace, the whitespace is
18758 overwritten, and the table is not marked as requiring realignment."
18759 (interactive "p")
18760 (org-check-before-invisible-edit 'insert)
18761 (cond
18762 ((and org-use-speed-commands
18763 (setq org-speed-command
18764 (run-hook-with-args-until-success
18765 'org-speed-command-hook (this-command-keys))))
18766 (cond
18767 ((commandp org-speed-command)
18768 (setq this-command org-speed-command)
18769 (call-interactively org-speed-command))
18770 ((functionp org-speed-command)
18771 (funcall org-speed-command))
18772 ((and org-speed-command (listp org-speed-command))
18773 (eval org-speed-command))
18774 (t (let (org-use-speed-commands)
18775 (call-interactively 'org-self-insert-command)))))
18776 ((and
18777 (org-table-p)
18778 (progn
18779 ;; check if we blank the field, and if that triggers align
18780 (and (featurep 'org-table) org-table-auto-blank-field
18781 (member last-command
18782 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18783 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18784 ;; got extra space, this field does not determine column width
18785 (let (org-table-may-need-update) (org-table-blank-field))
18786 ;; no extra space, this field may determine column width
18787 (org-table-blank-field)))
18789 (eq N 1)
18790 (looking-at "[^|\n]* |"))
18791 (let (org-table-may-need-update)
18792 (goto-char (1- (match-end 0)))
18793 (backward-delete-char 1)
18794 (goto-char (match-beginning 0))
18795 (self-insert-command N)))
18797 (setq org-table-may-need-update t)
18798 (self-insert-command N)
18799 (org-fix-tags-on-the-fly)
18800 (if org-self-insert-cluster-for-undo
18801 (if (not (eq last-command 'org-self-insert-command))
18802 (setq org-self-insert-command-undo-counter 1)
18803 (if (>= org-self-insert-command-undo-counter 20)
18804 (setq org-self-insert-command-undo-counter 1)
18805 (and (> org-self-insert-command-undo-counter 0)
18806 buffer-undo-list (listp buffer-undo-list)
18807 (not (cadr buffer-undo-list)) ; remove nil entry
18808 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18809 (setq org-self-insert-command-undo-counter
18810 (1+ org-self-insert-command-undo-counter))))))))
18812 (defun org-check-before-invisible-edit (kind)
18813 "Check is editing if kind KIND would be dangerous with invisible text around.
18814 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18815 ;; First, try to get out of here as quickly as possible, to reduce overhead
18816 (if (and org-catch-invisible-edits
18817 (or (not (boundp 'visible-mode)) (not visible-mode))
18818 (or (get-char-property (point) 'invisible)
18819 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18820 ;; OK, we need to take a closer look
18821 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18822 (invisible-before-point (if (bobp) nil (get-char-property
18823 (1- (point)) 'invisible)))
18824 (border-and-ok-direction
18826 ;; Check if we are acting predictably before invisible text
18827 (and invisible-at-point (not invisible-before-point)
18828 (memq kind '(insert delete-backward)))
18829 ;; Check if we are acting predictably after invisible text
18830 ;; This works not well, and I have turned it off. It seems
18831 ;; better to always show and stop after invisible text.
18832 ;; (and (not invisible-at-point) invisible-before-point
18833 ;; (memq kind '(insert delete)))
18835 (when (or (memq invisible-at-point '(outline org-hide-block t))
18836 (memq invisible-before-point '(outline org-hide-block t)))
18837 (if (eq org-catch-invisible-edits 'error)
18838 (error "Editing in invisible areas is prohibited - make visible first"))
18839 (if (and org-custom-properties-overlays
18840 (y-or-n-p "Display invisible properties in this buffer? "))
18841 (org-toggle-custom-properties-visibility)
18842 ;; Make the area visible
18843 (save-excursion
18844 (if invisible-before-point
18845 (goto-char (previous-single-char-property-change
18846 (point) 'invisible)))
18847 (org-cycle))
18848 (cond
18849 ((eq org-catch-invisible-edits 'show)
18850 ;; That's it, we do the edit after showing
18851 (message
18852 "Unfolding invisible region around point before editing")
18853 (sit-for 1))
18854 ((and (eq org-catch-invisible-edits 'smart)
18855 border-and-ok-direction)
18856 (message "Unfolding invisible region around point before editing"))
18858 ;; Don't do the edit, make the user repeat it in full visibility
18859 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18861 (defun org-fix-tags-on-the-fly ()
18862 (when (and (equal (char-after (point-at-bol)) ?*)
18863 (org-at-heading-p))
18864 (org-align-tags-here org-tags-column)))
18866 (defun org-delete-backward-char (N)
18867 "Like `delete-backward-char', insert whitespace at field end in tables.
18868 When deleting backwards, in tables this function will insert whitespace in
18869 front of the next \"|\" separator, to keep the table aligned. The table will
18870 still be marked for re-alignment if the field did fill the entire column,
18871 because, in this case the deletion might narrow the column."
18872 (interactive "p")
18873 (save-match-data
18874 (org-check-before-invisible-edit 'delete-backward)
18875 (if (and (org-table-p)
18876 (eq N 1)
18877 (string-match "|" (buffer-substring (point-at-bol) (point)))
18878 (looking-at ".*?|"))
18879 (let ((pos (point))
18880 (noalign (looking-at "[^|\n\r]* |"))
18881 (c org-table-may-need-update))
18882 (backward-delete-char N)
18883 (if (not overwrite-mode)
18884 (progn
18885 (skip-chars-forward "^|")
18886 (insert " ")
18887 (goto-char (1- pos))))
18888 ;; noalign: if there were two spaces at the end, this field
18889 ;; does not determine the width of the column.
18890 (if noalign (setq org-table-may-need-update c)))
18891 (backward-delete-char N)
18892 (org-fix-tags-on-the-fly))))
18894 (defun org-delete-char (N)
18895 "Like `delete-char', but insert whitespace at field end in tables.
18896 When deleting characters, in tables this function will insert whitespace in
18897 front of the next \"|\" separator, to keep the table aligned. The table will
18898 still be marked for re-alignment if the field did fill the entire column,
18899 because, in this case the deletion might narrow the column."
18900 (interactive "p")
18901 (save-match-data
18902 (org-check-before-invisible-edit 'delete)
18903 (if (and (org-table-p)
18904 (not (bolp))
18905 (not (= (char-after) ?|))
18906 (eq N 1))
18907 (if (looking-at ".*?|")
18908 (let ((pos (point))
18909 (noalign (looking-at "[^|\n\r]* |"))
18910 (c org-table-may-need-update))
18911 (replace-match (concat
18912 (substring (match-string 0) 1 -1)
18913 " |"))
18914 (goto-char pos)
18915 ;; noalign: if there were two spaces at the end, this field
18916 ;; does not determine the width of the column.
18917 (if noalign (setq org-table-may-need-update c)))
18918 (delete-char N))
18919 (delete-char N)
18920 (org-fix-tags-on-the-fly))))
18922 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18923 (put 'org-self-insert-command 'delete-selection t)
18924 (put 'orgtbl-self-insert-command 'delete-selection t)
18925 (put 'org-delete-char 'delete-selection 'supersede)
18926 (put 'org-delete-backward-char 'delete-selection 'supersede)
18927 (put 'org-yank 'delete-selection 'yank)
18929 ;; Make `flyspell-mode' delay after some commands
18930 (put 'org-self-insert-command 'flyspell-delayed t)
18931 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18932 (put 'org-delete-char 'flyspell-delayed t)
18933 (put 'org-delete-backward-char 'flyspell-delayed t)
18935 ;; Make pabbrev-mode expand after org-mode commands
18936 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18937 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18939 ;; How to do this: Measure non-white length of current string
18940 ;; If equal to column width, we should realign.
18942 (defun org-remap (map &rest commands)
18943 "In MAP, remap the functions given in COMMANDS.
18944 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18945 (let (new old)
18946 (while commands
18947 (setq old (pop commands) new (pop commands))
18948 (if (fboundp 'command-remapping)
18949 (org-defkey map (vector 'remap old) new)
18950 (substitute-key-definition old new map global-map)))))
18952 (when (eq org-enable-table-editor 'optimized)
18953 ;; If the user wants maximum table support, we need to hijack
18954 ;; some standard editing functions
18955 (org-remap org-mode-map
18956 'self-insert-command 'org-self-insert-command
18957 'delete-char 'org-delete-char
18958 'delete-backward-char 'org-delete-backward-char)
18959 (org-defkey org-mode-map "|" 'org-force-self-insert))
18961 (defvar org-ctrl-c-ctrl-c-hook nil
18962 "Hook for functions attaching themselves to `C-c C-c'.
18964 This can be used to add additional functionality to the C-c C-c
18965 key which executes context-dependent commands. This hook is run
18966 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18967 run after the last test.
18969 Each function will be called with no arguments. The function
18970 must check if the context is appropriate for it to act. If yes,
18971 it should do its thing and then return a non-nil value. If the
18972 context is wrong, just do nothing and return nil.")
18974 (defvar org-ctrl-c-ctrl-c-final-hook nil
18975 "Hook for functions attaching themselves to `C-c C-c'.
18977 This can be used to add additional functionality to the C-c C-c
18978 key which executes context-dependent commands. This hook is run
18979 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18980 before the first test.
18982 Each function will be called with no arguments. The function
18983 must check if the context is appropriate for it to act. If yes,
18984 it should do its thing and then return a non-nil value. If the
18985 context is wrong, just do nothing and return nil.")
18987 (defvar org-tab-first-hook nil
18988 "Hook for functions to attach themselves to TAB.
18989 See `org-ctrl-c-ctrl-c-hook' for more information.
18990 This hook runs as the first action when TAB is pressed, even before
18991 `org-cycle' messes around with the `outline-regexp' to cater for
18992 inline tasks and plain list item folding.
18993 If any function in this hook returns t, any other actions that
18994 would have been caused by TAB (such as table field motion or visibility
18995 cycling) will not occur.")
18997 (defvar org-tab-after-check-for-table-hook nil
18998 "Hook for functions to attach themselves to TAB.
18999 See `org-ctrl-c-ctrl-c-hook' for more information.
19000 This hook runs after it has been established that the cursor is not in a
19001 table, but before checking if the cursor is in a headline or if global cycling
19002 should be done.
19003 If any function in this hook returns t, not other actions like visibility
19004 cycling will be done.")
19006 (defvar org-tab-after-check-for-cycling-hook nil
19007 "Hook for functions to attach themselves to TAB.
19008 See `org-ctrl-c-ctrl-c-hook' for more information.
19009 This hook runs after it has been established that not table field motion and
19010 not visibility should be done because of current context. This is probably
19011 the place where a package like yasnippets can hook in.")
19013 (defvar org-tab-before-tab-emulation-hook nil
19014 "Hook for functions to attach themselves to TAB.
19015 See `org-ctrl-c-ctrl-c-hook' for more information.
19016 This hook runs after every other options for TAB have been exhausted, but
19017 before indentation and \t insertion takes place.")
19019 (defvar org-metaleft-hook nil
19020 "Hook for functions attaching themselves to `M-left'.
19021 See `org-ctrl-c-ctrl-c-hook' for more information.")
19022 (defvar org-metaright-hook nil
19023 "Hook for functions attaching themselves to `M-right'.
19024 See `org-ctrl-c-ctrl-c-hook' for more information.")
19025 (defvar org-metaup-hook nil
19026 "Hook for functions attaching themselves to `M-up'.
19027 See `org-ctrl-c-ctrl-c-hook' for more information.")
19028 (defvar org-metadown-hook nil
19029 "Hook for functions attaching themselves to `M-down'.
19030 See `org-ctrl-c-ctrl-c-hook' for more information.")
19031 (defvar org-shiftmetaleft-hook nil
19032 "Hook for functions attaching themselves to `M-S-left'.
19033 See `org-ctrl-c-ctrl-c-hook' for more information.")
19034 (defvar org-shiftmetaright-hook nil
19035 "Hook for functions attaching themselves to `M-S-right'.
19036 See `org-ctrl-c-ctrl-c-hook' for more information.")
19037 (defvar org-shiftmetaup-hook nil
19038 "Hook for functions attaching themselves to `M-S-up'.
19039 See `org-ctrl-c-ctrl-c-hook' for more information.")
19040 (defvar org-shiftmetadown-hook nil
19041 "Hook for functions attaching themselves to `M-S-down'.
19042 See `org-ctrl-c-ctrl-c-hook' for more information.")
19043 (defvar org-metareturn-hook nil
19044 "Hook for functions attaching themselves to `M-RET'.
19045 See `org-ctrl-c-ctrl-c-hook' for more information.")
19046 (defvar org-shiftup-hook nil
19047 "Hook for functions attaching themselves to `S-up'.
19048 See `org-ctrl-c-ctrl-c-hook' for more information.")
19049 (defvar org-shiftup-final-hook nil
19050 "Hook for functions attaching themselves to `S-up'.
19051 This one runs after all other options except shift-select have been excluded.
19052 See `org-ctrl-c-ctrl-c-hook' for more information.")
19053 (defvar org-shiftdown-hook nil
19054 "Hook for functions attaching themselves to `S-down'.
19055 See `org-ctrl-c-ctrl-c-hook' for more information.")
19056 (defvar org-shiftdown-final-hook nil
19057 "Hook for functions attaching themselves to `S-down'.
19058 This one runs after all other options except shift-select have been excluded.
19059 See `org-ctrl-c-ctrl-c-hook' for more information.")
19060 (defvar org-shiftleft-hook nil
19061 "Hook for functions attaching themselves to `S-left'.
19062 See `org-ctrl-c-ctrl-c-hook' for more information.")
19063 (defvar org-shiftleft-final-hook nil
19064 "Hook for functions attaching themselves to `S-left'.
19065 This one runs after all other options except shift-select have been excluded.
19066 See `org-ctrl-c-ctrl-c-hook' for more information.")
19067 (defvar org-shiftright-hook nil
19068 "Hook for functions attaching themselves to `S-right'.
19069 See `org-ctrl-c-ctrl-c-hook' for more information.")
19070 (defvar org-shiftright-final-hook nil
19071 "Hook for functions attaching themselves to `S-right'.
19072 This one runs after all other options except shift-select have been excluded.
19073 See `org-ctrl-c-ctrl-c-hook' for more information.")
19075 (defun org-modifier-cursor-error ()
19076 "Throw an error, a modified cursor command was applied in wrong context."
19077 (error "This command is active in special context like tables, headlines or items"))
19079 (defun org-shiftselect-error ()
19080 "Throw an error because Shift-Cursor command was applied in wrong context."
19081 (if (and (boundp 'shift-select-mode) shift-select-mode)
19082 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19083 (error "This command works only in special context like headlines or timestamps")))
19085 (defun org-call-for-shift-select (cmd)
19086 (let ((this-command-keys-shift-translated t))
19087 (call-interactively cmd)))
19089 (defun org-shifttab (&optional arg)
19090 "Global visibility cycling or move to previous table field.
19091 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19092 on context.
19093 See the individual commands for more information."
19094 (interactive "P")
19095 (cond
19096 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19097 ((integerp arg)
19098 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19099 (message "Content view to level: %d" arg)
19100 (org-content (prefix-numeric-value arg2))
19101 (setq org-cycle-global-status 'overview)))
19102 (t (call-interactively 'org-global-cycle))))
19104 (defun org-shiftmetaleft ()
19105 "Promote subtree or delete table column.
19106 Calls `org-promote-subtree', `org-outdent-item-tree', or
19107 `org-table-delete-column', depending on context. See the
19108 individual commands for more information."
19109 (interactive)
19110 (cond
19111 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19112 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19113 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19114 ((if (not (org-region-active-p)) (org-at-item-p)
19115 (save-excursion (goto-char (region-beginning))
19116 (org-at-item-p)))
19117 (call-interactively 'org-outdent-item-tree))
19118 (t (org-modifier-cursor-error))))
19120 (defun org-shiftmetaright ()
19121 "Demote subtree or insert table column.
19122 Calls `org-demote-subtree', `org-indent-item-tree', or
19123 `org-table-insert-column', depending on context. See the
19124 individual commands for more information."
19125 (interactive)
19126 (cond
19127 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19128 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19129 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19130 ((if (not (org-region-active-p)) (org-at-item-p)
19131 (save-excursion (goto-char (region-beginning))
19132 (org-at-item-p)))
19133 (call-interactively 'org-indent-item-tree))
19134 (t (org-modifier-cursor-error))))
19136 (defun org-shiftmetaup (&optional arg)
19137 "Move subtree up or kill table row.
19138 Calls `org-move-subtree-up' or `org-table-kill-row' or
19139 `org-move-item-up' or `org-timestamp-up', depending on context.
19140 See the individual commands for more information."
19141 (interactive "P")
19142 (cond
19143 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19144 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19145 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19146 ((org-at-item-p) (call-interactively 'org-move-item-up))
19147 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19148 (call-interactively 'org-timestamp-up)))
19149 (t (org-modifier-cursor-error))))
19151 (defun org-shiftmetadown (&optional arg)
19152 "Move subtree down or insert table row.
19153 Calls `org-move-subtree-down' or `org-table-insert-row' or
19154 `org-move-item-down' or `org-timestamp-up', depending on context.
19155 See the individual commands for more information."
19156 (interactive "P")
19157 (cond
19158 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19159 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19160 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19161 ((org-at-item-p) (call-interactively 'org-move-item-down))
19162 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19163 (call-interactively 'org-timestamp-down)))
19164 (t (org-modifier-cursor-error))))
19166 (defsubst org-hidden-tree-error ()
19167 (error
19168 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19170 (defun org-metaleft (&optional arg)
19171 "Promote heading or move table column to left.
19172 Calls `org-do-promote' or `org-table-move-column', depending on context.
19173 With no specific context, calls the Emacs default `backward-word'.
19174 See the individual commands for more information."
19175 (interactive "P")
19176 (cond
19177 ((run-hook-with-args-until-success 'org-metaleft-hook))
19178 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19179 ((org-with-limited-levels
19180 (or (org-at-heading-p)
19181 (and (org-region-active-p)
19182 (save-excursion
19183 (goto-char (region-beginning))
19184 (org-at-heading-p)))))
19185 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19186 (call-interactively 'org-do-promote))
19187 ;; At an inline task.
19188 ((org-at-heading-p)
19189 (call-interactively 'org-inlinetask-promote))
19190 ((or (org-at-item-p)
19191 (and (org-region-active-p)
19192 (save-excursion
19193 (goto-char (region-beginning))
19194 (org-at-item-p))))
19195 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19196 (call-interactively 'org-outdent-item))
19197 (t (call-interactively 'backward-word))))
19199 (defun org-metaright (&optional arg)
19200 "Demote a subtree, a list item or move table column to right.
19201 In front of a drawer or a block keyword, indent it correctly.
19202 With no specific context, calls the Emacs default `forward-word'.
19203 See the individual commands for more information."
19204 (interactive "P")
19205 (cond
19206 ((run-hook-with-args-until-success 'org-metaright-hook))
19207 ((org-at-table-p) (call-interactively 'org-table-move-column))
19208 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19209 ((org-at-block-p) (call-interactively 'org-indent-block))
19210 ((org-with-limited-levels
19211 (or (org-at-heading-p)
19212 (and (org-region-active-p)
19213 (save-excursion
19214 (goto-char (region-beginning))
19215 (org-at-heading-p)))))
19216 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19217 (call-interactively 'org-do-demote))
19218 ;; At an inline task.
19219 ((org-at-heading-p)
19220 (call-interactively 'org-inlinetask-demote))
19221 ((or (org-at-item-p)
19222 (and (org-region-active-p)
19223 (save-excursion
19224 (goto-char (region-beginning))
19225 (org-at-item-p))))
19226 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19227 (call-interactively 'org-indent-item))
19228 (t (call-interactively 'forward-word))))
19230 (defun org-check-for-hidden (what)
19231 "Check if there are hidden headlines/items in the current visual line.
19232 WHAT can be either `headlines' or `items'. If the current line is
19233 an outline or item heading and it has a folded subtree below it,
19234 this function returns t, nil otherwise."
19235 (let ((re (cond
19236 ((eq what 'headlines) org-outline-regexp-bol)
19237 ((eq what 'items) (org-item-beginning-re))
19238 (t (error "This should not happen"))))
19239 beg end)
19240 (save-excursion
19241 (catch 'exit
19242 (unless (org-region-active-p)
19243 (setq beg (point-at-bol))
19244 (beginning-of-line 2)
19245 (while (and (not (eobp)) ;; this is like `next-line'
19246 (get-char-property (1- (point)) 'invisible))
19247 (beginning-of-line 2))
19248 (setq end (point))
19249 (goto-char beg)
19250 (goto-char (point-at-eol))
19251 (setq end (max end (point)))
19252 (while (re-search-forward re end t)
19253 (if (get-char-property (match-beginning 0) 'invisible)
19254 (throw 'exit t))))
19255 nil))))
19257 (defun org-metaup (&optional arg)
19258 "Move subtree up or move table row up.
19259 Calls `org-move-subtree-up' or `org-table-move-row' or
19260 `org-move-item-up', depending on context. See the individual commands
19261 for more information."
19262 (interactive "P")
19263 (cond
19264 ((run-hook-with-args-until-success 'org-metaup-hook))
19265 ((org-region-active-p)
19266 (let* ((a (min (region-beginning) (region-end)))
19267 (b (1- (max (region-beginning) (region-end))))
19268 (c (save-excursion (goto-char a)
19269 (move-beginning-of-line 0)))
19270 (d (save-excursion (goto-char a)
19271 (move-end-of-line 0) (point))))
19272 (transpose-regions a b c d)
19273 (goto-char c)))
19274 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19275 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19276 ((org-at-item-p) (call-interactively 'org-move-item-up))
19277 (t (org-drag-element-backward))))
19279 (defun org-metadown (&optional arg)
19280 "Move subtree down or move table row down.
19281 Calls `org-move-subtree-down' or `org-table-move-row' or
19282 `org-move-item-down', depending on context. See the individual
19283 commands for more information."
19284 (interactive "P")
19285 (cond
19286 ((run-hook-with-args-until-success 'org-metadown-hook))
19287 ((org-region-active-p)
19288 (let* ((a (min (region-beginning) (region-end)))
19289 (b (max (region-beginning) (region-end)))
19290 (c (save-excursion (goto-char b)
19291 (move-beginning-of-line 1)))
19292 (d (save-excursion (goto-char b)
19293 (move-end-of-line 1) (1+ (point)))))
19294 (transpose-regions a b c d)
19295 (goto-char d)))
19296 ((org-at-table-p) (call-interactively 'org-table-move-row))
19297 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19298 ((org-at-item-p) (call-interactively 'org-move-item-down))
19299 (t (org-drag-element-forward))))
19301 (defun org-shiftup (&optional arg)
19302 "Increase item in timestamp or increase priority of current headline.
19303 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19304 depending on context. See the individual commands for more information."
19305 (interactive "P")
19306 (cond
19307 ((run-hook-with-args-until-success 'org-shiftup-hook))
19308 ((and org-support-shift-select (org-region-active-p))
19309 (org-call-for-shift-select 'previous-line))
19310 ((org-at-timestamp-p t)
19311 (call-interactively (if org-edit-timestamp-down-means-later
19312 'org-timestamp-down 'org-timestamp-up)))
19313 ((and (not (eq org-support-shift-select 'always))
19314 org-enable-priority-commands
19315 (org-at-heading-p))
19316 (call-interactively 'org-priority-up))
19317 ((and (not org-support-shift-select) (org-at-item-p))
19318 (call-interactively 'org-previous-item))
19319 ((org-clocktable-try-shift 'up arg))
19320 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19321 (org-support-shift-select
19322 (org-call-for-shift-select 'previous-line))
19323 (t (org-shiftselect-error))))
19325 (defun org-shiftdown (&optional arg)
19326 "Decrease item in timestamp or decrease priority of current headline.
19327 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19328 depending on context. See the individual commands for more information."
19329 (interactive "P")
19330 (cond
19331 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19332 ((and org-support-shift-select (org-region-active-p))
19333 (org-call-for-shift-select 'next-line))
19334 ((org-at-timestamp-p t)
19335 (call-interactively (if org-edit-timestamp-down-means-later
19336 'org-timestamp-up 'org-timestamp-down)))
19337 ((and (not (eq org-support-shift-select 'always))
19338 org-enable-priority-commands
19339 (org-at-heading-p))
19340 (call-interactively 'org-priority-down))
19341 ((and (not org-support-shift-select) (org-at-item-p))
19342 (call-interactively 'org-next-item))
19343 ((org-clocktable-try-shift 'down arg))
19344 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19345 (org-support-shift-select
19346 (org-call-for-shift-select 'next-line))
19347 (t (org-shiftselect-error))))
19349 (defun org-shiftright (&optional arg)
19350 "Cycle the thing at point or in the current line, depending on context.
19351 Depending on context, this does one of the following:
19353 - switch a timestamp at point one day into the future
19354 - on a headline, switch to the next TODO keyword.
19355 - on an item, switch entire list to the next bullet type
19356 - on a property line, switch to the next allowed value
19357 - on a clocktable definition line, move time block into the future"
19358 (interactive "P")
19359 (cond
19360 ((run-hook-with-args-until-success 'org-shiftright-hook))
19361 ((and org-support-shift-select (org-region-active-p))
19362 (org-call-for-shift-select 'forward-char))
19363 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19364 ((and (not (eq org-support-shift-select 'always))
19365 (org-at-heading-p))
19366 (let ((org-inhibit-logging
19367 (not org-treat-S-cursor-todo-selection-as-state-change))
19368 (org-inhibit-blocking
19369 (not org-treat-S-cursor-todo-selection-as-state-change)))
19370 (org-call-with-arg 'org-todo 'right)))
19371 ((or (and org-support-shift-select
19372 (not (eq org-support-shift-select 'always))
19373 (org-at-item-bullet-p))
19374 (and (not org-support-shift-select) (org-at-item-p)))
19375 (org-call-with-arg 'org-cycle-list-bullet nil))
19376 ((and (not (eq org-support-shift-select 'always))
19377 (org-at-property-p))
19378 (call-interactively 'org-property-next-allowed-value))
19379 ((org-clocktable-try-shift 'right arg))
19380 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19381 (org-support-shift-select
19382 (org-call-for-shift-select 'forward-char))
19383 (t (org-shiftselect-error))))
19385 (defun org-shiftleft (&optional arg)
19386 "Cycle the thing at point or in the current line, depending on context.
19387 Depending on context, this does one of the following:
19389 - switch a timestamp at point one day into the past
19390 - on a headline, switch to the previous TODO keyword.
19391 - on an item, switch entire list to the previous bullet type
19392 - on a property line, switch to the previous allowed value
19393 - on a clocktable definition line, move time block into the past"
19394 (interactive "P")
19395 (cond
19396 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19397 ((and org-support-shift-select (org-region-active-p))
19398 (org-call-for-shift-select 'backward-char))
19399 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19400 ((and (not (eq org-support-shift-select 'always))
19401 (org-at-heading-p))
19402 (let ((org-inhibit-logging
19403 (not org-treat-S-cursor-todo-selection-as-state-change))
19404 (org-inhibit-blocking
19405 (not org-treat-S-cursor-todo-selection-as-state-change)))
19406 (org-call-with-arg 'org-todo 'left)))
19407 ((or (and org-support-shift-select
19408 (not (eq org-support-shift-select 'always))
19409 (org-at-item-bullet-p))
19410 (and (not org-support-shift-select) (org-at-item-p)))
19411 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19412 ((and (not (eq org-support-shift-select 'always))
19413 (org-at-property-p))
19414 (call-interactively 'org-property-previous-allowed-value))
19415 ((org-clocktable-try-shift 'left arg))
19416 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19417 (org-support-shift-select
19418 (org-call-for-shift-select 'backward-char))
19419 (t (org-shiftselect-error))))
19421 (defun org-shiftcontrolright ()
19422 "Switch to next TODO set."
19423 (interactive)
19424 (cond
19425 ((and org-support-shift-select (org-region-active-p))
19426 (org-call-for-shift-select 'forward-word))
19427 ((and (not (eq org-support-shift-select 'always))
19428 (org-at-heading-p))
19429 (org-call-with-arg 'org-todo 'nextset))
19430 (org-support-shift-select
19431 (org-call-for-shift-select 'forward-word))
19432 (t (org-shiftselect-error))))
19434 (defun org-shiftcontrolleft ()
19435 "Switch to previous TODO set."
19436 (interactive)
19437 (cond
19438 ((and org-support-shift-select (org-region-active-p))
19439 (org-call-for-shift-select 'backward-word))
19440 ((and (not (eq org-support-shift-select 'always))
19441 (org-at-heading-p))
19442 (org-call-with-arg 'org-todo 'previousset))
19443 (org-support-shift-select
19444 (org-call-for-shift-select 'backward-word))
19445 (t (org-shiftselect-error))))
19447 (defun org-shiftcontrolup (&optional n)
19448 "Change timestamps synchronously up in CLOCK log lines.
19449 Optional argument N tells to change by that many units."
19450 (interactive "P")
19451 (cond ((and (not org-support-shift-select)
19452 (org-at-clock-log-p)
19453 (org-at-timestamp-p t))
19454 (org-clock-timestamps-up n))
19455 (t (org-shiftselect-error))))
19457 (defun org-shiftcontroldown (&optional n)
19458 "Change timestamps synchronously down in CLOCK log lines.
19459 Optional argument N tells to change by that many units."
19460 (interactive "P")
19461 (cond ((and (not org-support-shift-select)
19462 (org-at-clock-log-p)
19463 (org-at-timestamp-p t))
19464 (org-clock-timestamps-down n))
19465 (t (org-shiftselect-error))))
19467 (defun org-ctrl-c-ret ()
19468 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19469 (interactive)
19470 (cond
19471 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19472 (t (call-interactively 'org-insert-heading))))
19474 (defun org-find-visible ()
19475 (let ((s (point)))
19476 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19477 (get-char-property s 'invisible)))
19479 (defun org-find-invisible ()
19480 (let ((s (point)))
19481 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19482 (not (get-char-property s 'invisible))))
19485 (defun org-copy-visible (beg end)
19486 "Copy the visible parts of the region."
19487 (interactive "r")
19488 (let (snippets s)
19489 (save-excursion
19490 (save-restriction
19491 (narrow-to-region beg end)
19492 (setq s (goto-char (point-min)))
19493 (while (not (= (point) (point-max)))
19494 (goto-char (org-find-invisible))
19495 (push (buffer-substring s (point)) snippets)
19496 (setq s (goto-char (org-find-visible))))))
19497 (kill-new (apply 'concat (nreverse snippets)))))
19499 (defun org-copy-special ()
19500 "Copy region in table or copy current subtree.
19501 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19502 See the individual commands for more information."
19503 (interactive)
19504 (call-interactively
19505 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19507 (defun org-cut-special ()
19508 "Cut region in table or cut current subtree.
19509 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19510 See the individual commands for more information."
19511 (interactive)
19512 (call-interactively
19513 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19515 (defun org-paste-special (arg)
19516 "Paste rectangular region into table, or past subtree relative to level.
19517 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19518 See the individual commands for more information."
19519 (interactive "P")
19520 (if (org-at-table-p)
19521 (org-table-paste-rectangle)
19522 (org-paste-subtree arg)))
19524 (defsubst org-in-fixed-width-region-p ()
19525 "Is point in a fixed-width region?"
19526 (save-match-data
19527 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19529 (defun org-edit-special (&optional arg)
19530 "Call a special editor for the element at point.
19531 When at a table, call the formula editor with `org-table-edit-formulas'.
19532 When in a source code block, call `org-edit-src-code'.
19533 When in a fixed-width region, call `org-edit-fixed-width-region'.
19534 When at an #+INCLUDE keyword, visit the included file.
19535 On a link, call `ffap' to visit the link at point.
19536 Otherwise, return a user error."
19537 (interactive)
19538 (let ((element (org-element-at-point)))
19539 (assert (not buffer-read-only) nil
19540 "Buffer is read-only: %s" (buffer-name))
19541 (case (org-element-type element)
19542 (src-block
19543 (if (not arg) (org-edit-src-code)
19544 (let* ((info (org-babel-get-src-block-info))
19545 (lang (nth 0 info))
19546 (params (nth 2 info))
19547 (session (cdr (assq :session params))))
19548 (if (not session) (org-edit-src-code)
19549 ;; At a src-block with a session and function called with
19550 ;; an ARG: switch to the buffer related to the inferior
19551 ;; process.
19552 (funcall (intern (concat "org-babel-prep-session:" lang))
19553 session params)))))
19554 (keyword
19555 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19556 (find-file
19557 (org-remove-double-quotes
19558 (car (org-split-string (org-element-property :value element)))))
19559 (user-error "No special environment to edit here")))
19560 (table
19561 (if (eq (org-element-property :type element) 'table.el)
19562 (org-edit-src-code)
19563 (call-interactively 'org-table-edit-formulas)))
19564 ;; Only Org tables contain `table-row' type elements.
19565 (table-row (call-interactively 'org-table-edit-formulas))
19566 ((example-block export-block) (org-edit-src-code))
19567 (fixed-width (org-edit-fixed-width-region))
19568 (otherwise
19569 ;; No notable element at point. Though, we may be at a link,
19570 ;; which is an object. Thus, scan deeper.
19571 (if (eq (org-element-type (org-element-context element)) 'link)
19572 (call-interactively 'ffap)
19573 (user-error "No special environment to edit here"))))))
19575 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19576 (defun org-ctrl-c-ctrl-c (&optional arg)
19577 "Set tags in headline, or update according to changed information at point.
19579 This command does many different things, depending on context:
19581 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19582 this is what we do.
19584 - If the cursor is on a statistics cookie, update it.
19586 - If the cursor is in a headline, prompt for tags and insert them
19587 into the current line, aligned to `org-tags-column'. When called
19588 with prefix arg, realign all tags in the current buffer.
19590 - If the cursor is in one of the special #+KEYWORD lines, this
19591 triggers scanning the buffer for these lines and updating the
19592 information.
19594 - If the cursor is inside a table, realign the table. This command
19595 works even if the automatic table editor has been turned off.
19597 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19598 the entire table.
19600 - If the cursor is at a footnote reference or definition, jump to
19601 the corresponding definition or references, respectively.
19603 - If the cursor is a the beginning of a dynamic block, update it.
19605 - If the current buffer is a capture buffer, close note and file it.
19607 - If the cursor is on a <<<target>>>, update radio targets and
19608 corresponding links in this buffer.
19610 - If the cursor is on a numbered item in a plain list, renumber the
19611 ordered list.
19613 - If the cursor is on a checkbox, toggle it.
19615 - If the cursor is on a code block, evaluate it. The variable
19616 `org-confirm-babel-evaluate' can be used to control prompting
19617 before code block evaluation, by default every code block
19618 evaluation requires confirmation. Code block evaluation can be
19619 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19620 (interactive "P")
19621 (cond
19622 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19623 org-occur-highlights
19624 org-latex-fragment-image-overlays)
19625 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19626 (org-remove-occur-highlights)
19627 (org-remove-latex-fragment-image-overlays)
19628 (message "Temporary highlights/overlays removed from current buffer"))
19629 ((and (local-variable-p 'org-finish-function (current-buffer))
19630 (fboundp org-finish-function))
19631 (funcall org-finish-function))
19632 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19634 (let* ((context (org-element-context)) (type (org-element-type context)))
19635 ;; Test if point is within blanks at the end of an element.
19636 (if (save-excursion
19637 (or (not context)
19638 (beginning-of-line)
19639 (and (looking-at "[ \t]*$")
19640 (skip-chars-forward " \r\t\n")
19641 (>= (point) (org-element-property :end context)))))
19642 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19643 (user-error "C-c C-c can do nothing useful at this location"))
19644 ;; For convenience: at the first line of a paragraph on the
19645 ;; same line as an item, apply function on that item instead.
19646 (when (eq type 'paragraph)
19647 (let ((parent (org-element-property :parent context)))
19648 (when (and (eq (org-element-type parent) 'item)
19649 (= (point-at-bol) (org-element-property :begin parent)))
19650 (setq context parent type 'item))))
19651 ;; Act according to type of element or object at point.
19652 (case type
19653 (clock (org-clock-update-time-maybe))
19654 (dynamic-block
19655 (save-excursion
19656 (goto-char (org-element-property :post-affiliated context))
19657 (org-update-dblock)))
19658 (footnote-definition
19659 (goto-char (org-element-property :post-affiliated context))
19660 (call-interactively 'org-footnote-action))
19661 (footnote-reference (call-interactively 'org-footnote-action))
19662 ((headline inlinetask)
19663 (save-excursion (goto-char (org-element-property :begin context))
19664 (call-interactively 'org-set-tags)))
19665 (item
19666 ;; At an item: a double C-u set checkbox to "[-]"
19667 ;; unconditionally, whereas a single one will toggle its
19668 ;; presence. Without an universal argument, if the item
19669 ;; has a checkbox, toggle it. Otherwise repair the list.
19670 (let* ((box (org-element-property :checkbox context))
19671 (struct (org-element-property :structure context))
19672 (old-struct (copy-tree struct))
19673 (parents (org-list-parents-alist struct))
19674 (prevs (org-list-prevs-alist struct))
19675 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19676 (org-list-set-checkbox
19677 (org-element-property :begin context) struct
19678 (cond ((equal arg '(16)) "[-]")
19679 ((and (not box) (equal arg '(4))) "[ ]")
19680 ((or (not box) (equal arg '(4))) nil)
19681 ((eq box 'on) "[ ]")
19682 (t "[X]")))
19683 ;; Mimic `org-list-write-struct' but with grabbing
19684 ;; a return value from `org-list-struct-fix-box'.
19685 (org-list-struct-fix-ind struct parents 2)
19686 (org-list-struct-fix-item-end struct)
19687 (org-list-struct-fix-bul struct prevs)
19688 (org-list-struct-fix-ind struct parents)
19689 (let ((block-item
19690 (org-list-struct-fix-box struct parents prevs orderedp)))
19691 (if (and box (equal struct old-struct))
19692 (if (equal arg '(16))
19693 (message "Checkboxes already reset")
19694 (user-error "Cannot toggle this checkbox: %s"
19695 (if (eq box 'on)
19696 "all subitems checked"
19697 "unchecked subitems")))
19698 (org-list-struct-apply-struct struct old-struct)
19699 (org-update-checkbox-count-maybe))
19700 (when block-item
19701 (message "Checkboxes were removed due to empty box at line %d"
19702 (org-current-line block-item))))))
19703 (keyword
19704 (let ((org-inhibit-startup-visibility-stuff t)
19705 (org-startup-align-all-tables nil))
19706 (when (boundp 'org-table-coordinate-overlays)
19707 (mapc 'delete-overlay org-table-coordinate-overlays)
19708 (setq org-table-coordinate-overlays nil))
19709 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19710 (message "Local setup has been refreshed"))
19711 (plain-list
19712 ;; At a plain list, with a double C-u argument, set
19713 ;; checkboxes of each item to "[-]", whereas a single one
19714 ;; will toggle their presence according to the state of the
19715 ;; first item in the list. Without an argument, repair the
19716 ;; list.
19717 (let* ((begin (org-element-property :contents-begin context))
19718 (struct (org-element-property :structure context))
19719 (old-struct (copy-tree struct))
19720 (first-box (save-excursion
19721 (goto-char begin)
19722 (looking-at org-list-full-item-re)
19723 (match-string-no-properties 3)))
19724 (new-box (cond ((equal arg '(16)) "[-]")
19725 ((equal arg '(4)) (unless first-box "[ ]"))
19726 ((equal first-box "[X]") "[ ]")
19727 (t "[X]"))))
19728 (cond
19729 (arg
19730 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19731 (org-list-get-all-items
19732 begin struct (org-list-prevs-alist struct))))
19733 ((and first-box (eq (point) begin))
19734 ;; For convenience, when point is at bol on the first
19735 ;; item of the list and no argument is provided, simply
19736 ;; toggle checkbox of that item, if any.
19737 (org-list-set-checkbox begin struct new-box)))
19738 (org-list-write-struct
19739 struct (org-list-parents-alist struct) old-struct)
19740 (org-update-checkbox-count-maybe)
19741 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19742 ((property-drawer node-property)
19743 (call-interactively 'org-property-action))
19744 ((radio-target target)
19745 (call-interactively 'org-update-radio-target-regexp))
19746 (statistics-cookie
19747 (call-interactively 'org-update-statistics-cookies))
19748 ((table table-cell table-row)
19749 ;; At a table, recalculate every field and align it. Also
19750 ;; send the table if necessary. If the table has
19751 ;; a `table.el' type, just give up. At a table row or
19752 ;; cell, maybe recalculate line but always align table.
19753 (if (eq (org-element-property :type context) 'table.el)
19754 (message "Use C-c ' to edit table.el tables")
19755 (let ((org-enable-table-editor t))
19756 (if (or (eq type 'table)
19757 ;; Check if point is at a TBLFM line.
19758 (and (eq type 'table-row)
19759 (= (point) (org-element-property :end context))))
19760 (save-excursion
19761 (goto-char (org-element-property :contents-begin context))
19762 (org-call-with-arg 'org-table-recalculate (or arg t))
19763 (orgtbl-send-table 'maybe))
19764 (org-table-maybe-eval-formula)
19765 (cond (arg (call-interactively 'org-table-recalculate))
19766 ((org-table-maybe-recalculate-line))
19767 (t (org-table-align)))))))
19768 (timestamp (org-timestamp-change 0 'day))
19769 (otherwise
19770 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19771 (user-error
19772 "C-c C-c can do nothing useful at this location")))))))))
19774 (defun org-mode-restart ()
19775 "Restart Org-mode, to scan again for special lines.
19776 Also updates the keyword regular expressions."
19777 (interactive)
19778 (org-mode)
19779 (message "Org-mode restarted"))
19781 (defun org-kill-note-or-show-branches ()
19782 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19783 (interactive)
19784 (if (not org-finish-function)
19785 (progn
19786 (hide-subtree)
19787 (call-interactively 'show-branches))
19788 (let ((org-note-abort t))
19789 (funcall org-finish-function))))
19791 (defun org-return (&optional indent)
19792 "Goto next table row or insert a newline.
19793 Calls `org-table-next-row' or `newline', depending on context.
19794 See the individual commands for more information."
19795 (interactive)
19796 (let (org-ts-what)
19797 (cond
19798 ((or (bobp) (org-in-src-block-p))
19799 (if indent (newline-and-indent) (newline)))
19800 ((org-at-table-p)
19801 (org-table-justify-field-maybe)
19802 (call-interactively 'org-table-next-row))
19803 ;; when `newline-and-indent' is called within a list, make sure
19804 ;; text moved stays inside the item.
19805 ((and (org-in-item-p) indent)
19806 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19807 (progn
19808 (save-match-data (newline))
19809 (org-indent-line-to (length (match-string 0))))
19810 (let ((ind (org-get-indentation)))
19811 (newline)
19812 (if (org-looking-back org-list-end-re)
19813 (org-indent-line)
19814 (org-indent-line-to ind)))))
19815 ((and org-return-follows-link
19816 (org-at-timestamp-p t)
19817 (not (eq org-ts-what 'after)))
19818 (org-follow-timestamp-link))
19819 ((and org-return-follows-link
19820 (let ((tprop (get-text-property (point) 'face)))
19821 (or (eq tprop 'org-link)
19822 (and (listp tprop) (memq 'org-link tprop)))))
19823 (call-interactively 'org-open-at-point))
19824 ((and (org-at-heading-p)
19825 (looking-at
19826 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19827 (org-show-entry)
19828 (end-of-line 1)
19829 (newline))
19830 (t (if indent (newline-and-indent) (newline))))))
19832 (defun org-return-indent ()
19833 "Goto next table row or insert a newline and indent.
19834 Calls `org-table-next-row' or `newline-and-indent', depending on
19835 context. See the individual commands for more information."
19836 (interactive)
19837 (org-return t))
19839 (defun org-ctrl-c-star ()
19840 "Compute table, or change heading status of lines.
19841 Calls `org-table-recalculate' or `org-toggle-heading',
19842 depending on context."
19843 (interactive)
19844 (cond
19845 ((org-at-table-p)
19846 (call-interactively 'org-table-recalculate))
19848 ;; Convert all lines in region to list items
19849 (call-interactively 'org-toggle-heading))))
19851 (defun org-ctrl-c-minus ()
19852 "Insert separator line in table or modify bullet status of line.
19853 Also turns a plain line or a region of lines into list items.
19854 Calls `org-table-insert-hline', `org-toggle-item', or
19855 `org-cycle-list-bullet', depending on context."
19856 (interactive)
19857 (cond
19858 ((org-at-table-p)
19859 (call-interactively 'org-table-insert-hline))
19860 ((org-region-active-p)
19861 (call-interactively 'org-toggle-item))
19862 ((org-in-item-p)
19863 (call-interactively 'org-cycle-list-bullet))
19865 (call-interactively 'org-toggle-item))))
19867 (defun org-toggle-item (arg)
19868 "Convert headings or normal lines to items, items to normal lines.
19869 If there is no active region, only the current line is considered.
19871 If the first non blank line in the region is an headline, convert
19872 all headlines to items, shifting text accordingly.
19874 If it is an item, convert all items to normal lines.
19876 If it is normal text, change region into an item. With a prefix
19877 argument ARG, change each line in region into an item."
19878 (interactive "P")
19879 (let ((shift-text
19880 (function
19881 ;; Shift text in current section to IND, from point to END.
19882 ;; The function leaves point to END line.
19883 (lambda (ind end)
19884 (let ((min-i 1000) (end (copy-marker end)))
19885 ;; First determine the minimum indentation (MIN-I) of
19886 ;; the text.
19887 (save-excursion
19888 (catch 'exit
19889 (while (< (point) end)
19890 (let ((i (org-get-indentation)))
19891 (cond
19892 ;; Skip blank lines and inline tasks.
19893 ((looking-at "^[ \t]*$"))
19894 ((looking-at org-outline-regexp-bol))
19895 ;; We can't find less than 0 indentation.
19896 ((zerop i) (throw 'exit (setq min-i 0)))
19897 ((< i min-i) (setq min-i i))))
19898 (forward-line))))
19899 ;; Then indent each line so that a line indented to
19900 ;; MIN-I becomes indented to IND. Ignore blank lines
19901 ;; and inline tasks in the process.
19902 (let ((delta (- ind min-i)))
19903 (while (< (point) end)
19904 (unless (or (looking-at "^[ \t]*$")
19905 (looking-at org-outline-regexp-bol))
19906 (org-indent-line-to (+ (org-get-indentation) delta)))
19907 (forward-line)))))))
19908 (skip-blanks
19909 (function
19910 ;; Return beginning of first non-blank line, starting from
19911 ;; line at POS.
19912 (lambda (pos)
19913 (save-excursion
19914 (goto-char pos)
19915 (skip-chars-forward " \r\t\n")
19916 (point-at-bol)))))
19917 beg end)
19918 ;; Determine boundaries of changes.
19919 (if (org-region-active-p)
19920 (setq beg (funcall skip-blanks (region-beginning))
19921 end (copy-marker (region-end)))
19922 (setq beg (funcall skip-blanks (point-at-bol))
19923 end (copy-marker (point-at-eol))))
19924 ;; Depending on the starting line, choose an action on the text
19925 ;; between BEG and END.
19926 (org-with-limited-levels
19927 (save-excursion
19928 (goto-char beg)
19929 (cond
19930 ;; Case 1. Start at an item: de-itemize. Note that it only
19931 ;; happens when a region is active: `org-ctrl-c-minus'
19932 ;; would call `org-cycle-list-bullet' otherwise.
19933 ((org-at-item-p)
19934 (while (< (point) end)
19935 (when (org-at-item-p)
19936 (skip-chars-forward " \t")
19937 (delete-region (point) (match-end 0)))
19938 (forward-line)))
19939 ;; Case 2. Start at an heading: convert to items.
19940 ((org-at-heading-p)
19941 (let* ((bul (org-list-bullet-string "-"))
19942 (bul-len (length bul))
19943 ;; Indentation of the first heading. It should be
19944 ;; relative to the indentation of its parent, if any.
19945 (start-ind (save-excursion
19946 (cond
19947 ((not org-adapt-indentation) 0)
19948 ((not (outline-previous-heading)) 0)
19949 (t (length (match-string 0))))))
19950 ;; Level of first heading. Further headings will be
19951 ;; compared to it to determine hierarchy in the list.
19952 (ref-level (org-reduced-level (org-outline-level))))
19953 (while (< (point) end)
19954 (let* ((level (org-reduced-level (org-outline-level)))
19955 (delta (max 0 (- level ref-level))))
19956 ;; If current headline is less indented than the first
19957 ;; one, set it as reference, in order to preserve
19958 ;; subtrees.
19959 (when (< level ref-level) (setq ref-level level))
19960 (replace-match bul t t)
19961 (org-indent-line-to (+ start-ind (* delta bul-len)))
19962 ;; Ensure all text down to END (or SECTION-END) belongs
19963 ;; to the newly created item.
19964 (let ((section-end (save-excursion
19965 (or (outline-next-heading) (point)))))
19966 (forward-line)
19967 (funcall shift-text
19968 (+ start-ind (* (1+ delta) bul-len))
19969 (min end section-end)))))))
19970 ;; Case 3. Normal line with ARG: turn each non-item line into
19971 ;; an item.
19972 (arg
19973 (while (< (point) end)
19974 (unless (or (org-at-heading-p) (org-at-item-p))
19975 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19976 (replace-match
19977 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19978 (forward-line)))
19979 ;; Case 4. Normal line without ARG: make the first line of
19980 ;; region an item, and shift indentation of others
19981 ;; lines to set them as item's body.
19982 (t (let* ((bul (org-list-bullet-string "-"))
19983 (bul-len (length bul))
19984 (ref-ind (org-get-indentation)))
19985 (skip-chars-forward " \t")
19986 (insert bul)
19987 (forward-line)
19988 (while (< (point) end)
19989 ;; Ensure that lines less indented than first one
19990 ;; still get included in item body.
19991 (funcall shift-text
19992 (+ ref-ind bul-len)
19993 (min end (save-excursion (or (outline-next-heading)
19994 (point)))))
19995 (forward-line)))))))))
19997 (defun org-toggle-heading (&optional nstars)
19998 "Convert headings to normal text, or items or text to headings.
19999 If there is no active region, only the current line is considered.
20001 With a \\[universal-argument] prefix, convert the whole list at
20002 point into heading.
20004 In a region:
20006 - If the first non blank line is an headline, remove the stars
20007 from all headlines in the region.
20009 - If it is a normal line turn each and every normal line (i.e. not an
20010 heading or an item) in the region into a heading.
20012 - If it is a plain list item, turn all plain list items into headings.
20014 When converting a line into a heading, the number of stars is chosen
20015 such that the lines become children of the current entry. However,
20016 when a prefix argument is given, its value determines the number of
20017 stars to add."
20018 (interactive "P")
20019 (let ((skip-blanks
20020 (function
20021 ;; Return beginning of first non-blank line, starting from
20022 ;; line at POS.
20023 (lambda (pos)
20024 (save-excursion
20025 (goto-char pos)
20026 (while (org-at-comment-p) (forward-line))
20027 (skip-chars-forward " \r\t\n")
20028 (point-at-bol)))))
20029 beg end toggled)
20030 ;; Determine boundaries of changes. If a universal prefix has
20031 ;; been given, put the list in a region. If region ends at a bol,
20032 ;; do not consider the last line to be in the region.
20034 (when (and current-prefix-arg (org-at-item-p))
20035 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20036 (org-mark-element))
20038 (if (org-region-active-p)
20039 (setq beg (funcall skip-blanks (region-beginning))
20040 end (copy-marker (save-excursion
20041 (goto-char (region-end))
20042 (if (bolp) (point) (point-at-eol)))))
20043 (setq beg (funcall skip-blanks (point-at-bol))
20044 end (copy-marker (point-at-eol))))
20045 ;; Ensure inline tasks don't count as headings.
20046 (org-with-limited-levels
20047 (save-excursion
20048 (goto-char beg)
20049 (cond
20050 ;; Case 1. Started at an heading: de-star headings.
20051 ((org-at-heading-p)
20052 (while (< (point) end)
20053 (when (org-at-heading-p t)
20054 (looking-at org-outline-regexp) (replace-match "")
20055 (setq toggled t))
20056 (forward-line)))
20057 ;; Case 2. Started at an item: change items into headlines.
20058 ;; One star will be added by `org-list-to-subtree'.
20059 ((org-at-item-p)
20060 (let* ((stars (make-string
20061 (if nstars
20062 ;; subtract the star that will be added again by
20063 ;; `org-list-to-subtree'
20064 (1- (prefix-numeric-value current-prefix-arg))
20065 (or (org-current-level) 0))
20066 ?*))
20067 (add-stars
20068 (cond (nstars "") ; stars from prefix only
20069 ((equal stars "") "") ; before first heading
20070 (org-odd-levels-only "*") ; inside heading, odd
20071 (t "")))) ; inside heading, oddeven
20072 (while (< (point) end)
20073 (when (org-at-item-p)
20074 ;; Pay attention to cases when region ends before list.
20075 (let* ((struct (org-list-struct))
20076 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20077 (save-restriction
20078 (narrow-to-region (point) list-end)
20079 (insert
20080 (org-list-to-subtree
20081 (org-list-parse-list t)
20082 '(:istart (concat stars add-stars (funcall get-stars depth))
20083 :icount (concat stars add-stars (funcall get-stars depth)))))))
20084 (setq toggled t))
20085 (forward-line))))
20086 ;; Case 3. Started at normal text: make every line an heading,
20087 ;; skipping headlines and items.
20088 (t (let* ((stars (make-string
20089 (if nstars
20090 (prefix-numeric-value current-prefix-arg)
20091 (or (org-current-level) 0))
20092 ?*))
20093 (add-stars
20094 (cond (nstars "") ; stars from prefix only
20095 ((equal stars "") "*") ; before first heading
20096 (org-odd-levels-only "**") ; inside heading, odd
20097 (t "*"))) ; inside heading, oddeven
20098 (rpl (concat stars add-stars " ")))
20099 (while (< (point) end)
20100 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20101 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20102 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20103 (forward-line)))))))
20104 (unless toggled (message "Cannot toggle heading from here"))))
20106 (defun org-meta-return (&optional arg)
20107 "Insert a new heading or wrap a region in a table.
20108 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20109 See the individual commands for more information."
20110 (interactive "P")
20111 (cond
20112 ((run-hook-with-args-until-success 'org-metareturn-hook))
20113 ((or (org-at-drawer-p) (org-at-property-p))
20114 (newline-and-indent))
20115 ((org-at-table-p)
20116 (call-interactively 'org-table-wrap-region))
20117 (t (call-interactively 'org-insert-heading))))
20119 ;;; Menu entries
20121 (defsubst org-in-subtree-not-table-p ()
20122 "Are we in a subtree and not in a table?"
20123 (and (not (org-before-first-heading-p))
20124 (not (org-at-table-p))))
20126 ;; Define the Org-mode menus
20127 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20128 '("Tbl"
20129 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20130 ["Next Field" org-cycle (org-at-table-p)]
20131 ["Previous Field" org-shifttab (org-at-table-p)]
20132 ["Next Row" org-return (org-at-table-p)]
20133 "--"
20134 ["Blank Field" org-table-blank-field (org-at-table-p)]
20135 ["Edit Field" org-table-edit-field (org-at-table-p)]
20136 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20137 "--"
20138 ("Column"
20139 ["Move Column Left" org-metaleft (org-at-table-p)]
20140 ["Move Column Right" org-metaright (org-at-table-p)]
20141 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20142 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20143 ("Row"
20144 ["Move Row Up" org-metaup (org-at-table-p)]
20145 ["Move Row Down" org-metadown (org-at-table-p)]
20146 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20147 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20148 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20149 "--"
20150 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20151 ("Rectangle"
20152 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20153 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20154 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20155 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20156 "--"
20157 ("Calculate"
20158 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20159 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20160 ["Edit Formulas" org-edit-special (org-at-table-p)]
20161 "--"
20162 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20163 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20164 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20165 "--"
20166 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20167 "--"
20168 ["Sum Column/Rectangle" org-table-sum
20169 (or (org-at-table-p) (org-region-active-p))]
20170 ["Which Column?" org-table-current-column (org-at-table-p)])
20171 ["Debug Formulas"
20172 org-table-toggle-formula-debugger
20173 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20174 ["Show Col/Row Numbers"
20175 org-table-toggle-coordinate-overlays
20176 :style toggle
20177 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20178 "--"
20179 ["Create" org-table-create (and (not (org-at-table-p))
20180 org-enable-table-editor)]
20181 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20182 ["Import from File" org-table-import (not (org-at-table-p))]
20183 ["Export to File" org-table-export (org-at-table-p)]
20184 "--"
20185 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20187 (easy-menu-define org-org-menu org-mode-map "Org menu"
20188 '("Org"
20189 ("Show/Hide"
20190 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20191 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20192 ["Sparse Tree..." org-sparse-tree t]
20193 ["Reveal Context" org-reveal t]
20194 ["Show All" show-all t]
20195 "--"
20196 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20197 "--"
20198 ["New Heading" org-insert-heading t]
20199 ("Navigate Headings"
20200 ["Up" outline-up-heading t]
20201 ["Next" outline-next-visible-heading t]
20202 ["Previous" outline-previous-visible-heading t]
20203 ["Next Same Level" outline-forward-same-level t]
20204 ["Previous Same Level" outline-backward-same-level t]
20205 "--"
20206 ["Jump" org-goto t])
20207 ("Edit Structure"
20208 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20209 "--"
20210 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20211 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20212 "--"
20213 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20214 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20215 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20216 "--"
20217 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20218 "--"
20219 ["Copy visible text" org-copy-visible t]
20220 "--"
20221 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20222 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20223 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20224 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20225 "--"
20226 ["Sort Region/Children" org-sort t]
20227 "--"
20228 ["Convert to odd levels" org-convert-to-odd-levels t]
20229 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20230 ("Editing"
20231 ["Emphasis..." org-emphasize t]
20232 ["Edit Source Example" org-edit-special t]
20233 "--"
20234 ["Footnote new/jump" org-footnote-action t]
20235 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20236 ("Archive"
20237 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20238 "--"
20239 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20240 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20241 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20243 "--"
20244 ("Hyperlinks"
20245 ["Store Link (Global)" org-store-link t]
20246 ["Find existing link to here" org-occur-link-in-agenda-files t]
20247 ["Insert Link" org-insert-link t]
20248 ["Follow Link" org-open-at-point t]
20249 "--"
20250 ["Next link" org-next-link t]
20251 ["Previous link" org-previous-link t]
20252 "--"
20253 ["Descriptive Links"
20254 org-toggle-link-display
20255 :style radio
20256 :selected org-descriptive-links
20258 ["Literal Links"
20259 org-toggle-link-display
20260 :style radio
20261 :selected (not org-descriptive-links)])
20262 "--"
20263 ("TODO Lists"
20264 ["TODO/DONE/-" org-todo t]
20265 ("Select keyword"
20266 ["Next keyword" org-shiftright (org-at-heading-p)]
20267 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20268 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20269 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20270 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20271 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20272 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20273 "--"
20274 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20275 :selected org-enforce-todo-dependencies :style toggle :active t]
20276 "Settings for tree at point"
20277 ["Do Children sequentially" org-toggle-ordered-property :style radio
20278 :selected (org-entry-get nil "ORDERED")
20279 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20280 ["Do Children parallel" org-toggle-ordered-property :style radio
20281 :selected (not (org-entry-get nil "ORDERED"))
20282 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20283 "--"
20284 ["Set Priority" org-priority t]
20285 ["Priority Up" org-shiftup t]
20286 ["Priority Down" org-shiftdown t]
20287 "--"
20288 ["Get news from all feeds" org-feed-update-all t]
20289 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20290 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20291 ("TAGS and Properties"
20292 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20293 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20294 "--"
20295 ["Set property" org-set-property (not (org-before-first-heading-p))]
20296 ["Column view of properties" org-columns t]
20297 ["Insert Column View DBlock" org-insert-columns-dblock t])
20298 ("Dates and Scheduling"
20299 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20300 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20301 ("Change Date"
20302 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20303 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20304 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20305 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20306 ["Compute Time Range" org-evaluate-time-range t]
20307 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20308 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20309 "--"
20310 ["Custom time format" org-toggle-time-stamp-overlays
20311 :style radio :selected org-display-custom-times]
20312 "--"
20313 ["Goto Calendar" org-goto-calendar t]
20314 ["Date from Calendar" org-date-from-calendar t]
20315 "--"
20316 ["Start/Restart Timer" org-timer-start t]
20317 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20318 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20319 ["Insert Timer String" org-timer t]
20320 ["Insert Timer Item" org-timer-item t])
20321 ("Logging work"
20322 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20323 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20324 ["Clock out" org-clock-out t]
20325 ["Clock cancel" org-clock-cancel t]
20326 "--"
20327 ["Mark as default task" org-clock-mark-default-task t]
20328 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20329 ["Goto running clock" org-clock-goto t]
20330 "--"
20331 ["Display times" org-clock-display t]
20332 ["Create clock table" org-clock-report t]
20333 "--"
20334 ["Record DONE time"
20335 (progn (setq org-log-done (not org-log-done))
20336 (message "Switching to %s will %s record a timestamp"
20337 (car org-done-keywords)
20338 (if org-log-done "automatically" "not")))
20339 :style toggle :selected org-log-done])
20340 "--"
20341 ["Agenda Command..." org-agenda t]
20342 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20343 ("File List for Agenda")
20344 ("Special views current file"
20345 ["TODO Tree" org-show-todo-tree t]
20346 ["Check Deadlines" org-check-deadlines t]
20347 ["Timeline" org-timeline t]
20348 ["Tags/Property tree" org-match-sparse-tree t])
20349 "--"
20350 ["Export/Publish..." org-export-dispatch t]
20351 ("LaTeX"
20352 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20353 :selected org-cdlatex-mode]
20354 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20355 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20356 ["Modify math symbol" org-cdlatex-math-modify
20357 (org-inside-LaTeX-fragment-p)]
20358 ["Insert citation" org-reftex-citation t]
20359 "--"
20360 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20361 "--"
20362 ("MobileOrg"
20363 ["Push Files and Views" org-mobile-push t]
20364 ["Get Captured and Flagged" org-mobile-pull t]
20365 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20366 "--"
20367 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20368 "--"
20369 ("Documentation"
20370 ["Show Version" org-version t]
20371 ["Info Documentation" org-info t])
20372 ("Customize"
20373 ["Browse Org Group" org-customize t]
20374 "--"
20375 ["Expand This Menu" org-create-customize-menu
20376 (fboundp 'customize-menu-create)])
20377 ["Send bug report" org-submit-bug-report t]
20378 "--"
20379 ("Refresh/Reload"
20380 ["Refresh setup current buffer" org-mode-restart t]
20381 ["Reload Org (after update)" org-reload t]
20382 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20385 (defun org-info (&optional node)
20386 "Read documentation for Org-mode in the info system.
20387 With optional NODE, go directly to that node."
20388 (interactive)
20389 (info (format "(org)%s" (or node ""))))
20391 ;;;###autoload
20392 (defun org-submit-bug-report ()
20393 "Submit a bug report on Org-mode via mail.
20395 Don't hesitate to report any problems or inaccurate documentation.
20397 If you don't have setup sending mail from (X)Emacs, please copy the
20398 output buffer into your mail program, as it gives us important
20399 information about your Org-mode version and configuration."
20400 (interactive)
20401 (require 'reporter)
20402 (org-load-modules-maybe)
20403 (org-require-autoloaded-modules)
20404 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20405 (reporter-submit-bug-report
20406 "emacs-orgmode@gnu.org"
20407 (org-version nil 'full)
20408 (let (list)
20409 (save-window-excursion
20410 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20411 (delete-other-windows)
20412 (erase-buffer)
20413 (insert "You are about to submit a bug report to the Org-mode mailing list.
20415 We would like to add your full Org-mode and Outline configuration to the
20416 bug report. This greatly simplifies the work of the maintainer and
20417 other experts on the mailing list.
20419 HOWEVER, some variables you have customized may contain private
20420 information. The names of customers, colleagues, or friends, might
20421 appear in the form of file names, tags, todo states, or search strings.
20422 If you answer yes to the prompt, you might want to check and remove
20423 such private information before sending the email.")
20424 (add-text-properties (point-min) (point-max) '(face org-warning))
20425 (when (yes-or-no-p "Include your Org-mode configuration ")
20426 (mapatoms
20427 (lambda (v)
20428 (and (boundp v)
20429 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20430 (or (and (symbol-value v)
20431 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20432 (and
20433 (get v 'custom-type) (get v 'standard-value)
20434 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20435 (push v list)))))
20436 (kill-buffer (get-buffer "*Warn about privacy*"))
20437 list))
20438 nil nil
20439 "Remember to cover the basics, that is, what you expected to happen and
20440 what in fact did happen. You don't know how to make a good report? See
20442 http://orgmode.org/manual/Feedback.html#Feedback
20444 Your bug report will be posted to the Org-mode mailing list.
20445 ------------------------------------------------------------------------")
20446 (save-excursion
20447 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20448 (replace-match "\\1Bug: \\3 [\\2]")))))
20451 (defun org-install-agenda-files-menu ()
20452 (let ((bl (buffer-list)))
20453 (save-excursion
20454 (while bl
20455 (set-buffer (pop bl))
20456 (if (derived-mode-p 'org-mode) (setq bl nil)))
20457 (when (derived-mode-p 'org-mode)
20458 (easy-menu-change
20459 '("Org") "File List for Agenda"
20460 (append
20461 (list
20462 ["Edit File List" (org-edit-agenda-file-list) t]
20463 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20464 ["Remove Current File from List" org-remove-file t]
20465 ["Cycle through agenda files" org-cycle-agenda-files t]
20466 ["Occur in all agenda files" org-occur-in-agenda-files t]
20467 "--")
20468 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20470 ;;;; Documentation
20472 (defun org-require-autoloaded-modules ()
20473 (interactive)
20474 (mapc 'require
20475 '(org-agenda org-archive org-attach org-clock org-colview org-id
20476 org-remember org-table org-timer)))
20478 ;;;###autoload
20479 (defun org-reload (&optional uncompiled)
20480 "Reload all org lisp files.
20481 With prefix arg UNCOMPILED, load the uncompiled versions."
20482 (interactive "P")
20483 (require 'loadhist)
20484 (let* ((org-dir (org-find-library-dir "org"))
20485 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20486 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20487 (remove-re (mapconcat 'identity
20488 (mapcar (lambda (f) (concat "^" f "$"))
20489 (list (if (featurep 'xemacs)
20490 "org-colview"
20491 "org-colview-xemacs")
20492 "org" "org-loaddefs" "org-version"))
20493 "\\|"))
20494 (feats (delete-dups
20495 (mapcar 'file-name-sans-extension
20496 (mapcar 'file-name-nondirectory
20497 (delq nil
20498 (mapcar 'feature-file
20499 features))))))
20500 (lfeat (append
20501 (sort
20502 (setq feats
20503 (delq nil (mapcar
20504 (lambda (f)
20505 (if (and (string-match feature-re f)
20506 (not (string-match remove-re f)))
20507 f nil))
20508 feats)))
20509 'string-lessp)
20510 (list "org-version" "org")))
20511 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20512 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20513 load-uncore load-misses)
20514 (setq load-misses
20515 (delq 't
20516 (mapcar (lambda (f)
20517 (or (org-load-noerror-mustsuffix (concat org-dir f))
20518 (and (string= org-dir contrib-dir)
20519 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20520 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20521 (add-to-list 'load-uncore f 'append)
20524 lfeat)))
20525 (if load-uncore
20526 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20527 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20528 (if load-misses
20529 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20530 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20531 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20533 ;;;###autoload
20534 (defun org-customize ()
20535 "Call the customize function with org as argument."
20536 (interactive)
20537 (org-load-modules-maybe)
20538 (org-require-autoloaded-modules)
20539 (customize-browse 'org))
20541 (defun org-create-customize-menu ()
20542 "Create a full customization menu for Org-mode, insert it into the menu."
20543 (interactive)
20544 (org-load-modules-maybe)
20545 (org-require-autoloaded-modules)
20546 (if (fboundp 'customize-menu-create)
20547 (progn
20548 (easy-menu-change
20549 '("Org") "Customize"
20550 `(["Browse Org group" org-customize t]
20551 "--"
20552 ,(customize-menu-create 'org)
20553 ["Set" Custom-set t]
20554 ["Save" Custom-save t]
20555 ["Reset to Current" Custom-reset-current t]
20556 ["Reset to Saved" Custom-reset-saved t]
20557 ["Reset to Standard Settings" Custom-reset-standard t]))
20558 (message "\"Org\"-menu now contains full customization menu"))
20559 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20561 ;;;; Miscellaneous stuff
20563 ;;; Generally useful functions
20565 (defun org-get-at-bol (property)
20566 "Get text property PROPERTY at beginning of line."
20567 (get-text-property (point-at-bol) property))
20569 (defun org-find-text-property-in-string (prop s)
20570 "Return the first non-nil value of property PROP in string S."
20571 (or (get-text-property 0 prop s)
20572 (get-text-property (or (next-single-property-change 0 prop s) 0)
20573 prop s)))
20575 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20576 "Display the given MESSAGE as a warning."
20577 (if (fboundp 'display-warning)
20578 (display-warning 'org message
20579 (if (featurep 'xemacs) 'warning :warning))
20580 (let ((buf (get-buffer-create "*Org warnings*")))
20581 (with-current-buffer buf
20582 (goto-char (point-max))
20583 (insert "Warning (Org): " message)
20584 (unless (bolp)
20585 (newline)))
20586 (display-buffer buf)
20587 (sit-for 0))))
20589 (defun org-eval (form)
20590 "Eval FORM and return result."
20591 (condition-case error
20592 (eval form)
20593 (error (format "%%![Error: %s]" error))))
20595 (defun org-in-clocktable-p ()
20596 "Check if the cursor is in a clocktable."
20597 (let ((pos (point)) start)
20598 (save-excursion
20599 (end-of-line 1)
20600 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20601 (setq start (match-beginning 0))
20602 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20603 (>= (match-end 0) pos)
20604 start))))
20606 (defun org-in-commented-line ()
20607 "Is point in a line starting with `#'?"
20608 (equal (char-after (point-at-bol)) ?#))
20610 (defun org-in-indented-comment-line ()
20611 "Is point in a line starting with `#' after some white space?"
20612 (save-excursion
20613 (save-match-data
20614 (goto-char (point-at-bol))
20615 (looking-at "[ \t]*#"))))
20617 (defun org-in-verbatim-emphasis ()
20618 (save-match-data
20619 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20621 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20622 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20623 (if (and marker (marker-buffer marker)
20624 (buffer-live-p (marker-buffer marker)))
20625 (progn
20626 (org-pop-to-buffer-same-window (marker-buffer marker))
20627 (if (or (> marker (point-max)) (< marker (point-min)))
20628 (widen))
20629 (goto-char marker)
20630 (org-show-context 'org-goto))
20631 (if bookmark
20632 (bookmark-jump bookmark)
20633 (error "Cannot find location"))))
20635 (defun org-quote-csv-field (s)
20636 "Quote field for inclusion in CSV material."
20637 (if (string-match "[\",]" s)
20638 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20641 (defun org-force-self-insert (N)
20642 "Needed to enforce self-insert under remapping."
20643 (interactive "p")
20644 (self-insert-command N))
20646 (defun org-string-width (s)
20647 "Compute width of string, ignoring invisible characters.
20648 This ignores character with invisibility property `org-link', and also
20649 characters with property `org-cwidth', because these will become invisible
20650 upon the next fontification round."
20651 (let (b l)
20652 (when (or (eq t buffer-invisibility-spec)
20653 (assq 'org-link buffer-invisibility-spec))
20654 (while (setq b (text-property-any 0 (length s)
20655 'invisible 'org-link s))
20656 (setq s (concat (substring s 0 b)
20657 (substring s (or (next-single-property-change
20658 b 'invisible s) (length s)))))))
20659 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20660 (setq s (concat (substring s 0 b)
20661 (substring s (or (next-single-property-change
20662 b 'org-cwidth s) (length s))))))
20663 (setq l (string-width s) b -1)
20664 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20665 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20668 (defun org-shorten-string (s maxlength)
20669 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20670 If the string is shorter or has length MAXLENGTH, just return the
20671 original string. If it is longer, the functions finds a space in the
20672 string, breaks this string off at that locations and adds three dots
20673 as ellipsis. Including the ellipsis, the string will not be longer
20674 than MAXLENGTH. If finding a good breaking point in the string does
20675 not work, the string is just chopped off in the middle of a word
20676 if necessary."
20677 (if (<= (length s) maxlength)
20679 (let* ((n (max (- maxlength 4) 1))
20680 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20681 (if (string-match re s)
20682 (concat (match-string 1 s) "...")
20683 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20685 (defun org-get-indentation (&optional line)
20686 "Get the indentation of the current line, interpreting tabs.
20687 When LINE is given, assume it represents a line and compute its indentation."
20688 (if line
20689 (if (string-match "^ *" (org-remove-tabs line))
20690 (match-end 0))
20691 (save-excursion
20692 (beginning-of-line 1)
20693 (skip-chars-forward " \t")
20694 (current-column))))
20696 (defun org-get-string-indentation (s)
20697 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20698 (let ((n -1) (i 0) (w tab-width) c)
20699 (catch 'exit
20700 (while (< (setq n (1+ n)) (length s))
20701 (setq c (aref s n))
20702 (cond ((= c ?\ ) (setq i (1+ i)))
20703 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20704 (t (throw 'exit t)))))
20707 (defun org-remove-tabs (s &optional width)
20708 "Replace tabulators in S with spaces.
20709 Assumes that s is a single line, starting in column 0."
20710 (setq width (or width tab-width))
20711 (while (string-match "\t" s)
20712 (setq s (replace-match
20713 (make-string
20714 (- (* width (/ (+ (match-beginning 0) width) width))
20715 (match-beginning 0)) ?\ )
20716 t t s)))
20719 (defun org-fix-indentation (line ind)
20720 "Fix indentation in LINE.
20721 IND is a cons cell with target and minimum indentation.
20722 If the current indentation in LINE is smaller than the minimum,
20723 leave it alone. If it is larger than ind, set it to the target."
20724 (let* ((l (org-remove-tabs line))
20725 (i (org-get-indentation l))
20726 (i1 (car ind)) (i2 (cdr ind)))
20727 (if (>= i i2) (setq l (substring line i2)))
20728 (if (> i1 0)
20729 (concat (make-string i1 ?\ ) l)
20730 l)))
20732 (defun org-remove-indentation (code &optional n)
20733 "Remove the maximum common indentation from the lines in CODE.
20734 N may optionally be the number of spaces to remove."
20735 (with-temp-buffer
20736 (insert code)
20737 (org-do-remove-indentation n)
20738 (buffer-string)))
20740 (defun org-do-remove-indentation (&optional n)
20741 "Remove the maximum common indentation from the buffer."
20742 (untabify (point-min) (point-max))
20743 (let ((min 10000) re)
20744 (if n
20745 (setq min n)
20746 (goto-char (point-min))
20747 (while (re-search-forward "^ *[^ \n]" nil t)
20748 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20749 (unless (or (= min 0) (= min 10000))
20750 (setq re (format "^ \\{%d\\}" min))
20751 (goto-char (point-min))
20752 (while (re-search-forward re nil t)
20753 (replace-match "")
20754 (end-of-line 1))
20755 min)))
20757 (defun org-fill-template (template alist)
20758 "Find each %key of ALIST in TEMPLATE and replace it."
20759 (let ((case-fold-search nil)
20760 entry key value)
20761 (setq alist (sort (copy-sequence alist)
20762 (lambda (a b) (< (length (car a)) (length (car b))))))
20763 (while (setq entry (pop alist))
20764 (setq template
20765 (replace-regexp-in-string
20766 (concat "%" (regexp-quote (car entry)))
20767 (or (cdr entry) "") template t t)))
20768 template))
20770 (defun org-base-buffer (buffer)
20771 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20772 (if (not buffer)
20773 buffer
20774 (or (buffer-base-buffer buffer)
20775 buffer)))
20777 (defun org-trim (s)
20778 "Remove whitespace at beginning and end of string."
20779 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20780 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20783 (defun org-wrap (string &optional width lines)
20784 "Wrap string to either a number of lines, or a width in characters.
20785 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20786 that costs. If there is a word longer than WIDTH, the text is actually
20787 wrapped to the length of that word.
20788 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20789 many lines, whatever width that takes.
20790 The return value is a list of lines, without newlines at the end."
20791 (let* ((words (org-split-string string "[ \t\n]+"))
20792 (maxword (apply 'max (mapcar 'org-string-width words)))
20793 w ll)
20794 (cond (width
20795 (org-do-wrap words (max maxword width)))
20796 (lines
20797 (setq w maxword)
20798 (setq ll (org-do-wrap words maxword))
20799 (if (<= (length ll) lines)
20801 (setq ll words)
20802 (while (> (length ll) lines)
20803 (setq w (1+ w))
20804 (setq ll (org-do-wrap words w)))
20805 ll))
20806 (t (error "Cannot wrap this")))))
20808 (defun org-do-wrap (words width)
20809 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20810 (let (lines line)
20811 (while words
20812 (setq line (pop words))
20813 (while (and words (< (+ (length line) (length (car words))) width))
20814 (setq line (concat line " " (pop words))))
20815 (setq lines (push line lines)))
20816 (nreverse lines)))
20818 (defun org-split-string (string &optional separators)
20819 "Splits STRING into substrings at SEPARATORS.
20820 No empty strings are returned if there are matches at the beginning
20821 and end of string."
20822 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20823 (start 0)
20824 notfirst
20825 (list nil))
20826 (while (and (string-match rexp string
20827 (if (and notfirst
20828 (= start (match-beginning 0))
20829 (< start (length string)))
20830 (1+ start) start))
20831 (< (match-beginning 0) (length string)))
20832 (setq notfirst t)
20833 (or (eq (match-beginning 0) 0)
20834 (and (eq (match-beginning 0) (match-end 0))
20835 (eq (match-beginning 0) start))
20836 (setq list
20837 (cons (substring string start (match-beginning 0))
20838 list)))
20839 (setq start (match-end 0)))
20840 (or (eq start (length string))
20841 (setq list
20842 (cons (substring string start)
20843 list)))
20844 (nreverse list)))
20846 (defun org-quote-vert (s)
20847 "Replace \"|\" with \"\\vert\"."
20848 (while (string-match "|" s)
20849 (setq s (replace-match "\\vert" t t s)))
20852 (defun org-uuidgen-p (s)
20853 "Is S an ID created by UUIDGEN?"
20854 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20856 (defun org-in-src-block-p (&optional inside)
20857 "Whether point is in a code source block.
20858 When INSIDE is non-nil, don't consider we are within a src block
20859 when point is at #+BEGIN_SRC or #+END_SRC."
20860 (let ((case-fold-search t) ov)
20861 (or (and (setq ov (overlays-at (point)))
20862 (memq 'org-block-background
20863 (overlay-properties (car ov))))
20864 (and (not inside)
20865 (save-match-data
20866 (save-excursion
20867 (beginning-of-line)
20868 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20870 (defun org-context ()
20871 "Return a list of contexts of the current cursor position.
20872 If several contexts apply, all are returned.
20873 Each context entry is a list with a symbol naming the context, and
20874 two positions indicating start and end of the context. Possible
20875 contexts are:
20877 :headline anywhere in a headline
20878 :headline-stars on the leading stars in a headline
20879 :todo-keyword on a TODO keyword (including DONE) in a headline
20880 :tags on the TAGS in a headline
20881 :priority on the priority cookie in a headline
20882 :item on the first line of a plain list item
20883 :item-bullet on the bullet/number of a plain list item
20884 :checkbox on the checkbox in a plain list item
20885 :table in an org-mode table
20886 :table-special on a special filed in a table
20887 :table-table in a table.el table
20888 :clocktable in a clocktable
20889 :src-block in a source block
20890 :link on a hyperlink
20891 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20892 :target on a <<target>>
20893 :radio-target on a <<<radio-target>>>
20894 :latex-fragment on a LaTeX fragment
20895 :latex-preview on a LaTeX fragment with overlaid preview image
20897 This function expects the position to be visible because it uses font-lock
20898 faces as a help to recognize the following contexts: :table-special, :link,
20899 and :keyword."
20900 (let* ((f (get-text-property (point) 'face))
20901 (faces (if (listp f) f (list f)))
20902 (case-fold-search t)
20903 (p (point)) clist o)
20904 ;; First the large context
20905 (cond
20906 ((org-at-heading-p t)
20907 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20908 (when (progn
20909 (beginning-of-line 1)
20910 (looking-at org-todo-line-tags-regexp))
20911 (push (org-point-in-group p 1 :headline-stars) clist)
20912 (push (org-point-in-group p 2 :todo-keyword) clist)
20913 (push (org-point-in-group p 4 :tags) clist))
20914 (goto-char p)
20915 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20916 (if (looking-at "\\[#[A-Z0-9]\\]")
20917 (push (org-point-in-group p 0 :priority) clist)))
20919 ((org-at-item-p)
20920 (push (org-point-in-group p 2 :item-bullet) clist)
20921 (push (list :item (point-at-bol)
20922 (save-excursion (org-end-of-item) (point)))
20923 clist)
20924 (and (org-at-item-checkbox-p)
20925 (push (org-point-in-group p 0 :checkbox) clist)))
20927 ((org-at-table-p)
20928 (push (list :table (org-table-begin) (org-table-end)) clist)
20929 (if (memq 'org-formula faces)
20930 (push (list :table-special
20931 (previous-single-property-change p 'face)
20932 (next-single-property-change p 'face)) clist)))
20933 ((org-at-table-p 'any)
20934 (push (list :table-table) clist)))
20935 (goto-char p)
20937 (let ((case-fold-search t))
20938 ;; New the "medium" contexts: clocktables, source blocks
20939 (cond ((org-in-clocktable-p)
20940 (push (list :clocktable
20941 (and (or (looking-at "#\\+BEGIN: clocktable")
20942 (search-backward "#+BEGIN: clocktable" nil t))
20943 (match-beginning 0))
20944 (and (re-search-forward "#\\+END:?" nil t)
20945 (match-end 0))) clist))
20946 ((org-in-src-block-p)
20947 (push (list :src-block
20948 (and (or (looking-at "#\\+BEGIN_SRC")
20949 (search-backward "#+BEGIN_SRC" nil t))
20950 (match-beginning 0))
20951 (and (search-forward "#+END_SRC" nil t)
20952 (match-beginning 0))) clist))))
20953 (goto-char p)
20955 ;; Now the small context
20956 (cond
20957 ((org-at-timestamp-p)
20958 (push (org-point-in-group p 0 :timestamp) clist))
20959 ((memq 'org-link faces)
20960 (push (list :link
20961 (previous-single-property-change p 'face)
20962 (next-single-property-change p 'face)) clist))
20963 ((memq 'org-special-keyword faces)
20964 (push (list :keyword
20965 (previous-single-property-change p 'face)
20966 (next-single-property-change p 'face)) clist))
20967 ((org-at-target-p)
20968 (push (org-point-in-group p 0 :target) clist)
20969 (goto-char (1- (match-beginning 0)))
20970 (if (looking-at org-radio-target-regexp)
20971 (push (org-point-in-group p 0 :radio-target) clist))
20972 (goto-char p))
20973 ((setq o (car (delq nil
20974 (mapcar
20975 (lambda (x)
20976 (if (memq x org-latex-fragment-image-overlays) x))
20977 (overlays-at (point))))))
20978 (push (list :latex-fragment
20979 (overlay-start o) (overlay-end o)) clist)
20980 (push (list :latex-preview
20981 (overlay-start o) (overlay-end o)) clist))
20982 ((org-inside-LaTeX-fragment-p)
20983 ;; FIXME: positions wrong.
20984 (push (list :latex-fragment (point) (point)) clist)))
20986 (setq clist (nreverse (delq nil clist)))
20987 clist))
20989 ;; FIXME: Compare with at-regexp-p Do we need both?
20990 (defun org-in-regexp (re &optional nlines visually)
20991 "Check if point is inside a match of regexp.
20992 Normally only the current line is checked, but you can include NLINES extra
20993 lines both before and after point into the search.
20994 If VISUALLY is set, require that the cursor is not after the match but
20995 really on, so that the block visually is on the match."
20996 (catch 'exit
20997 (let ((pos (point))
20998 (eol (point-at-eol (+ 1 (or nlines 0))))
20999 (inc (if visually 1 0)))
21000 (save-excursion
21001 (beginning-of-line (- 1 (or nlines 0)))
21002 (while (re-search-forward re eol t)
21003 (if (and (<= (match-beginning 0) pos)
21004 (>= (+ inc (match-end 0)) pos))
21005 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21007 (defun org-at-regexp-p (regexp)
21008 "Is point inside a match of REGEXP in the current line?"
21009 (catch 'exit
21010 (save-excursion
21011 (let ((pos (point)) (end (point-at-eol)))
21012 (beginning-of-line 1)
21013 (while (re-search-forward regexp end t)
21014 (if (and (<= (match-beginning 0) pos)
21015 (>= (match-end 0) pos))
21016 (throw 'exit t)))
21017 nil))))
21019 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21020 "Non-nil when point is between matches of START-RE and END-RE.
21022 Also return a non-nil value when point is on one of the matches.
21024 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21025 buffer positions. Default values are the positions of headlines
21026 surrounding the point.
21028 The functions returns a cons cell whose car (resp. cdr) is the
21029 position before START-RE (resp. after END-RE)."
21030 (save-match-data
21031 (let ((pos (point))
21032 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21033 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21034 beg end)
21035 (save-excursion
21036 ;; Point is on a block when on START-RE or if START-RE can be
21037 ;; found before it...
21038 (and (or (org-at-regexp-p start-re)
21039 (re-search-backward start-re limit-up t))
21040 (setq beg (match-beginning 0))
21041 ;; ... and END-RE after it...
21042 (goto-char (match-end 0))
21043 (re-search-forward end-re limit-down t)
21044 (> (setq end (match-end 0)) pos)
21045 ;; ... without another START-RE in-between.
21046 (goto-char (match-beginning 0))
21047 (not (re-search-backward start-re (1+ beg) t))
21048 ;; Return value.
21049 (cons beg end))))))
21051 (defun org-in-block-p (names)
21052 "Non-nil when point belongs to a block whose name belongs to NAMES.
21054 NAMES is a list of strings containing names of blocks.
21056 Return first block name matched, or nil. Beware that in case of
21057 nested blocks, the returned name may not belong to the closest
21058 block from point."
21059 (save-match-data
21060 (catch 'exit
21061 (let ((case-fold-search t)
21062 (lim-up (save-excursion (outline-previous-heading)))
21063 (lim-down (save-excursion (outline-next-heading))))
21064 (mapc (lambda (name)
21065 (let ((n (regexp-quote name)))
21066 (when (org-between-regexps-p
21067 (concat "^[ \t]*#\\+begin_" n)
21068 (concat "^[ \t]*#\\+end_" n)
21069 lim-up lim-down)
21070 (throw 'exit n))))
21071 names))
21072 nil)))
21074 (defun org-occur-in-agenda-files (regexp &optional nlines)
21075 "Call `multi-occur' with buffers for all agenda files."
21076 (interactive "sOrg-files matching: \np")
21077 (let* ((files (org-agenda-files))
21078 (tnames (mapcar 'file-truename files))
21079 (extra org-agenda-text-search-extra-files)
21081 (when (eq (car extra) 'agenda-archives)
21082 (setq extra (cdr extra))
21083 (setq files (org-add-archive-files files)))
21084 (while (setq f (pop extra))
21085 (unless (member (file-truename f) tnames)
21086 (add-to-list 'files f 'append)
21087 (add-to-list 'tnames (file-truename f) 'append)))
21088 (multi-occur
21089 (mapcar (lambda (x)
21090 (with-current-buffer
21091 (or (get-file-buffer x) (find-file-noselect x))
21092 (widen)
21093 (current-buffer)))
21094 files)
21095 regexp)))
21097 (if (boundp 'occur-mode-find-occurrence-hook)
21098 ;; Emacs 23
21099 (add-hook 'occur-mode-find-occurrence-hook
21100 (lambda ()
21101 (when (derived-mode-p 'org-mode)
21102 (org-reveal))))
21103 ;; Emacs 22
21104 (defadvice occur-mode-goto-occurrence
21105 (after org-occur-reveal activate)
21106 (and (derived-mode-p 'org-mode) (org-reveal)))
21107 (defadvice occur-mode-goto-occurrence-other-window
21108 (after org-occur-reveal activate)
21109 (and (derived-mode-p 'org-mode) (org-reveal)))
21110 (defadvice occur-mode-display-occurrence
21111 (after org-occur-reveal activate)
21112 (when (derived-mode-p 'org-mode)
21113 (let ((pos (occur-mode-find-occurrence)))
21114 (with-current-buffer (marker-buffer pos)
21115 (save-excursion
21116 (goto-char pos)
21117 (org-reveal)))))))
21119 (defun org-occur-link-in-agenda-files ()
21120 "Create a link and search for it in the agendas.
21121 The link is not stored in `org-stored-links', it is just created
21122 for the search purpose."
21123 (interactive)
21124 (let ((link (condition-case nil
21125 (org-store-link nil)
21126 (error "Unable to create a link to here"))))
21127 (org-occur-in-agenda-files (regexp-quote link))))
21129 (defun org-uniquify (list)
21130 "Remove duplicate elements from LIST."
21131 (let (res)
21132 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21133 res))
21135 (defun org-delete-all (elts list)
21136 "Remove all elements in ELTS from LIST."
21137 (while elts
21138 (setq list (delete (pop elts) list)))
21139 list)
21141 (defun org-count (cl-item cl-seq)
21142 "Count the number of occurrences of ITEM in SEQ.
21143 Taken from `count' in cl-seq.el with all keyword arguments removed."
21144 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21145 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21146 (while (< cl-start cl-end)
21147 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21148 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21149 (setq cl-start (1+ cl-start)))
21150 cl-count))
21152 (defun org-remove-if (predicate seq)
21153 "Remove everything from SEQ that fulfills PREDICATE."
21154 (let (res e)
21155 (while seq
21156 (setq e (pop seq))
21157 (if (not (funcall predicate e)) (push e res)))
21158 (nreverse res)))
21160 (defun org-remove-if-not (predicate seq)
21161 "Remove everything from SEQ that does not fulfill PREDICATE."
21162 (let (res e)
21163 (while seq
21164 (setq e (pop seq))
21165 (if (funcall predicate e) (push e res)))
21166 (nreverse res)))
21168 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21169 "Reduce two-argument FUNCTION across SEQ.
21170 Taken from `reduce' in cl-seq.el with all keyword arguments but
21171 \":initial-value\" removed."
21172 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21173 (cadr (memq :initial-value cl-keys)))
21174 (cl-seq (pop cl-seq))
21175 (t (funcall cl-func)))))
21176 (while cl-seq
21177 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21178 cl-accum))
21180 (defun org-back-over-empty-lines ()
21181 "Move backwards over whitespace, to the beginning of the first empty line.
21182 Returns the number of empty lines passed."
21183 (let ((pos (point)))
21184 (if (cdr (assoc 'heading org-blank-before-new-entry))
21185 (skip-chars-backward " \t\n\r")
21186 (unless (eobp)
21187 (forward-line -1)))
21188 (beginning-of-line 2)
21189 (goto-char (min (point) pos))
21190 (count-lines (point) pos)))
21192 (defun org-skip-whitespace ()
21193 (skip-chars-forward " \t\n\r"))
21195 (defun org-point-in-group (point group &optional context)
21196 "Check if POINT is in match-group GROUP.
21197 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21198 match. If the match group does not exist or point is not inside it,
21199 return nil."
21200 (and (match-beginning group)
21201 (>= point (match-beginning group))
21202 (<= point (match-end group))
21203 (if context
21204 (list context (match-beginning group) (match-end group))
21205 t)))
21207 (defun org-switch-to-buffer-other-window (&rest args)
21208 "Switch to buffer in a second window on the current frame.
21209 In particular, do not allow pop-up frames.
21210 Returns the newly created buffer."
21211 (org-no-popups
21212 (apply 'switch-to-buffer-other-window args)))
21214 (defun org-combine-plists (&rest plists)
21215 "Create a single property list from all plists in PLISTS.
21216 The process starts by copying the first list, and then setting properties
21217 from the other lists. Settings in the last list are the most significant
21218 ones and overrule settings in the other lists."
21219 (let ((rtn (copy-sequence (pop plists)))
21220 p v ls)
21221 (while plists
21222 (setq ls (pop plists))
21223 (while ls
21224 (setq p (pop ls) v (pop ls))
21225 (setq rtn (plist-put rtn p v))))
21226 rtn))
21228 (defun org-replace-escapes (string table)
21229 "Replace %-escapes in STRING with values in TABLE.
21230 TABLE is an association list with keys like \"%a\" and string values.
21231 The sequences in STRING may contain normal field width and padding information,
21232 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21233 so values can contain further %-escapes if they are define later in TABLE."
21234 (let ((tbl (copy-alist table))
21235 (case-fold-search nil)
21236 (pchg 0)
21237 e re rpl)
21238 (while (setq e (pop tbl))
21239 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21240 (when (and (cdr e) (string-match re (cdr e)))
21241 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21242 (safe "SREF"))
21243 (add-text-properties 0 3 (list 'sref sref) safe)
21244 (setcdr e (replace-match safe t t (cdr e)))))
21245 (while (string-match re string)
21246 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21247 (cdr e)))
21248 (setq string (replace-match rpl t t string))))
21249 (while (setq pchg (next-property-change pchg string))
21250 (let ((sref (get-text-property pchg 'sref string)))
21251 (when (and sref (string-match "SREF" string pchg))
21252 (setq string (replace-match sref t t string)))))
21253 string))
21255 (defun org-sublist (list start end)
21256 "Return a section of LIST, from START to END.
21257 Counting starts at 1."
21258 (let (rtn (c start))
21259 (setq list (nthcdr (1- start) list))
21260 (while (and list (<= c end))
21261 (push (pop list) rtn)
21262 (setq c (1+ c)))
21263 (nreverse rtn)))
21265 (defun org-find-base-buffer-visiting (file)
21266 "Like `find-buffer-visiting' but always return the base buffer and
21267 not an indirect buffer."
21268 (let ((buf (or (get-file-buffer file)
21269 (find-buffer-visiting file))))
21270 (if buf
21271 (or (buffer-base-buffer buf) buf)
21272 nil)))
21274 (defun org-image-file-name-regexp (&optional extensions)
21275 "Return regexp matching the file names of images.
21276 If EXTENSIONS is given, only match these."
21277 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21278 (image-file-name-regexp)
21279 (let ((image-file-name-extensions
21280 (or extensions
21281 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21282 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21283 (concat "\\."
21284 (regexp-opt (nconc (mapcar 'upcase
21285 image-file-name-extensions)
21286 image-file-name-extensions)
21288 "\\'"))))
21290 (defun org-file-image-p (file &optional extensions)
21291 "Return non-nil if FILE is an image."
21292 (save-match-data
21293 (string-match (org-image-file-name-regexp extensions) file)))
21295 (defun org-get-cursor-date (&optional with-time)
21296 "Return the date at cursor in as a time.
21297 This works in the calendar and in the agenda, anywhere else it just
21298 returns the current time.
21299 If WITH-TIME is non-nil, returns the time of the event at point (in
21300 the agenda) or the current time of the day."
21301 (let (date day defd tp tm hod mod)
21302 (when with-time
21303 (setq tp (get-text-property (point) 'time))
21304 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21305 (setq hod (string-to-number (match-string 1 tp))
21306 mod (string-to-number (match-string 2 tp))))
21307 (or tp (setq hod (nth 2 (decode-time (current-time)))
21308 mod (nth 1 (decode-time (current-time))))))
21309 (cond
21310 ((eq major-mode 'calendar-mode)
21311 (setq date (calendar-cursor-to-date)
21312 defd (encode-time 0 (or mod 0) (or hod 0)
21313 (nth 1 date) (nth 0 date) (nth 2 date))))
21314 ((eq major-mode 'org-agenda-mode)
21315 (setq day (get-text-property (point) 'day))
21316 (if day
21317 (setq date (calendar-gregorian-from-absolute day)
21318 defd (encode-time 0 (or mod 0) (or hod 0)
21319 (nth 1 date) (nth 0 date) (nth 2 date))))))
21320 (or defd (current-time))))
21322 (defun org-mark-subtree (&optional up)
21323 "Mark the current subtree.
21324 This puts point at the start of the current subtree, and mark at
21325 the end. If a numeric prefix UP is given, move up into the
21326 hierarchy of headlines by UP levels before marking the subtree."
21327 (interactive "P")
21328 (org-with-limited-levels
21329 (cond ((org-at-heading-p) (beginning-of-line))
21330 ((org-before-first-heading-p) (error "Not in a subtree"))
21331 (t (outline-previous-visible-heading 1))))
21332 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21333 (if (org-called-interactively-p 'any)
21334 (call-interactively 'org-mark-element)
21335 (org-mark-element)))
21338 ;;; Macros
21340 ;; Macros are expanded with `org-macro-replace-all', which relies
21341 ;; internally on `org-macro-expand'.
21343 ;; Default templates for expansion are stored in the buffer-local
21344 ;; variable `org-macro-templates'. This variable is updated by
21345 ;; `org-macro-initialize-templates'.
21347 ;; Along with macros defined through #+MACRO: keyword, default
21348 ;; templates include the following hard-coded macros:
21349 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21350 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21352 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21353 ;; {{{title}}} will also be provided.
21356 (defvar org-macro-templates nil
21357 "Alist containing all macro templates in current buffer.
21358 Associations are in the shape of (NAME . TEMPLATE) where NAME
21359 stands for macro's name and template for its replacement value,
21360 both as strings. This is an internal variable. Do not set it
21361 directly, use instead:
21363 #+MACRO: name template")
21364 (make-variable-buffer-local 'org-macro-templates)
21366 (defun org-macro-expand (macro templates)
21367 "Return expanded MACRO, as a string.
21368 MACRO is an object, obtained, for example, with
21369 `org-element-context'. TEMPLATES is an alist of templates used
21370 for expansion. See `org-macro-templates' for a buffer-local
21371 default value. Return nil if no template was found."
21372 (let ((template
21373 ;; Macro names are case-insensitive.
21374 (cdr (assoc-string (org-element-property :key macro) templates t))))
21375 (when template
21376 (let ((value (replace-regexp-in-string
21377 "\\$[0-9]+"
21378 (lambda (arg)
21379 (or (nth (1- (string-to-number (substring arg 1)))
21380 (org-element-property :args macro))
21381 ;; No argument provided: remove
21382 ;; place-holder.
21383 ""))
21384 template)))
21385 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21386 (when (string-match "\\`(eval\\>" value)
21387 (setq value (eval (read value))))
21388 ;; Return string.
21389 (format "%s" (or value ""))))))
21391 (defun org-macro-replace-all (templates)
21392 "Replace all macros in current buffer by their expansion.
21393 TEMPLATES is an alist of templates used for expansion. See
21394 `org-macro-templates' for a buffer-local default value."
21395 (save-excursion
21396 (goto-char (point-min))
21397 (let (record)
21398 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21399 (let ((object (org-element-context)))
21400 (when (eq (org-element-type object) 'macro)
21401 (let* ((value (org-macro-expand object templates))
21402 (begin (org-element-property :begin object))
21403 (signature (list begin
21404 object
21405 (org-element-property :args object))))
21406 ;; Avoid circular dependencies by checking if the same
21407 ;; macro with the same arguments is expanded at the same
21408 ;; position twice.
21409 (if (member signature record)
21410 (error "Circular macro expansion: %s"
21411 (org-element-property :key object))
21412 (when value
21413 (push signature record)
21414 (delete-region
21415 begin
21416 ;; Preserve white spaces after the macro.
21417 (progn (goto-char (org-element-property :end object))
21418 (skip-chars-backward " \t")
21419 (point)))
21420 ;; Leave point before replacement in case of recursive
21421 ;; expansions.
21422 (save-excursion (insert value)))))))))))
21424 (defun org-macro-initialize-templates ()
21425 "Collect macro templates defined in current buffer.
21426 Templates are stored in buffer-local variable
21427 `org-macro-templates'. In addition to buffer-defined macros, the
21428 function installs the following ones: \"property\",
21429 \"time\". and, if the buffer is associated to a file,
21430 \"input-file\" and \"modification-time\"."
21431 (let ((case-fold-search t)
21432 (set-template
21433 (lambda (cell)
21434 ;; Add CELL to `org-macro-templates' if there's no
21435 ;; association matching its name already. Otherwise,
21436 ;; replace old association with the new one in that
21437 ;; variable.
21438 (let ((old-template (assoc (car cell) org-macro-templates)))
21439 (if old-template (setcdr old-template (cdr cell))
21440 (push cell org-macro-templates))))))
21441 ;; Install buffer-local macros.
21442 (org-with-wide-buffer
21443 (goto-char (point-min))
21444 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21445 (let ((element (org-element-at-point)))
21446 (when (eq (org-element-type element) 'keyword)
21447 (let ((value (org-element-property :value element)))
21448 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21449 (funcall set-template
21450 (cons (match-string 1 value)
21451 (or (match-string 2 value) "")))))))))
21452 ;; Install hard-coded macros.
21453 (mapc (lambda (cell) (funcall set-template cell))
21454 (list
21455 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21456 (cons "time" "(eval (format-time-string \"$1\"))")))
21457 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21458 (when (and visited-file (file-exists-p visited-file))
21459 (mapc (lambda (cell) (funcall set-template cell))
21460 (list
21461 (cons "input-file" (file-name-nondirectory visited-file))
21462 (cons "modification-time"
21463 (format "(eval (format-time-string \"$1\" '%s))"
21464 (prin1-to-string
21465 (nth 5 (file-attributes visited-file)))))))))))
21468 ;;; Indentation
21470 (defun org-indent-line ()
21471 "Indent line depending on context."
21472 (interactive)
21473 (let* ((pos (point))
21474 (itemp (org-at-item-p))
21475 (case-fold-search t)
21476 (org-drawer-regexp (or org-drawer-regexp "\000"))
21477 (inline-task-p (and (featurep 'org-inlinetask)
21478 (org-inlinetask-in-task-p)))
21479 (inline-re (and inline-task-p
21480 (org-inlinetask-outline-regexp)))
21481 column)
21482 (if (and orgstruct-is-++ (eq pos (point)))
21483 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21484 (indent-according-to-mode))
21485 (beginning-of-line 1)
21486 (cond
21487 ;; Headings
21488 ((looking-at org-outline-regexp) (setq column 0))
21489 ;; Footnote definition
21490 ((looking-at org-footnote-definition-re) (setq column 0))
21491 ;; Literal examples
21492 ((looking-at "[ \t]*:\\( \\|$\\)")
21493 (setq column (org-get-indentation))) ; do nothing
21494 ;; Lists
21495 ((ignore-errors (goto-char (org-in-item-p)))
21496 (setq column (if itemp
21497 (org-get-indentation)
21498 (org-list-item-body-column (point))))
21499 (goto-char pos))
21500 ;; Drawers
21501 ((and (looking-at "[ \t]*:END:")
21502 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21503 (save-excursion
21504 (goto-char (1- (match-beginning 1)))
21505 (setq column (current-column))))
21506 ;; Special blocks
21507 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21508 (save-excursion
21509 (re-search-backward
21510 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21511 (setq column (org-get-indentation (match-string 0))))
21512 ((and (not (looking-at "[ \t]*#\\+begin_"))
21513 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21514 (save-excursion
21515 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21516 (setq column
21517 (cond ((equal (downcase (match-string 1)) "src")
21518 ;; src blocks: let `org-edit-src-exit' handle them
21519 (org-get-indentation))
21520 ((equal (downcase (match-string 1)) "example")
21521 (max (org-get-indentation)
21522 (org-get-indentation (match-string 0))))
21524 (org-get-indentation (match-string 0))))))
21525 ;; This line has nothing special, look at the previous relevant
21526 ;; line to compute indentation
21528 (beginning-of-line 0)
21529 (while (and (not (bobp))
21530 (not (looking-at org-table-line-regexp))
21531 (not (looking-at org-drawer-regexp))
21532 ;; When point started in an inline task, do not move
21533 ;; above task starting line.
21534 (not (and inline-task-p (looking-at inline-re)))
21535 ;; Skip drawers, blocks, empty lines, verbatim,
21536 ;; comments, tables, footnotes definitions, lists,
21537 ;; inline tasks.
21538 (or (and (looking-at "[ \t]*:END:")
21539 (re-search-backward org-drawer-regexp nil t))
21540 (and (looking-at "[ \t]*#\\+end_")
21541 (re-search-backward "[ \t]*#\\+begin_"nil t))
21542 (looking-at "[ \t]*[\n:#|]")
21543 (looking-at org-footnote-definition-re)
21544 (and (ignore-errors (goto-char (org-in-item-p)))
21545 (goto-char
21546 (org-list-get-top-point (org-list-struct))))
21547 (and (not inline-task-p)
21548 (featurep 'org-inlinetask)
21549 (org-inlinetask-in-task-p)
21550 (or (org-inlinetask-goto-beginning) t))))
21551 (beginning-of-line 0))
21552 (cond
21553 ;; There was an heading above.
21554 ((looking-at "\\*+[ \t]+")
21555 (if (not org-adapt-indentation)
21556 (setq column 0)
21557 (goto-char (match-end 0))
21558 (setq column (current-column))))
21559 ;; A drawer had started and is unfinished
21560 ((looking-at org-drawer-regexp)
21561 (goto-char (1- (match-beginning 1)))
21562 (setq column (current-column)))
21563 ;; Else, nothing noticeable found: get indentation and go on.
21564 (t (setq column (org-get-indentation))))))
21565 ;; Now apply indentation and move cursor accordingly
21566 (goto-char pos)
21567 (if (<= (current-column) (current-indentation))
21568 (org-indent-line-to column)
21569 (save-excursion (org-indent-line-to column)))
21570 ;; Special polishing for properties, see `org-property-format'
21571 (setq column (current-column))
21572 (beginning-of-line 1)
21573 (if (looking-at
21574 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21575 (replace-match (concat (match-string 1)
21576 (format org-property-format
21577 (match-string 2) (match-string 3)))
21578 t t))
21579 (org-move-to-column column))))
21581 (defun org-indent-drawer ()
21582 "Indent the drawer at point."
21583 (interactive)
21584 (let ((p (point))
21585 (e (and (save-excursion (re-search-forward ":END:" nil t))
21586 (match-end 0)))
21587 (folded
21588 (save-excursion
21589 (end-of-line)
21590 (when (overlays-at (point))
21591 (member 'invisible (overlay-properties
21592 (car (overlays-at (point)))))))))
21593 (when folded (org-cycle))
21594 (indent-for-tab-command)
21595 (while (and (move-beginning-of-line 2) (< (point) e))
21596 (indent-for-tab-command))
21597 (goto-char p)
21598 (when folded (org-cycle)))
21599 (message "Drawer at point indented"))
21601 (defun org-indent-block ()
21602 "Indent the block at point."
21603 (interactive)
21604 (let ((p (point))
21605 (case-fold-search t)
21606 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21607 (match-end 0)))
21608 (folded
21609 (save-excursion
21610 (end-of-line)
21611 (when (overlays-at (point))
21612 (member 'invisible (overlay-properties
21613 (car (overlays-at (point)))))))))
21614 (when folded (org-cycle))
21615 (indent-for-tab-command)
21616 (while (and (move-beginning-of-line 2) (< (point) e))
21617 (indent-for-tab-command))
21618 (goto-char p)
21619 (when folded (org-cycle)))
21620 (message "Block at point indented"))
21622 (defun org-indent-region (start end)
21623 "Indent region."
21624 (interactive "r")
21625 (save-excursion
21626 (let ((line-end (org-current-line end)))
21627 (goto-char start)
21628 (while (< (org-current-line) line-end)
21629 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21630 (t (call-interactively 'org-indent-line)))
21631 (move-beginning-of-line 2)))))
21634 ;;; Filling
21636 ;; We use our own fill-paragraph and auto-fill functions.
21638 ;; `org-fill-paragraph' relies on adaptive filling and context
21639 ;; checking. Appropriate `fill-prefix' is computed with
21640 ;; `org-adaptive-fill-function'.
21642 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21643 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21644 ;; `org-adaptive-fill-function' value. Internally,
21645 ;; `org-comment-line-break-function' breaks the line.
21647 ;; `org-setup-filling' installs filling and auto-filling related
21648 ;; variables during `org-mode' initialization.
21650 (defun org-setup-filling ()
21651 (interactive)
21652 ;; Prevent auto-fill from inserting unwanted new items.
21653 (when (boundp 'fill-nobreak-predicate)
21654 (org-set-local
21655 'fill-nobreak-predicate
21656 (org-uniquify
21657 (append fill-nobreak-predicate
21658 '(org-fill-paragraph-separate-nobreak-p
21659 org-fill-line-break-nobreak-p
21660 org-fill-paragraph-with-timestamp-nobreak-p)))))
21661 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21662 (org-set-local 'auto-fill-inhibit-regexp nil)
21663 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21664 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21665 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21667 (defvar org-element-paragraph-separate) ; org-element.el
21668 (defun org-fill-paragraph-separate-nobreak-p ()
21669 "Non-nil when a line break at point would insert a new item."
21670 (looking-at (substring org-element-paragraph-separate 1)))
21672 (defun org-fill-line-break-nobreak-p ()
21673 "Non-nil when a line break at point would create an Org line break."
21674 (save-excursion
21675 (skip-chars-backward "[ \t]")
21676 (skip-chars-backward "\\\\")
21677 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21679 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21680 "Non-nil when a line break at point would insert a new item."
21681 (and (org-at-timestamp-p t)
21682 (not (looking-at org-ts-regexp-both))))
21684 (declare-function message-in-body-p "message" ())
21685 (defvar orgtbl-line-start-regexp) ; From org-table.el
21686 (defun org-adaptive-fill-function ()
21687 "Compute a fill prefix for the current line.
21688 Return fill prefix, as a string, or nil if current line isn't
21689 meant to be filled."
21690 (let (prefix)
21691 (catch 'exit
21692 (when (derived-mode-p 'message-mode)
21693 (save-excursion
21694 (beginning-of-line)
21695 (cond ((or (not (message-in-body-p))
21696 (looking-at orgtbl-line-start-regexp))
21697 (throw 'exit nil))
21698 ((looking-at message-cite-prefix-regexp)
21699 (throw 'exit (match-string-no-properties 0)))
21700 ((looking-at org-outline-regexp)
21701 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21702 (org-with-wide-buffer
21703 (let* ((p (line-beginning-position))
21704 (element (save-excursion (beginning-of-line)
21705 (org-element-at-point)))
21706 (type (org-element-type element))
21707 (post-affiliated (org-element-property :post-affiliated element)))
21708 (unless (and post-affiliated (< p post-affiliated))
21709 (case type
21710 (comment (looking-at "[ \t]*# ?") (match-string 0))
21711 (footnote-definition "")
21712 ((item plain-list)
21713 (make-string (org-list-item-body-column
21714 (or post-affiliated
21715 (org-element-property :begin element)))
21716 ? ))
21717 (paragraph
21718 ;; Fill prefix is usually the same as the current line,
21719 ;; except if the paragraph is at the beginning of an item.
21720 (let ((parent (org-element-property :parent element)))
21721 (cond ((eq (org-element-type parent) 'item)
21722 (make-string (org-list-item-body-column
21723 (org-element-property :begin parent))
21724 ? ))
21725 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21726 (match-string 0))
21727 (t ""))))
21728 (comment-block
21729 ;; Only fill contents if P is within block boundaries.
21730 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21731 (forward-line)
21732 (point)))
21733 (cend (save-excursion
21734 (goto-char (org-element-property :end element))
21735 (skip-chars-backward " \r\t\n")
21736 (line-beginning-position))))
21737 (when (and (>= p cbeg) (< p cend))
21738 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21739 (match-string 0)
21740 "")))))))))))
21742 (declare-function message-goto-body "message" ())
21743 (defvar message-cite-prefix-regexp) ; From message.el
21744 (defvar org-element-all-objects) ; From org-element.el
21745 (defun org-fill-paragraph (&optional justify)
21746 "Fill element at point, when applicable.
21748 This function only applies to comment blocks, comments, example
21749 blocks and paragraphs. Also, as a special case, re-align table
21750 when point is at one.
21752 If JUSTIFY is non-nil (interactively, with prefix argument),
21753 justify as well. If `sentence-end-double-space' is non-nil, then
21754 period followed by one space does not end a sentence, so don't
21755 break a line there. The variable `fill-column' controls the
21756 width for filling.
21758 For convenience, when point is at a plain list, an item or
21759 a footnote definition, try to fill the first paragraph within."
21760 (interactive)
21761 (if (and (derived-mode-p 'message-mode)
21762 (or (not (message-in-body-p))
21763 (save-excursion (move-beginning-of-line 1)
21764 (looking-at message-cite-prefix-regexp))))
21765 ;; First ensure filling is correct in message-mode.
21766 (let ((fill-paragraph-function
21767 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21768 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21769 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21770 (paragraph-separate
21771 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21772 (fill-paragraph nil))
21773 (save-excursion
21774 ;; Move to end of line in order to get the first paragraph
21775 ;; within a plain list or a footnote definition.
21776 (end-of-line)
21777 (let ((element (org-element-at-point)))
21778 ;; First check if point is in a blank line at the beginning of
21779 ;; the buffer. In that case, ignore filling.
21780 (if (< (point) (org-element-property :begin element)) t
21781 (case (org-element-type element)
21782 ;; Use major mode filling function is src blocks.
21783 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21784 ;; Align Org tables, leave table.el tables as-is.
21785 (table-row (org-table-align) t)
21786 (table
21787 (when (eq (org-element-property :type element) 'org)
21788 (org-table-align))
21790 (paragraph
21791 ;; Paragraphs may contain `line-break' type objects.
21792 (let ((beg (max (point-min)
21793 (org-element-property :contents-begin element)))
21794 (end (min (point-max)
21795 (org-element-property :contents-end element))))
21796 ;; Do nothing if point is at an affiliated keyword.
21797 (if (< (point) beg) t
21798 (when (derived-mode-p 'message-mode)
21799 ;; In `message-mode', do not fill following
21800 ;; citation in current paragraph nor text before
21801 ;; message body.
21802 (let ((body-start (save-excursion (message-goto-body))))
21803 (when body-start (setq beg (max body-start beg))))
21804 (when (save-excursion
21805 (re-search-forward
21806 (concat "^" message-cite-prefix-regexp) end t))
21807 (setq end (match-beginning 0))))
21808 ;; Fill paragraph, taking line breaks into
21809 ;; consideration. For that, slice the paragraph
21810 ;; using line breaks as separators, and fill the
21811 ;; parts in reverse order to avoid messing with
21812 ;; markers.
21813 (save-excursion
21814 (goto-char end)
21815 (mapc
21816 (lambda (pos)
21817 (fill-region-as-paragraph pos (point) justify)
21818 (goto-char pos))
21819 ;; Find the list of ending positions for line
21820 ;; breaks in the current paragraph. Add paragraph
21821 ;; beginning to include first slice.
21822 (nreverse
21823 (cons
21825 (org-element-map
21826 (org-element--parse-objects
21827 beg end nil org-element-all-objects)
21828 'line-break
21829 (lambda (lb) (org-element-property :end lb)))))))
21830 t)))
21831 ;; Contents of `comment-block' type elements should be
21832 ;; filled as plain text, but only if point is within block
21833 ;; markers.
21834 (comment-block
21835 (let* ((case-fold-search t)
21836 (beg (save-excursion
21837 (goto-char (org-element-property :begin element))
21838 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21839 (forward-line)
21840 (point)))
21841 (end (save-excursion
21842 (goto-char (org-element-property :end element))
21843 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21844 (line-beginning-position))))
21845 (when (and (>= (point) beg) (< (point) end))
21846 (fill-region-as-paragraph
21847 (save-excursion
21848 (end-of-line)
21849 (re-search-backward "^[ \t]*$" beg 'move)
21850 (line-beginning-position))
21851 (save-excursion
21852 (beginning-of-line)
21853 (re-search-forward "^[ \t]*$" end 'move)
21854 (line-beginning-position))
21855 justify)))
21857 ;; Fill comments.
21858 (comment (fill-comment-paragraph justify))
21859 ;; Ignore every other element.
21860 (otherwise t)))))))
21862 (defun org-auto-fill-function ()
21863 "Auto-fill function."
21864 ;; Check if auto-filling is meaningful.
21865 (let ((fc (current-fill-column)))
21866 (when (and fc (> (current-column) fc))
21867 (let* ((fill-prefix (org-adaptive-fill-function))
21868 ;; Enforce empty fill prefix, if required. Otherwise, it
21869 ;; will be computed again.
21870 (adaptive-fill-mode (not (equal fill-prefix ""))))
21871 (when fill-prefix (do-auto-fill))))))
21873 (defun org-comment-line-break-function (&optional soft)
21874 "Break line at point and indent, continuing comment if within one.
21875 The inserted newline is marked hard if variable
21876 `use-hard-newlines' is true, unless optional argument SOFT is
21877 non-nil."
21878 (if soft (insert-and-inherit ?\n) (newline 1))
21879 (save-excursion (forward-char -1) (delete-horizontal-space))
21880 (delete-horizontal-space)
21881 (indent-to-left-margin)
21882 (insert-before-markers-and-inherit fill-prefix))
21885 ;;; Comments
21887 ;; Org comments syntax is quite complex. It requires the entire line
21888 ;; to be just a comment. Also, even with the right syntax at the
21889 ;; beginning of line, some some elements (i.e. verse-block or
21890 ;; example-block) don't accept comments. Usual Emacs comment commands
21891 ;; cannot cope with those requirements. Therefore, Org replaces them.
21893 ;; Org still relies on `comment-dwim', but cannot trust
21894 ;; `comment-only-p'. So, `comment-region-function' and
21895 ;; `uncomment-region-function' both point
21896 ;; to`org-comment-or-uncomment-region'. Eventually,
21897 ;; `org-insert-comment' takes care of insertion of comments at the
21898 ;; beginning of line.
21900 ;; `org-setup-comments-handling' install comments related variables
21901 ;; during `org-mode' initialization.
21903 (defun org-setup-comments-handling ()
21904 (interactive)
21905 (org-set-local 'comment-use-syntax nil)
21906 (org-set-local 'comment-start "# ")
21907 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21908 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21909 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21910 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21912 (defun org-insert-comment ()
21913 "Insert an empty comment above current line.
21914 If the line is empty, insert comment at its beginning."
21915 (beginning-of-line)
21916 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21917 (org-indent-line)
21918 (insert "# "))
21920 (defvar comment-empty-lines) ; From newcomment.el.
21921 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21922 "Comment or uncomment each non-blank line in the region.
21923 Uncomment each non-blank line between BEG and END if it only
21924 contains commented lines. Otherwise, comment them."
21925 (save-restriction
21926 ;; Restrict region
21927 (narrow-to-region (save-excursion (goto-char beg)
21928 (skip-chars-forward " \r\t\n" end)
21929 (line-beginning-position))
21930 (save-excursion (goto-char end)
21931 (skip-chars-backward " \r\t\n" beg)
21932 (line-end-position)))
21933 (let ((uncommentp
21934 ;; UNCOMMENTP is non-nil when every non blank line between
21935 ;; BEG and END is a comment.
21936 (save-excursion
21937 (goto-char (point-min))
21938 (while (and (not (eobp))
21939 (let ((element (org-element-at-point)))
21940 (and (eq (org-element-type element) 'comment)
21941 (goto-char (min (point-max)
21942 (org-element-property
21943 :end element)))))))
21944 (eobp))))
21945 (if uncommentp
21946 ;; Only blank lines and comments in region: uncomment it.
21947 (save-excursion
21948 (goto-char (point-min))
21949 (while (not (eobp))
21950 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21951 (replace-match "" nil nil nil 1))
21952 (forward-line)))
21953 ;; Comment each line in region.
21954 (let ((min-indent (point-max)))
21955 ;; First find the minimum indentation across all lines.
21956 (save-excursion
21957 (goto-char (point-min))
21958 (while (and (not (eobp)) (not (zerop min-indent)))
21959 (unless (looking-at "[ \t]*$")
21960 (setq min-indent (min min-indent (current-indentation))))
21961 (forward-line)))
21962 ;; Then loop over all lines.
21963 (save-excursion
21964 (goto-char (point-min))
21965 (while (not (eobp))
21966 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21967 (org-move-to-column min-indent t)
21968 (insert comment-start))
21969 (forward-line))))))))
21972 ;;; Planning
21974 ;; This section contains tools to operate on timestamp objects, as
21975 ;; returned by, e.g. `org-element-context'.
21977 (defun org-timestamp-has-time-p (timestamp)
21978 "Non-nil when TIMESTAMP has a time specified."
21979 (org-element-property :hour-start timestamp))
21981 (defun org-timestamp-format (timestamp format &optional end utc)
21982 "Format a TIMESTAMP element into a string.
21984 FORMAT is a format specifier to be passed to
21985 `format-time-string'.
21987 When optional argument END is non-nil, use end of date-range or
21988 time-range, if possible.
21990 When optional argument UTC is non-nil, time will be expressed as
21991 Universal Time."
21992 (format-time-string
21993 format
21994 (apply 'encode-time
21995 (cons 0
21996 (mapcar
21997 (lambda (prop) (or (org-element-property prop timestamp) 0))
21998 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21999 '(:minute-start :hour-start :day-start :month-start
22000 :year-start)))))
22001 utc))
22003 (defun org-timestamp-split-range (timestamp &optional end)
22004 "Extract a timestamp object from a date or time range.
22006 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22007 the end of the range. Otherwise, extract its start.
22009 Return a new timestamp object sharing the same parent as
22010 TIMESTAMP."
22011 (let ((type (org-element-property :type timestamp)))
22012 (if (memq type '(active inactive diary)) timestamp
22013 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22014 ;; Set new type.
22015 (org-element-put-property
22016 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22017 ;; Copy start properties over end properties if END is
22018 ;; non-nil. Otherwise, copy end properties over `start' ones.
22019 (let ((p-alist '((:minute-start . :minute-end)
22020 (:hour-start . :hour-end)
22021 (:day-start . :day-end)
22022 (:month-start . :month-end)
22023 (:year-start . :year-end))))
22024 (dolist (p-cell p-alist)
22025 (org-element-put-property
22026 split-ts
22027 (funcall (if end 'car 'cdr) p-cell)
22028 (org-element-property
22029 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22030 ;; Eventually refresh `:raw-value'.
22031 (org-element-put-property split-ts :raw-value nil)
22032 (org-element-put-property
22033 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22035 (defun org-timestamp-translate (timestamp &optional boundary)
22036 "Apply `org-translate-time' on a TIMESTAMP object.
22037 When optional argument BOUNDARY is non-nil, it is either the
22038 symbol `start' or `end'. In this case, only translate the
22039 starting or ending part of TIMESTAMP if it is a date or time
22040 range. Otherwise, translate both parts."
22041 (if (and (not boundary)
22042 (memq (org-element-property :type timestamp)
22043 '(active-range inactive-range)))
22044 (concat
22045 (org-translate-time
22046 (org-element-property :raw-value
22047 (org-timestamp-split-range timestamp)))
22048 "--"
22049 (org-translate-time
22050 (org-element-property :raw-value
22051 (org-timestamp-split-range timestamp t))))
22052 (org-translate-time
22053 (org-element-property
22054 :raw-value
22055 (if (not boundary) timestamp
22056 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22060 ;;; Other stuff.
22062 (defun org-toggle-fixed-width-section (arg)
22063 "Toggle the fixed-width export.
22064 If there is no active region, the QUOTE keyword at the current headline is
22065 inserted or removed. When present, it causes the text between this headline
22066 and the next to be exported as fixed-width text, and unmodified.
22067 If there is an active region, this command adds or removes a colon as the
22068 first character of this line. If the first character of a line is a colon,
22069 this line is also exported in fixed-width font."
22070 (interactive "P")
22071 (let* ((cc 0)
22072 (regionp (org-region-active-p))
22073 (beg (if regionp (region-beginning) (point)))
22074 (end (if regionp (region-end)))
22075 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22076 (case-fold-search nil)
22077 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22078 off)
22079 (if regionp
22080 (save-excursion
22081 (goto-char beg)
22082 (setq cc (current-column))
22083 (beginning-of-line 1)
22084 (setq off (looking-at re))
22085 (while (> nlines 0)
22086 (setq nlines (1- nlines))
22087 (beginning-of-line 1)
22088 (cond
22089 (arg
22090 (org-move-to-column cc t)
22091 (insert ": \n")
22092 (forward-line -1))
22093 ((and off (looking-at re))
22094 (replace-match "" t t nil 1))
22095 ((not off) (org-move-to-column cc t) (insert ": ")))
22096 (forward-line 1)))
22097 (save-excursion
22098 (org-back-to-heading)
22099 (cond
22100 ((looking-at (format org-heading-keyword-regexp-format
22101 org-quote-string))
22102 (goto-char (match-end 1))
22103 (looking-at (concat " +" org-quote-string))
22104 (replace-match "" t t)
22105 (when (eolp) (insert " ")))
22106 ((looking-at org-outline-regexp)
22107 (goto-char (match-end 0))
22108 (insert org-quote-string " ")))))))
22110 (defun org-reftex-citation ()
22111 "Use reftex-citation to insert a citation into the buffer.
22112 This looks for a line like
22114 #+BIBLIOGRAPHY: foo plain option:-d
22116 and derives from it that foo.bib is the bibliography file relevant
22117 for this document. It then installs the necessary environment for RefTeX
22118 to work in this buffer and calls `reftex-citation' to insert a citation
22119 into the buffer.
22121 Export of such citations to both LaTeX and HTML is handled by the contributed
22122 package org-exp-bibtex by Taru Karttunen."
22123 (interactive)
22124 (let ((reftex-docstruct-symbol 'rds)
22125 (reftex-cite-format "\\cite{%l}")
22126 rds bib)
22127 (save-excursion
22128 (save-restriction
22129 (widen)
22130 (let ((case-fold-search t)
22131 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22132 (if (not (save-excursion
22133 (or (re-search-forward re nil t)
22134 (re-search-backward re nil t))))
22135 (error "No bibliography defined in file")
22136 (setq bib (concat (match-string 1) ".bib")
22137 rds (list (list 'bib bib)))))))
22138 (call-interactively 'reftex-citation)))
22140 ;;;; Functions extending outline functionality
22142 (defun org-beginning-of-line (&optional arg)
22143 "Go to the beginning of the current line. If that is invisible, continue
22144 to a visible line beginning. This makes the function of C-a more intuitive.
22145 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22146 first attempt, and only move to after the tags when the cursor is already
22147 beyond the end of the headline."
22148 (interactive "P")
22149 (let ((pos (point))
22150 (special (if (consp org-special-ctrl-a/e)
22151 (car org-special-ctrl-a/e)
22152 org-special-ctrl-a/e))
22153 refpos)
22154 (if (org-bound-and-true-p visual-line-mode)
22155 (beginning-of-visual-line 1)
22156 (beginning-of-line 1))
22157 (if (and arg (fboundp 'move-beginning-of-line))
22158 (call-interactively 'move-beginning-of-line)
22159 (if (bobp)
22161 (backward-char 1)
22162 (if (org-truely-invisible-p)
22163 (while (and (not (bobp)) (org-truely-invisible-p))
22164 (backward-char 1)
22165 (beginning-of-line 1))
22166 (forward-char 1))))
22167 (when special
22168 (cond
22169 ((and (looking-at org-complex-heading-regexp)
22170 (= (char-after (match-end 1)) ?\ ))
22171 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22172 (point-at-eol)))
22173 (goto-char
22174 (if (eq special t)
22175 (cond ((> pos refpos) refpos)
22176 ((= pos (point)) refpos)
22177 (t (point)))
22178 (cond ((> pos (point)) (point))
22179 ((not (eq last-command this-command)) (point))
22180 (t refpos)))))
22181 ((org-at-item-p)
22182 ;; Being at an item and not looking at an the item means point
22183 ;; was previously moved to beginning of a visual line, which
22184 ;; doesn't contain the item. Therefore, do nothing special,
22185 ;; just stay here.
22186 (when (looking-at org-list-full-item-re)
22187 ;; Set special position at first white space character after
22188 ;; bullet, and check-box, if any.
22189 (let ((after-bullet
22190 (let ((box (match-end 3)))
22191 (if (not box) (match-end 1)
22192 (let ((after (char-after box)))
22193 (if (and after (= after ? )) (1+ box) box))))))
22194 ;; Special case: Move point to special position when
22195 ;; currently after it or at beginning of line.
22196 (if (eq special t)
22197 (when (or (> pos after-bullet) (= (point) pos))
22198 (goto-char after-bullet))
22199 ;; Reversed case: Move point to special position when
22200 ;; point was already at beginning of line and command is
22201 ;; repeated.
22202 (when (and (= (point) pos) (eq last-command this-command))
22203 (goto-char after-bullet))))))))
22204 (org-no-warnings
22205 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22207 (defun org-end-of-line (&optional arg)
22208 "Go to the end of the line.
22209 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22210 tags on the first attempt, and only move to after the tags when
22211 the cursor is already beyond the end of the headline."
22212 (interactive "P")
22213 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22214 org-special-ctrl-a/e))
22215 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22216 'end-of-visual-line)
22217 ((fboundp 'move-end-of-line) 'move-end-of-line)
22218 (t 'end-of-line))))
22219 (if (or (not special) arg) (call-interactively move-fun)
22220 (let* ((element (save-excursion (beginning-of-line)
22221 (org-element-at-point)))
22222 (type (org-element-type element)))
22223 (cond
22224 ((memq type '(headline inlinetask))
22225 (let ((pos (point)))
22226 (beginning-of-line 1)
22227 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22228 (if (eq special t)
22229 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22230 (goto-char (match-beginning 1))
22231 (goto-char (match-end 0)))
22232 (if (or (< pos (match-end 0))
22233 (not (eq this-command last-command)))
22234 (goto-char (match-end 0))
22235 (goto-char (match-beginning 1))))
22236 (call-interactively move-fun))))
22237 ((org-element-property :hiddenp element)
22238 ;; If element is hidden, `move-end-of-line' would put point
22239 ;; after it. Use `end-of-line' to stay on current line.
22240 (call-interactively 'end-of-line))
22241 (t (call-interactively move-fun)))))
22242 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22244 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22245 (define-key org-mode-map "\C-e" 'org-end-of-line)
22247 (defun org-backward-sentence (&optional arg)
22248 "Go to beginning of sentence, or beginning of table field.
22249 This will call `backward-sentence' or `org-table-beginning-of-field',
22250 depending on context."
22251 (interactive "P")
22252 (cond
22253 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22254 (t (call-interactively 'backward-sentence))))
22256 (defun org-forward-sentence (&optional arg)
22257 "Go to end of sentence, or end of table field.
22258 This will call `forward-sentence' or `org-table-end-of-field',
22259 depending on context."
22260 (interactive "P")
22261 (cond
22262 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22263 (t (call-interactively 'forward-sentence))))
22265 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22266 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22268 (defun org-kill-line (&optional arg)
22269 "Kill line, to tags or end of line."
22270 (interactive "P")
22271 (cond
22272 ((or (not org-special-ctrl-k)
22273 (bolp)
22274 (not (org-at-heading-p)))
22275 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22276 org-ctrl-k-protect-subtree)
22277 (if (or (eq org-ctrl-k-protect-subtree 'error)
22278 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22279 (error "C-k aborted - would kill hidden subtree")))
22280 (call-interactively
22281 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22282 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22283 (kill-region (point) (match-beginning 1))
22284 (org-set-tags nil t))
22285 (t (kill-region (point) (point-at-eol)))))
22287 (define-key org-mode-map "\C-k" 'org-kill-line)
22289 (defun org-yank (&optional arg)
22290 "Yank. If the kill is a subtree, treat it specially.
22291 This command will look at the current kill and check if is a single
22292 subtree, or a series of subtrees[1]. If it passes the test, and if the
22293 cursor is at the beginning of a line or after the stars of a currently
22294 empty headline, then the yank is handled specially. How exactly depends
22295 on the value of the following variables, both set by default.
22297 org-yank-folded-subtrees
22298 When set, the subtree(s) will be folded after insertion, but only
22299 if doing so would now swallow text after the yanked text.
22301 org-yank-adjusted-subtrees
22302 When set, the subtree will be promoted or demoted in order to
22303 fit into the local outline tree structure, which means that the level
22304 will be adjusted so that it becomes the smaller one of the two
22305 *visible* surrounding headings.
22307 Any prefix to this command will cause `yank' to be called directly with
22308 no special treatment. In particular, a simple \\[universal-argument] prefix \
22309 will just
22310 plainly yank the text as it is.
22312 \[1] The test checks if the first non-white line is a heading
22313 and if there are no other headings with fewer stars."
22314 (interactive "P")
22315 (org-yank-generic 'yank arg))
22317 (defun org-yank-generic (command arg)
22318 "Perform some yank-like command.
22320 This function implements the behavior described in the `org-yank'
22321 documentation. However, it has been generalized to work for any
22322 interactive command with similar behavior."
22324 ;; pretend to be command COMMAND
22325 (setq this-command command)
22327 (if arg
22328 (call-interactively command)
22330 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22331 (and (org-kill-is-subtree-p)
22332 (or (bolp)
22333 (and (looking-at "[ \t]*$")
22334 (string-match
22335 "\\`\\*+\\'"
22336 (buffer-substring (point-at-bol) (point)))))))
22337 swallowp)
22338 (cond
22339 ((and subtreep org-yank-folded-subtrees)
22340 (let ((beg (point))
22341 end)
22342 (if (and subtreep org-yank-adjusted-subtrees)
22343 (org-paste-subtree nil nil 'for-yank)
22344 (call-interactively command))
22346 (setq end (point))
22347 (goto-char beg)
22348 (when (and (bolp) subtreep
22349 (not (setq swallowp
22350 (org-yank-folding-would-swallow-text beg end))))
22351 (org-with-limited-levels
22352 (or (looking-at org-outline-regexp)
22353 (re-search-forward org-outline-regexp-bol end t))
22354 (while (and (< (point) end) (looking-at org-outline-regexp))
22355 (hide-subtree)
22356 (org-cycle-show-empty-lines 'folded)
22357 (condition-case nil
22358 (outline-forward-same-level 1)
22359 (error (goto-char end))))))
22360 (when swallowp
22361 (message
22362 "Inserted text not folded because that would swallow text"))
22364 (goto-char end)
22365 (skip-chars-forward " \t\n\r")
22366 (beginning-of-line 1)
22367 (push-mark beg 'nomsg)))
22368 ((and subtreep org-yank-adjusted-subtrees)
22369 (let ((beg (point-at-bol)))
22370 (org-paste-subtree nil nil 'for-yank)
22371 (push-mark beg 'nomsg)))
22373 (call-interactively command))))))
22375 (defun org-yank-folding-would-swallow-text (beg end)
22376 "Would hide-subtree at BEG swallow any text after END?"
22377 (let (level)
22378 (org-with-limited-levels
22379 (save-excursion
22380 (goto-char beg)
22381 (when (or (looking-at org-outline-regexp)
22382 (re-search-forward org-outline-regexp-bol end t))
22383 (setq level (org-outline-level)))
22384 (goto-char end)
22385 (skip-chars-forward " \t\r\n\v\f")
22386 (if (or (eobp)
22387 (and (bolp) (looking-at org-outline-regexp)
22388 (<= (org-outline-level) level)))
22389 nil ; Nothing would be swallowed
22390 t))))) ; something would swallow
22392 (define-key org-mode-map "\C-y" 'org-yank)
22394 (defun org-truely-invisible-p ()
22395 "Check if point is at a character currently not visible.
22396 This version does not only check the character property, but also
22397 `visible-mode'."
22398 ;; Early versions of noutline don't have `outline-invisible-p'.
22399 (if (org-bound-and-true-p visible-mode)
22401 (outline-invisible-p)))
22403 (defun org-invisible-p2 ()
22404 "Check if point is at a character currently not visible."
22405 (save-excursion
22406 (if (and (eolp) (not (bobp))) (backward-char 1))
22407 ;; Early versions of noutline don't have `outline-invisible-p'.
22408 (outline-invisible-p)))
22410 (defun org-back-to-heading (&optional invisible-ok)
22411 "Call `outline-back-to-heading', but provide a better error message."
22412 (condition-case nil
22413 (outline-back-to-heading invisible-ok)
22414 (error (error "Before first headline at position %d in buffer %s"
22415 (point) (current-buffer)))))
22417 (defun org-before-first-heading-p ()
22418 "Before first heading?"
22419 (save-excursion
22420 (end-of-line)
22421 (null (re-search-backward org-outline-regexp-bol nil t))))
22423 (defun org-at-heading-p (&optional ignored)
22424 (outline-on-heading-p t))
22425 ;; Compatibility alias with Org versions < 7.8.03
22426 (defalias 'org-on-heading-p 'org-at-heading-p)
22428 (defun org-at-comment-p nil
22429 "Is cursor in a line starting with a # character?"
22430 (save-excursion
22431 (beginning-of-line)
22432 (looking-at "^#")))
22434 (defun org-at-drawer-p nil
22435 "Is cursor at a drawer keyword?"
22436 (save-excursion
22437 (move-beginning-of-line 1)
22438 (looking-at org-drawer-regexp)))
22440 (defun org-at-block-p nil
22441 "Is cursor at a block keyword?"
22442 (save-excursion
22443 (move-beginning-of-line 1)
22444 (looking-at org-block-regexp)))
22446 (defun org-point-at-end-of-empty-headline ()
22447 "If point is at the end of an empty headline, return t, else nil.
22448 If the heading only contains a TODO keyword, it is still still considered
22449 empty."
22450 (and (looking-at "[ \t]*$")
22451 (when org-todo-line-regexp
22452 (save-excursion
22453 (beginning-of-line 1)
22454 (let ((case-fold-search nil))
22455 (looking-at org-todo-line-regexp)
22456 (string= (match-string 3) ""))))))
22458 (defun org-at-heading-or-item-p ()
22459 (or (org-at-heading-p) (org-at-item-p)))
22461 (defun org-at-target-p ()
22462 (or (org-in-regexp org-radio-target-regexp)
22463 (org-in-regexp org-target-regexp)))
22464 ;; Compatibility alias with Org versions < 7.8.03
22465 (defalias 'org-on-target-p 'org-at-target-p)
22467 (defun org-up-heading-all (arg)
22468 "Move to the heading line of which the present line is a subheading.
22469 This function considers both visible and invisible heading lines.
22470 With argument, move up ARG levels."
22471 (if (fboundp 'outline-up-heading-all)
22472 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22473 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22475 (defun org-up-heading-safe ()
22476 "Move to the heading line of which the present line is a subheading.
22477 This version will not throw an error. It will return the level of the
22478 headline found, or nil if no higher level is found.
22480 Also, this function will be a lot faster than `outline-up-heading',
22481 because it relies on stars being the outline starters. This can really
22482 make a significant difference in outlines with very many siblings."
22483 (let (start-level re)
22484 (org-back-to-heading t)
22485 (setq start-level (funcall outline-level))
22486 (if (equal start-level 1)
22488 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22489 (if (re-search-backward re nil t)
22490 (funcall outline-level)))))
22492 (defun org-first-sibling-p ()
22493 "Is this heading the first child of its parents?"
22494 (interactive)
22495 (let ((re org-outline-regexp-bol)
22496 level l)
22497 (unless (org-at-heading-p t)
22498 (error "Not at a heading"))
22499 (setq level (funcall outline-level))
22500 (save-excursion
22501 (if (not (re-search-backward re nil t))
22503 (setq l (funcall outline-level))
22504 (< l level)))))
22506 (defun org-goto-sibling (&optional previous)
22507 "Goto the next sibling, even if it is invisible.
22508 When PREVIOUS is set, go to the previous sibling instead. Returns t
22509 when a sibling was found. When none is found, return nil and don't
22510 move point."
22511 (let ((fun (if previous 're-search-backward 're-search-forward))
22512 (pos (point))
22513 (re org-outline-regexp-bol)
22514 level l)
22515 (when (condition-case nil (org-back-to-heading t) (error nil))
22516 (setq level (funcall outline-level))
22517 (catch 'exit
22518 (or previous (forward-char 1))
22519 (while (funcall fun re nil t)
22520 (setq l (funcall outline-level))
22521 (when (< l level) (goto-char pos) (throw 'exit nil))
22522 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22523 (goto-char pos)
22524 nil))))
22526 (defun org-show-siblings ()
22527 "Show all siblings of the current headline."
22528 (save-excursion
22529 (while (org-goto-sibling) (org-flag-heading nil)))
22530 (save-excursion
22531 (while (org-goto-sibling 'previous)
22532 (org-flag-heading nil))))
22534 (defun org-goto-first-child ()
22535 "Goto the first child, even if it is invisible.
22536 Return t when a child was found. Otherwise don't move point and
22537 return nil."
22538 (let (level (pos (point)) (re org-outline-regexp-bol))
22539 (when (condition-case nil (org-back-to-heading t) (error nil))
22540 (setq level (outline-level))
22541 (forward-char 1)
22542 (if (and (re-search-forward re nil t) (> (outline-level) level))
22543 (progn (goto-char (match-beginning 0)) t)
22544 (goto-char pos) nil))))
22546 (defun org-show-hidden-entry ()
22547 "Show an entry where even the heading is hidden."
22548 (save-excursion
22549 (org-show-entry)))
22551 (defun org-flag-heading (flag &optional entry)
22552 "Flag the current heading. FLAG non-nil means make invisible.
22553 When ENTRY is non-nil, show the entire entry."
22554 (save-excursion
22555 (org-back-to-heading t)
22556 ;; Check if we should show the entire entry
22557 (if entry
22558 (progn
22559 (org-show-entry)
22560 (save-excursion
22561 (and (outline-next-heading)
22562 (org-flag-heading nil))))
22563 (outline-flag-region (max (point-min) (1- (point)))
22564 (save-excursion (outline-end-of-heading) (point))
22565 flag))))
22567 (defun org-get-next-sibling ()
22568 "Move to next heading of the same level, and return point.
22569 If there is no such heading, return nil.
22570 This is like outline-next-sibling, but invisible headings are ok."
22571 (let ((level (funcall outline-level)))
22572 (outline-next-heading)
22573 (while (and (not (eobp)) (> (funcall outline-level) level))
22574 (outline-next-heading))
22575 (if (or (eobp) (< (funcall outline-level) level))
22577 (point))))
22579 (defun org-get-last-sibling ()
22580 "Move to previous heading of the same level, and return point.
22581 If there is no such heading, return nil."
22582 (let ((opoint (point))
22583 (level (funcall outline-level)))
22584 (outline-previous-heading)
22585 (when (and (/= (point) opoint) (outline-on-heading-p t))
22586 (while (and (> (funcall outline-level) level)
22587 (not (bobp)))
22588 (outline-previous-heading))
22589 (if (< (funcall outline-level) level)
22591 (point)))))
22593 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22594 "Goto to the end of a subtree."
22595 ;; This contains an exact copy of the original function, but it uses
22596 ;; `org-back-to-heading', to make it work also in invisible
22597 ;; trees. And is uses an invisible-ok argument.
22598 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22599 ;; Furthermore, when used inside Org, finding the end of a large subtree
22600 ;; with many children and grandchildren etc, this can be much faster
22601 ;; than the outline version.
22602 (org-back-to-heading invisible-ok)
22603 (let ((first t)
22604 (level (funcall outline-level)))
22605 (if (and (derived-mode-p 'org-mode) (< level 1000))
22606 ;; A true heading (not a plain list item), in Org-mode
22607 ;; This means we can easily find the end by looking
22608 ;; only for the right number of stars. Using a regexp to do
22609 ;; this is so much faster than using a Lisp loop.
22610 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22611 (forward-char 1)
22612 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22613 ;; something else, do it the slow way
22614 (while (and (not (eobp))
22615 (or first (> (funcall outline-level) level)))
22616 (setq first nil)
22617 (outline-next-heading)))
22618 (unless to-heading
22619 (if (memq (preceding-char) '(?\n ?\^M))
22620 (progn
22621 ;; Go to end of line before heading
22622 (forward-char -1)
22623 (if (memq (preceding-char) '(?\n ?\^M))
22624 ;; leave blank line before heading
22625 (forward-char -1))))))
22626 (point))
22628 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22629 "Use Org version in org-mode, for dramatic speed-up."
22630 (if (derived-mode-p 'org-mode)
22631 (progn
22632 (org-end-of-subtree nil t)
22633 (unless (eobp) (backward-char 1)))
22634 ad-do-it))
22636 (defun org-end-of-meta-data-and-drawers ()
22637 "Jump to the first text after meta data and drawers in the current entry.
22638 This will move over empty lines, lines with planning time stamps,
22639 clocking lines, and drawers."
22640 (org-back-to-heading t)
22641 (let ((end (save-excursion (outline-next-heading) (point)))
22642 (re (concat "\\(" org-drawer-regexp "\\)"
22643 "\\|" "[ \t]*" org-keyword-time-regexp)))
22644 (forward-line 1)
22645 (while (re-search-forward re end t)
22646 (if (not (match-end 1))
22647 ;; empty or planning line
22648 (forward-line 1)
22649 ;; a drawer, find the end
22650 (re-search-forward "^[ \t]*:END:" end 'move)
22651 (forward-line 1)))
22652 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22653 (point)))
22655 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22656 "Move forward to the ARG'th subheading at same level as this one.
22657 Stop at the first and last subheadings of a superior heading.
22658 Normally this only looks at visible headings, but when INVISIBLE-OK is
22659 non-nil it will also look at invisible ones."
22660 (interactive "p")
22661 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22662 (if (and arg (< arg 0))
22663 (goto-char (point-min))
22664 (outline-next-heading))
22665 (org-at-heading-p)
22666 (let ((level (- (match-end 0) (match-beginning 0) 1))
22667 (f (if (and arg (< arg 0))
22668 're-search-backward
22669 're-search-forward))
22670 (count (if arg (abs arg) 1))
22671 (result (point)))
22672 (forward-char (if (and arg (< arg 0)) -1 1))
22673 (while (and (> count 0)
22674 (funcall f org-outline-regexp-bol nil 'move))
22675 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22676 (cond ((< l level) (setq count 0))
22677 ((and (= l level)
22678 (or invisible-ok
22679 (progn
22680 (goto-char (line-beginning-position))
22681 (not (outline-invisible-p)))))
22682 (setq count (1- count))
22683 (when (eq l level)
22684 (setq result (point)))))))
22685 (goto-char result))
22686 (beginning-of-line 1)))
22688 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22689 "Move backward to the ARG'th subheading at same level as this one.
22690 Stop at the first and last subheadings of a superior heading."
22691 (interactive "p")
22692 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22694 (defun org-next-block (arg &optional backward block-regexp)
22695 "Jump to the next block.
22696 With a prefix argument ARG, jump forward ARG many source blocks.
22697 When BACKWARD is non-nil, jump to the previous block.
22698 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22699 (interactive "p")
22700 (let ((re (or block-regexp org-block-regexp))
22701 (re-search-fn (or (and backward 're-search-backward)
22702 're-search-forward)))
22703 (if (looking-at re) (forward-char 1))
22704 (condition-case nil
22705 (funcall re-search-fn re nil nil arg)
22706 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22707 (goto-char (match-beginning 0)) (org-show-context)))
22709 (defun org-previous-block (arg &optional block-regexp)
22710 "Jump to the previous block.
22711 With a prefix argument ARG, jump backward ARG many source blocks.
22712 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22713 (interactive "p")
22714 (org-next-block arg t block-regexp))
22716 (defun org-forward-element ()
22717 "Move forward by one element.
22718 Move to the next element at the same level, when possible."
22719 (interactive)
22720 (cond ((eobp) (error "Cannot move further down"))
22721 ((org-with-limited-levels (org-at-heading-p))
22722 (let ((origin (point)))
22723 (goto-char (org-end-of-subtree nil t))
22724 (unless (org-with-limited-levels (org-at-heading-p))
22725 (goto-char origin)
22726 (error "Cannot move further down"))))
22728 (let* ((elem (org-element-at-point))
22729 (end (org-element-property :end elem))
22730 (parent (org-element-property :parent elem)))
22731 (if (and parent (= (org-element-property :contents-end parent) end))
22732 (goto-char (org-element-property :end parent))
22733 (goto-char end))))))
22735 (defun org-backward-element ()
22736 "Move backward by one element.
22737 Move to the previous element at the same level, when possible."
22738 (interactive)
22739 (cond ((bobp) (error "Cannot move further up"))
22740 ((org-with-limited-levels (org-at-heading-p))
22741 ;; At an headline, move to the previous one, if any, or stay
22742 ;; here.
22743 (let ((origin (point)))
22744 (org-with-limited-levels (org-backward-heading-same-level 1))
22745 ;; When current headline has no sibling above, move to its
22746 ;; parent.
22747 (when (= (point) origin)
22748 (or (org-with-limited-levels (org-up-heading-safe))
22749 (progn (goto-char origin)
22750 (error "Cannot move further up"))))))
22752 (let* ((trail (org-element-at-point 'keep-trail))
22753 (elem (car trail))
22754 (prev-elem (nth 1 trail))
22755 (beg (org-element-property :begin elem)))
22756 (cond
22757 ;; Move to beginning of current element if point isn't
22758 ;; there already.
22759 ((/= (point) beg) (goto-char beg))
22760 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22761 ((org-before-first-heading-p) (goto-char (point-min)))
22762 (t (org-back-to-heading)))))))
22764 (defun org-up-element ()
22765 "Move to upper element."
22766 (interactive)
22767 (if (org-with-limited-levels (org-at-heading-p))
22768 (unless (org-up-heading-safe) (error "No surrounding element"))
22769 (let* ((elem (org-element-at-point))
22770 (parent (org-element-property :parent elem)))
22771 (if parent (goto-char (org-element-property :begin parent))
22772 (if (org-with-limited-levels (org-before-first-heading-p))
22773 (error "No surrounding element")
22774 (org-with-limited-levels (org-back-to-heading)))))))
22776 (defvar org-element-greater-elements)
22777 (defun org-down-element ()
22778 "Move to inner element."
22779 (interactive)
22780 (let ((element (org-element-at-point)))
22781 (cond
22782 ((memq (org-element-type element) '(plain-list table))
22783 (goto-char (org-element-property :contents-begin element))
22784 (forward-char))
22785 ((memq (org-element-type element) org-element-greater-elements)
22786 ;; If contents are hidden, first disclose them.
22787 (when (org-element-property :hiddenp element) (org-cycle))
22788 (goto-char (or (org-element-property :contents-begin element)
22789 (error "No content for this element"))))
22790 (t (error "No inner element")))))
22792 (defun org-drag-element-backward ()
22793 "Move backward element at point."
22794 (interactive)
22795 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22796 (let* ((trail (org-element-at-point 'keep-trail))
22797 (elem (car trail))
22798 (prev-elem (nth 1 trail)))
22799 ;; Error out if no previous element or previous element is
22800 ;; a parent of the current one.
22801 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22802 (error "Cannot drag element backward")
22803 (let ((pos (point)))
22804 (org-element-swap-A-B prev-elem elem)
22805 (goto-char (+ (org-element-property :begin prev-elem)
22806 (- pos (org-element-property :begin elem)))))))))
22808 (defun org-drag-element-forward ()
22809 "Move forward element at point."
22810 (interactive)
22811 (let* ((pos (point))
22812 (elem (org-element-at-point)))
22813 (when (= (point-max) (org-element-property :end elem))
22814 (error "Cannot drag element forward"))
22815 (goto-char (org-element-property :end elem))
22816 (let ((next-elem (org-element-at-point)))
22817 (when (or (org-element-nested-p elem next-elem)
22818 (and (eq (org-element-type next-elem) 'headline)
22819 (not (eq (org-element-type elem) 'headline))))
22820 (goto-char pos)
22821 (error "Cannot drag element forward"))
22822 ;; Compute new position of point: it's shifted by NEXT-ELEM
22823 ;; body's length (without final blanks) and by the length of
22824 ;; blanks between ELEM and NEXT-ELEM.
22825 (let ((size-next (- (save-excursion
22826 (goto-char (org-element-property :end next-elem))
22827 (skip-chars-backward " \r\t\n")
22828 (forward-line)
22829 ;; Small correction if buffer doesn't end
22830 ;; with a newline character.
22831 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22832 (org-element-property :begin next-elem)))
22833 (size-blank (- (org-element-property :end elem)
22834 (save-excursion
22835 (goto-char (org-element-property :end elem))
22836 (skip-chars-backward " \r\t\n")
22837 (forward-line)
22838 (point)))))
22839 (org-element-swap-A-B elem next-elem)
22840 (goto-char (+ pos size-next size-blank))))))
22842 (defun org-mark-element ()
22843 "Put point at beginning of this element, mark at end.
22845 Interactively, if this command is repeated or (in Transient Mark
22846 mode) if the mark is active, it marks the next element after the
22847 ones already marked."
22848 (interactive)
22849 (let (deactivate-mark)
22850 (if (and (org-called-interactively-p 'any)
22851 (or (and (eq last-command this-command) (mark t))
22852 (and transient-mark-mode mark-active)))
22853 (set-mark
22854 (save-excursion
22855 (goto-char (mark))
22856 (goto-char (org-element-property :end (org-element-at-point)))))
22857 (let ((element (org-element-at-point)))
22858 (end-of-line)
22859 (push-mark (org-element-property :end element) t t)
22860 (goto-char (org-element-property :begin element))))))
22862 (defun org-narrow-to-element ()
22863 "Narrow buffer to current element."
22864 (interactive)
22865 (let ((elem (org-element-at-point)))
22866 (cond
22867 ((eq (car elem) 'headline)
22868 (narrow-to-region
22869 (org-element-property :begin elem)
22870 (org-element-property :end elem)))
22871 ((memq (car elem) org-element-greater-elements)
22872 (narrow-to-region
22873 (org-element-property :contents-begin elem)
22874 (org-element-property :contents-end elem)))
22876 (narrow-to-region
22877 (org-element-property :begin elem)
22878 (org-element-property :end elem))))))
22880 (defun org-transpose-words ()
22881 "Transpose words, using `org-mode' syntax table."
22882 (interactive)
22883 (with-syntax-table org-syntax-table
22884 (call-interactively 'transpose-words)))
22885 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22887 (defun org-transpose-element ()
22888 "Transpose current and previous elements, keeping blank lines between.
22889 Point is moved after both elements."
22890 (interactive)
22891 (org-skip-whitespace)
22892 (let ((end (org-element-property :end (org-element-at-point))))
22893 (org-drag-element-backward)
22894 (goto-char end)))
22896 (defun org-unindent-buffer ()
22897 "Un-indent the visible part of the buffer.
22898 Relative indentation (between items, inside blocks, etc.) isn't
22899 modified."
22900 (interactive)
22901 (unless (eq major-mode 'org-mode)
22902 (error "Cannot un-indent a buffer not in Org mode"))
22903 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22904 unindent-tree ; For byte-compiler.
22905 (unindent-tree
22906 (function
22907 (lambda (contents)
22908 (mapc
22909 (lambda (element)
22910 (if (memq (org-element-type element) '(headline section))
22911 (funcall unindent-tree (org-element-contents element))
22912 (save-excursion
22913 (save-restriction
22914 (narrow-to-region
22915 (org-element-property :begin element)
22916 (org-element-property :end element))
22917 (org-do-remove-indentation)))))
22918 (reverse contents))))))
22919 (funcall unindent-tree (org-element-contents parse-tree))))
22921 (defun org-show-subtree ()
22922 "Show everything after this heading at deeper levels."
22923 (interactive)
22924 (outline-flag-region
22925 (point)
22926 (save-excursion
22927 (org-end-of-subtree t t))
22928 nil))
22930 (defun org-show-entry ()
22931 "Show the body directly following this heading.
22932 Show the heading too, if it is currently invisible."
22933 (interactive)
22934 (save-excursion
22935 (condition-case nil
22936 (progn
22937 (org-back-to-heading t)
22938 (outline-flag-region
22939 (max (point-min) (1- (point)))
22940 (save-excursion
22941 (if (re-search-forward
22942 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22943 (match-beginning 1)
22944 (point-max)))
22945 nil)
22946 (org-cycle-hide-drawers 'children))
22947 (error nil))))
22949 (defun org-make-options-regexp (kwds &optional extra)
22950 "Make a regular expression for keyword lines."
22951 (concat
22952 "^#\\+\\("
22953 (mapconcat 'regexp-quote kwds "\\|")
22954 (if extra (concat "\\|" extra))
22955 "\\):[ \t]*\\(.*\\)"))
22957 ;; Make isearch reveal the necessary context
22958 (defun org-isearch-end ()
22959 "Reveal context after isearch exits."
22960 (when isearch-success ; only if search was successful
22961 (if (featurep 'xemacs)
22962 ;; Under XEmacs, the hook is run in the correct place,
22963 ;; we directly show the context.
22964 (org-show-context 'isearch)
22965 ;; In Emacs the hook runs *before* restoring the overlays.
22966 ;; So we have to use a one-time post-command-hook to do this.
22967 ;; (Emacs 22 has a special variable, see function `org-mode')
22968 (unless (and (boundp 'isearch-mode-end-hook-quit)
22969 isearch-mode-end-hook-quit)
22970 ;; Only when the isearch was not quitted.
22971 (org-add-hook 'post-command-hook 'org-isearch-post-command
22972 'append 'local)))))
22974 (defun org-isearch-post-command ()
22975 "Remove self from hook, and show context."
22976 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22977 (org-show-context 'isearch))
22980 ;;;; Integration with and fixes for other packages
22982 ;;; Imenu support
22984 (defvar org-imenu-markers nil
22985 "All markers currently used by Imenu.")
22986 (make-variable-buffer-local 'org-imenu-markers)
22988 (defun org-imenu-new-marker (&optional pos)
22989 "Return a new marker for use by Imenu, and remember the marker."
22990 (let ((m (make-marker)))
22991 (move-marker m (or pos (point)))
22992 (push m org-imenu-markers)
22995 (defun org-imenu-get-tree ()
22996 "Produce the index for Imenu."
22997 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22998 (setq org-imenu-markers nil)
22999 (let* ((n org-imenu-depth)
23000 (re (concat "^" (org-get-limited-outline-regexp)))
23001 (subs (make-vector (1+ n) nil))
23002 (last-level 0)
23003 m level head)
23004 (save-excursion
23005 (save-restriction
23006 (widen)
23007 (goto-char (point-max))
23008 (while (re-search-backward re nil t)
23009 (setq level (org-reduced-level (funcall outline-level)))
23010 (when (and (<= level n)
23011 (looking-at org-complex-heading-regexp))
23012 (setq head (org-link-display-format
23013 (org-match-string-no-properties 4))
23014 m (org-imenu-new-marker))
23015 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23016 (if (>= level last-level)
23017 (push (cons head m) (aref subs level))
23018 (push (cons head (aref subs (1+ level))) (aref subs level))
23019 (loop for i from (1+ level) to n do (aset subs i nil)))
23020 (setq last-level level)))))
23021 (aref subs 1)))
23023 (eval-after-load "imenu"
23024 '(progn
23025 (add-hook 'imenu-after-jump-hook
23026 (lambda ()
23027 (if (derived-mode-p 'org-mode)
23028 (org-show-context 'org-goto))))))
23030 (defun org-link-display-format (link)
23031 "Replace a link with either the description, or the link target
23032 if no description is present"
23033 (save-match-data
23034 (if (string-match org-bracket-link-analytic-regexp link)
23035 (replace-match (if (match-end 5)
23036 (match-string 5 link)
23037 (concat (match-string 1 link)
23038 (match-string 3 link)))
23039 nil t link)
23040 link)))
23042 (defun org-toggle-link-display ()
23043 "Toggle the literal or descriptive display of links."
23044 (interactive)
23045 (if org-descriptive-links
23046 (progn (org-remove-from-invisibility-spec '(org-link))
23047 (org-restart-font-lock)
23048 (setq org-descriptive-links nil))
23049 (progn (add-to-invisibility-spec '(org-link))
23050 (org-restart-font-lock)
23051 (setq org-descriptive-links t))))
23053 ;; Speedbar support
23055 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23056 "Overlay marking the agenda restriction line in speedbar.")
23057 (overlay-put org-speedbar-restriction-lock-overlay
23058 'face 'org-agenda-restriction-lock)
23059 (overlay-put org-speedbar-restriction-lock-overlay
23060 'help-echo "Agendas are currently limited to this item.")
23061 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23063 (defun org-speedbar-set-agenda-restriction ()
23064 "Restrict future agenda commands to the location at point in speedbar.
23065 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23066 (interactive)
23067 (require 'org-agenda)
23068 (let (p m tp np dir txt)
23069 (cond
23070 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23071 'org-imenu t))
23072 (setq m (get-text-property p 'org-imenu-marker))
23073 (with-current-buffer (marker-buffer m)
23074 (goto-char m)
23075 (org-agenda-set-restriction-lock 'subtree)))
23076 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23077 'speedbar-function 'speedbar-find-file))
23078 (setq tp (previous-single-property-change
23079 (1+ p) 'speedbar-function)
23080 np (next-single-property-change
23081 tp 'speedbar-function)
23082 dir (speedbar-line-directory)
23083 txt (buffer-substring-no-properties (or tp (point-min))
23084 (or np (point-max))))
23085 (with-current-buffer (find-file-noselect
23086 (let ((default-directory dir))
23087 (expand-file-name txt)))
23088 (unless (derived-mode-p 'org-mode)
23089 (error "Cannot restrict to non-Org-mode file"))
23090 (org-agenda-set-restriction-lock 'file)))
23091 (t (error "Don't know how to restrict Org-mode's agenda")))
23092 (move-overlay org-speedbar-restriction-lock-overlay
23093 (point-at-bol) (point-at-eol))
23094 (setq current-prefix-arg nil)
23095 (org-agenda-maybe-redo)))
23097 (eval-after-load "speedbar"
23098 '(progn
23099 (speedbar-add-supported-extension ".org")
23100 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23101 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23102 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23103 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23104 (add-hook 'speedbar-visiting-tag-hook
23105 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23107 ;;; Fixes and Hacks for problems with other packages
23109 ;; Make flyspell not check words in links, to not mess up our keymap
23110 (defvar org-element-affiliated-keywords) ; From org-element.el
23111 (defvar org-element-block-name-alist) ; From org-element.el
23112 (defun org-mode-flyspell-verify ()
23113 "Don't let flyspell put overlays at active buttons, or on
23114 {todo,all-time,additional-option-like}-keywords."
23115 (let ((pos (max (1- (point)) (point-min)))
23116 (word (thing-at-point 'word)))
23117 (and (not (get-text-property pos 'keymap))
23118 (not (get-text-property pos 'org-no-flyspell))
23119 (not (member word org-todo-keywords-1))
23120 (not (member word org-all-time-keywords))
23121 (not (member word org-options-keywords))
23122 (not (member word (mapcar 'car org-startup-options)))
23123 (not (member-ignore-case word org-element-affiliated-keywords))
23124 (not (member-ignore-case word (org-get-export-keywords)))
23125 (not (member-ignore-case
23126 word (mapcar 'car org-element-block-name-alist)))
23127 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23129 (defun org-remove-flyspell-overlays-in (beg end)
23130 "Remove flyspell overlays in region."
23131 (and (org-bound-and-true-p flyspell-mode)
23132 (fboundp 'flyspell-delete-region-overlays)
23133 (flyspell-delete-region-overlays beg end))
23134 (add-text-properties beg end '(org-no-flyspell t)))
23136 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23137 (eval-after-load "bookmark"
23138 '(if (boundp 'bookmark-after-jump-hook)
23139 ;; We can use the hook
23140 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23141 ;; Hook not available, use advice
23142 (defadvice bookmark-jump (after org-make-visible activate)
23143 "Make the position visible."
23144 (org-bookmark-jump-unhide))))
23146 ;; Make sure saveplace shows the location if it was hidden
23147 (eval-after-load "saveplace"
23148 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23149 "Make the position visible."
23150 (org-bookmark-jump-unhide)))
23152 ;; Make sure ecb shows the location if it was hidden
23153 (eval-after-load "ecb"
23154 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23155 "Make hierarchy visible when jumping into location from ECB tree buffer."
23156 (if (derived-mode-p 'org-mode)
23157 (org-show-context))))
23159 (defun org-bookmark-jump-unhide ()
23160 "Unhide the current position, to show the bookmark location."
23161 (and (derived-mode-p 'org-mode)
23162 (or (outline-invisible-p)
23163 (save-excursion (goto-char (max (point-min) (1- (point))))
23164 (outline-invisible-p)))
23165 (org-show-context 'bookmark-jump)))
23167 ;; Make session.el ignore our circular variable
23168 (eval-after-load "session"
23169 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23171 ;;;; Experimental code
23173 (defun org-closed-in-range ()
23174 "Sparse tree of items closed in a certain time range.
23175 Still experimental, may disappear in the future."
23176 (interactive)
23177 ;; Get the time interval from the user.
23178 (let* ((time1 (org-float-time
23179 (org-read-date nil 'to-time nil "Starting date: ")))
23180 (time2 (org-float-time
23181 (org-read-date nil 'to-time nil "End date:")))
23182 ;; callback function
23183 (callback (lambda ()
23184 (let ((time
23185 (org-float-time
23186 (apply 'encode-time
23187 (org-parse-time-string
23188 (match-string 1))))))
23189 ;; check if time in interval
23190 (and (>= time time1) (<= time time2))))))
23191 ;; make tree, check each match with the callback
23192 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23194 ;;;; Finish up
23196 (provide 'org)
23198 (run-hooks 'org-load-hook)
23200 ;;; org.el ends here