org.el (org-paste-subtree): Fix typo in docstring
[org-mode.git] / lisp / org.el
blob4555ed1635809996408a4f956eb2b7fc15abecc3
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t t)
83 (require 'org-macs)
84 (require 'org-compat)
86 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
87 ;; some places -- e.g. see the macro org-with-limited-levels.
89 ;; In Org buffers, the value of `outline-regexp' is that of
90 ;; `org-outline-regexp'. The only function still directly relying on
91 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
92 ;; job when `orgstruct-mode' is active.
93 (defvar org-outline-regexp "\\*+ "
94 "Regexp to match Org headlines.")
96 (defvar org-outline-regexp-bol "^\\*+ "
97 "Regexp to match Org headlines.
98 This is similar to `org-outline-regexp' but additionally makes
99 sure that we are at the beginning of the line.")
101 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
102 "Matches an headline, putting stars and text into groups.
103 Stars are put in group 1 and the trimmed body in group 2.")
105 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
106 (when (fboundp 'defvaralias)
107 (unless (boundp 'calendar-view-holidays-initially-flag)
108 (defvaralias 'calendar-view-holidays-initially-flag
109 'view-calendar-holidays-initially))
110 (unless (boundp 'calendar-view-diary-initially-flag)
111 (defvaralias 'calendar-view-diary-initially-flag
112 'view-diary-entries-initially))
113 (unless (boundp 'diary-fancy-buffer)
114 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
116 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
117 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
118 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
119 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
120 (declare-function org-at-clock-log-p "org-clock" ())
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
123 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function orgtbl-mode "org-table" (&optional arg))
127 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
128 (declare-function org-beamer-mode "ox-beamer" ())
129 (declare-function org-table-edit-field "org-table" (arg))
130 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
131 (declare-function org-id-get-create "org-id" (&optional force))
132 (declare-function org-id-find-id-file "org-id" (id))
133 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
134 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (autoload 'org-element-at-point "org-element")
141 (autoload 'org-element-type "org-element")
143 (declare-function org-element--parse-objects "org-element"
144 (beg end acc restriction))
145 (declare-function org-element-at-point "org-element" (&optional keep-trail))
146 (declare-function org-element-contents "org-element" (element))
147 (declare-function org-element-context "org-element" (&optional element))
148 (declare-function org-element-interpret-data "org-element"
149 (data &optional parent))
150 (declare-function org-element-map "org-element"
151 (data types fun &optional info first-match no-recursion))
152 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
153 (declare-function org-element-parse-buffer "org-element"
154 (&optional granularity visible-only))
155 (declare-function org-element-property "org-element" (property element))
156 (declare-function org-element-put-property "org-element"
157 (element property value))
158 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
159 (declare-function org-element--parse-objects "org-element"
160 (beg end acc restriction))
161 (declare-function org-element-parse-buffer "org-element"
162 (&optional granularity visible-only))
163 (declare-function org-element-interpret-data "org-element"
164 (data &optional parent))
166 ;; load languages based on value of `org-babel-load-languages'
167 (defvar org-babel-load-languages)
169 ;;;###autoload
170 (defun org-babel-do-load-languages (sym value)
171 "Load the languages defined in `org-babel-load-languages'."
172 (set-default sym value)
173 (mapc (lambda (pair)
174 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
175 (if active
176 (progn
177 (require (intern (concat "ob-" lang))))
178 (progn
179 (funcall 'fmakunbound
180 (intern (concat "org-babel-execute:" lang)))
181 (funcall 'fmakunbound
182 (intern (concat "org-babel-expand-body:" lang)))))))
183 org-babel-load-languages))
185 (defcustom org-babel-load-languages '((emacs-lisp . t))
186 "Languages which can be evaluated in Org-mode buffers.
187 This list can be used to load support for any of the languages
188 below, note that each language will depend on a different set of
189 system executables and/or Emacs modes. When a language is
190 \"loaded\", then code blocks in that language can be evaluated
191 with `org-babel-execute-src-block' bound by default to C-c
192 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
193 be set to remove code block evaluation from the C-c C-c
194 keybinding. By default only Emacs Lisp (which has no
195 requirements) is loaded."
196 :group 'org-babel
197 :set 'org-babel-do-load-languages
198 :version "24.1"
199 :type '(alist :tag "Babel Languages"
200 :key-type
201 (choice
202 (const :tag "Awk" awk)
203 (const :tag "C" C)
204 (const :tag "R" R)
205 (const :tag "Asymptote" asymptote)
206 (const :tag "Calc" calc)
207 (const :tag "Clojure" clojure)
208 (const :tag "CSS" css)
209 (const :tag "Ditaa" ditaa)
210 (const :tag "Dot" dot)
211 (const :tag "Emacs Lisp" emacs-lisp)
212 (const :tag "Fortran" fortran)
213 (const :tag "Gnuplot" gnuplot)
214 (const :tag "Haskell" haskell)
215 (const :tag "IO" io)
216 (const :tag "Java" java)
217 (const :tag "Javascript" js)
218 (const :tag "LaTeX" latex)
219 (const :tag "Ledger" ledger)
220 (const :tag "Lilypond" lilypond)
221 (const :tag "Lisp" lisp)
222 (const :tag "Makefile" makefile)
223 (const :tag "Maxima" maxima)
224 (const :tag "Matlab" matlab)
225 (const :tag "Mscgen" mscgen)
226 (const :tag "Ocaml" ocaml)
227 (const :tag "Octave" octave)
228 (const :tag "Org" org)
229 (const :tag "Perl" perl)
230 (const :tag "Pico Lisp" picolisp)
231 (const :tag "PlantUML" plantuml)
232 (const :tag "Python" python)
233 (const :tag "Ruby" ruby)
234 (const :tag "Sass" sass)
235 (const :tag "Scala" scala)
236 (const :tag "Scheme" scheme)
237 (const :tag "Screen" screen)
238 (const :tag "Shell Script" sh)
239 (const :tag "Shen" shen)
240 (const :tag "Sql" sql)
241 (const :tag "Sqlite" sqlite))
242 :value-type (boolean :tag "Activate" :value t)))
244 ;;;; Customization variables
245 (defcustom org-clone-delete-id nil
246 "Remove ID property of clones of a subtree.
247 When non-nil, clones of a subtree don't inherit the ID property.
248 Otherwise they inherit the ID property with a new unique
249 identifier."
250 :type 'boolean
251 :version "24.1"
252 :group 'org-id)
254 ;;; Version
255 (org-check-version)
257 ;;;###autoload
258 (defun org-version (&optional here full message)
259 "Show the org-mode version in the echo area.
260 With prefix argument HERE, insert it at point.
261 When FULL is non-nil, use a verbose version string.
262 When MESSAGE is non-nil, display a message with the version."
263 (interactive "P")
264 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
265 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
266 (load-suffixes (list ".el"))
267 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
268 (org-trash (or
269 (and (fboundp 'org-release) (fboundp 'org-git-version))
270 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
271 (load-suffixes save-load-suffixes)
272 (org-version (org-release))
273 (git-version (org-git-version))
274 (version (format "Org-mode version %s (%s @ %s)"
275 org-version
276 git-version
277 (if org-install-dir
278 (if (string= org-dir org-install-dir)
279 org-install-dir
280 (concat "mixed installation! " org-install-dir " and " org-dir))
281 "org-loaddefs.el can not be found!")))
282 (_version (if full version org-version)))
283 (if (org-called-interactively-p 'interactive)
284 (if here
285 (insert version)
286 (message version))
287 (if message (message _version))
288 _version)))
290 (defconst org-version (org-version))
292 ;;; Compatibility constants
294 ;;; The custom variables
296 (defgroup org nil
297 "Outline-based notes management and organizer."
298 :tag "Org"
299 :group 'outlines
300 :group 'calendar)
302 (defcustom org-mode-hook nil
303 "Mode hook for Org-mode, run after the mode was turned on."
304 :group 'org
305 :type 'hook)
307 (defcustom org-load-hook nil
308 "Hook that is run after org.el has been loaded."
309 :group 'org
310 :type 'hook)
312 (defcustom org-log-buffer-setup-hook nil
313 "Hook that is run after an Org log buffer is created."
314 :group 'org
315 :version "24.1"
316 :type 'hook)
318 (defvar org-modules) ; defined below
319 (defvar org-modules-loaded nil
320 "Have the modules been loaded already?")
322 (defun org-load-modules-maybe (&optional force)
323 "Load all extensions listed in `org-modules'."
324 (when (or force (not org-modules-loaded))
325 (mapc (lambda (ext)
326 (condition-case nil (require ext)
327 (error (message "Problems while trying to load feature `%s'" ext))))
328 org-modules)
329 (setq org-modules-loaded t)))
331 (defun org-set-modules (var value)
332 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
333 (set var value)
334 (when (featurep 'org)
335 (org-load-modules-maybe 'force)))
337 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
338 "Modules that should always be loaded together with org.el.
340 If a description starts with <C>, the file is not part of Emacs
341 and loading it will require that you have downloaded and properly
342 installed the Org mode distribution.
344 You can also use this system to load external packages (i.e. neither Org
345 core modules, nor modules from the CONTRIB directory). Just add symbols
346 to the end of the list. If the package is called org-xyz.el, then you need
347 to add the symbol `xyz', and the package must have a call to:
349 \(provide 'org-xyz)
351 For export specific modules, see also `org-export-backends'."
352 :group 'org
353 :set 'org-set-modules
354 :type
355 '(set :greedy t
356 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
357 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
358 (const :tag " crypt: Encryption of subtrees" org-crypt)
359 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
360 (const :tag " docview: Links to doc-view buffers" org-docview)
361 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
362 (const :tag " id: Global IDs for identifying entries" org-id)
363 (const :tag " info: Links to Info nodes" org-info)
364 (const :tag " habit: Track your consistency with habits" org-habit)
365 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
366 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
367 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
368 (const :tag " mew Links to Mew folders/messages" org-mew)
369 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
370 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
371 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
372 (const :tag " vm: Links to VM folders/messages" org-vm)
373 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
374 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
375 (const :tag " mouse: Additional mouse support" org-mouse)
377 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
378 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
379 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
380 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
381 (const :tag "C collector: Collect properties into tables" org-collector)
382 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
383 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
384 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
385 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
386 (const :tag "C eval: Include command output as text" org-eval)
387 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
388 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
389 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
390 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
391 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
393 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
395 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
396 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
397 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
398 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
399 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
400 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
401 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
402 (const :tag "C mtags: Support for muse-like tags" org-mtags)
403 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
404 (const :tag "C registry: A registry for Org-mode links" org-registry)
405 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
406 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
407 (const :tag "C secretary: Team management with org-mode" org-secretary)
408 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
409 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
410 (const :tag "C track: Keep up with Org-mode development" org-track)
411 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
412 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
413 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
415 (defvar org-export-registered-backends) ; From ox.el
416 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
417 (defcustom org-export-backends '(ascii html icalendar latex)
418 "List of export back-ends that should be always available.
420 If a description starts with <C>, the file is not part of Emacs
421 and loading it will require that you have downloaded and properly
422 installed the Org mode distribution.
424 Unlike to `org-modules', libraries in this list will not be
425 loaded along with Org, but only once the export framework is
426 needed.
428 This variable needs to be set before org.el is loaded. If you
429 need to make a change while Emacs is running, use the customize
430 interface or run the following code, , where VALUE stands for the
431 new value of the variable, after updating it:
433 \(progn
434 \(setq org-export-registered-backends
435 \(org-remove-if-not
436 \(lambda (backend)
437 \(or (memq backend val)
438 \(catch 'parentp
439 \(mapc
440 \(lambda (b)
441 \(and (org-export-derived-backend-p b (car backend))
442 \(throw 'parentp t)))
443 val)
444 nil)))
445 org-export-registered-backends))
446 \(let ((new-list (mapcar 'car org-export-registered-backends)))
447 \(dolist (backend val)
448 \(cond
449 \((not (load (format \"ox-%s\" backend) t t))
450 \(message \"Problems while trying to load export back-end `%s'\"
451 backend))
452 \((not (memq backend new-list)) (push backend new-list))))
453 \(set-default var new-list)))
455 Adding a back-end to this list will also pull the back-end it
456 depends on, if any."
457 :group 'org
458 :group 'org-export
459 :set (lambda (var val)
460 (if (not (featurep 'ox)) (set-default var val)
461 ;; Any back-end not required anymore (not present in VAL and not
462 ;; a parent of any back-end in the new value) is removed from the
463 ;; list of registered back-ends.
464 (setq org-export-registered-backends
465 (org-remove-if-not
466 (lambda (backend)
467 (or (memq backend val)
468 (catch 'parentp
469 (mapc
470 (lambda (b)
471 (and (org-export-derived-backend-p b (car backend))
472 (throw 'parentp t)))
473 val)
474 nil)))
475 org-export-registered-backends))
476 ;; Now build NEW-LIST of both new back-ends and required
477 ;; parents.
478 (let ((new-list (mapcar 'car org-export-registered-backends)))
479 (dolist (backend val)
480 (cond
481 ((not (load (format "ox-%s" backend) t t))
482 (message "Problems while trying to load export back-end `%s'"
483 backend))
484 ((not (memq backend new-list)) (push backend new-list))))
485 ;; Set VAR to that list with fixed dependencies.
486 (set-default var new-list))))
487 :type '(set :greedy t
488 (const :tag " ascii Export buffer to ASCII format" ascii)
489 (const :tag " beamer Export buffer to Beamer presentation" beamer)
490 (const :tag " html Export buffer to HTML format" html)
491 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
492 (const :tag " latex Export buffer to LaTeX format" latex)
493 (const :tag " man Export buffer to MAN format" man)
494 (const :tag " md Export buffer to Markdown format" md)
495 (const :tag " odt Export buffer to ODT format" odt)
496 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
497 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" jsinfo)
498 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
499 (const :tag "C groff Export buffer to Groff format" groff)
500 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)))
502 (eval-after-load 'ox
503 '(mapc
504 (lambda (backend)
505 (condition-case nil (require (intern (format "ox-%s" backend)))
506 (error (message "Problems while trying to load export back-end `%s'"
507 backend))))
508 org-export-backends))
510 (defcustom org-support-shift-select nil
511 "Non-nil means make shift-cursor commands select text when possible.
513 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
514 start selecting a region, or enlarge regions started in this way.
515 In Org-mode, in special contexts, these same keys are used for
516 other purposes, important enough to compete with shift selection.
517 Org tries to balance these needs by supporting `shift-select-mode'
518 outside these special contexts, under control of this variable.
520 The default of this variable is nil, to avoid confusing behavior. Shifted
521 cursor keys will then execute Org commands in the following contexts:
522 - on a headline, changing TODO state (left/right) and priority (up/down)
523 - on a time stamp, changing the time
524 - in a plain list item, changing the bullet type
525 - in a property definition line, switching between allowed values
526 - in the BEGIN line of a clock table (changing the time block).
527 Outside these contexts, the commands will throw an error.
529 When this variable is t and the cursor is not in a special
530 context, Org-mode will support shift-selection for making and
531 enlarging regions. To make this more effective, the bullet
532 cycling will no longer happen anywhere in an item line, but only
533 if the cursor is exactly on the bullet.
535 If you set this variable to the symbol `always', then the keys
536 will not be special in headlines, property lines, and item lines,
537 to make shift selection work there as well. If this is what you
538 want, you can use the following alternative commands: `C-c C-t'
539 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
540 can be used to switch TODO sets, `C-c -' to cycle item bullet
541 types, and properties can be edited by hand or in column view.
543 However, when the cursor is on a timestamp, shift-cursor commands
544 will still edit the time stamp - this is just too good to give up.
546 XEmacs user should have this variable set to nil, because
547 `shift-select-mode' is in Emacs 23 or later only."
548 :group 'org
549 :type '(choice
550 (const :tag "Never" nil)
551 (const :tag "When outside special context" t)
552 (const :tag "Everywhere except timestamps" always)))
554 (defcustom org-loop-over-headlines-in-active-region nil
555 "Shall some commands act upon headlines in the active region?
557 When set to `t', some commands will be performed in all headlines
558 within the active region.
560 When set to `start-level', some commands will be performed in all
561 headlines within the active region, provided that these headlines
562 are of the same level than the first one.
564 When set to a string, those commands will be performed on the
565 matching headlines within the active region. Such string must be
566 a tags/property/todo match as it is used in the agenda tags view.
568 The list of commands is: `org-schedule', `org-deadline',
569 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
570 `org-archive-to-archive-sibling'. The archiving commands skip
571 already archived entries."
572 :type '(choice (const :tag "Don't loop" nil)
573 (const :tag "All headlines in active region" t)
574 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
575 (string :tag "Tags/Property/Todo matcher"))
576 :version "24.1"
577 :group 'org-todo
578 :group 'org-archive)
580 (defgroup org-startup nil
581 "Options concerning startup of Org-mode."
582 :tag "Org Startup"
583 :group 'org)
585 (defcustom org-startup-folded t
586 "Non-nil means entering Org-mode will switch to OVERVIEW.
587 This can also be configured on a per-file basis by adding one of
588 the following lines anywhere in the buffer:
590 #+STARTUP: fold (or `overview', this is equivalent)
591 #+STARTUP: nofold (or `showall', this is equivalent)
592 #+STARTUP: content
593 #+STARTUP: showeverything"
594 :group 'org-startup
595 :type '(choice
596 (const :tag "nofold: show all" nil)
597 (const :tag "fold: overview" t)
598 (const :tag "content: all headlines" content)
599 (const :tag "show everything, even drawers" showeverything)))
601 (defcustom org-startup-truncated t
602 "Non-nil means entering Org-mode will set `truncate-lines'.
603 This is useful since some lines containing links can be very long and
604 uninteresting. Also tables look terrible when wrapped."
605 :group 'org-startup
606 :type 'boolean)
608 (defcustom org-startup-indented nil
609 "Non-nil means turn on `org-indent-mode' on startup.
610 This can also be configured on a per-file basis by adding one of
611 the following lines anywhere in the buffer:
613 #+STARTUP: indent
614 #+STARTUP: noindent"
615 :group 'org-structure
616 :type '(choice
617 (const :tag "Not" nil)
618 (const :tag "Globally (slow on startup in large files)" t)))
620 (defcustom org-use-sub-superscripts t
621 "Non-nil means interpret \"_\" and \"^\" for display.
622 When this option is turned on, you can use TeX-like syntax for sub- and
623 superscripts. Several characters after \"_\" or \"^\" will be
624 considered as a single item - so grouping with {} is normally not
625 needed. For example, the following things will be parsed as single
626 sub- or superscripts.
628 10^24 or 10^tau several digits will be considered 1 item.
629 10^-12 or 10^-tau a leading sign with digits or a word
630 x^2-y^3 will be read as x^2 - y^3, because items are
631 terminated by almost any nonword/nondigit char.
632 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
634 Still, ambiguity is possible - so when in doubt use {} to enclose
635 the sub/superscript. If you set this variable to the symbol
636 `{}', the braces are *required* in order to trigger
637 interpretations as sub/superscript. This can be helpful in
638 documents that need \"_\" frequently in plain text."
639 :group 'org-startup
640 :version "24.1"
641 :type '(choice
642 (const :tag "Always interpret" t)
643 (const :tag "Only with braces" {})
644 (const :tag "Never interpret" nil)))
646 (defcustom org-startup-with-beamer-mode nil
647 "Non-nil means turn on `org-beamer-mode' on startup.
648 This can also be configured on a per-file basis by adding one of
649 the following lines anywhere in the buffer:
651 #+STARTUP: beamer"
652 :group 'org-startup
653 :version "24.1"
654 :type 'boolean)
656 (defcustom org-startup-align-all-tables nil
657 "Non-nil means align all tables when visiting a file.
658 This is useful when the column width in tables is forced with <N> cookies
659 in table fields. Such tables will look correct only after the first re-align.
660 This can also be configured on a per-file basis by adding one of
661 the following lines anywhere in the buffer:
662 #+STARTUP: align
663 #+STARTUP: noalign"
664 :group 'org-startup
665 :type 'boolean)
667 (defcustom org-startup-with-inline-images nil
668 "Non-nil means show inline images when loading a new Org file.
669 This can also be configured on a per-file basis by adding one of
670 the following lines anywhere in the buffer:
671 #+STARTUP: inlineimages
672 #+STARTUP: noinlineimages"
673 :group 'org-startup
674 :version "24.1"
675 :type 'boolean)
677 (defcustom org-insert-mode-line-in-empty-file nil
678 "Non-nil means insert the first line setting Org-mode in empty files.
679 When the function `org-mode' is called interactively in an empty file, this
680 normally means that the file name does not automatically trigger Org-mode.
681 To ensure that the file will always be in Org-mode in the future, a
682 line enforcing Org-mode will be inserted into the buffer, if this option
683 has been set."
684 :group 'org-startup
685 :type 'boolean)
687 (defcustom org-replace-disputed-keys nil
688 "Non-nil means use alternative key bindings for some keys.
689 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
690 These keys are also used by other packages like shift-selection-mode'
691 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
692 If you want to use Org-mode together with one of these other modes,
693 or more generally if you would like to move some Org-mode commands to
694 other keys, set this variable and configure the keys with the variable
695 `org-disputed-keys'.
697 This option is only relevant at load-time of Org-mode, and must be set
698 *before* org.el is loaded. Changing it requires a restart of Emacs to
699 become effective."
700 :group 'org-startup
701 :type 'boolean)
703 (defcustom org-use-extra-keys nil
704 "Non-nil means use extra key sequence definitions for certain commands.
705 This happens automatically if you run XEmacs or if `window-system'
706 is nil. This variable lets you do the same manually. You must
707 set it before loading org.
709 Example: on Carbon Emacs 22 running graphically, with an external
710 keyboard on a Powerbook, the default way of setting M-left might
711 not work for either Alt or ESC. Setting this variable will make
712 it work for ESC."
713 :group 'org-startup
714 :type 'boolean)
716 (if (fboundp 'defvaralias)
717 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
719 (defcustom org-disputed-keys
720 '(([(shift up)] . [(meta p)])
721 ([(shift down)] . [(meta n)])
722 ([(shift left)] . [(meta -)])
723 ([(shift right)] . [(meta +)])
724 ([(control shift right)] . [(meta shift +)])
725 ([(control shift left)] . [(meta shift -)]))
726 "Keys for which Org-mode and other modes compete.
727 This is an alist, cars are the default keys, second element specifies
728 the alternative to use when `org-replace-disputed-keys' is t.
730 Keys can be specified in any syntax supported by `define-key'.
731 The value of this option takes effect only at Org-mode's startup,
732 therefore you'll have to restart Emacs to apply it after changing."
733 :group 'org-startup
734 :type 'alist)
736 (defun org-key (key)
737 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
738 Or return the original if not disputed.
739 Also apply the translations defined in `org-xemacs-key-equivalents'."
740 (when org-replace-disputed-keys
741 (let* ((nkey (key-description key))
742 (x (org-find-if (lambda (x)
743 (equal (key-description (car x)) nkey))
744 org-disputed-keys)))
745 (setq key (if x (cdr x) key))))
746 (when (featurep 'xemacs)
747 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
748 key)
750 (defun org-find-if (predicate seq)
751 (catch 'exit
752 (while seq
753 (if (funcall predicate (car seq))
754 (throw 'exit (car seq))
755 (pop seq)))))
757 (defun org-defkey (keymap key def)
758 "Define a key, possibly translated, as returned by `org-key'."
759 (define-key keymap (org-key key) def))
761 (defcustom org-ellipsis nil
762 "The ellipsis to use in the Org-mode outline.
763 When nil, just use the standard three dots. When a string, use that instead,
764 When a face, use the standard 3 dots, but with the specified face.
765 The change affects only Org-mode (which will then use its own display table).
766 Changing this requires executing `M-x org-mode' in a buffer to become
767 effective."
768 :group 'org-startup
769 :type '(choice (const :tag "Default" nil)
770 (face :tag "Face" :value org-warning)
771 (string :tag "String" :value "...#")))
773 (defvar org-display-table nil
774 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
776 (defgroup org-keywords nil
777 "Keywords in Org-mode."
778 :tag "Org Keywords"
779 :group 'org)
781 (defcustom org-deadline-string "DEADLINE:"
782 "String to mark deadline entries.
783 A deadline is this string, followed by a time stamp. Should be a word,
784 terminated by a colon. You can insert a schedule keyword and
785 a timestamp with \\[org-deadline].
786 Changes become only effective after restarting Emacs."
787 :group 'org-keywords
788 :type 'string)
790 (defcustom org-scheduled-string "SCHEDULED:"
791 "String to mark scheduled TODO entries.
792 A schedule is this string, followed by a time stamp. Should be a word,
793 terminated by a colon. You can insert a schedule keyword and
794 a timestamp with \\[org-schedule].
795 Changes become only effective after restarting Emacs."
796 :group 'org-keywords
797 :type 'string)
799 (defcustom org-closed-string "CLOSED:"
800 "String used as the prefix for timestamps logging closing a TODO entry."
801 :group 'org-keywords
802 :type 'string)
804 (defcustom org-clock-string "CLOCK:"
805 "String used as prefix for timestamps clocking work hours on an item."
806 :group 'org-keywords
807 :type 'string)
809 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
810 org-scheduled-string "\\|"
811 org-deadline-string "\\|"
812 org-closed-string "\\|"
813 org-clock-string "\\)")
814 "Matches a line with planning or clock info.")
816 (defcustom org-comment-string "COMMENT"
817 "Entries starting with this keyword will never be exported.
818 An entry can be toggled between COMMENT and normal with
819 \\[org-toggle-comment].
820 Changes become only effective after restarting Emacs."
821 :group 'org-keywords
822 :type 'string)
824 (defcustom org-quote-string "QUOTE"
825 "Entries starting with this keyword will be exported in fixed-width font.
826 Quoting applies only to the text in the entry following the headline, and does
827 not extend beyond the next headline, even if that is lower level.
828 An entry can be toggled between QUOTE and normal with
829 \\[org-toggle-fixed-width-section]."
830 :group 'org-keywords
831 :type 'string)
833 (defconst org-repeat-re
834 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
835 "Regular expression for specifying repeated events.
836 After a match, group 1 contains the repeat expression.")
838 (defgroup org-structure nil
839 "Options concerning the general structure of Org-mode files."
840 :tag "Org Structure"
841 :group 'org)
843 (defgroup org-reveal-location nil
844 "Options about how to make context of a location visible."
845 :tag "Org Reveal Location"
846 :group 'org-structure)
848 (defconst org-context-choice
849 '(choice
850 (const :tag "Always" t)
851 (const :tag "Never" nil)
852 (repeat :greedy t :tag "Individual contexts"
853 (cons
854 (choice :tag "Context"
855 (const agenda)
856 (const org-goto)
857 (const occur-tree)
858 (const tags-tree)
859 (const link-search)
860 (const mark-goto)
861 (const bookmark-jump)
862 (const isearch)
863 (const default))
864 (boolean))))
865 "Contexts for the reveal options.")
867 (defcustom org-show-hierarchy-above '((default . t))
868 "Non-nil means show full hierarchy when revealing a location.
869 Org-mode often shows locations in an org-mode file which might have
870 been invisible before. When this is set, the hierarchy of headings
871 above the exposed location is shown.
872 Turning this off for example for sparse trees makes them very compact.
873 Instead of t, this can also be an alist specifying this option for different
874 contexts. Valid contexts are
875 agenda when exposing an entry from the agenda
876 org-goto when using the command `org-goto' on key C-c C-j
877 occur-tree when using the command `org-occur' on key C-c /
878 tags-tree when constructing a sparse tree based on tags matches
879 link-search when exposing search matches associated with a link
880 mark-goto when exposing the jump goal of a mark
881 bookmark-jump when exposing a bookmark location
882 isearch when exiting from an incremental search
883 default default for all contexts not set explicitly"
884 :group 'org-reveal-location
885 :type org-context-choice)
887 (defcustom org-show-following-heading '((default . nil))
888 "Non-nil means show following heading when revealing a location.
889 Org-mode often shows locations in an org-mode file which might have
890 been invisible before. When this is set, the heading following the
891 match is shown.
892 Turning this off for example for sparse trees makes them very compact,
893 but makes it harder to edit the location of the match. In such a case,
894 use the command \\[org-reveal] to show more context.
895 Instead of t, this can also be an alist specifying this option for different
896 contexts. See `org-show-hierarchy-above' for valid contexts."
897 :group 'org-reveal-location
898 :type org-context-choice)
900 (defcustom org-show-siblings '((default . nil) (isearch t))
901 "Non-nil means show all sibling heading when revealing a location.
902 Org-mode often shows locations in an org-mode file which might have
903 been invisible before. When this is set, the sibling of the current entry
904 heading are all made visible. If `org-show-hierarchy-above' is t,
905 the same happens on each level of the hierarchy above the current entry.
907 By default this is on for the isearch context, off for all other contexts.
908 Turning this off for example for sparse trees makes them very compact,
909 but makes it harder to edit the location of the match. In such a case,
910 use the command \\[org-reveal] to show more context.
911 Instead of t, this can also be an alist specifying this option for different
912 contexts. See `org-show-hierarchy-above' for valid contexts."
913 :group 'org-reveal-location
914 :type org-context-choice)
916 (defcustom org-show-entry-below '((default . nil))
917 "Non-nil means show the entry below a headline when revealing a location.
918 Org-mode often shows locations in an org-mode file which might have
919 been invisible before. When this is set, the text below the headline that is
920 exposed is also shown.
922 By default this is off for all contexts.
923 Instead of t, this can also be an alist specifying this option for different
924 contexts. See `org-show-hierarchy-above' for valid contexts."
925 :group 'org-reveal-location
926 :type org-context-choice)
928 (defcustom org-indirect-buffer-display 'other-window
929 "How should indirect tree buffers be displayed?
930 This applies to indirect buffers created with the commands
931 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
932 Valid values are:
933 current-window Display in the current window
934 other-window Just display in another window.
935 dedicated-frame Create one new frame, and re-use it each time.
936 new-frame Make a new frame each time. Note that in this case
937 previously-made indirect buffers are kept, and you need to
938 kill these buffers yourself."
939 :group 'org-structure
940 :group 'org-agenda-windows
941 :type '(choice
942 (const :tag "In current window" current-window)
943 (const :tag "In current frame, other window" other-window)
944 (const :tag "Each time a new frame" new-frame)
945 (const :tag "One dedicated frame" dedicated-frame)))
947 (defcustom org-use-speed-commands nil
948 "Non-nil means activate single letter commands at beginning of a headline.
949 This may also be a function to test for appropriate locations where speed
950 commands should be active."
951 :group 'org-structure
952 :type '(choice
953 (const :tag "Never" nil)
954 (const :tag "At beginning of headline stars" t)
955 (function)))
957 (defcustom org-speed-commands-user nil
958 "Alist of additional speed commands.
959 This list will be checked before `org-speed-commands-default'
960 when the variable `org-use-speed-commands' is non-nil
961 and when the cursor is at the beginning of a headline.
962 The car if each entry is a string with a single letter, which must
963 be assigned to `self-insert-command' in the global map.
964 The cdr is either a command to be called interactively, a function
965 to be called, or a form to be evaluated.
966 An entry that is just a list with a single string will be interpreted
967 as a descriptive headline that will be added when listing the speed
968 commands in the Help buffer using the `?' speed command."
969 :group 'org-structure
970 :type '(repeat :value ("k" . ignore)
971 (choice :value ("k" . ignore)
972 (list :tag "Descriptive Headline" (string :tag "Headline"))
973 (cons :tag "Letter and Command"
974 (string :tag "Command letter")
975 (choice
976 (function)
977 (sexp))))))
979 (defgroup org-cycle nil
980 "Options concerning visibility cycling in Org-mode."
981 :tag "Org Cycle"
982 :group 'org-structure)
984 (defcustom org-cycle-skip-children-state-if-no-children t
985 "Non-nil means skip CHILDREN state in entries that don't have any."
986 :group 'org-cycle
987 :type 'boolean)
989 (defcustom org-cycle-max-level nil
990 "Maximum level which should still be subject to visibility cycling.
991 Levels higher than this will, for cycling, be treated as text, not a headline.
992 When `org-odd-levels-only' is set, a value of N in this variable actually
993 means 2N-1 stars as the limiting headline.
994 When nil, cycle all levels.
995 Note that the limiting level of cycling is also influenced by
996 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
997 `org-inlinetask-min-level' is, cycling will be limited to levels one less
998 than its value."
999 :group 'org-cycle
1000 :type '(choice
1001 (const :tag "No limit" nil)
1002 (integer :tag "Maximum level")))
1004 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1005 "Names of drawers. Drawers are not opened by cycling on the headline above.
1006 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1007 this:
1008 :DRAWERNAME:
1009 .....
1010 :END:
1011 The drawer \"PROPERTIES\" is special for capturing properties through
1012 the property API.
1014 Drawers can be defined on the per-file basis with a line like:
1016 #+DRAWERS: HIDDEN STATE PROPERTIES"
1017 :group 'org-structure
1018 :group 'org-cycle
1019 :type '(repeat (string :tag "Drawer Name")))
1021 (defcustom org-hide-block-startup nil
1022 "Non-nil means entering Org-mode will fold all blocks.
1023 This can also be set in on a per-file basis with
1025 #+STARTUP: hideblocks
1026 #+STARTUP: showblocks"
1027 :group 'org-startup
1028 :group 'org-cycle
1029 :type 'boolean)
1031 (defcustom org-cycle-global-at-bob nil
1032 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1033 This makes it possible to do global cycling without having to use S-TAB or
1034 \\[universal-argument] TAB. For this special case to work, the first line
1035 of the buffer must not be a headline -- it may be empty or some other text.
1036 When used in this way, `org-cycle-hook' is disabled temporarily to make
1037 sure the cursor stays at the beginning of the buffer. When this option is
1038 nil, don't do anything special at the beginning of the buffer."
1039 :group 'org-cycle
1040 :type 'boolean)
1042 (defcustom org-cycle-level-after-item/entry-creation t
1043 "Non-nil means cycle entry level or item indentation in new empty entries.
1045 When the cursor is at the end of an empty headline, i.e with only stars
1046 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1047 and then all possible ancestor states, before returning to the original state.
1048 This makes data entry extremely fast: M-RET to create a new headline,
1049 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1051 When the cursor is at the end of an empty plain list item, one TAB will
1052 make it a subitem, two or more tabs will back up to make this an item
1053 higher up in the item hierarchy."
1054 :group 'org-cycle
1055 :type 'boolean)
1057 (defcustom org-cycle-emulate-tab t
1058 "Where should `org-cycle' emulate TAB.
1059 nil Never
1060 white Only in completely white lines
1061 whitestart Only at the beginning of lines, before the first non-white char
1062 t Everywhere except in headlines
1063 exc-hl-bol Everywhere except at the start of a headline
1064 If TAB is used in a place where it does not emulate TAB, the current subtree
1065 visibility is cycled."
1066 :group 'org-cycle
1067 :type '(choice (const :tag "Never" nil)
1068 (const :tag "Only in completely white lines" white)
1069 (const :tag "Before first char in a line" whitestart)
1070 (const :tag "Everywhere except in headlines" t)
1071 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1074 (defcustom org-cycle-separator-lines 2
1075 "Number of empty lines needed to keep an empty line between collapsed trees.
1076 If you leave an empty line between the end of a subtree and the following
1077 headline, this empty line is hidden when the subtree is folded.
1078 Org-mode will leave (exactly) one empty line visible if the number of
1079 empty lines is equal or larger to the number given in this variable.
1080 So the default 2 means at least 2 empty lines after the end of a subtree
1081 are needed to produce free space between a collapsed subtree and the
1082 following headline.
1084 If the number is negative, and the number of empty lines is at least -N,
1085 all empty lines are shown.
1087 Special case: when 0, never leave empty lines in collapsed view."
1088 :group 'org-cycle
1089 :type 'integer)
1090 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1092 (defcustom org-pre-cycle-hook nil
1093 "Hook that is run before visibility cycling is happening.
1094 The function(s) in this hook must accept a single argument which indicates
1095 the new state that will be set right after running this hook. The
1096 argument is a symbol. Before a global state change, it can have the values
1097 `overview', `content', or `all'. Before a local state change, it can have
1098 the values `folded', `children', or `subtree'."
1099 :group 'org-cycle
1100 :type 'hook)
1102 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1103 org-cycle-hide-drawers
1104 org-cycle-hide-inline-tasks
1105 org-cycle-show-empty-lines
1106 org-optimize-window-after-visibility-change)
1107 "Hook that is run after `org-cycle' has changed the buffer visibility.
1108 The function(s) in this hook must accept a single argument which indicates
1109 the new state that was set by the most recent `org-cycle' command. The
1110 argument is a symbol. After a global state change, it can have the values
1111 `overview', `contents', or `all'. After a local state change, it can have
1112 the values `folded', `children', or `subtree'."
1113 :group 'org-cycle
1114 :type 'hook)
1116 (defgroup org-edit-structure nil
1117 "Options concerning structure editing in Org-mode."
1118 :tag "Org Edit Structure"
1119 :group 'org-structure)
1121 (defcustom org-odd-levels-only nil
1122 "Non-nil means skip even levels and only use odd levels for the outline.
1123 This has the effect that two stars are being added/taken away in
1124 promotion/demotion commands. It also influences how levels are
1125 handled by the exporters.
1126 Changing it requires restart of `font-lock-mode' to become effective
1127 for fontification also in regions already fontified.
1128 You may also set this on a per-file basis by adding one of the following
1129 lines to the buffer:
1131 #+STARTUP: odd
1132 #+STARTUP: oddeven"
1133 :group 'org-edit-structure
1134 :group 'org-appearance
1135 :type 'boolean)
1137 (defcustom org-adapt-indentation t
1138 "Non-nil means adapt indentation to outline node level.
1140 When this variable is set, Org assumes that you write outlines by
1141 indenting text in each node to align with the headline (after the stars).
1142 The following issues are influenced by this variable:
1144 - When this is set and the *entire* text in an entry is indented, the
1145 indentation is increased by one space in a demotion command, and
1146 decreased by one in a promotion command. If any line in the entry
1147 body starts with text at column 0, indentation is not changed at all.
1149 - Property drawers and planning information is inserted indented when
1150 this variable s set. When nil, they will not be indented.
1152 - TAB indents a line relative to context. The lines below a headline
1153 will be indented when this variable is set.
1155 Note that this is all about true indentation, by adding and removing
1156 space characters. See also `org-indent.el' which does level-dependent
1157 indentation in a virtual way, i.e. at display time in Emacs."
1158 :group 'org-edit-structure
1159 :type 'boolean)
1161 (defcustom org-special-ctrl-a/e nil
1162 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1164 When t, `C-a' will bring back the cursor to the beginning of the
1165 headline text, i.e. after the stars and after a possible TODO
1166 keyword. In an item, this will be the position after bullet and
1167 check-box, if any. When the cursor is already at that position,
1168 another `C-a' will bring it to the beginning of the line.
1170 `C-e' will jump to the end of the headline, ignoring the presence
1171 of tags in the headline. A second `C-e' will then jump to the
1172 true end of the line, after any tags. This also means that, when
1173 this variable is non-nil, `C-e' also will never jump beyond the
1174 end of the heading of a folded section, i.e. not after the
1175 ellipses.
1177 When set to the symbol `reversed', the first `C-a' or `C-e' works
1178 normally, going to the true line boundary first. Only a directly
1179 following, identical keypress will bring the cursor to the
1180 special positions.
1182 This may also be a cons cell where the behavior for `C-a' and
1183 `C-e' is set separately."
1184 :group 'org-edit-structure
1185 :type '(choice
1186 (const :tag "off" nil)
1187 (const :tag "on: after stars/bullet and before tags first" t)
1188 (const :tag "reversed: true line boundary first" reversed)
1189 (cons :tag "Set C-a and C-e separately"
1190 (choice :tag "Special C-a"
1191 (const :tag "off" nil)
1192 (const :tag "on: after stars/bullet first" t)
1193 (const :tag "reversed: before stars/bullet first" reversed))
1194 (choice :tag "Special C-e"
1195 (const :tag "off" nil)
1196 (const :tag "on: before tags first" t)
1197 (const :tag "reversed: after tags first" reversed)))))
1198 (if (fboundp 'defvaralias)
1199 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1201 (defcustom org-special-ctrl-k nil
1202 "Non-nil means `C-k' will behave specially in headlines.
1203 When nil, `C-k' will call the default `kill-line' command.
1204 When t, the following will happen while the cursor is in the headline:
1206 - When the cursor is at the beginning of a headline, kill the entire
1207 line and possible the folded subtree below the line.
1208 - When in the middle of the headline text, kill the headline up to the tags.
1209 - When after the headline text, kill the tags."
1210 :group 'org-edit-structure
1211 :type 'boolean)
1213 (defcustom org-ctrl-k-protect-subtree nil
1214 "Non-nil means, do not delete a hidden subtree with C-k.
1215 When set to the symbol `error', simply throw an error when C-k is
1216 used to kill (part-of) a headline that has hidden text behind it.
1217 Any other non-nil value will result in a query to the user, if it is
1218 OK to kill that hidden subtree. When nil, kill without remorse."
1219 :group 'org-edit-structure
1220 :version "24.1"
1221 :type '(choice
1222 (const :tag "Do not protect hidden subtrees" nil)
1223 (const :tag "Protect hidden subtrees with a security query" t)
1224 (const :tag "Never kill a hidden subtree with C-k" error)))
1226 (defcustom org-catch-invisible-edits nil
1227 "Check if in invisible region before inserting or deleting a character.
1228 Valid values are:
1230 nil Do not check, so just do invisible edits.
1231 error Throw an error and do nothing.
1232 show Make point visible, and do the requested edit.
1233 show-and-error Make point visible, then throw an error and abort the edit.
1234 smart Make point visible, and do insertion/deletion if it is
1235 adjacent to visible text and the change feels predictable.
1236 Never delete a previously invisible character or add in the
1237 middle or right after an invisible region. Basically, this
1238 allows insertion and backward-delete right before ellipses.
1239 FIXME: maybe in this case we should not even show?"
1240 :group 'org-edit-structure
1241 :version "24.1"
1242 :type '(choice
1243 (const :tag "Do not check" nil)
1244 (const :tag "Throw error when trying to edit" error)
1245 (const :tag "Unhide, but do not do the edit" show-and-error)
1246 (const :tag "Show invisible part and do the edit" show)
1247 (const :tag "Be smart and do the right thing" smart)))
1249 (defcustom org-yank-folded-subtrees t
1250 "Non-nil means when yanking subtrees, fold them.
1251 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1252 it starts with a heading and all other headings in it are either children
1253 or siblings, then fold all the subtrees. However, do this only if no
1254 text after the yank would be swallowed into a folded tree by this action."
1255 :group 'org-edit-structure
1256 :type 'boolean)
1258 (defcustom org-yank-adjusted-subtrees nil
1259 "Non-nil means when yanking subtrees, adjust the level.
1260 With this setting, `org-paste-subtree' is used to insert the subtree, see
1261 this function for details."
1262 :group 'org-edit-structure
1263 :type 'boolean)
1265 (defcustom org-M-RET-may-split-line '((default . t))
1266 "Non-nil means M-RET will split the line at the cursor position.
1267 When nil, it will go to the end of the line before making a
1268 new line.
1269 You may also set this option in a different way for different
1270 contexts. Valid contexts are:
1272 headline when creating a new headline
1273 item when creating a new item
1274 table in a table field
1275 default the value to be used for all contexts not explicitly
1276 customized"
1277 :group 'org-structure
1278 :group 'org-table
1279 :type '(choice
1280 (const :tag "Always" t)
1281 (const :tag "Never" nil)
1282 (repeat :greedy t :tag "Individual contexts"
1283 (cons
1284 (choice :tag "Context"
1285 (const headline)
1286 (const item)
1287 (const table)
1288 (const default))
1289 (boolean)))))
1292 (defcustom org-insert-heading-respect-content nil
1293 "Non-nil means insert new headings after the current subtree.
1294 When nil, the new heading is created directly after the current line.
1295 The commands \\[org-insert-heading-respect-content] and
1296 \\[org-insert-todo-heading-respect-content] turn this variable on
1297 for the duration of the command."
1298 :group 'org-structure
1299 :type 'boolean)
1301 (defcustom org-blank-before-new-entry '((heading . auto)
1302 (plain-list-item . auto))
1303 "Should `org-insert-heading' leave a blank line before new heading/item?
1304 The value is an alist, with `heading' and `plain-list-item' as CAR,
1305 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1306 which case Org will look at the surrounding headings/items and try to
1307 make an intelligent decision whether to insert a blank line or not.
1309 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1310 set, the setting here is ignored and no empty line is inserted, to avoid
1311 breaking the list structure."
1312 :group 'org-edit-structure
1313 :type '(list
1314 (cons (const heading)
1315 (choice (const :tag "Never" nil)
1316 (const :tag "Always" t)
1317 (const :tag "Auto" auto)))
1318 (cons (const plain-list-item)
1319 (choice (const :tag "Never" nil)
1320 (const :tag "Always" t)
1321 (const :tag "Auto" auto)))))
1323 (defcustom org-insert-heading-hook nil
1324 "Hook being run after inserting a new heading."
1325 :group 'org-edit-structure
1326 :type 'hook)
1328 (defcustom org-enable-fixed-width-editor t
1329 "Non-nil means lines starting with \":\" are treated as fixed-width.
1330 This currently only means they are never auto-wrapped.
1331 When nil, such lines will be treated like ordinary lines.
1332 See also the QUOTE keyword."
1333 :group 'org-edit-structure
1334 :type 'boolean)
1336 (defcustom org-goto-auto-isearch t
1337 "Non-nil means typing characters in `org-goto' starts incremental search.
1338 When nil, you can use these keybindings to navigate the buffer:
1340 q Quit the org-goto interface
1341 n Go to the next visible heading
1342 p Go to the previous visible heading
1343 f Go one heading forward on same level
1344 b Go one heading backward on same level
1345 u Go one heading up"
1346 :group 'org-edit-structure
1347 :type 'boolean)
1349 (defgroup org-sparse-trees nil
1350 "Options concerning sparse trees in Org-mode."
1351 :tag "Org Sparse Trees"
1352 :group 'org-structure)
1354 (defcustom org-highlight-sparse-tree-matches t
1355 "Non-nil means highlight all matches that define a sparse tree.
1356 The highlights will automatically disappear the next time the buffer is
1357 changed by an edit command."
1358 :group 'org-sparse-trees
1359 :type 'boolean)
1361 (defcustom org-remove-highlights-with-change t
1362 "Non-nil means any change to the buffer will remove temporary highlights.
1363 Such highlights are created by `org-occur' and `org-clock-display'.
1364 When nil, `C-c C-c needs to be used to get rid of the highlights.
1365 The highlights created by `org-preview-latex-fragment' always need
1366 `C-c C-c' to be removed."
1367 :group 'org-sparse-trees
1368 :group 'org-time
1369 :type 'boolean)
1372 (defcustom org-occur-hook '(org-first-headline-recenter)
1373 "Hook that is run after `org-occur' has constructed a sparse tree.
1374 This can be used to recenter the window to show as much of the structure
1375 as possible."
1376 :group 'org-sparse-trees
1377 :type 'hook)
1379 (defgroup org-imenu-and-speedbar nil
1380 "Options concerning imenu and speedbar in Org-mode."
1381 :tag "Org Imenu and Speedbar"
1382 :group 'org-structure)
1384 (defcustom org-imenu-depth 2
1385 "The maximum level for Imenu access to Org-mode headlines.
1386 This also applied for speedbar access."
1387 :group 'org-imenu-and-speedbar
1388 :type 'integer)
1390 (defgroup org-table nil
1391 "Options concerning tables in Org-mode."
1392 :tag "Org Table"
1393 :group 'org)
1395 (defcustom org-enable-table-editor 'optimized
1396 "Non-nil means lines starting with \"|\" are handled by the table editor.
1397 When nil, such lines will be treated like ordinary lines.
1399 When equal to the symbol `optimized', the table editor will be optimized to
1400 do the following:
1401 - Automatic overwrite mode in front of whitespace in table fields.
1402 This makes the structure of the table stay in tact as long as the edited
1403 field does not exceed the column width.
1404 - Minimize the number of realigns. Normally, the table is aligned each time
1405 TAB or RET are pressed to move to another field. With optimization this
1406 happens only if changes to a field might have changed the column width.
1407 Optimization requires replacing the functions `self-insert-command',
1408 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1409 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1410 very good at guessing when a re-align will be necessary, but you can always
1411 force one with \\[org-ctrl-c-ctrl-c].
1413 If you would like to use the optimized version in Org-mode, but the
1414 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1416 This variable can be used to turn on and off the table editor during a session,
1417 but in order to toggle optimization, a restart is required.
1419 See also the variable `org-table-auto-blank-field'."
1420 :group 'org-table
1421 :type '(choice
1422 (const :tag "off" nil)
1423 (const :tag "on" t)
1424 (const :tag "on, optimized" optimized)))
1426 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1427 (version<= emacs-version "24.1"))
1428 "Non-nil means cluster self-insert commands for undo when possible.
1429 If this is set, then, like in the Emacs command loop, 20 consecutive
1430 characters will be undone together.
1431 This is configurable, because there is some impact on typing performance."
1432 :group 'org-table
1433 :type 'boolean)
1435 (defcustom org-table-tab-recognizes-table.el t
1436 "Non-nil means TAB will automatically notice a table.el table.
1437 When it sees such a table, it moves point into it and - if necessary -
1438 calls `table-recognize-table'."
1439 :group 'org-table-editing
1440 :type 'boolean)
1442 (defgroup org-link nil
1443 "Options concerning links in Org-mode."
1444 :tag "Org Link"
1445 :group 'org)
1447 (defvar org-link-abbrev-alist-local nil
1448 "Buffer-local version of `org-link-abbrev-alist', which see.
1449 The value of this is taken from the #+LINK lines.")
1450 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1452 (defcustom org-link-abbrev-alist nil
1453 "Alist of link abbreviations.
1454 The car of each element is a string, to be replaced at the start of a link.
1455 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1456 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1458 [[linkkey:tag][description]]
1460 The 'linkkey' must be a word word, starting with a letter, followed
1461 by letters, numbers, '-' or '_'.
1463 If REPLACE is a string, the tag will simply be appended to create the link.
1464 If the string contains \"%s\", the tag will be inserted there. If the string
1465 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1466 at that point (see the function `url-hexify-string'). If the string contains
1467 the specifier \"%(my-function)\", then the custom function `my-function' will
1468 be invoked: this function takes the tag as its only argument and must return
1469 a string.
1471 REPLACE may also be a function that will be called with the tag as the
1472 only argument to create the link, which should be returned as a string.
1474 See the manual for examples."
1475 :group 'org-link
1476 :type '(repeat
1477 (cons
1478 (string :tag "Protocol")
1479 (choice
1480 (string :tag "Format")
1481 (function)))))
1483 (defcustom org-descriptive-links t
1484 "Non-nil means Org will display descriptive links.
1485 E.g. [[http://orgmode.org][Org website]] will be displayed as
1486 \"Org Website\", hiding the link itself and just displaying its
1487 description. When set to `nil', Org will display the full links
1488 literally.
1490 You can interactively set the value of this variable by calling
1491 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1492 :group 'org-link
1493 :type 'boolean)
1495 (defcustom org-link-file-path-type 'adaptive
1496 "How the path name in file links should be stored.
1497 Valid values are:
1499 relative Relative to the current directory, i.e. the directory of the file
1500 into which the link is being inserted.
1501 absolute Absolute path, if possible with ~ for home directory.
1502 noabbrev Absolute path, no abbreviation of home directory.
1503 adaptive Use relative path for files in the current directory and sub-
1504 directories of it. For other files, use an absolute path."
1505 :group 'org-link
1506 :type '(choice
1507 (const relative)
1508 (const absolute)
1509 (const noabbrev)
1510 (const adaptive)))
1512 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1513 "Types of links that should be activated in Org-mode files.
1514 This is a list of symbols, each leading to the activation of a certain link
1515 type. In principle, it does not hurt to turn on most link types - there may
1516 be a small gain when turning off unused link types. The types are:
1518 bracket The recommended [[link][description]] or [[link]] links with hiding.
1519 angle Links in angular brackets that may contain whitespace like
1520 <bbdb:Carsten Dominik>.
1521 plain Plain links in normal text, no whitespace, like http://google.com.
1522 radio Text that is matched by a radio target, see manual for details.
1523 tag Tag settings in a headline (link to tag search).
1524 date Time stamps (link to calendar).
1525 footnote Footnote labels.
1527 Changing this variable requires a restart of Emacs to become effective."
1528 :group 'org-link
1529 :type '(set :greedy t
1530 (const :tag "Double bracket links" bracket)
1531 (const :tag "Angular bracket links" angle)
1532 (const :tag "Plain text links" plain)
1533 (const :tag "Radio target matches" radio)
1534 (const :tag "Tags" tag)
1535 (const :tag "Timestamps" date)
1536 (const :tag "Footnotes" footnote)))
1538 (defcustom org-make-link-description-function nil
1539 "Function to use for generating link descriptions from links.
1540 When nil, the link location will be used. This function must take
1541 two parameters: the first one is the link, the second one is the
1542 description generated by `org-insert-link'. The function should
1543 return the description to use."
1544 :group 'org-link
1545 :type 'function)
1547 (defgroup org-link-store nil
1548 "Options concerning storing links in Org-mode."
1549 :tag "Org Store Link"
1550 :group 'org-link)
1552 (defcustom org-url-hexify-p t
1553 "When non-nil, hexify URL when creating a link."
1554 :type 'boolean
1555 :version "24.3"
1556 :group 'org-link-store)
1558 (defcustom org-email-link-description-format "Email %c: %.30s"
1559 "Format of the description part of a link to an email or usenet message.
1560 The following %-escapes will be replaced by corresponding information:
1562 %F full \"From\" field
1563 %f name, taken from \"From\" field, address if no name
1564 %T full \"To\" field
1565 %t first name in \"To\" field, address if no name
1566 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1567 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1568 %s subject
1569 %d date
1570 %m message-id.
1572 You may use normal field width specification between the % and the letter.
1573 This is for example useful to limit the length of the subject.
1575 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1576 :group 'org-link-store
1577 :type 'string)
1579 (defcustom org-from-is-user-regexp
1580 (let (r1 r2)
1581 (when (and user-mail-address (not (string= user-mail-address "")))
1582 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1583 (when (and user-full-name (not (string= user-full-name "")))
1584 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1585 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1586 "Regexp matched against the \"From:\" header of an email or usenet message.
1587 It should match if the message is from the user him/herself."
1588 :group 'org-link-store
1589 :type 'regexp)
1591 (defcustom org-context-in-file-links t
1592 "Non-nil means file links from `org-store-link' contain context.
1593 A search string will be added to the file name with :: as separator and
1594 used to find the context when the link is activated by the command
1595 `org-open-at-point'. When this option is t, the entire active region
1596 will be placed in the search string of the file link. If set to a
1597 positive integer, only the first n lines of context will be stored.
1599 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1600 negates this setting for the duration of the command."
1601 :group 'org-link-store
1602 :type '(choice boolean integer))
1604 (defcustom org-keep-stored-link-after-insertion nil
1605 "Non-nil means keep link in list for entire session.
1607 The command `org-store-link' adds a link pointing to the current
1608 location to an internal list. These links accumulate during a session.
1609 The command `org-insert-link' can be used to insert links into any
1610 Org-mode file (offering completion for all stored links). When this
1611 option is nil, every link which has been inserted once using \\[org-insert-link]
1612 will be removed from the list, to make completing the unused links
1613 more efficient."
1614 :group 'org-link-store
1615 :type 'boolean)
1617 (defgroup org-link-follow nil
1618 "Options concerning following links in Org-mode."
1619 :tag "Org Follow Link"
1620 :group 'org-link)
1622 (defcustom org-link-translation-function nil
1623 "Function to translate links with different syntax to Org syntax.
1624 This can be used to translate links created for example by the Planner
1625 or emacs-wiki packages to Org syntax.
1626 The function must accept two parameters, a TYPE containing the link
1627 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1628 which is everything after the link protocol. It should return a cons
1629 with possibly modified values of type and path.
1630 Org contains a function for this, so if you set this variable to
1631 `org-translate-link-from-planner', you should be able follow many
1632 links created by planner."
1633 :group 'org-link-follow
1634 :type 'function)
1636 (defcustom org-follow-link-hook nil
1637 "Hook that is run after a link has been followed."
1638 :group 'org-link-follow
1639 :type 'hook)
1641 (defcustom org-tab-follows-link nil
1642 "Non-nil means on links TAB will follow the link.
1643 Needs to be set before org.el is loaded.
1644 This really should not be used, it does not make sense, and the
1645 implementation is bad."
1646 :group 'org-link-follow
1647 :type 'boolean)
1649 (defcustom org-return-follows-link nil
1650 "Non-nil means on links RET will follow the link."
1651 :group 'org-link-follow
1652 :type 'boolean)
1654 (defcustom org-mouse-1-follows-link
1655 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1656 "Non-nil means mouse-1 on a link will follow the link.
1657 A longer mouse click will still set point. Does not work on XEmacs.
1658 Needs to be set before org.el is loaded."
1659 :group 'org-link-follow
1660 :type 'boolean)
1662 (defcustom org-mark-ring-length 4
1663 "Number of different positions to be recorded in the ring.
1664 Changing this requires a restart of Emacs to work correctly."
1665 :group 'org-link-follow
1666 :type 'integer)
1668 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1669 "Non-nil means internal links in Org files must exactly match a headline.
1670 When nil, the link search tries to match a phrase with all words
1671 in the search text."
1672 :group 'org-link-follow
1673 :version "24.1"
1674 :type '(choice
1675 (const :tag "Use fuzzy text search" nil)
1676 (const :tag "Match only exact headline" t)
1677 (const :tag "Match exact headline or query to create it"
1678 query-to-create)))
1680 (defcustom org-link-frame-setup
1681 '((vm . vm-visit-folder-other-frame)
1682 (vm-imap . vm-visit-imap-folder-other-frame)
1683 (gnus . org-gnus-no-new-news)
1684 (file . find-file-other-window)
1685 (wl . wl-other-frame))
1686 "Setup the frame configuration for following links.
1687 When following a link with Emacs, it may often be useful to display
1688 this link in another window or frame. This variable can be used to
1689 set this up for the different types of links.
1690 For VM, use any of
1691 `vm-visit-folder'
1692 `vm-visit-folder-other-window'
1693 `vm-visit-folder-other-frame'
1694 For Gnus, use any of
1695 `gnus'
1696 `gnus-other-frame'
1697 `org-gnus-no-new-news'
1698 For FILE, use any of
1699 `find-file'
1700 `find-file-other-window'
1701 `find-file-other-frame'
1702 For Wanderlust use any of
1703 `wl'
1704 `wl-other-frame'
1705 For the calendar, use the variable `calendar-setup'.
1706 For BBDB, it is currently only possible to display the matches in
1707 another window."
1708 :group 'org-link-follow
1709 :type '(list
1710 (cons (const vm)
1711 (choice
1712 (const vm-visit-folder)
1713 (const vm-visit-folder-other-window)
1714 (const vm-visit-folder-other-frame)))
1715 (cons (const gnus)
1716 (choice
1717 (const gnus)
1718 (const gnus-other-frame)
1719 (const org-gnus-no-new-news)))
1720 (cons (const file)
1721 (choice
1722 (const find-file)
1723 (const find-file-other-window)
1724 (const find-file-other-frame)))
1725 (cons (const wl)
1726 (choice
1727 (const wl)
1728 (const wl-other-frame)))))
1730 (defcustom org-display-internal-link-with-indirect-buffer nil
1731 "Non-nil means use indirect buffer to display infile links.
1732 Activating internal links (from one location in a file to another location
1733 in the same file) normally just jumps to the location. When the link is
1734 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1735 is displayed in
1736 another window. When this option is set, the other window actually displays
1737 an indirect buffer clone of the current buffer, to avoid any visibility
1738 changes to the current buffer."
1739 :group 'org-link-follow
1740 :type 'boolean)
1742 (defcustom org-open-non-existing-files nil
1743 "Non-nil means `org-open-file' will open non-existing files.
1744 When nil, an error will be generated.
1745 This variable applies only to external applications because they
1746 might choke on non-existing files. If the link is to a file that
1747 will be opened in Emacs, the variable is ignored."
1748 :group 'org-link-follow
1749 :type 'boolean)
1751 (defcustom org-open-directory-means-index-dot-org nil
1752 "Non-nil means a link to a directory really means to index.org.
1753 When nil, following a directory link will run dired or open a finder/explorer
1754 window on that directory."
1755 :group 'org-link-follow
1756 :type 'boolean)
1758 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1759 "Function and arguments to call for following mailto links.
1760 This is a list with the first element being a Lisp function, and the
1761 remaining elements being arguments to the function. In string arguments,
1762 %a will be replaced by the address, and %s will be replaced by the subject
1763 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1764 :group 'org-link-follow
1765 :type '(choice
1766 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1767 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1768 (const :tag "message-mail" (message-mail "%a" "%s"))
1769 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1771 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1772 "Non-nil means ask for confirmation before executing shell links.
1773 Shell links can be dangerous: just think about a link
1775 [[shell:rm -rf ~/*][Google Search]]
1777 This link would show up in your Org-mode document as \"Google Search\",
1778 but really it would remove your entire home directory.
1779 Therefore we advise against setting this variable to nil.
1780 Just change it to `y-or-n-p' if you want to confirm with a
1781 single keystroke rather than having to type \"yes\"."
1782 :group 'org-link-follow
1783 :type '(choice
1784 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1785 (const :tag "with y-or-n (faster)" y-or-n-p)
1786 (const :tag "no confirmation (dangerous)" nil)))
1787 (put 'org-confirm-shell-link-function
1788 'safe-local-variable
1789 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1791 (defcustom org-confirm-shell-link-not-regexp ""
1792 "A regexp to skip confirmation for shell links."
1793 :group 'org-link-follow
1794 :version "24.1"
1795 :type 'regexp)
1797 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1798 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1799 Elisp links can be dangerous: just think about a link
1801 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1803 This link would show up in your Org-mode document as \"Google Search\",
1804 but really it would remove your entire home directory.
1805 Therefore we advise against setting this variable to nil.
1806 Just change it to `y-or-n-p' if you want to confirm with a
1807 single keystroke rather than having to type \"yes\"."
1808 :group 'org-link-follow
1809 :type '(choice
1810 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1811 (const :tag "with y-or-n (faster)" y-or-n-p)
1812 (const :tag "no confirmation (dangerous)" nil)))
1813 (put 'org-confirm-shell-link-function
1814 'safe-local-variable
1815 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1817 (defcustom org-confirm-elisp-link-not-regexp ""
1818 "A regexp to skip confirmation for Elisp links."
1819 :group 'org-link-follow
1820 :version "24.1"
1821 :type 'regexp)
1823 (defconst org-file-apps-defaults-gnu
1824 '((remote . emacs)
1825 (system . mailcap)
1826 (t . mailcap))
1827 "Default file applications on a UNIX or GNU/Linux system.
1828 See `org-file-apps'.")
1830 (defconst org-file-apps-defaults-macosx
1831 '((remote . emacs)
1832 (t . "open %s")
1833 (system . "open %s")
1834 ("ps.gz" . "gv %s")
1835 ("eps.gz" . "gv %s")
1836 ("dvi" . "xdvi %s")
1837 ("fig" . "xfig %s"))
1838 "Default file applications on a MacOS X system.
1839 The system \"open\" is known as a default, but we use X11 applications
1840 for some files for which the OS does not have a good default.
1841 See `org-file-apps'.")
1843 (defconst org-file-apps-defaults-windowsnt
1844 (list
1845 '(remote . emacs)
1846 (cons t
1847 (list (if (featurep 'xemacs)
1848 'mswindows-shell-execute
1849 'w32-shell-execute)
1850 "open" 'file))
1851 (cons 'system
1852 (list (if (featurep 'xemacs)
1853 'mswindows-shell-execute
1854 'w32-shell-execute)
1855 "open" 'file)))
1856 "Default file applications on a Windows NT system.
1857 The system \"open\" is used for most files.
1858 See `org-file-apps'.")
1860 (defcustom org-file-apps
1862 (auto-mode . emacs)
1863 ("\\.mm\\'" . default)
1864 ("\\.x?html?\\'" . default)
1865 ("\\.pdf\\'" . default)
1867 "External applications for opening `file:path' items in a document.
1868 Org-mode uses system defaults for different file types, but
1869 you can use this variable to set the application for a given file
1870 extension. The entries in this list are cons cells where the car identifies
1871 files and the cdr the corresponding command. Possible values for the
1872 file identifier are
1873 \"string\" A string as a file identifier can be interpreted in different
1874 ways, depending on its contents:
1876 - Alphanumeric characters only:
1877 Match links with this file extension.
1878 Example: (\"pdf\" . \"evince %s\")
1879 to open PDFs with evince.
1881 - Regular expression: Match links where the
1882 filename matches the regexp. If you want to
1883 use groups here, use shy groups.
1885 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1886 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1887 to open *.html and *.xhtml with firefox.
1889 - Regular expression which contains (non-shy) groups:
1890 Match links where the whole link, including \"::\", and
1891 anything after that, matches the regexp.
1892 In a custom command string, %1, %2, etc. are replaced with
1893 the parts of the link that were matched by the groups.
1894 For backwards compatibility, if a command string is given
1895 that does not use any of the group matches, this case is
1896 handled identically to the second one (i.e. match against
1897 file name only).
1898 In a custom lisp form, you can access the group matches with
1899 (match-string n link).
1901 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1902 to open [[file:document.pdf::5]] with evince at page 5.
1904 `directory' Matches a directory
1905 `remote' Matches a remote file, accessible through tramp or efs.
1906 Remote files most likely should be visited through Emacs
1907 because external applications cannot handle such paths.
1908 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1909 so all files Emacs knows how to handle. Using this with
1910 command `emacs' will open most files in Emacs. Beware that this
1911 will also open html files inside Emacs, unless you add
1912 (\"html\" . default) to the list as well.
1913 t Default for files not matched by any of the other options.
1914 `system' The system command to open files, like `open' on Windows
1915 and Mac OS X, and mailcap under GNU/Linux. This is the command
1916 that will be selected if you call `C-c C-o' with a double
1917 \\[universal-argument] \\[universal-argument] prefix.
1919 Possible values for the command are:
1920 `emacs' The file will be visited by the current Emacs process.
1921 `default' Use the default application for this file type, which is the
1922 association for t in the list, most likely in the system-specific
1923 part.
1924 This can be used to overrule an unwanted setting in the
1925 system-specific variable.
1926 `system' Use the system command for opening files, like \"open\".
1927 This command is specified by the entry whose car is `system'.
1928 Most likely, the system-specific version of this variable
1929 does define this command, but you can overrule/replace it
1930 here.
1931 string A command to be executed by a shell; %s will be replaced
1932 by the path to the file.
1933 sexp A Lisp form which will be evaluated. The file path will
1934 be available in the Lisp variable `file'.
1935 For more examples, see the system specific constants
1936 `org-file-apps-defaults-macosx'
1937 `org-file-apps-defaults-windowsnt'
1938 `org-file-apps-defaults-gnu'."
1939 :group 'org-link-follow
1940 :type '(repeat
1941 (cons (choice :value ""
1942 (string :tag "Extension")
1943 (const :tag "System command to open files" system)
1944 (const :tag "Default for unrecognized files" t)
1945 (const :tag "Remote file" remote)
1946 (const :tag "Links to a directory" directory)
1947 (const :tag "Any files that have Emacs modes"
1948 auto-mode))
1949 (choice :value ""
1950 (const :tag "Visit with Emacs" emacs)
1951 (const :tag "Use default" default)
1952 (const :tag "Use the system command" system)
1953 (string :tag "Command")
1954 (sexp :tag "Lisp form")))))
1956 (defcustom org-doi-server-url "http://dx.doi.org/"
1957 "The URL of the DOI server."
1958 :type 'string
1959 :version "24.3"
1960 :group 'org-link-follow)
1962 (defgroup org-refile nil
1963 "Options concerning refiling entries in Org-mode."
1964 :tag "Org Refile"
1965 :group 'org)
1967 (defcustom org-directory "~/org"
1968 "Directory with org files.
1969 This is just a default location to look for Org files. There is no need
1970 at all to put your files into this directory. It is only used in the
1971 following situations:
1973 1. When a capture template specifies a target file that is not an
1974 absolute path. The path will then be interpreted relative to
1975 `org-directory'
1976 2. When a capture note is filed away in an interactive way (when exiting the
1977 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1978 with `org-directory' as the default path."
1979 :group 'org-refile
1980 :group 'org-remember
1981 :group 'org-capture
1982 :type 'directory)
1984 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1985 "Default target for storing notes.
1986 Used as a fall back file for org-remember.el and org-capture.el, for
1987 templates that do not specify a target file."
1988 :group 'org-refile
1989 :group 'org-remember
1990 :group 'org-capture
1991 :type '(choice
1992 (const :tag "Default from remember-data-file" nil)
1993 file))
1995 (defcustom org-goto-interface 'outline
1996 "The default interface to be used for `org-goto'.
1997 Allowed values are:
1998 outline The interface shows an outline of the relevant file
1999 and the correct heading is found by moving through
2000 the outline or by searching with incremental search.
2001 outline-path-completion Headlines in the current buffer are offered via
2002 completion. This is the interface also used by
2003 the refile command."
2004 :group 'org-refile
2005 :type '(choice
2006 (const :tag "Outline" outline)
2007 (const :tag "Outline-path-completion" outline-path-completion)))
2009 (defcustom org-goto-max-level 5
2010 "Maximum target level when running `org-goto' with refile interface."
2011 :group 'org-refile
2012 :type 'integer)
2014 (defcustom org-reverse-note-order nil
2015 "Non-nil means store new notes at the beginning of a file or entry.
2016 When nil, new notes will be filed to the end of a file or entry.
2017 This can also be a list with cons cells of regular expressions that
2018 are matched against file names, and values."
2019 :group 'org-remember
2020 :group 'org-capture
2021 :group 'org-refile
2022 :type '(choice
2023 (const :tag "Reverse always" t)
2024 (const :tag "Reverse never" nil)
2025 (repeat :tag "By file name regexp"
2026 (cons regexp boolean))))
2028 (defcustom org-log-refile nil
2029 "Information to record when a task is refiled.
2031 Possible values are:
2033 nil Don't add anything
2034 time Add a time stamp to the task
2035 note Prompt for a note and add it with template `org-log-note-headings'
2037 This option can also be set with on a per-file-basis with
2039 #+STARTUP: nologrefile
2040 #+STARTUP: logrefile
2041 #+STARTUP: lognoterefile
2043 You can have local logging settings for a subtree by setting the LOGGING
2044 property to one or more of these keywords.
2046 When bulk-refiling from the agenda, the value `note' is forbidden and
2047 will temporarily be changed to `time'."
2048 :group 'org-refile
2049 :group 'org-progress
2050 :version "24.1"
2051 :type '(choice
2052 (const :tag "No logging" nil)
2053 (const :tag "Record timestamp" time)
2054 (const :tag "Record timestamp with note." note)))
2056 (defcustom org-refile-targets nil
2057 "Targets for refiling entries with \\[org-refile].
2058 This is a list of cons cells. Each cell contains:
2059 - a specification of the files to be considered, either a list of files,
2060 or a symbol whose function or variable value will be used to retrieve
2061 a file name or a list of file names. If you use `org-agenda-files' for
2062 that, all agenda files will be scanned for targets. Nil means consider
2063 headings in the current buffer.
2064 - A specification of how to find candidate refile targets. This may be
2065 any of:
2066 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2067 This tag has to be present in all target headlines, inheritance will
2068 not be considered.
2069 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2070 todo keyword.
2071 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2072 headlines that are refiling targets.
2073 - a cons cell (:level . N). Any headline of level N is considered a target.
2074 Note that, when `org-odd-levels-only' is set, level corresponds to
2075 order in hierarchy, not to the number of stars.
2076 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2077 Note that, when `org-odd-levels-only' is set, level corresponds to
2078 order in hierarchy, not to the number of stars.
2080 Each element of this list generates a set of possible targets.
2081 The union of these sets is presented (with completion) to
2082 the user by `org-refile'.
2084 You can set the variable `org-refile-target-verify-function' to a function
2085 to verify each headline found by the simple criteria above.
2087 When this variable is nil, all top-level headlines in the current buffer
2088 are used, equivalent to the value `((nil . (:level . 1))'."
2089 :group 'org-refile
2090 :type '(repeat
2091 (cons
2092 (choice :value org-agenda-files
2093 (const :tag "All agenda files" org-agenda-files)
2094 (const :tag "Current buffer" nil)
2095 (function) (variable) (file))
2096 (choice :tag "Identify target headline by"
2097 (cons :tag "Specific tag" (const :value :tag) (string))
2098 (cons :tag "TODO keyword" (const :value :todo) (string))
2099 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2100 (cons :tag "Level number" (const :value :level) (integer))
2101 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2103 (defcustom org-refile-target-verify-function nil
2104 "Function to verify if the headline at point should be a refile target.
2105 The function will be called without arguments, with point at the
2106 beginning of the headline. It should return t and leave point
2107 where it is if the headline is a valid target for refiling.
2109 If the target should not be selected, the function must return nil.
2110 In addition to this, it may move point to a place from where the search
2111 should be continued. For example, the function may decide that the entire
2112 subtree of the current entry should be excluded and move point to the end
2113 of the subtree."
2114 :group 'org-refile
2115 :type 'function)
2117 (defcustom org-refile-use-cache nil
2118 "Non-nil means cache refile targets to speed up the process.
2119 The cache for a particular file will be updated automatically when
2120 the buffer has been killed, or when any of the marker used for flagging
2121 refile targets no longer points at a live buffer.
2122 If you have added new entries to a buffer that might themselves be targets,
2123 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2124 find that easier, `C-u C-u C-u C-c C-w'."
2125 :group 'org-refile
2126 :version "24.1"
2127 :type 'boolean)
2129 (defcustom org-refile-use-outline-path nil
2130 "Non-nil means provide refile targets as paths.
2131 So a level 3 headline will be available as level1/level2/level3.
2133 When the value is `file', also include the file name (without directory)
2134 into the path. In this case, you can also stop the completion after
2135 the file name, to get entries inserted as top level in the file.
2137 When `full-file-path', include the full file path."
2138 :group 'org-refile
2139 :type '(choice
2140 (const :tag "Not" nil)
2141 (const :tag "Yes" t)
2142 (const :tag "Start with file name" file)
2143 (const :tag "Start with full file path" full-file-path)))
2145 (defcustom org-outline-path-complete-in-steps t
2146 "Non-nil means complete the outline path in hierarchical steps.
2147 When Org-mode uses the refile interface to select an outline path
2148 \(see variable `org-refile-use-outline-path'), the completion of
2149 the path can be done is a single go, or if can be done in steps down
2150 the headline hierarchy. Going in steps is probably the best if you
2151 do not use a special completion package like `ido' or `icicles'.
2152 However, when using these packages, going in one step can be very
2153 fast, while still showing the whole path to the entry."
2154 :group 'org-refile
2155 :type 'boolean)
2157 (defcustom org-refile-allow-creating-parent-nodes nil
2158 "Non-nil means allow to create new nodes as refile targets.
2159 New nodes are then created by adding \"/new node name\" to the completion
2160 of an existing node. When the value of this variable is `confirm',
2161 new node creation must be confirmed by the user (recommended)
2162 When nil, the completion must match an existing entry.
2164 Note that, if the new heading is not seen by the criteria
2165 listed in `org-refile-targets', multiple instances of the same
2166 heading would be created by trying again to file under the new
2167 heading."
2168 :group 'org-refile
2169 :type '(choice
2170 (const :tag "Never" nil)
2171 (const :tag "Always" t)
2172 (const :tag "Prompt for confirmation" confirm)))
2174 (defcustom org-refile-active-region-within-subtree nil
2175 "Non-nil means also refile active region within a subtree.
2177 By default `org-refile' doesn't allow refiling regions if they
2178 don't contain a set of subtrees, but it might be convenient to
2179 do so sometimes: in that case, the first line of the region is
2180 converted to a headline before refiling."
2181 :group 'org-refile
2182 :version "24.1"
2183 :type 'boolean)
2185 (defgroup org-todo nil
2186 "Options concerning TODO items in Org-mode."
2187 :tag "Org TODO"
2188 :group 'org)
2190 (defgroup org-progress nil
2191 "Options concerning Progress logging in Org-mode."
2192 :tag "Org Progress"
2193 :group 'org-time)
2195 (defvar org-todo-interpretation-widgets
2196 '((:tag "Sequence (cycling hits every state)" sequence)
2197 (:tag "Type (cycling directly to DONE)" type))
2198 "The available interpretation symbols for customizing `org-todo-keywords'.
2199 Interested libraries should add to this list.")
2201 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2202 "List of TODO entry keyword sequences and their interpretation.
2203 \\<org-mode-map>This is a list of sequences.
2205 Each sequence starts with a symbol, either `sequence' or `type',
2206 indicating if the keywords should be interpreted as a sequence of
2207 action steps, or as different types of TODO items. The first
2208 keywords are states requiring action - these states will select a headline
2209 for inclusion into the global TODO list Org-mode produces. If one of
2210 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2211 signify that no further action is necessary. If \"|\" is not found,
2212 the last keyword is treated as the only DONE state of the sequence.
2214 The command \\[org-todo] cycles an entry through these states, and one
2215 additional state where no keyword is present. For details about this
2216 cycling, see the manual.
2218 TODO keywords and interpretation can also be set on a per-file basis with
2219 the special #+SEQ_TODO and #+TYP_TODO lines.
2221 Each keyword can optionally specify a character for fast state selection
2222 \(in combination with the variable `org-use-fast-todo-selection')
2223 and specifiers for state change logging, using the same syntax that
2224 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2225 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2226 indicates to record a time stamp each time this state is selected.
2228 Each keyword may also specify if a timestamp or a note should be
2229 recorded when entering or leaving the state, by adding additional
2230 characters in the parenthesis after the keyword. This looks like this:
2231 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2232 record only the time of the state change. With X and Y being either
2233 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2234 Y when leaving the state if and only if the *target* state does not
2235 define X. You may omit any of the fast-selection key or X or /Y,
2236 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2238 For backward compatibility, this variable may also be just a list
2239 of keywords. In this case the interpretation (sequence or type) will be
2240 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2241 :group 'org-todo
2242 :group 'org-keywords
2243 :type '(choice
2244 (repeat :tag "Old syntax, just keywords"
2245 (string :tag "Keyword"))
2246 (repeat :tag "New syntax"
2247 (cons
2248 (choice
2249 :tag "Interpretation"
2250 ;;Quick and dirty way to see
2251 ;;`org-todo-interpretations'. This takes the
2252 ;;place of item arguments
2253 :convert-widget
2254 (lambda (widget)
2255 (widget-put widget
2256 :args (mapcar
2257 #'(lambda (x)
2258 (widget-convert
2259 (cons 'const x)))
2260 org-todo-interpretation-widgets))
2261 widget))
2262 (repeat
2263 (string :tag "Keyword"))))))
2265 (defvar org-todo-keywords-1 nil
2266 "All TODO and DONE keywords active in a buffer.")
2267 (make-variable-buffer-local 'org-todo-keywords-1)
2268 (defvar org-todo-keywords-for-agenda nil)
2269 (defvar org-done-keywords-for-agenda nil)
2270 (defvar org-drawers-for-agenda nil)
2271 (defvar org-todo-keyword-alist-for-agenda nil)
2272 (defvar org-tag-alist-for-agenda nil)
2273 (defvar org-agenda-contributing-files nil)
2274 (defvar org-not-done-keywords nil)
2275 (make-variable-buffer-local 'org-not-done-keywords)
2276 (defvar org-done-keywords nil)
2277 (make-variable-buffer-local 'org-done-keywords)
2278 (defvar org-todo-heads nil)
2279 (make-variable-buffer-local 'org-todo-heads)
2280 (defvar org-todo-sets nil)
2281 (make-variable-buffer-local 'org-todo-sets)
2282 (defvar org-todo-log-states nil)
2283 (make-variable-buffer-local 'org-todo-log-states)
2284 (defvar org-todo-kwd-alist nil)
2285 (make-variable-buffer-local 'org-todo-kwd-alist)
2286 (defvar org-todo-key-alist nil)
2287 (make-variable-buffer-local 'org-todo-key-alist)
2288 (defvar org-todo-key-trigger nil)
2289 (make-variable-buffer-local 'org-todo-key-trigger)
2291 (defcustom org-todo-interpretation 'sequence
2292 "Controls how TODO keywords are interpreted.
2293 This variable is in principle obsolete and is only used for
2294 backward compatibility, if the interpretation of todo keywords is
2295 not given already in `org-todo-keywords'. See that variable for
2296 more information."
2297 :group 'org-todo
2298 :group 'org-keywords
2299 :type '(choice (const sequence)
2300 (const type)))
2302 (defcustom org-use-fast-todo-selection t
2303 "Non-nil means use the fast todo selection scheme with C-c C-t.
2304 This variable describes if and under what circumstances the cycling
2305 mechanism for TODO keywords will be replaced by a single-key, direct
2306 selection scheme.
2308 When nil, fast selection is never used.
2310 When the symbol `prefix', it will be used when `org-todo' is called
2311 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2312 `C-u t' in an agenda buffer.
2314 When t, fast selection is used by default. In this case, the prefix
2315 argument forces cycling instead.
2317 In all cases, the special interface is only used if access keys have
2318 actually been assigned by the user, i.e. if keywords in the configuration
2319 are followed by a letter in parenthesis, like TODO(t)."
2320 :group 'org-todo
2321 :type '(choice
2322 (const :tag "Never" nil)
2323 (const :tag "By default" t)
2324 (const :tag "Only with C-u C-c C-t" prefix)))
2326 (defcustom org-provide-todo-statistics t
2327 "Non-nil means update todo statistics after insert and toggle.
2328 ALL-HEADLINES means update todo statistics by including headlines
2329 with no TODO keyword as well, counting them as not done.
2330 A list of TODO keywords means the same, but skip keywords that are
2331 not in this list.
2333 When this is set, todo statistics is updated in the parent of the
2334 current entry each time a todo state is changed."
2335 :group 'org-todo
2336 :type '(choice
2337 (const :tag "Yes, only for TODO entries" t)
2338 (const :tag "Yes, including all entries" 'all-headlines)
2339 (repeat :tag "Yes, for TODOs in this list"
2340 (string :tag "TODO keyword"))
2341 (other :tag "No TODO statistics" nil)))
2343 (defcustom org-hierarchical-todo-statistics t
2344 "Non-nil means TODO statistics covers just direct children.
2345 When nil, all entries in the subtree are considered.
2346 This has only an effect if `org-provide-todo-statistics' is set.
2347 To set this to nil for only a single subtree, use a COOKIE_DATA
2348 property and include the word \"recursive\" into the value."
2349 :group 'org-todo
2350 :type 'boolean)
2352 (defcustom org-after-todo-state-change-hook nil
2353 "Hook which is run after the state of a TODO item was changed.
2354 The new state (a string with a TODO keyword, or nil) is available in the
2355 Lisp variable `org-state'."
2356 :group 'org-todo
2357 :type 'hook)
2359 (defvar org-blocker-hook nil
2360 "Hook for functions that are allowed to block a state change.
2362 Functions in this hook should not modify the buffer.
2363 Each function gets as its single argument a property list,
2364 see `org-trigger-hook' for more information about this list.
2366 If any of the functions in this hook returns nil, the state change
2367 is blocked.")
2369 (defvar org-trigger-hook nil
2370 "Hook for functions that are triggered by a state change.
2372 Each function gets as its single argument a property list with at
2373 least the following elements:
2375 (:type type-of-change :position pos-at-entry-start
2376 :from old-state :to new-state)
2378 Depending on the type, more properties may be present.
2380 This mechanism is currently implemented for:
2382 TODO state changes
2383 ------------------
2384 :type todo-state-change
2385 :from previous state (keyword as a string), or nil, or a symbol
2386 'todo' or 'done', to indicate the general type of state.
2387 :to new state, like in :from")
2389 (defcustom org-enforce-todo-dependencies nil
2390 "Non-nil means undone TODO entries will block switching the parent to DONE.
2391 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2392 be blocked if any prior sibling is not yet done.
2393 Finally, if the parent is blocked because of ordered siblings of its own,
2394 the child will also be blocked."
2395 :set (lambda (var val)
2396 (set var val)
2397 (if val
2398 (add-hook 'org-blocker-hook
2399 'org-block-todo-from-children-or-siblings-or-parent)
2400 (remove-hook 'org-blocker-hook
2401 'org-block-todo-from-children-or-siblings-or-parent)))
2402 :group 'org-todo
2403 :type 'boolean)
2405 (defcustom org-enforce-todo-checkbox-dependencies nil
2406 "Non-nil means unchecked boxes will block switching the parent to DONE.
2407 When this is nil, checkboxes have no influence on switching TODO states.
2408 When non-nil, you first need to check off all check boxes before the TODO
2409 entry can be switched to DONE.
2410 This variable needs to be set before org.el is loaded, and you need to
2411 restart Emacs after a change to make the change effective. The only way
2412 to change is while Emacs is running is through the customize interface."
2413 :set (lambda (var val)
2414 (set var val)
2415 (if val
2416 (add-hook 'org-blocker-hook
2417 'org-block-todo-from-checkboxes)
2418 (remove-hook 'org-blocker-hook
2419 'org-block-todo-from-checkboxes)))
2420 :group 'org-todo
2421 :type 'boolean)
2423 (defcustom org-treat-insert-todo-heading-as-state-change nil
2424 "Non-nil means inserting a TODO heading is treated as state change.
2425 So when the command \\[org-insert-todo-heading] is used, state change
2426 logging will apply if appropriate. When nil, the new TODO item will
2427 be inserted directly, and no logging will take place."
2428 :group 'org-todo
2429 :type 'boolean)
2431 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2432 "Non-nil means switching TODO states with S-cursor counts as state change.
2433 This is the default behavior. However, setting this to nil allows a
2434 convenient way to select a TODO state and bypass any logging associated
2435 with that."
2436 :group 'org-todo
2437 :type 'boolean)
2439 (defcustom org-todo-state-tags-triggers nil
2440 "Tag changes that should be triggered by TODO state changes.
2441 This is a list. Each entry is
2443 (state-change (tag . flag) .......)
2445 State-change can be a string with a state, and empty string to indicate the
2446 state that has no TODO keyword, or it can be one of the symbols `todo'
2447 or `done', meaning any not-done or done state, respectively."
2448 :group 'org-todo
2449 :group 'org-tags
2450 :type '(repeat
2451 (cons (choice :tag "When changing to"
2452 (const :tag "Not-done state" todo)
2453 (const :tag "Done state" done)
2454 (string :tag "State"))
2455 (repeat
2456 (cons :tag "Tag action"
2457 (string :tag "Tag")
2458 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2460 (defcustom org-log-done nil
2461 "Information to record when a task moves to the DONE state.
2463 Possible values are:
2465 nil Don't add anything, just change the keyword
2466 time Add a time stamp to the task
2467 note Prompt for a note and add it with template `org-log-note-headings'
2469 This option can also be set with on a per-file-basis with
2471 #+STARTUP: nologdone
2472 #+STARTUP: logdone
2473 #+STARTUP: lognotedone
2475 You can have local logging settings for a subtree by setting the LOGGING
2476 property to one or more of these keywords."
2477 :group 'org-todo
2478 :group 'org-progress
2479 :type '(choice
2480 (const :tag "No logging" nil)
2481 (const :tag "Record CLOSED timestamp" time)
2482 (const :tag "Record CLOSED timestamp with note." note)))
2484 ;; Normalize old uses of org-log-done.
2485 (cond
2486 ((eq org-log-done t) (setq org-log-done 'time))
2487 ((and (listp org-log-done) (memq 'done org-log-done))
2488 (setq org-log-done 'note)))
2490 (defcustom org-log-reschedule nil
2491 "Information to record when the scheduling date of a tasks is modified.
2493 Possible values are:
2495 nil Don't add anything, just change the date
2496 time Add a time stamp to the task
2497 note Prompt for a note and add it with template `org-log-note-headings'
2499 This option can also be set with on a per-file-basis with
2501 #+STARTUP: nologreschedule
2502 #+STARTUP: logreschedule
2503 #+STARTUP: lognotereschedule"
2504 :group 'org-todo
2505 :group 'org-progress
2506 :type '(choice
2507 (const :tag "No logging" nil)
2508 (const :tag "Record timestamp" time)
2509 (const :tag "Record timestamp with note." note)))
2511 (defcustom org-log-redeadline nil
2512 "Information to record when the deadline date of a tasks is modified.
2514 Possible values are:
2516 nil Don't add anything, just change the date
2517 time Add a time stamp to the task
2518 note Prompt for a note and add it with template `org-log-note-headings'
2520 This option can also be set with on a per-file-basis with
2522 #+STARTUP: nologredeadline
2523 #+STARTUP: logredeadline
2524 #+STARTUP: lognoteredeadline
2526 You can have local logging settings for a subtree by setting the LOGGING
2527 property to one or more of these keywords."
2528 :group 'org-todo
2529 :group 'org-progress
2530 :type '(choice
2531 (const :tag "No logging" nil)
2532 (const :tag "Record timestamp" time)
2533 (const :tag "Record timestamp with note." note)))
2535 (defcustom org-log-note-clock-out nil
2536 "Non-nil means record a note when clocking out of an item.
2537 This can also be configured on a per-file basis by adding one of
2538 the following lines anywhere in the buffer:
2540 #+STARTUP: lognoteclock-out
2541 #+STARTUP: nolognoteclock-out"
2542 :group 'org-todo
2543 :group 'org-progress
2544 :type 'boolean)
2546 (defcustom org-log-done-with-time t
2547 "Non-nil means the CLOSED time stamp will contain date and time.
2548 When nil, only the date will be recorded."
2549 :group 'org-progress
2550 :type 'boolean)
2552 (defcustom org-log-note-headings
2553 '((done . "CLOSING NOTE %t")
2554 (state . "State %-12s from %-12S %t")
2555 (note . "Note taken on %t")
2556 (reschedule . "Rescheduled from %S on %t")
2557 (delschedule . "Not scheduled, was %S on %t")
2558 (redeadline . "New deadline from %S on %t")
2559 (deldeadline . "Removed deadline, was %S on %t")
2560 (refile . "Refiled on %t")
2561 (clock-out . ""))
2562 "Headings for notes added to entries.
2563 The value is an alist, with the car being a symbol indicating the note
2564 context, and the cdr is the heading to be used. The heading may also be the
2565 empty string.
2566 %t in the heading will be replaced by a time stamp.
2567 %T will be an active time stamp instead the default inactive one
2568 %d will be replaced by a short-format time stamp.
2569 %D will be replaced by an active short-format time stamp.
2570 %s will be replaced by the new TODO state, in double quotes.
2571 %S will be replaced by the old TODO state, in double quotes.
2572 %u will be replaced by the user name.
2573 %U will be replaced by the full user name.
2575 In fact, it is not a good idea to change the `state' entry, because
2576 agenda log mode depends on the format of these entries."
2577 :group 'org-todo
2578 :group 'org-progress
2579 :type '(list :greedy t
2580 (cons (const :tag "Heading when closing an item" done) string)
2581 (cons (const :tag
2582 "Heading when changing todo state (todo sequence only)"
2583 state) string)
2584 (cons (const :tag "Heading when just taking a note" note) string)
2585 (cons (const :tag "Heading when clocking out" clock-out) string)
2586 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2587 (cons (const :tag "Heading when rescheduling" reschedule) string)
2588 (cons (const :tag "Heading when changing deadline" redeadline) string)
2589 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2590 (cons (const :tag "Heading when refiling" refile) string)))
2592 (unless (assq 'note org-log-note-headings)
2593 (push '(note . "%t") org-log-note-headings))
2595 (defcustom org-log-into-drawer nil
2596 "Non-nil means insert state change notes and time stamps into a drawer.
2597 When nil, state changes notes will be inserted after the headline and
2598 any scheduling and clock lines, but not inside a drawer.
2600 The value of this variable should be the name of the drawer to use.
2601 LOGBOOK is proposed as the default drawer for this purpose, you can
2602 also set this to a string to define the drawer of your choice.
2604 A value of t is also allowed, representing \"LOGBOOK\".
2606 A value of t or nil can also be set with on a per-file-basis with
2608 #+STARTUP: logdrawer
2609 #+STARTUP: nologdrawer
2611 If this variable is set, `org-log-state-notes-insert-after-drawers'
2612 will be ignored.
2614 You can set the property LOG_INTO_DRAWER to overrule this setting for
2615 a subtree."
2616 :group 'org-todo
2617 :group 'org-progress
2618 :type '(choice
2619 (const :tag "Not into a drawer" nil)
2620 (const :tag "LOGBOOK" t)
2621 (string :tag "Other")))
2623 (if (fboundp 'defvaralias)
2624 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2626 (defun org-log-into-drawer ()
2627 "Return the value of `org-log-into-drawer', but let properties overrule.
2628 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2629 used instead of the default value."
2630 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2631 (cond
2632 ((not p) org-log-into-drawer)
2633 ((equal p "nil") nil)
2634 ((equal p "t") "LOGBOOK")
2635 (t p))))
2637 (defcustom org-log-state-notes-insert-after-drawers nil
2638 "Non-nil means insert state change notes after any drawers in entry.
2639 Only the drawers that *immediately* follow the headline and the
2640 deadline/scheduled line are skipped.
2641 When nil, insert notes right after the heading and perhaps the line
2642 with deadline/scheduling if present.
2644 This variable will have no effect if `org-log-into-drawer' is
2645 set."
2646 :group 'org-todo
2647 :group 'org-progress
2648 :type 'boolean)
2650 (defcustom org-log-states-order-reversed t
2651 "Non-nil means the latest state note will be directly after heading.
2652 When nil, the state change notes will be ordered according to time.
2654 This option can also be set with on a per-file-basis with
2656 #+STARTUP: logstatesreversed
2657 #+STARTUP: nologstatesreversed"
2658 :group 'org-todo
2659 :group 'org-progress
2660 :type 'boolean)
2662 (defcustom org-todo-repeat-to-state nil
2663 "The TODO state to which a repeater should return the repeating task.
2664 By default this is the first task in a TODO sequence, or the previous state
2665 in a TODO_TYP set. But you can specify another task here.
2666 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2667 :group 'org-todo
2668 :version "24.1"
2669 :type '(choice (const :tag "Head of sequence" nil)
2670 (string :tag "Specific state")))
2672 (defcustom org-log-repeat 'time
2673 "Non-nil means record moving through the DONE state when triggering repeat.
2674 An auto-repeating task is immediately switched back to TODO when
2675 marked DONE. If you are not logging state changes (by adding \"@\"
2676 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2677 record a closing note, there will be no record of the task moving
2678 through DONE. This variable forces taking a note anyway.
2680 nil Don't force a record
2681 time Record a time stamp
2682 note Prompt for a note and add it with template `org-log-note-headings'
2684 This option can also be set with on a per-file-basis with
2686 #+STARTUP: nologrepeat
2687 #+STARTUP: logrepeat
2688 #+STARTUP: lognoterepeat
2690 You can have local logging settings for a subtree by setting the LOGGING
2691 property to one or more of these keywords."
2692 :group 'org-todo
2693 :group 'org-progress
2694 :type '(choice
2695 (const :tag "Don't force a record" nil)
2696 (const :tag "Force recording the DONE state" time)
2697 (const :tag "Force recording a note with the DONE state" note)))
2700 (defgroup org-priorities nil
2701 "Priorities in Org-mode."
2702 :tag "Org Priorities"
2703 :group 'org-todo)
2705 (defcustom org-enable-priority-commands t
2706 "Non-nil means priority commands are active.
2707 When nil, these commands will be disabled, so that you never accidentally
2708 set a priority."
2709 :group 'org-priorities
2710 :type 'boolean)
2712 (defcustom org-highest-priority ?A
2713 "The highest priority of TODO items. A character like ?A, ?B etc.
2714 Must have a smaller ASCII number than `org-lowest-priority'."
2715 :group 'org-priorities
2716 :type 'character)
2718 (defcustom org-lowest-priority ?C
2719 "The lowest priority of TODO items. A character like ?A, ?B etc.
2720 Must have a larger ASCII number than `org-highest-priority'."
2721 :group 'org-priorities
2722 :type 'character)
2724 (defcustom org-default-priority ?B
2725 "The default priority of TODO items.
2726 This is the priority an item gets if no explicit priority is given.
2727 When starting to cycle on an empty priority the first step in the cycle
2728 depends on `org-priority-start-cycle-with-default'. The resulting first
2729 step priority must not exceed the range from `org-highest-priority' to
2730 `org-lowest-priority' which means that `org-default-priority' has to be
2731 in this range exclusive or inclusive the range boundaries. Else the
2732 first step refuses to set the default and the second will fall back
2733 to (depending on the command used) the highest or lowest priority."
2734 :group 'org-priorities
2735 :type 'character)
2737 (defcustom org-priority-start-cycle-with-default t
2738 "Non-nil means start with default priority when starting to cycle.
2739 When this is nil, the first step in the cycle will be (depending on the
2740 command used) one higher or lower than the default priority.
2741 See also `org-default-priority'."
2742 :group 'org-priorities
2743 :type 'boolean)
2745 (defcustom org-get-priority-function nil
2746 "Function to extract the priority from a string.
2747 The string is normally the headline. If this is nil Org computes the
2748 priority from the priority cookie like [#A] in the headline. It returns
2749 an integer, increasing by 1000 for each priority level.
2750 The user can set a different function here, which should take a string
2751 as an argument and return the numeric priority."
2752 :group 'org-priorities
2753 :version "24.1"
2754 :type 'function)
2756 (defgroup org-time nil
2757 "Options concerning time stamps and deadlines in Org-mode."
2758 :tag "Org Time"
2759 :group 'org)
2761 (defcustom org-insert-labeled-timestamps-at-point nil
2762 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2763 When nil, these labeled time stamps are forces into the second line of an
2764 entry, just after the headline. When scheduling from the global TODO list,
2765 the time stamp will always be forced into the second line."
2766 :group 'org-time
2767 :type 'boolean)
2769 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2770 "Formats for `format-time-string' which are used for time stamps.
2771 It is not recommended to change this constant.")
2773 (defcustom org-time-stamp-rounding-minutes '(0 5)
2774 "Number of minutes to round time stamps to.
2775 These are two values, the first applies when first creating a time stamp.
2776 The second applies when changing it with the commands `S-up' and `S-down'.
2777 When changing the time stamp, this means that it will change in steps
2778 of N minutes, as given by the second value.
2780 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2781 numbers should be factors of 60, so for example 5, 10, 15.
2783 When this is larger than 1, you can still force an exact time stamp by using
2784 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2785 and by using a prefix arg to `S-up/down' to specify the exact number
2786 of minutes to shift."
2787 :group 'org-time
2788 :get #'(lambda (var) ; Make sure both elements are there
2789 (if (integerp (default-value var))
2790 (list (default-value var) 5)
2791 (default-value var)))
2792 :type '(list
2793 (integer :tag "when inserting times")
2794 (integer :tag "when modifying times")))
2796 ;; Normalize old customizations of this variable.
2797 (when (integerp org-time-stamp-rounding-minutes)
2798 (setq org-time-stamp-rounding-minutes
2799 (list org-time-stamp-rounding-minutes
2800 org-time-stamp-rounding-minutes)))
2802 (defcustom org-display-custom-times nil
2803 "Non-nil means overlay custom formats over all time stamps.
2804 The formats are defined through the variable `org-time-stamp-custom-formats'.
2805 To turn this on on a per-file basis, insert anywhere in the file:
2806 #+STARTUP: customtime"
2807 :group 'org-time
2808 :set 'set-default
2809 :type 'sexp)
2810 (make-variable-buffer-local 'org-display-custom-times)
2812 (defcustom org-time-stamp-custom-formats
2813 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2814 "Custom formats for time stamps. See `format-time-string' for the syntax.
2815 These are overlaid over the default ISO format if the variable
2816 `org-display-custom-times' is set. Time like %H:%M should be at the
2817 end of the second format. The custom formats are also honored by export
2818 commands, if custom time display is turned on at the time of export."
2819 :group 'org-time
2820 :type 'sexp)
2822 (defun org-time-stamp-format (&optional long inactive)
2823 "Get the right format for a time string."
2824 (let ((f (if long (cdr org-time-stamp-formats)
2825 (car org-time-stamp-formats))))
2826 (if inactive
2827 (concat "[" (substring f 1 -1) "]")
2828 f)))
2830 (defcustom org-time-clocksum-format
2831 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2832 "The format string used when creating CLOCKSUM lines.
2833 This is also used when Org mode generates a time duration.
2835 The value can be a single format string containing two
2836 %-sequences, which will be filled with the number of hours and
2837 minutes in that order.
2839 Alternatively, the value can be a plist associating any of the
2840 keys :years, :months, :weeks, :days, :hours or :minutes with
2841 format strings. The time duration is formatted using only the
2842 time components that are needed and concatenating the results.
2843 If a time unit in absent, it falls back to the next smallest
2844 unit.
2846 The keys :require-years, :require-months, :require-days,
2847 :require-weeks, :require-hours, :require-minutes are also
2848 meaningful. A non-nil value for these keys indicates that the
2849 corresponding time component should always be included, even if
2850 its value is 0.
2853 For example,
2855 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2856 :require-minutes t)
2858 means durations longer than a day will be expressed in days,
2859 hours and minutes, and durations less than a day will always be
2860 expressed in hours and minutes (even for durations less than an
2861 hour).
2863 The value
2865 \(:days \"%dd\" :minutes \"%dm\")
2867 means durations longer than a day will be expressed in days and
2868 minutes, and durations less than a day will be expressed entirely
2869 in minutes (even for durations longer than an hour)."
2870 :group 'org-time
2871 :group 'org-clock
2872 :version "24.3"
2873 :type '(choice (string :tag "Format string")
2874 (set :tag "Plist"
2875 (group :inline t (const :tag "Years" :years)
2876 (string :tag "Format string"))
2877 (group :inline t
2878 (const :tag "Always show years" :require-years)
2879 (const t))
2880 (group :inline t (const :tag "Months" :months)
2881 (string :tag "Format string"))
2882 (group :inline t
2883 (const :tag "Always show months" :require-months)
2884 (const t))
2885 (group :inline t (const :tag "Weeks" :weeks)
2886 (string :tag "Format string"))
2887 (group :inline t
2888 (const :tag "Always show weeks" :require-weeks)
2889 (const t))
2890 (group :inline t (const :tag "Days" :days)
2891 (string :tag "Format string"))
2892 (group :inline t
2893 (const :tag "Always show days" :require-days)
2894 (const t))
2895 (group :inline t (const :tag "Hours" :hours)
2896 (string :tag "Format string"))
2897 (group :inline t
2898 (const :tag "Always show hours" :require-hours)
2899 (const t))
2900 (group :inline t (const :tag "Minutes" :minutes)
2901 (string :tag "Format string"))
2902 (group :inline t
2903 (const :tag "Always show minutes" :require-minutes)
2904 (const t)))))
2906 (defcustom org-time-clocksum-use-fractional nil
2907 "When non-nil, \\[org-clock-display] uses fractional times.
2908 See `org-time-clocksum-format' for more on time clock formats."
2909 :group 'org-time
2910 :group 'org-clock
2911 :version "24.3"
2912 :type 'boolean)
2914 (defcustom org-time-clocksum-use-effort-durations t
2915 "When non-nil, \\[org-clock-display] uses effort durations.
2916 E.g. by default, one day is considered to be a 8 hours effort,
2917 so a task that has been clocked for 16 hours will be displayed
2918 as during 2 days in the clock display or in the clocktable.
2920 See `org-effort-durations' on how to set effort durations
2921 and `org-time-clocksum-format' for more on time clock formats."
2922 :group 'org-time
2923 :group 'org-clock
2924 :version "24.3"
2925 :type 'boolean)
2927 (defcustom org-time-clocksum-fractional-format "%.2f"
2928 "The format string used when creating CLOCKSUM lines,
2929 or when Org mode generates a time duration, if
2930 `org-time-clocksum-use-fractional' is enabled.
2932 The value can be a single format string containing one
2933 %-sequence, which will be filled with the number of hours as
2934 a float.
2936 Alternatively, the value can be a plist associating any of the
2937 keys :years, :months, :weeks, :days, :hours or :minutes with
2938 a format string. The time duration is formatted using the
2939 largest time unit which gives a non-zero integer part. If all
2940 specified formats have zero integer part, the smallest time unit
2941 is used."
2942 :group 'org-time
2943 :type '(choice (string :tag "Format string")
2944 (set (group :inline t (const :tag "Years" :years)
2945 (string :tag "Format string"))
2946 (group :inline t (const :tag "Months" :months)
2947 (string :tag "Format string"))
2948 (group :inline t (const :tag "Weeks" :weeks)
2949 (string :tag "Format string"))
2950 (group :inline t (const :tag "Days" :days)
2951 (string :tag "Format string"))
2952 (group :inline t (const :tag "Hours" :hours)
2953 (string :tag "Format string"))
2954 (group :inline t (const :tag "Minutes" :minutes)
2955 (string :tag "Format string")))))
2957 (defcustom org-deadline-warning-days 14
2958 "Number of days before expiration during which a deadline becomes active.
2959 This variable governs the display in sparse trees and in the agenda.
2960 When 0 or negative, it means use this number (the absolute value of it)
2961 even if a deadline has a different individual lead time specified.
2963 Custom commands can set this variable in the options section."
2964 :group 'org-time
2965 :group 'org-agenda-daily/weekly
2966 :type 'integer)
2968 (defcustom org-scheduled-delay-days 0
2969 "Number of days before a scheduled item becomes active.
2970 This variable governs the display in sparse trees and in the agenda.
2971 The default value (i.e. 0) means: don't delay scheduled item.
2972 When negative, it means use this number (the absolute value of it)
2973 even if a scheduled item has a different individual delay time
2974 specified.
2976 Custom commands can set this variable in the options section."
2977 :group 'org-time
2978 :group 'org-agenda-daily/weekly
2979 :version "24.3"
2980 :type 'integer)
2982 (defcustom org-read-date-prefer-future t
2983 "Non-nil means assume future for incomplete date input from user.
2984 This affects the following situations:
2985 1. The user gives a month but not a year.
2986 For example, if it is April and you enter \"feb 2\", this will be read
2987 as Feb 2, *next* year. \"May 5\", however, will be this year.
2988 2. The user gives a day, but no month.
2989 For example, if today is the 15th, and you enter \"3\", Org-mode will
2990 read this as the third of *next* month. However, if you enter \"17\",
2991 it will be considered as *this* month.
2993 If you set this variable to the symbol `time', then also the following
2994 will work:
2996 3. If the user gives a time.
2997 If the time is before now, it will be interpreted as tomorrow.
2999 Currently none of this works for ISO week specifications.
3001 When this option is nil, the current day, month and year will always be
3002 used as defaults.
3004 See also `org-agenda-jump-prefer-future'."
3005 :group 'org-time
3006 :type '(choice
3007 (const :tag "Never" nil)
3008 (const :tag "Check month and day" t)
3009 (const :tag "Check month, day, and time" time)))
3011 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3012 "Should the agenda jump command prefer the future for incomplete dates?
3013 The default is to do the same as configured in `org-read-date-prefer-future'.
3014 But you can also set a deviating value here.
3015 This may t or nil, or the symbol `org-read-date-prefer-future'."
3016 :group 'org-agenda
3017 :group 'org-time
3018 :version "24.1"
3019 :type '(choice
3020 (const :tag "Use org-read-date-prefer-future"
3021 org-read-date-prefer-future)
3022 (const :tag "Never" nil)
3023 (const :tag "Always" t)))
3025 (defcustom org-read-date-force-compatible-dates t
3026 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3028 Depending on the system Emacs is running on, certain dates cannot
3029 be represented with the type used internally to represent time.
3030 Dates between 1970-1-1 and 2038-1-1 can always be represented
3031 correctly. Some systems allow for earlier dates, some for later,
3032 some for both. One way to find out it to insert any date into an
3033 Org buffer, putting the cursor on the year and hitting S-up and
3034 S-down to test the range.
3036 When this variable is set to t, the date/time prompt will not let
3037 you specify dates outside the 1970-2037 range, so it is certain that
3038 these dates will work in whatever version of Emacs you are
3039 running, and also that you can move a file from one Emacs implementation
3040 to another. WHenever Org is forcing the year for you, it will display
3041 a message and beep.
3043 When this variable is nil, Org will check if the date is
3044 representable in the specific Emacs implementation you are using.
3045 If not, it will force a year, usually the current year, and beep
3046 to remind you. Currently this setting is not recommended because
3047 the likelihood that you will open your Org files in an Emacs that
3048 has limited date range is not negligible.
3050 A workaround for this problem is to use diary sexp dates for time
3051 stamps outside of this range."
3052 :group 'org-time
3053 :version "24.1"
3054 :type 'boolean)
3056 (defcustom org-read-date-display-live t
3057 "Non-nil means display current interpretation of date prompt live.
3058 This display will be in an overlay, in the minibuffer."
3059 :group 'org-time
3060 :type 'boolean)
3062 (defcustom org-read-date-popup-calendar t
3063 "Non-nil means pop up a calendar when prompting for a date.
3064 In the calendar, the date can be selected with mouse-1. However, the
3065 minibuffer will also be active, and you can simply enter the date as well.
3066 When nil, only the minibuffer will be available."
3067 :group 'org-time
3068 :type 'boolean)
3069 (if (fboundp 'defvaralias)
3070 (defvaralias 'org-popup-calendar-for-date-prompt
3071 'org-read-date-popup-calendar))
3073 (make-obsolete-variable
3074 'org-read-date-minibuffer-setup-hook
3075 "Set `org-read-date-minibuffer-local-map' instead." "24.3")
3076 (defcustom org-read-date-minibuffer-setup-hook nil
3077 "Hook to be used to set up keys for the date/time interface.
3078 Add key definitions to `minibuffer-local-map', which will be a
3079 temporary copy.
3081 WARNING: This option is obsolete, you should use
3082 `org-read-date-minibuffer-local-map' to set up keys."
3083 :group 'org-time
3084 :type 'hook)
3086 (defcustom org-extend-today-until 0
3087 "The hour when your day really ends. Must be an integer.
3088 This has influence for the following applications:
3089 - When switching the agenda to \"today\". It it is still earlier than
3090 the time given here, the day recognized as TODAY is actually yesterday.
3091 - When a date is read from the user and it is still before the time given
3092 here, the current date and time will be assumed to be yesterday, 23:59.
3093 Also, timestamps inserted in capture templates follow this rule.
3095 IMPORTANT: This is a feature whose implementation is and likely will
3096 remain incomplete. Really, it is only here because past midnight seems to
3097 be the favorite working time of John Wiegley :-)"
3098 :group 'org-time
3099 :type 'integer)
3101 (defcustom org-use-effective-time nil
3102 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3103 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3104 \"effective time\" of any timestamps between midnight and 8am will be
3105 23:59 of the previous day."
3106 :group 'org-time
3107 :version "24.1"
3108 :type 'boolean)
3110 (defcustom org-use-last-clock-out-time-as-effective-time nil
3111 "When non-nil, use the last clock out time for `org-todo'.
3112 Note that this option has precedence over the combined use of
3113 `org-use-effective-time' and `org-extend-today-until'."
3114 :group 'org-time
3115 ;; :version "24.3"
3116 :type 'boolean)
3118 (defcustom org-edit-timestamp-down-means-later nil
3119 "Non-nil means S-down will increase the time in a time stamp.
3120 When nil, S-up will increase."
3121 :group 'org-time
3122 :type 'boolean)
3124 (defcustom org-calendar-follow-timestamp-change t
3125 "Non-nil means make the calendar window follow timestamp changes.
3126 When a timestamp is modified and the calendar window is visible, it will be
3127 moved to the new date."
3128 :group 'org-time
3129 :type 'boolean)
3131 (defgroup org-tags nil
3132 "Options concerning tags in Org-mode."
3133 :tag "Org Tags"
3134 :group 'org)
3136 (defcustom org-tag-alist nil
3137 "List of tags allowed in Org-mode files.
3138 When this list is nil, Org-mode will base TAG input on what is already in the
3139 buffer.
3140 The value of this variable is an alist, the car of each entry must be a
3141 keyword as a string, the cdr may be a character that is used to select
3142 that tag through the fast-tag-selection interface.
3143 See the manual for details."
3144 :group 'org-tags
3145 :type '(repeat
3146 (choice
3147 (cons (string :tag "Tag name")
3148 (character :tag "Access char"))
3149 (list :tag "Start radio group"
3150 (const :startgroup)
3151 (option (string :tag "Group description")))
3152 (list :tag "End radio group"
3153 (const :endgroup)
3154 (option (string :tag "Group description")))
3155 (const :tag "New line" (:newline)))))
3157 (defcustom org-tag-persistent-alist nil
3158 "List of tags that will always appear in all Org-mode files.
3159 This is in addition to any in buffer settings or customizations
3160 of `org-tag-alist'.
3161 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3162 The value of this variable is an alist, the car of each entry must be a
3163 keyword as a string, the cdr may be a character that is used to select
3164 that tag through the fast-tag-selection interface.
3165 See the manual for details.
3166 To disable these tags on a per-file basis, insert anywhere in the file:
3167 #+STARTUP: noptag"
3168 :group 'org-tags
3169 :type '(repeat
3170 (choice
3171 (cons (string :tag "Tag name")
3172 (character :tag "Access char"))
3173 (const :tag "Start radio group" (:startgroup))
3174 (const :tag "End radio group" (:endgroup))
3175 (const :tag "New line" (:newline)))))
3177 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3178 "If non-nil, always offer completion for all tags of all agenda files.
3179 Instead of customizing this variable directly, you might want to
3180 set it locally for capture buffers, because there no list of
3181 tags in that file can be created dynamically (there are none).
3183 (add-hook 'org-capture-mode-hook
3184 (lambda ()
3185 (set (make-local-variable
3186 'org-complete-tags-always-offer-all-agenda-tags)
3187 t)))"
3188 :group 'org-tags
3189 :version "24.1"
3190 :type 'boolean)
3192 (defvar org-file-tags nil
3193 "List of tags that can be inherited by all entries in the file.
3194 The tags will be inherited if the variable `org-use-tag-inheritance'
3195 says they should be.
3196 This variable is populated from #+FILETAGS lines.")
3198 (defcustom org-use-fast-tag-selection 'auto
3199 "Non-nil means use fast tag selection scheme.
3200 This is a special interface to select and deselect tags with single keys.
3201 When nil, fast selection is never used.
3202 When the symbol `auto', fast selection is used if and only if selection
3203 characters for tags have been configured, either through the variable
3204 `org-tag-alist' or through a #+TAGS line in the buffer.
3205 When t, fast selection is always used and selection keys are assigned
3206 automatically if necessary."
3207 :group 'org-tags
3208 :type '(choice
3209 (const :tag "Always" t)
3210 (const :tag "Never" nil)
3211 (const :tag "When selection characters are configured" 'auto)))
3213 (defcustom org-fast-tag-selection-single-key nil
3214 "Non-nil means fast tag selection exits after first change.
3215 When nil, you have to press RET to exit it.
3216 During fast tag selection, you can toggle this flag with `C-c'.
3217 This variable can also have the value `expert'. In this case, the window
3218 displaying the tags menu is not even shown, until you press C-c again."
3219 :group 'org-tags
3220 :type '(choice
3221 (const :tag "No" nil)
3222 (const :tag "Yes" t)
3223 (const :tag "Expert" expert)))
3225 (defvar org-fast-tag-selection-include-todo nil
3226 "Non-nil means fast tags selection interface will also offer TODO states.
3227 This is an undocumented feature, you should not rely on it.")
3229 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3230 "The column to which tags should be indented in a headline.
3231 If this number is positive, it specifies the column. If it is negative,
3232 it means that the tags should be flushright to that column. For example,
3233 -80 works well for a normal 80 character screen.
3234 When 0, place tags directly after headline text, with only one space in
3235 between."
3236 :group 'org-tags
3237 :type 'integer)
3239 (defcustom org-auto-align-tags t
3240 "Non-nil keeps tags aligned when modifying headlines.
3241 Some operations (i.e. demoting) change the length of a headline and
3242 therefore shift the tags around. With this option turned on, after
3243 each such operation the tags are again aligned to `org-tags-column'."
3244 :group 'org-tags
3245 :type 'boolean)
3247 (defcustom org-use-tag-inheritance t
3248 "Non-nil means tags in levels apply also for sublevels.
3249 When nil, only the tags directly given in a specific line apply there.
3250 This may also be a list of tags that should be inherited, or a regexp that
3251 matches tags that should be inherited. Additional control is possible
3252 with the variable `org-tags-exclude-from-inheritance' which gives an
3253 explicit list of tags to be excluded from inheritance, even if the value of
3254 `org-use-tag-inheritance' would select it for inheritance.
3256 If this option is t, a match early-on in a tree can lead to a large
3257 number of matches in the subtree when constructing the agenda or creating
3258 a sparse tree. If you only want to see the first match in a tree during
3259 a search, check out the variable `org-tags-match-list-sublevels'."
3260 :group 'org-tags
3261 :type '(choice
3262 (const :tag "Not" nil)
3263 (const :tag "Always" t)
3264 (repeat :tag "Specific tags" (string :tag "Tag"))
3265 (regexp :tag "Tags matched by regexp")))
3267 (defcustom org-tags-exclude-from-inheritance nil
3268 "List of tags that should never be inherited.
3269 This is a way to exclude a few tags from inheritance. For way to do
3270 the opposite, to actively allow inheritance for selected tags,
3271 see the variable `org-use-tag-inheritance'."
3272 :group 'org-tags
3273 :type '(repeat (string :tag "Tag")))
3275 (defun org-tag-inherit-p (tag)
3276 "Check if TAG is one that should be inherited."
3277 (cond
3278 ((member tag org-tags-exclude-from-inheritance) nil)
3279 ((eq org-use-tag-inheritance t) t)
3280 ((not org-use-tag-inheritance) nil)
3281 ((stringp org-use-tag-inheritance)
3282 (string-match org-use-tag-inheritance tag))
3283 ((listp org-use-tag-inheritance)
3284 (member tag org-use-tag-inheritance))
3285 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3287 (defcustom org-tags-match-list-sublevels t
3288 "Non-nil means list also sublevels of headlines matching a search.
3289 This variable applies to tags/property searches, and also to stuck
3290 projects because this search is based on a tags match as well.
3292 When set to the symbol `indented', sublevels are indented with
3293 leading dots.
3295 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3296 the sublevels of a headline matching a tag search often also match
3297 the same search. Listing all of them can create very long lists.
3298 Setting this variable to nil causes subtrees of a match to be skipped.
3300 This variable is semi-obsolete and probably should always be true. It
3301 is better to limit inheritance to certain tags using the variables
3302 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3303 :group 'org-tags
3304 :type '(choice
3305 (const :tag "No, don't list them" nil)
3306 (const :tag "Yes, do list them" t)
3307 (const :tag "List them, indented with leading dots" indented)))
3309 (defcustom org-tags-sort-function nil
3310 "When set, tags are sorted using this function as a comparator."
3311 :group 'org-tags
3312 :type '(choice
3313 (const :tag "No sorting" nil)
3314 (const :tag "Alphabetical" string<)
3315 (const :tag "Reverse alphabetical" string>)
3316 (function :tag "Custom function" nil)))
3318 (defvar org-tags-history nil
3319 "History of minibuffer reads for tags.")
3320 (defvar org-last-tags-completion-table nil
3321 "The last used completion table for tags.")
3322 (defvar org-after-tags-change-hook nil
3323 "Hook that is run after the tags in a line have changed.")
3325 (defgroup org-properties nil
3326 "Options concerning properties in Org-mode."
3327 :tag "Org Properties"
3328 :group 'org)
3330 (defcustom org-property-format "%-10s %s"
3331 "How property key/value pairs should be formatted by `indent-line'.
3332 When `indent-line' hits a property definition, it will format the line
3333 according to this format, mainly to make sure that the values are
3334 lined-up with respect to each other."
3335 :group 'org-properties
3336 :type 'string)
3338 (defcustom org-properties-postprocess-alist nil
3339 "Alist of properties and functions to adjust inserted values.
3340 Elements of this alist must be of the form
3342 ([string] [function])
3344 where [string] must be a property name and [function] must be a
3345 lambda expression: this lambda expression must take one argument,
3346 the value to adjust, and return the new value as a string.
3348 For example, this element will allow the property \"Remaining\"
3349 to be updated wrt the relation between the \"Effort\" property
3350 and the clock summary:
3352 ((\"Remaining\" (lambda(value)
3353 (let ((clocksum (org-clock-sum-current-item))
3354 (effort (org-duration-string-to-minutes
3355 (org-entry-get (point) \"Effort\"))))
3356 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3357 :group 'org-properties
3358 :version "24.1"
3359 :type '(alist :key-type (string :tag "Property")
3360 :value-type (function :tag "Function")))
3362 (defcustom org-use-property-inheritance nil
3363 "Non-nil means properties apply also for sublevels.
3365 This setting is chiefly used during property searches. Turning it on can
3366 cause significant overhead when doing a search, which is why it is not
3367 on by default.
3369 When nil, only the properties directly given in the current entry count.
3370 When t, every property is inherited. The value may also be a list of
3371 properties that should have inheritance, or a regular expression matching
3372 properties that should be inherited.
3374 However, note that some special properties use inheritance under special
3375 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3376 and the properties ending in \"_ALL\" when they are used as descriptor
3377 for valid values of a property.
3379 Note for programmers:
3380 When querying an entry with `org-entry-get', you can control if inheritance
3381 should be used. By default, `org-entry-get' looks only at the local
3382 properties. You can request inheritance by setting the inherit argument
3383 to t (to force inheritance) or to `selective' (to respect the setting
3384 in this variable)."
3385 :group 'org-properties
3386 :type '(choice
3387 (const :tag "Not" nil)
3388 (const :tag "Always" t)
3389 (repeat :tag "Specific properties" (string :tag "Property"))
3390 (regexp :tag "Properties matched by regexp")))
3392 (defun org-property-inherit-p (property)
3393 "Check if PROPERTY is one that should be inherited."
3394 (cond
3395 ((eq org-use-property-inheritance t) t)
3396 ((not org-use-property-inheritance) nil)
3397 ((stringp org-use-property-inheritance)
3398 (string-match org-use-property-inheritance property))
3399 ((listp org-use-property-inheritance)
3400 (member property org-use-property-inheritance))
3401 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3403 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3404 "The default column format, if no other format has been defined.
3405 This variable can be set on the per-file basis by inserting a line
3407 #+COLUMNS: %25ITEM ....."
3408 :group 'org-properties
3409 :type 'string)
3411 (defcustom org-columns-ellipses ".."
3412 "The ellipses to be used when a field in column view is truncated.
3413 When this is the empty string, as many characters as possible are shown,
3414 but then there will be no visual indication that the field has been truncated.
3415 When this is a string of length N, the last N characters of a truncated
3416 field are replaced by this string. If the column is narrower than the
3417 ellipses string, only part of the ellipses string will be shown."
3418 :group 'org-properties
3419 :type 'string)
3421 (defcustom org-columns-modify-value-for-display-function nil
3422 "Function that modifies values for display in column view.
3423 For example, it can be used to cut out a certain part from a time stamp.
3424 The function must take 2 arguments:
3426 column-title The title of the column (*not* the property name)
3427 value The value that should be modified.
3429 The function should return the value that should be displayed,
3430 or nil if the normal value should be used."
3431 :group 'org-properties
3432 :type 'function)
3434 (defcustom org-effort-property "Effort"
3435 "The property that is being used to keep track of effort estimates.
3436 Effort estimates given in this property need to have the format H:MM."
3437 :group 'org-properties
3438 :group 'org-progress
3439 :type '(string :tag "Property"))
3441 (defconst org-global-properties-fixed
3442 '(("VISIBILITY_ALL" . "folded children content all")
3443 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3444 "List of property/value pairs that can be inherited by any entry.
3446 These are fixed values, for the preset properties. The user variable
3447 that can be used to add to this list is `org-global-properties'.
3449 The entries in this list are cons cells where the car is a property
3450 name and cdr is a string with the value. If the value represents
3451 multiple items like an \"_ALL\" property, separate the items by
3452 spaces.")
3454 (defcustom org-global-properties nil
3455 "List of property/value pairs that can be inherited by any entry.
3457 This list will be combined with the constant `org-global-properties-fixed'.
3459 The entries in this list are cons cells where the car is a property
3460 name and cdr is a string with the value.
3462 You can set buffer-local values for the same purpose in the variable
3463 `org-file-properties' this by adding lines like
3465 #+PROPERTY: NAME VALUE"
3466 :group 'org-properties
3467 :type '(repeat
3468 (cons (string :tag "Property")
3469 (string :tag "Value"))))
3471 (defvar org-file-properties nil
3472 "List of property/value pairs that can be inherited by any entry.
3473 Valid for the current buffer.
3474 This variable is populated from #+PROPERTY lines.")
3475 (make-variable-buffer-local 'org-file-properties)
3477 (defgroup org-agenda nil
3478 "Options concerning agenda views in Org-mode."
3479 :tag "Org Agenda"
3480 :group 'org)
3482 (defvar org-category nil
3483 "Variable used by org files to set a category for agenda display.
3484 Such files should use a file variable to set it, for example
3486 # -*- mode: org; org-category: \"ELisp\"
3488 or contain a special line
3490 #+CATEGORY: ELisp
3492 If the file does not specify a category, then file's base name
3493 is used instead.")
3494 (make-variable-buffer-local 'org-category)
3495 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3497 (defcustom org-agenda-files nil
3498 "The files to be used for agenda display.
3499 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3500 \\[org-remove-file]. You can also use customize to edit the list.
3502 If an entry is a directory, all files in that directory that are matched by
3503 `org-agenda-file-regexp' will be part of the file list.
3505 If the value of the variable is not a list but a single file name, then
3506 the list of agenda files is actually stored and maintained in that file, one
3507 agenda file per line. In this file paths can be given relative to
3508 `org-directory'. Tilde expansion and environment variable substitution
3509 are also made."
3510 :group 'org-agenda
3511 :type '(choice
3512 (repeat :tag "List of files and directories" file)
3513 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3515 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3516 "Regular expression to match files for `org-agenda-files'.
3517 If any element in the list in that variable contains a directory instead
3518 of a normal file, all files in that directory that are matched by this
3519 regular expression will be included."
3520 :group 'org-agenda
3521 :type 'regexp)
3523 (defcustom org-agenda-text-search-extra-files nil
3524 "List of extra files to be searched by text search commands.
3525 These files will be search in addition to the agenda files by the
3526 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3527 Note that these files will only be searched for text search commands,
3528 not for the other agenda views like todo lists, tag searches or the weekly
3529 agenda. This variable is intended to list notes and possibly archive files
3530 that should also be searched by these two commands.
3531 In fact, if the first element in the list is the symbol `agenda-archives',
3532 than all archive files of all agenda files will be added to the search
3533 scope."
3534 :group 'org-agenda
3535 :type '(set :greedy t
3536 (const :tag "Agenda Archives" agenda-archives)
3537 (repeat :inline t (file))))
3539 (if (fboundp 'defvaralias)
3540 (defvaralias 'org-agenda-multi-occur-extra-files
3541 'org-agenda-text-search-extra-files))
3543 (defcustom org-agenda-skip-unavailable-files nil
3544 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3545 A nil value means to remove them, after a query, from the list."
3546 :group 'org-agenda
3547 :type 'boolean)
3549 (defcustom org-calendar-to-agenda-key [?c]
3550 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3551 The command `org-calendar-goto-agenda' will be bound to this key. The
3552 default is the character `c' because then `c' can be used to switch back and
3553 forth between agenda and calendar."
3554 :group 'org-agenda
3555 :type 'sexp)
3557 (defcustom org-calendar-insert-diary-entry-key [?i]
3558 "The key to be installed in `calendar-mode-map' for adding diary entries.
3559 This option is irrelevant until `org-agenda-diary-file' has been configured
3560 to point to an Org-mode file. When that is the case, the command
3561 `org-agenda-diary-entry' will be bound to the key given here, by default
3562 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3563 if you want to continue doing this, you need to change this to a different
3564 key."
3565 :group 'org-agenda
3566 :type 'sexp)
3568 (defcustom org-agenda-diary-file 'diary-file
3569 "File to which to add new entries with the `i' key in agenda and calendar.
3570 When this is the symbol `diary-file', the functionality in the Emacs
3571 calendar will be used to add entries to the `diary-file'. But when this
3572 points to a file, `org-agenda-diary-entry' will be used instead."
3573 :group 'org-agenda
3574 :type '(choice
3575 (const :tag "The standard Emacs diary file" diary-file)
3576 (file :tag "Special Org file diary entries")))
3578 (eval-after-load "calendar"
3579 '(progn
3580 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3581 'org-calendar-goto-agenda)
3582 (add-hook 'calendar-mode-hook
3583 (lambda ()
3584 (unless (eq org-agenda-diary-file 'diary-file)
3585 (define-key calendar-mode-map
3586 org-calendar-insert-diary-entry-key
3587 'org-agenda-diary-entry))))))
3589 (defgroup org-latex nil
3590 "Options for embedding LaTeX code into Org-mode."
3591 :tag "Org LaTeX"
3592 :group 'org)
3594 (defcustom org-format-latex-options
3595 '(:foreground default :background default :scale 1.0
3596 :html-foreground "Black" :html-background "Transparent"
3597 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3598 "Options for creating images from LaTeX fragments.
3599 This is a property list with the following properties:
3600 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3601 `default' means use the foreground of the default face.
3602 `auto' means use the foreground from the text face.
3603 :background the background color, or \"Transparent\".
3604 `default' means use the background of the default face.
3605 `auto' means use the background from the text face.
3606 :scale a scaling factor for the size of the images, to get more pixels
3607 :html-foreground, :html-background, :html-scale
3608 the same numbers for HTML export.
3609 :matchers a list indicating which matchers should be used to
3610 find LaTeX fragments. Valid members of this list are:
3611 \"begin\" find environments
3612 \"$1\" find single characters surrounded by $.$
3613 \"$\" find math expressions surrounded by $...$
3614 \"$$\" find math expressions surrounded by $$....$$
3615 \"\\(\" find math expressions surrounded by \\(...\\)
3616 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3617 :group 'org-latex
3618 :type 'plist)
3620 (defcustom org-format-latex-signal-error t
3621 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3622 When nil, just push out a message."
3623 :group 'org-latex
3624 :version "24.1"
3625 :type 'boolean)
3627 (defcustom org-latex-to-mathml-jar-file nil
3628 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3629 Use this to specify additional executable file say a jar file.
3631 When using MathToWeb as the converter, specify the full-path to
3632 your mathtoweb.jar file."
3633 :group 'org-latex
3634 :version "24.1"
3635 :type '(choice
3636 (const :tag "None" nil)
3637 (file :tag "JAR file" :must-match t)))
3639 (defcustom org-latex-to-mathml-convert-command nil
3640 "Command to convert LaTeX fragments to MathML.
3641 Replace format-specifiers in the command as noted below and use
3642 `shell-command' to convert LaTeX to MathML.
3643 %j: Executable file in fully expanded form as specified by
3644 `org-latex-to-mathml-jar-file'.
3645 %I: Input LaTeX file in fully expanded form
3646 %o: Output MathML file
3647 This command is used by `org-create-math-formula'.
3649 When using MathToWeb as the converter, set this to
3650 \"java -jar %j -unicode -force -df %o %I\"."
3651 :group 'org-latex
3652 :version "24.1"
3653 :type '(choice
3654 (const :tag "None" nil)
3655 (string :tag "\nShell command")))
3657 (defcustom org-latex-create-formula-image-program 'dvipng
3658 "Program to convert LaTeX fragments with.
3660 dvipng Process the LaTeX fragments to dvi file, then convert
3661 dvi files to png files using dvipng.
3662 This will also include processing of non-math environments.
3663 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3664 to convert pdf files to png files"
3665 :group 'org-latex
3666 :version "24.1"
3667 :type '(choice
3668 (const :tag "dvipng" dvipng)
3669 (const :tag "imagemagick" imagemagick)))
3671 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3672 "Path to store latex preview images.
3673 A relative path here creates many directories relative to the
3674 processed org files paths. An absolute path puts all preview
3675 images at the same place."
3676 :group 'org-latex
3677 :version "24.3"
3678 :type 'string)
3680 (defun org-format-latex-mathml-available-p ()
3681 "Return t if `org-latex-to-mathml-convert-command' is usable."
3682 (save-match-data
3683 (when (and (boundp 'org-latex-to-mathml-convert-command)
3684 org-latex-to-mathml-convert-command)
3685 (let ((executable (car (split-string
3686 org-latex-to-mathml-convert-command))))
3687 (when (executable-find executable)
3688 (if (string-match
3689 "%j" org-latex-to-mathml-convert-command)
3690 (file-readable-p org-latex-to-mathml-jar-file)
3691 t))))))
3693 (defcustom org-format-latex-header "\\documentclass{article}
3694 \\usepackage[usenames]{color}
3695 \\usepackage{amsmath}
3696 \\usepackage[mathscr]{eucal}
3697 \\pagestyle{empty} % do not remove
3698 \[PACKAGES]
3699 \[DEFAULT-PACKAGES]
3700 % The settings below are copied from fullpage.sty
3701 \\setlength{\\textwidth}{\\paperwidth}
3702 \\addtolength{\\textwidth}{-3cm}
3703 \\setlength{\\oddsidemargin}{1.5cm}
3704 \\addtolength{\\oddsidemargin}{-2.54cm}
3705 \\setlength{\\evensidemargin}{\\oddsidemargin}
3706 \\setlength{\\textheight}{\\paperheight}
3707 \\addtolength{\\textheight}{-\\headheight}
3708 \\addtolength{\\textheight}{-\\headsep}
3709 \\addtolength{\\textheight}{-\\footskip}
3710 \\addtolength{\\textheight}{-3cm}
3711 \\setlength{\\topmargin}{1.5cm}
3712 \\addtolength{\\topmargin}{-2.54cm}"
3713 "The document header used for processing LaTeX fragments.
3714 It is imperative that this header make sure that no page number
3715 appears on the page. The package defined in the variables
3716 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3717 will either replace the placeholder \"[PACKAGES]\" in this
3718 header, or they will be appended."
3719 :group 'org-latex
3720 :type 'string)
3722 (defun org-set-packages-alist (var val)
3723 "Set the packages alist and make sure it has 3 elements per entry."
3724 (set var (mapcar (lambda (x)
3725 (if (and (consp x) (= (length x) 2))
3726 (list (car x) (nth 1 x) t)
3728 val)))
3730 (defun org-get-packages-alist (var)
3731 "Get the packages alist and make sure it has 3 elements per entry."
3732 (mapcar (lambda (x)
3733 (if (and (consp x) (= (length x) 2))
3734 (list (car x) (nth 1 x) t)
3736 (default-value var)))
3738 (defcustom org-latex-default-packages-alist
3739 '(("AUTO" "inputenc" t)
3740 ("T1" "fontenc" t)
3741 ("" "fixltx2e" nil)
3742 ("" "graphicx" t)
3743 ("" "longtable" nil)
3744 ("" "float" nil)
3745 ("" "wrapfig" nil)
3746 ("" "soul" t)
3747 ("" "textcomp" t)
3748 ("" "marvosym" t)
3749 ("" "wasysym" t)
3750 ("" "latexsym" t)
3751 ("" "amssymb" t)
3752 ("" "hyperref" nil)
3753 "\\tolerance=1000")
3754 "Alist of default packages to be inserted in the header.
3756 Change this only if one of the packages here causes an
3757 incompatibility with another package you are using.
3759 The packages in this list are needed by one part or another of
3760 Org mode to function properly:
3762 - inputenc, fontenc: for basic font and character selection
3763 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3764 symbols used for interpreting the entities in `org-entities'.
3765 You can skip some of these packages if you don't use any of the
3766 symbols in it.
3767 - graphicx: for including images
3768 - float, wrapfig: for figure placement
3769 - longtable: for long tables
3770 - hyperref: for cross references
3772 Therefore you should not modify this variable unless you know
3773 what you are doing. The one reason to change it anyway is that
3774 you might be loading some other package that conflicts with one
3775 of the default packages. Each cell is of the format
3776 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3777 the package also needs to be included when compiling LaTeX
3778 snippets into images for inclusion into non-LaTeX output."
3779 :group 'org-latex
3780 :group 'org-export-latex
3781 :set 'org-set-packages-alist
3782 :get 'org-get-packages-alist
3783 :version "24.1"
3784 :type '(repeat
3785 (choice
3786 (list :tag "options/package pair"
3787 (string :tag "options")
3788 (string :tag "package")
3789 (boolean :tag "Snippet"))
3790 (string :tag "A line of LaTeX"))))
3792 (defcustom org-latex-packages-alist nil
3793 "Alist of packages to be inserted in every LaTeX header.
3795 These will be inserted after `org-latex-default-packages-alist'.
3796 Each cell is of the format:
3798 \(\"options\" \"package\" snippet-flag)
3800 SNIPPET-FLAG, when t, indicates that this package is also needed
3801 when turning LaTeX snippets into images for inclusion into
3802 non-LaTeX output.
3804 Make sure that you only list packages here which:
3806 - you want in every file
3807 - do not conflict with the setup in `org-format-latex-header'.
3808 - do not conflict with the default packages in
3809 `org-latex-default-packages-alist'."
3810 :group 'org-latex
3811 :group 'org-export-latex
3812 :set 'org-set-packages-alist
3813 :get 'org-get-packages-alist
3814 :type '(repeat
3815 (choice
3816 (list :tag "options/package pair"
3817 (string :tag "options")
3818 (string :tag "package")
3819 (boolean :tag "Snippet"))
3820 (string :tag "A line of LaTeX"))))
3822 (defgroup org-appearance nil
3823 "Settings for Org-mode appearance."
3824 :tag "Org Appearance"
3825 :group 'org)
3827 (defcustom org-level-color-stars-only nil
3828 "Non-nil means fontify only the stars in each headline.
3829 When nil, the entire headline is fontified.
3830 Changing it requires restart of `font-lock-mode' to become effective
3831 also in regions already fontified."
3832 :group 'org-appearance
3833 :type 'boolean)
3835 (defcustom org-hide-leading-stars nil
3836 "Non-nil means hide the first N-1 stars in a headline.
3837 This works by using the face `org-hide' for these stars. This
3838 face is white for a light background, and black for a dark
3839 background. You may have to customize the face `org-hide' to
3840 make this work.
3841 Changing it requires restart of `font-lock-mode' to become effective
3842 also in regions already fontified.
3843 You may also set this on a per-file basis by adding one of the following
3844 lines to the buffer:
3846 #+STARTUP: hidestars
3847 #+STARTUP: showstars"
3848 :group 'org-appearance
3849 :type 'boolean)
3851 (defcustom org-hidden-keywords nil
3852 "List of symbols corresponding to keywords to be hidden the org buffer.
3853 For example, a value '(title) for this list will make the document's title
3854 appear in the buffer without the initial #+TITLE: keyword."
3855 :group 'org-appearance
3856 :version "24.1"
3857 :type '(set (const :tag "#+AUTHOR" author)
3858 (const :tag "#+DATE" date)
3859 (const :tag "#+EMAIL" email)
3860 (const :tag "#+TITLE" title)))
3862 (defcustom org-custom-properties nil
3863 "List of properties (as strings) with a special meaning.
3864 The default use of these custom properties is to let the user
3865 hide them with `org-toggle-custom-properties-visibility'."
3866 :group 'org-properties
3867 :group 'org-appearance
3868 :version "24.3"
3869 :type '(repeat (string :tag "Property Name")))
3871 (defcustom org-fontify-done-headline nil
3872 "Non-nil means change the face of a headline if it is marked DONE.
3873 Normally, only the TODO/DONE keyword indicates the state of a headline.
3874 When this is non-nil, the headline after the keyword is set to the
3875 `org-headline-done' as an additional indication."
3876 :group 'org-appearance
3877 :type 'boolean)
3879 (defcustom org-fontify-emphasized-text t
3880 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3881 Changing this variable requires a restart of Emacs to take effect."
3882 :group 'org-appearance
3883 :type 'boolean)
3885 (defcustom org-fontify-whole-heading-line nil
3886 "Non-nil means fontify the whole line for headings.
3887 This is useful when setting a background color for the
3888 org-level-* faces."
3889 :group 'org-appearance
3890 :type 'boolean)
3892 (defcustom org-hide-emphasis-markers nil
3893 "Non-nil mean font-lock should hide the emphasis marker characters."
3894 :group 'org-appearance
3895 :type 'boolean)
3897 (defcustom org-pretty-entities nil
3898 "Non-nil means show entities as UTF8 characters.
3899 When nil, the \\name form remains in the buffer."
3900 :group 'org-appearance
3901 :version "24.1"
3902 :type 'boolean)
3904 (defcustom org-pretty-entities-include-sub-superscripts t
3905 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3906 :group 'org-appearance
3907 :version "24.1"
3908 :type 'boolean)
3910 (defvar org-emph-re nil
3911 "Regular expression for matching emphasis.
3912 After a match, the match groups contain these elements:
3913 0 The match of the full regular expression, including the characters
3914 before and after the proper match
3915 1 The character before the proper match, or empty at beginning of line
3916 2 The proper match, including the leading and trailing markers
3917 3 The leading marker like * or /, indicating the type of highlighting
3918 4 The text between the emphasis markers, not including the markers
3919 5 The character after the match, empty at the end of a line")
3920 (defvar org-verbatim-re nil
3921 "Regular expression for matching verbatim text.")
3922 (defvar org-emphasis-regexp-components) ; defined just below
3923 (defvar org-emphasis-alist) ; defined just below
3924 (defun org-set-emph-re (var val)
3925 "Set variable and compute the emphasis regular expression."
3926 (set var val)
3927 (when (and (boundp 'org-emphasis-alist)
3928 (boundp 'org-emphasis-regexp-components)
3929 org-emphasis-alist org-emphasis-regexp-components)
3930 (let* ((e org-emphasis-regexp-components)
3931 (pre (car e))
3932 (post (nth 1 e))
3933 (border (nth 2 e))
3934 (body (nth 3 e))
3935 (nl (nth 4 e))
3936 (body1 (concat body "*?"))
3937 (markers (mapconcat 'car org-emphasis-alist ""))
3938 (vmarkers (mapconcat
3939 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3940 org-emphasis-alist "")))
3941 ;; make sure special characters appear at the right position in the class
3942 (if (string-match "\\^" markers)
3943 (setq markers (concat (replace-match "" t t markers) "^")))
3944 (if (string-match "-" markers)
3945 (setq markers (concat (replace-match "" t t markers) "-")))
3946 (if (string-match "\\^" vmarkers)
3947 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3948 (if (string-match "-" vmarkers)
3949 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3950 (if (> nl 0)
3951 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3952 (int-to-string nl) "\\}")))
3953 ;; Make the regexp
3954 (setq org-emph-re
3955 (concat "\\([" pre "]\\|^\\)"
3956 "\\("
3957 "\\([" markers "]\\)"
3958 "\\("
3959 "[^" border "]\\|"
3960 "[^" border "]"
3961 body1
3962 "[^" border "]"
3963 "\\)"
3964 "\\3\\)"
3965 "\\([" post "]\\|$\\)"))
3966 (setq org-verbatim-re
3967 (concat "\\([" pre "]\\|^\\)"
3968 "\\("
3969 "\\([" vmarkers "]\\)"
3970 "\\("
3971 "[^" border "]\\|"
3972 "[^" border "]"
3973 body1
3974 "[^" border "]"
3975 "\\)"
3976 "\\3\\)"
3977 "\\([" post "]\\|$\\)")))))
3979 (defcustom org-emphasis-regexp-components
3980 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3981 "Components used to build the regular expression for emphasis.
3982 This is a list with five entries. Terminology: In an emphasis string
3983 like \" *strong word* \", we call the initial space PREMATCH, the final
3984 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3985 and \"trong wor\" is the body. The different components in this variable
3986 specify what is allowed/forbidden in each part:
3988 pre Chars allowed as prematch. Beginning of line will be allowed too.
3989 post Chars allowed as postmatch. End of line will be allowed too.
3990 border The chars *forbidden* as border characters.
3991 body-regexp A regexp like \".\" to match a body character. Don't use
3992 non-shy groups here, and don't allow newline here.
3993 newline The maximum number of newlines allowed in an emphasis exp.
3995 Use customize to modify this, or restart Emacs after changing it."
3996 :group 'org-appearance
3997 :set 'org-set-emph-re
3998 :type '(list
3999 (sexp :tag "Allowed chars in pre ")
4000 (sexp :tag "Allowed chars in post ")
4001 (sexp :tag "Forbidden chars in border ")
4002 (sexp :tag "Regexp for body ")
4003 (integer :tag "number of newlines allowed")
4004 (option (boolean :tag "Please ignore this button"))))
4006 (defcustom org-emphasis-alist
4007 `(("*" bold "<b>" "</b>")
4008 ("/" italic "<i>" "</i>")
4009 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4010 ("=" org-code "<code>" "</code>" verbatim)
4011 ("~" org-verbatim "<code>" "</code>" verbatim)
4012 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4013 "<del>" "</del>")
4015 "Special syntax for emphasized text.
4016 Text starting and ending with a special character will be emphasized, for
4017 example *bold*, _underlined_ and /italic/. This variable sets the marker
4018 characters, the face to be used by font-lock for highlighting in Org-mode
4019 Emacs buffers, and the HTML tags to be used for this.
4020 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4021 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
4022 Use customize to modify this, or restart Emacs after changing it."
4023 :group 'org-appearance
4024 :set 'org-set-emph-re
4025 :type '(repeat
4026 (list
4027 (string :tag "Marker character")
4028 (choice
4029 (face :tag "Font-lock-face")
4030 (plist :tag "Face property list"))
4031 (string :tag "HTML start tag")
4032 (string :tag "HTML end tag")
4033 (option (const verbatim)))))
4035 (defvar org-syntax-table
4036 (let ((st (make-syntax-table)))
4037 (mapc (lambda(c) (modify-syntax-entry
4038 (string-to-char (car c)) "w p" st))
4039 org-emphasis-alist)
4040 st))
4042 (defvar org-protecting-blocks
4043 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
4044 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4045 This is needed for font-lock setup.")
4047 ;;; Miscellaneous options
4049 (defgroup org-completion nil
4050 "Completion in Org-mode."
4051 :tag "Org Completion"
4052 :group 'org)
4054 (defcustom org-completion-use-ido nil
4055 "Non-nil means use ido completion wherever possible.
4056 Note that `ido-mode' must be active for this variable to be relevant.
4057 If you decide to turn this variable on, you might well want to turn off
4058 `org-outline-path-complete-in-steps'.
4059 See also `org-completion-use-iswitchb'."
4060 :group 'org-completion
4061 :type 'boolean)
4063 (defcustom org-completion-use-iswitchb nil
4064 "Non-nil means use iswitchb completion wherever possible.
4065 Note that `iswitchb-mode' must be active for this variable to be relevant.
4066 If you decide to turn this variable on, you might well want to turn off
4067 `org-outline-path-complete-in-steps'.
4068 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4069 :group 'org-completion
4070 :type 'boolean)
4072 (defcustom org-completion-fallback-command 'hippie-expand
4073 "The expansion command called by \\[pcomplete] in normal context.
4074 Normal means, no org-mode-specific context."
4075 :group 'org-completion
4076 :type 'function)
4078 ;;; Functions and variables from their packages
4079 ;; Declared here to avoid compiler warnings
4081 ;; XEmacs only
4082 (defvar outline-mode-menu-heading)
4083 (defvar outline-mode-menu-show)
4084 (defvar outline-mode-menu-hide)
4085 (defvar zmacs-regions) ; XEmacs regions
4087 ;; Emacs only
4088 (defvar mark-active)
4090 ;; Various packages
4091 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4092 (declare-function calendar-forward-day "cal-move" (arg))
4093 (declare-function calendar-goto-date "cal-move" (date))
4094 (declare-function calendar-goto-today "cal-move" ())
4095 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4096 (defvar calc-embedded-close-formula)
4097 (defvar calc-embedded-open-formula)
4098 (declare-function cdlatex-tab "ext:cdlatex" ())
4099 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4100 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4101 (defvar font-lock-unfontify-region-function)
4102 (declare-function iswitchb-read-buffer "iswitchb"
4103 (prompt &optional default require-match start matches-set))
4104 (defvar iswitchb-temp-buflist)
4105 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4106 (defvar org-agenda-tags-todo-honor-ignore-options)
4107 (declare-function org-agenda-skip "org-agenda" ())
4108 (declare-function
4109 org-agenda-format-item "org-agenda"
4110 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4111 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4112 (declare-function org-agenda-change-all-lines "org-agenda"
4113 (newhead hdmarker &optional fixface just-this))
4114 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4115 (declare-function org-agenda-maybe-redo "org-agenda" ())
4116 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4117 (beg end))
4118 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4119 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4120 "org-agenda" (&optional end))
4121 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4122 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4123 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4124 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4125 (declare-function org-indent-mode "org-indent" (&optional arg))
4126 (declare-function parse-time-string "parse-time" (string))
4127 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4128 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4129 (defvar remember-data-file)
4130 (defvar texmathp-why)
4131 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4132 (declare-function table--at-cell-p "table" (position &optional object at-column))
4134 (defvar org-latex-regexps)
4136 ;;; Autoload and prepare some org modules
4138 ;; Some table stuff that needs to be defined here, because it is used
4139 ;; by the functions setting up org-mode or checking for table context.
4141 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4142 "Detect an org-type or table-type table.")
4143 (defconst org-table-line-regexp "^[ \t]*|"
4144 "Detect an org-type table line.")
4145 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4146 "Detect an org-type table line.")
4147 (defconst org-table-hline-regexp "^[ \t]*|-"
4148 "Detect an org-type table hline.")
4149 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4150 "Detect a table-type table hline.")
4151 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4152 "Detect the first line outside a table when searching from within it.
4153 This works for both table types.")
4155 ;; Autoload the functions in org-table.el that are needed by functions here.
4157 (eval-and-compile
4158 (org-autoload "org-table"
4159 '(org-table-begin org-table-blank-field org-table-end)))
4161 ;;;###autoload
4162 (defun turn-on-orgtbl ()
4163 "Unconditionally turn on `orgtbl-mode'."
4164 (require 'org-table)
4165 (orgtbl-mode 1))
4167 (defun org-at-table-p (&optional table-type)
4168 "Return t if the cursor is inside an org-type table.
4169 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4170 (if org-enable-table-editor
4171 (save-excursion
4172 (beginning-of-line 1)
4173 (looking-at (if table-type org-table-any-line-regexp
4174 org-table-line-regexp)))
4175 nil))
4176 (defsubst org-table-p () (org-at-table-p))
4178 (defun org-at-table.el-p ()
4179 "Return t if and only if we are at a table.el table."
4180 (and (org-at-table-p 'any)
4181 (save-excursion
4182 (goto-char (org-table-begin 'any))
4183 (looking-at org-table1-hline-regexp))))
4184 (defun org-table-recognize-table.el ()
4185 "If there is a table.el table nearby, recognize it and move into it."
4186 (if org-table-tab-recognizes-table.el
4187 (if (org-at-table.el-p)
4188 (progn
4189 (beginning-of-line 1)
4190 (if (looking-at org-table-dataline-regexp)
4192 (if (looking-at org-table1-hline-regexp)
4193 (progn
4194 (beginning-of-line 2)
4195 (if (looking-at org-table-any-border-regexp)
4196 (beginning-of-line -1)))))
4197 (if (re-search-forward "|" (org-table-end t) t)
4198 (progn
4199 (require 'table)
4200 (if (table--at-cell-p (point))
4202 (message "recognizing table.el table...")
4203 (table-recognize-table)
4204 (message "recognizing table.el table...done")))
4205 (error "This should not happen"))
4207 nil)
4208 nil))
4210 (defun org-at-table-hline-p ()
4211 "Return t if the cursor is inside a hline in a table."
4212 (if org-enable-table-editor
4213 (save-excursion
4214 (beginning-of-line 1)
4215 (looking-at org-table-hline-regexp))
4216 nil))
4218 (defvar org-table-clean-did-remove-column nil)
4220 (defun org-table-map-tables (function &optional quietly)
4221 "Apply FUNCTION to the start of all tables in the buffer."
4222 (save-excursion
4223 (save-restriction
4224 (widen)
4225 (goto-char (point-min))
4226 (while (re-search-forward org-table-any-line-regexp nil t)
4227 (unless quietly
4228 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4229 (beginning-of-line 1)
4230 (when (and (looking-at org-table-line-regexp)
4231 ;; Exclude tables in src/example/verbatim/clocktable blocks
4232 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4233 (save-excursion (funcall function))
4234 (or (looking-at org-table-line-regexp)
4235 (forward-char 1)))
4236 (re-search-forward org-table-any-border-regexp nil 1))))
4237 (unless quietly (message "Mapping tables: done")))
4239 ;; Declare and autoload functions from ox.el and al.
4241 (declare-function org-export-get-environment "ox"
4242 (&optional backend subtreep ext-plist))
4243 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4245 ;; Declare and autoload functions from org-agenda.el
4247 (eval-and-compile
4248 (org-autoload "org-agenda"
4249 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4251 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4252 (declare-function org-clock-update-mode-line "org-clock" ())
4253 (declare-function org-resolve-clocks "org-clock"
4254 (&optional also-non-dangling-p prompt last-valid))
4255 (defvar org-clock-start-time)
4256 (defvar org-clock-marker (make-marker)
4257 "Marker recording the last clock-in.")
4258 (defvar org-clock-hd-marker (make-marker)
4259 "Marker recording the last clock-in, but the headline position.")
4260 (defvar org-clock-heading ""
4261 "The heading of the current clock entry.")
4262 (defun org-clock-is-active ()
4263 "Return non-nil if clock is currently running.
4264 The return value is actually the clock marker."
4265 (marker-buffer org-clock-marker))
4267 (eval-and-compile
4268 (org-autoload "org-clock" '(org-clock-remove-overlays
4269 org-clock-update-time-maybe
4270 org-clocktable-shift)))
4272 (defun org-check-running-clock ()
4273 "Check if the current buffer contains the running clock.
4274 If yes, offer to stop it and to save the buffer with the changes."
4275 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4276 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4277 (buffer-name))))
4278 (org-clock-out)
4279 (when (y-or-n-p "Save changed buffer?")
4280 (save-buffer))))
4282 (defun org-clocktable-try-shift (dir n)
4283 "Check if this line starts a clock table, if yes, shift the time block."
4284 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4285 (org-clocktable-shift dir n)))
4287 ;;;###autoload
4288 (defun org-clock-persistence-insinuate ()
4289 "Set up hooks for clock persistence."
4290 (require 'org-clock)
4291 (add-hook 'org-mode-hook 'org-clock-load)
4292 (add-hook 'kill-emacs-hook 'org-clock-save))
4294 ;; Define the variable already here, to make sure we have it.
4295 (defvar org-indent-mode nil
4296 "Non-nil if Org-Indent mode is enabled.
4297 Use the command `org-indent-mode' to change this variable.")
4299 ;; Autoload archiving code
4300 ;; The stuff that is needed for cycling and tags has to be defined here.
4302 (defgroup org-archive nil
4303 "Options concerning archiving in Org-mode."
4304 :tag "Org Archive"
4305 :group 'org-structure)
4307 (defcustom org-archive-location "%s_archive::"
4308 "The location where subtrees should be archived.
4310 The value of this variable is a string, consisting of two parts,
4311 separated by a double-colon. The first part is a filename and
4312 the second part is a headline.
4314 When the filename is omitted, archiving happens in the same file.
4315 %s in the filename will be replaced by the current file
4316 name (without the directory part). Archiving to a different file
4317 is useful to keep archived entries from contributing to the
4318 Org-mode Agenda.
4320 The archived entries will be filed as subtrees of the specified
4321 headline. When the headline is omitted, the subtrees are simply
4322 filed away at the end of the file, as top-level entries. Also in
4323 the heading you can use %s to represent the file name, this can be
4324 useful when using the same archive for a number of different files.
4326 Here are a few examples:
4327 \"%s_archive::\"
4328 If the current file is Projects.org, archive in file
4329 Projects.org_archive, as top-level trees. This is the default.
4331 \"::* Archived Tasks\"
4332 Archive in the current file, under the top-level headline
4333 \"* Archived Tasks\".
4335 \"~/org/archive.org::\"
4336 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4338 \"~/org/archive.org::* From %s\"
4339 Archive in file ~/org/archive.org (absolute path), under headlines
4340 \"From FILENAME\" where file name is the current file name.
4342 \"~/org/datetree.org::datetree/* Finished Tasks\"
4343 The \"datetree/\" string is special, signifying to archive
4344 items to the datetree. Items are placed in either the CLOSED
4345 date of the item, or the current date if there is no CLOSED date.
4346 The heading will be a subentry to the current date. There doesn't
4347 need to be a heading, but there always needs to be a slash after
4348 datetree. For example, to store archived items directly in the
4349 datetree, use \"~/org/datetree.org::datetree/\".
4351 \"basement::** Finished Tasks\"
4352 Archive in file ./basement (relative path), as level 3 trees
4353 below the level 2 heading \"** Finished Tasks\".
4355 You may set this option on a per-file basis by adding to the buffer a
4356 line like
4358 #+ARCHIVE: basement::** Finished Tasks
4360 You may also define it locally for a subtree by setting an ARCHIVE property
4361 in the entry. If such a property is found in an entry, or anywhere up
4362 the hierarchy, it will be used."
4363 :group 'org-archive
4364 :type 'string)
4366 (defcustom org-archive-tag "ARCHIVE"
4367 "The tag that marks a subtree as archived.
4368 An archived subtree does not open during visibility cycling, and does
4369 not contribute to the agenda listings.
4370 After changing this, font-lock must be restarted in the relevant buffers to
4371 get the proper fontification."
4372 :group 'org-archive
4373 :group 'org-keywords
4374 :type 'string)
4376 (defcustom org-agenda-skip-archived-trees t
4377 "Non-nil means the agenda will skip any items located in archived trees.
4378 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4379 variable is no longer recommended, you should leave it at the value t.
4380 Instead, use the key `v' to cycle the archives-mode in the agenda."
4381 :group 'org-archive
4382 :group 'org-agenda-skip
4383 :type 'boolean)
4385 (defcustom org-columns-skip-archived-trees t
4386 "Non-nil means ignore archived trees when creating column view."
4387 :group 'org-archive
4388 :group 'org-properties
4389 :type 'boolean)
4391 (defcustom org-cycle-open-archived-trees nil
4392 "Non-nil means `org-cycle' will open archived trees.
4393 An archived tree is a tree marked with the tag ARCHIVE.
4394 When nil, archived trees will stay folded. You can still open them with
4395 normal outline commands like `show-all', but not with the cycling commands."
4396 :group 'org-archive
4397 :group 'org-cycle
4398 :type 'boolean)
4400 (defcustom org-sparse-tree-open-archived-trees nil
4401 "Non-nil means sparse tree construction shows matches in archived trees.
4402 When nil, matches in these trees are highlighted, but the trees are kept in
4403 collapsed state."
4404 :group 'org-archive
4405 :group 'org-sparse-trees
4406 :type 'boolean)
4408 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4409 "The default date type when building a sparse tree.
4410 When this is nil, a date is a scheduled or a deadline timestamp.
4411 Otherwise, these types are allowed:
4413 all: all timestamps
4414 active: only active timestamps (<...>)
4415 inactive: only inactive timestamps (<...)
4416 scheduled: only scheduled timestamps
4417 deadline: only deadline timestamps"
4418 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4419 (const :tag "All timestamps" all)
4420 (const :tag "Only active timestamps" active)
4421 (const :tag "Only inactive timestamps" inactive)
4422 (const :tag "Only scheduled timestamps" scheduled)
4423 (const :tag "Only deadline timestamps" deadline))
4424 :version "24.3"
4425 :group 'org-sparse-trees)
4427 (defun org-cycle-hide-archived-subtrees (state)
4428 "Re-hide all archived subtrees after a visibility state change."
4429 (when (and (not org-cycle-open-archived-trees)
4430 (not (memq state '(overview folded))))
4431 (save-excursion
4432 (let* ((globalp (memq state '(contents all)))
4433 (beg (if globalp (point-min) (point)))
4434 (end (if globalp (point-max) (org-end-of-subtree t))))
4435 (org-hide-archived-subtrees beg end)
4436 (goto-char beg)
4437 (if (looking-at (concat ".*:" org-archive-tag ":"))
4438 (message "%s" (substitute-command-keys
4439 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4441 (defun org-force-cycle-archived ()
4442 "Cycle subtree even if it is archived."
4443 (interactive)
4444 (setq this-command 'org-cycle)
4445 (let ((org-cycle-open-archived-trees t))
4446 (call-interactively 'org-cycle)))
4448 (defun org-hide-archived-subtrees (beg end)
4449 "Re-hide all archived subtrees after a visibility state change."
4450 (save-excursion
4451 (let* ((re (concat ":" org-archive-tag ":")))
4452 (goto-char beg)
4453 (while (re-search-forward re end t)
4454 (when (org-at-heading-p)
4455 (org-flag-subtree t)
4456 (org-end-of-subtree t))))))
4458 (declare-function outline-end-of-heading "outline" ())
4459 (declare-function outline-flag-region "outline" (from to flag))
4460 (defun org-flag-subtree (flag)
4461 (save-excursion
4462 (org-back-to-heading t)
4463 (outline-end-of-heading)
4464 (outline-flag-region (point)
4465 (progn (org-end-of-subtree t) (point))
4466 flag)))
4468 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4470 (eval-and-compile
4471 (org-autoload "org-archive"
4472 '(org-add-archive-files)))
4474 ;; Autoload Column View Code
4476 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4477 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4478 (declare-function org-columns-compute "org-colview" (property))
4480 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4481 '(org-columns-number-to-string
4482 org-columns-get-format-and-top-level
4483 org-columns-compute
4484 org-columns-remove-overlays))
4486 ;; Autoload ID code
4488 (declare-function org-id-store-link "org-id")
4489 (declare-function org-id-locations-load "org-id")
4490 (declare-function org-id-locations-save "org-id")
4491 (defvar org-id-track-globally)
4492 (org-autoload "org-id"
4493 '(org-id-new
4494 org-id-copy
4495 org-id-get-with-outline-path-completion
4496 org-id-get-with-outline-drilling))
4498 ;;; Variables for pre-computed regular expressions, all buffer local
4500 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4501 "Matches first line of a hidden block.")
4502 (make-variable-buffer-local 'org-drawer-regexp)
4503 (defvar org-todo-regexp nil
4504 "Matches any of the TODO state keywords.")
4505 (make-variable-buffer-local 'org-todo-regexp)
4506 (defvar org-not-done-regexp nil
4507 "Matches any of the TODO state keywords except the last one.")
4508 (make-variable-buffer-local 'org-not-done-regexp)
4509 (defvar org-not-done-heading-regexp nil
4510 "Matches a TODO headline that is not done.")
4511 (make-variable-buffer-local 'org-not-done-regexp)
4512 (defvar org-todo-line-regexp nil
4513 "Matches a headline and puts TODO state into group 2 if present.")
4514 (make-variable-buffer-local 'org-todo-line-regexp)
4515 (defvar org-complex-heading-regexp nil
4516 "Matches a headline and puts everything into groups:
4517 group 1: the stars
4518 group 2: The todo keyword, maybe
4519 group 3: Priority cookie
4520 group 4: True headline
4521 group 5: Tags")
4522 (make-variable-buffer-local 'org-complex-heading-regexp)
4523 (defvar org-complex-heading-regexp-format nil
4524 "Printf format to make regexp to match an exact headline.
4525 This regexp will match the headline of any node which has the
4526 exact headline text that is put into the format, but may have any
4527 TODO state, priority and tags.")
4528 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4529 (defvar org-todo-line-tags-regexp nil
4530 "Matches a headline and puts TODO state into group 2 if present.
4531 Also put tags into group 4 if tags are present.")
4532 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4533 (defvar org-ds-keyword-length 12
4534 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4535 (make-variable-buffer-local 'org-ds-keyword-length)
4536 (defvar org-deadline-regexp nil
4537 "Matches the DEADLINE keyword.")
4538 (make-variable-buffer-local 'org-deadline-regexp)
4539 (defvar org-deadline-time-regexp nil
4540 "Matches the DEADLINE keyword together with a time stamp.")
4541 (make-variable-buffer-local 'org-deadline-time-regexp)
4542 (defvar org-deadline-line-regexp nil
4543 "Matches the DEADLINE keyword and the rest of the line.")
4544 (make-variable-buffer-local 'org-deadline-line-regexp)
4545 (defvar org-scheduled-regexp nil
4546 "Matches the SCHEDULED keyword.")
4547 (make-variable-buffer-local 'org-scheduled-regexp)
4548 (defvar org-scheduled-time-regexp nil
4549 "Matches the SCHEDULED keyword together with a time stamp.")
4550 (make-variable-buffer-local 'org-scheduled-time-regexp)
4551 (defvar org-closed-time-regexp nil
4552 "Matches the CLOSED keyword together with a time stamp.")
4553 (make-variable-buffer-local 'org-closed-time-regexp)
4555 (defvar org-keyword-time-regexp nil
4556 "Matches any of the 4 keywords, together with the time stamp.")
4557 (make-variable-buffer-local 'org-keyword-time-regexp)
4558 (defvar org-keyword-time-not-clock-regexp nil
4559 "Matches any of the 3 keywords, together with the time stamp.")
4560 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4561 (defvar org-maybe-keyword-time-regexp nil
4562 "Matches a timestamp, possibly preceded by a keyword.")
4563 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4564 (defvar org-all-time-keywords nil
4565 "List of time keywords.")
4566 (make-variable-buffer-local 'org-all-time-keywords)
4568 (defconst org-plain-time-of-day-regexp
4569 (concat
4570 "\\(\\<[012]?[0-9]"
4571 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4572 "\\(--?"
4573 "\\(\\<[012]?[0-9]"
4574 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4575 "\\)?")
4576 "Regular expression to match a plain time or time range.
4577 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4578 groups carry important information:
4579 0 the full match
4580 1 the first time, range or not
4581 8 the second time, if it is a range.")
4583 (defconst org-plain-time-extension-regexp
4584 (concat
4585 "\\(\\<[012]?[0-9]"
4586 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4587 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4588 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4589 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4590 groups carry important information:
4591 0 the full match
4592 7 hours of duration
4593 9 minutes of duration")
4595 (defconst org-stamp-time-of-day-regexp
4596 (concat
4597 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4598 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4599 "\\(--?"
4600 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4601 "Regular expression to match a timestamp time or time range.
4602 After a match, the following groups carry important information:
4603 0 the full match
4604 1 date plus weekday, for back referencing to make sure both times are on the same day
4605 2 the first time, range or not
4606 4 the second time, if it is a range.")
4608 (defconst org-startup-options
4609 '(("fold" org-startup-folded t)
4610 ("overview" org-startup-folded t)
4611 ("nofold" org-startup-folded nil)
4612 ("showall" org-startup-folded nil)
4613 ("showeverything" org-startup-folded showeverything)
4614 ("content" org-startup-folded content)
4615 ("indent" org-startup-indented t)
4616 ("noindent" org-startup-indented nil)
4617 ("hidestars" org-hide-leading-stars t)
4618 ("showstars" org-hide-leading-stars nil)
4619 ("odd" org-odd-levels-only t)
4620 ("oddeven" org-odd-levels-only nil)
4621 ("align" org-startup-align-all-tables t)
4622 ("noalign" org-startup-align-all-tables nil)
4623 ("inlineimages" org-startup-with-inline-images t)
4624 ("noinlineimages" org-startup-with-inline-images nil)
4625 ("customtime" org-display-custom-times t)
4626 ("logdone" org-log-done time)
4627 ("lognotedone" org-log-done note)
4628 ("nologdone" org-log-done nil)
4629 ("lognoteclock-out" org-log-note-clock-out t)
4630 ("nolognoteclock-out" org-log-note-clock-out nil)
4631 ("logrepeat" org-log-repeat state)
4632 ("lognoterepeat" org-log-repeat note)
4633 ("logdrawer" org-log-into-drawer t)
4634 ("nologdrawer" org-log-into-drawer nil)
4635 ("logstatesreversed" org-log-states-order-reversed t)
4636 ("nologstatesreversed" org-log-states-order-reversed nil)
4637 ("nologrepeat" org-log-repeat nil)
4638 ("logreschedule" org-log-reschedule time)
4639 ("lognotereschedule" org-log-reschedule note)
4640 ("nologreschedule" org-log-reschedule nil)
4641 ("logredeadline" org-log-redeadline time)
4642 ("lognoteredeadline" org-log-redeadline note)
4643 ("nologredeadline" org-log-redeadline nil)
4644 ("logrefile" org-log-refile time)
4645 ("lognoterefile" org-log-refile note)
4646 ("nologrefile" org-log-refile nil)
4647 ("fninline" org-footnote-define-inline t)
4648 ("nofninline" org-footnote-define-inline nil)
4649 ("fnlocal" org-footnote-section nil)
4650 ("fnauto" org-footnote-auto-label t)
4651 ("fnprompt" org-footnote-auto-label nil)
4652 ("fnconfirm" org-footnote-auto-label confirm)
4653 ("fnplain" org-footnote-auto-label plain)
4654 ("fnadjust" org-footnote-auto-adjust t)
4655 ("nofnadjust" org-footnote-auto-adjust nil)
4656 ("constcgs" constants-unit-system cgs)
4657 ("constSI" constants-unit-system SI)
4658 ("noptag" org-tag-persistent-alist nil)
4659 ("hideblocks" org-hide-block-startup t)
4660 ("nohideblocks" org-hide-block-startup nil)
4661 ("beamer" org-startup-with-beamer-mode t)
4662 ("entitiespretty" org-pretty-entities t)
4663 ("entitiesplain" org-pretty-entities nil))
4664 "Variable associated with STARTUP options for org-mode.
4665 Each element is a list of three items: the startup options (as written
4666 in the #+STARTUP line), the corresponding variable, and the value to set
4667 this variable to if the option is found. An optional forth element PUSH
4668 means to push this value onto the list in the variable.")
4670 (defun org-update-property-plist (key val props)
4671 "Update PROPS with KEY and VAL."
4672 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4673 (key (if appending (substring key 0 (- (length key) 1)) key))
4674 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4675 (previous (cdr (assoc key props))))
4676 (if appending
4677 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4678 (cons (cons key val) remainder))))
4680 (defconst org-block-regexp
4681 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4682 "Regular expression for hiding blocks.")
4683 (defconst org-heading-keyword-regexp-format
4684 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4685 "Printf format for a regexp matching an headline with some keyword.
4686 This regexp will match the headline of any node which has the
4687 exact keyword that is put into the format. The keyword isn't in
4688 any group by default, but the stars and the body are.")
4689 (defconst org-heading-keyword-maybe-regexp-format
4690 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4691 "Printf format for a regexp matching an headline, possibly with some keyword.
4692 This regexp can match any headline with the specified keyword, or
4693 without a keyword. The keyword isn't in any group by default,
4694 but the stars and the body are.")
4696 (defun org-set-regexps-and-options ()
4697 "Precompute regular expressions for current buffer."
4698 (when (derived-mode-p 'org-mode)
4699 (org-set-local 'org-todo-kwd-alist nil)
4700 (org-set-local 'org-todo-key-alist nil)
4701 (org-set-local 'org-todo-key-trigger nil)
4702 (org-set-local 'org-todo-keywords-1 nil)
4703 (org-set-local 'org-done-keywords nil)
4704 (org-set-local 'org-todo-heads nil)
4705 (org-set-local 'org-todo-sets nil)
4706 (org-set-local 'org-todo-log-states nil)
4707 (org-set-local 'org-file-properties nil)
4708 (org-set-local 'org-file-tags nil)
4709 (let ((re (org-make-options-regexp
4710 '("CATEGORY" "TODO" "COLUMNS"
4711 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4712 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4713 "OPTIONS")
4714 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4715 (splitre "[ \t]+")
4716 (scripts org-use-sub-superscripts)
4717 kwds kws0 kwsa key log value cat arch tags const links hw dws
4718 tail sep kws1 prio props ftags drawers beamer-p
4719 ext-setup-or-nil setup-contents (start 0))
4720 (save-excursion
4721 (save-restriction
4722 (widen)
4723 (goto-char (point-min))
4724 (while (or (and ext-setup-or-nil
4725 (string-match re ext-setup-or-nil start)
4726 (setq start (match-end 0)))
4727 (and (setq ext-setup-or-nil nil start 0)
4728 (re-search-forward re nil t)))
4729 (setq key (upcase (match-string 1 ext-setup-or-nil))
4730 value (org-match-string-no-properties 2 ext-setup-or-nil))
4731 (if (stringp value) (setq value (org-trim value)))
4732 (cond
4733 ((equal key "CATEGORY")
4734 (setq cat value))
4735 ((member key '("SEQ_TODO" "TODO"))
4736 (push (cons 'sequence (org-split-string value splitre)) kwds))
4737 ((equal key "TYP_TODO")
4738 (push (cons 'type (org-split-string value splitre)) kwds))
4739 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4740 ;; general TODO-like setup
4741 (push (cons (intern (downcase (match-string 1 key)))
4742 (org-split-string value splitre)) kwds))
4743 ((equal key "TAGS")
4744 (setq tags (append tags (if tags '("\\n") nil)
4745 (org-split-string value splitre))))
4746 ((equal key "COLUMNS")
4747 (org-set-local 'org-columns-default-format value))
4748 ((equal key "LINK")
4749 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4750 (push (cons (match-string 1 value)
4751 (org-trim (match-string 2 value)))
4752 links)))
4753 ((equal key "PRIORITIES")
4754 (setq prio (org-split-string value " +")))
4755 ((equal key "PROPERTY")
4756 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4757 (setq props (org-update-property-plist (match-string 1 value)
4758 (match-string 2 value)
4759 props))))
4760 ((equal key "FILETAGS")
4761 (when (string-match "\\S-" value)
4762 (setq ftags
4763 (append
4764 ftags
4765 (apply 'append
4766 (mapcar (lambda (x) (org-split-string x ":"))
4767 (org-split-string value)))))))
4768 ((equal key "DRAWERS")
4769 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4770 ((equal key "CONSTANTS")
4771 (setq const (append const (org-split-string value splitre))))
4772 ((equal key "STARTUP")
4773 (let ((opts (org-split-string value splitre))
4774 l var val)
4775 (while (setq l (pop opts))
4776 (when (setq l (assoc l org-startup-options))
4777 (setq var (nth 1 l) val (nth 2 l))
4778 (if (not (nth 3 l))
4779 (set (make-local-variable var) val)
4780 (if (not (listp (symbol-value var)))
4781 (set (make-local-variable var) nil))
4782 (set (make-local-variable var) (symbol-value var))
4783 (add-to-list var val))))))
4784 ((equal key "ARCHIVE")
4785 (setq arch value)
4786 (remove-text-properties 0 (length arch)
4787 '(face t fontified t) arch))
4788 ((equal key "LATEX_CLASS")
4789 (setq beamer-p (equal value "beamer")))
4790 ((equal key "OPTIONS")
4791 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4792 (setq scripts (read (match-string 2 value)))))
4793 ((equal key "SETUPFILE")
4794 (setq setup-contents (org-file-contents
4795 (expand-file-name
4796 (org-remove-double-quotes value))
4797 'noerror))
4798 (if (not ext-setup-or-nil)
4799 (setq ext-setup-or-nil setup-contents start 0)
4800 (setq ext-setup-or-nil
4801 (concat (substring ext-setup-or-nil 0 start)
4802 "\n" setup-contents "\n"
4803 (substring ext-setup-or-nil start)))))))
4804 ;; search for property blocks
4805 (goto-char (point-min))
4806 (while (re-search-forward org-block-regexp nil t)
4807 (when (equal "PROPERTY" (upcase (match-string 1)))
4808 (setq value (replace-regexp-in-string
4809 "[\n\r]" " " (match-string 4)))
4810 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4811 (setq props (org-update-property-plist (match-string 1 value)
4812 (match-string 2 value)
4813 props)))))))
4814 (org-set-local 'org-use-sub-superscripts scripts)
4815 (when cat
4816 (org-set-local 'org-category (intern cat))
4817 (push (cons "CATEGORY" cat) props))
4818 (when prio
4819 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4820 (setq prio (mapcar 'string-to-char prio))
4821 (org-set-local 'org-highest-priority (nth 0 prio))
4822 (org-set-local 'org-lowest-priority (nth 1 prio))
4823 (org-set-local 'org-default-priority (nth 2 prio)))
4824 (and props (org-set-local 'org-file-properties (nreverse props)))
4825 (and ftags (org-set-local 'org-file-tags
4826 (mapcar 'org-add-prop-inherited ftags)))
4827 (and drawers (org-set-local 'org-drawers drawers))
4828 (and arch (org-set-local 'org-archive-location arch))
4829 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4830 ;; Process the TODO keywords
4831 (unless kwds
4832 ;; Use the global values as if they had been given locally.
4833 (setq kwds (default-value 'org-todo-keywords))
4834 (if (stringp (car kwds))
4835 (setq kwds (list (cons org-todo-interpretation
4836 (default-value 'org-todo-keywords)))))
4837 (setq kwds (reverse kwds)))
4838 (setq kwds (nreverse kwds))
4839 (let (inter kws kw)
4840 (while (setq kws (pop kwds))
4841 (let ((kws (or
4842 (run-hook-with-args-until-success
4843 'org-todo-setup-filter-hook kws)
4844 kws)))
4845 (setq inter (pop kws) sep (member "|" kws)
4846 kws0 (delete "|" (copy-sequence kws))
4847 kwsa nil
4848 kws1 (mapcar
4849 (lambda (x)
4850 ;; 1 2
4851 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4852 (progn
4853 (setq kw (match-string 1 x)
4854 key (and (match-end 2) (match-string 2 x))
4855 log (org-extract-log-state-settings x))
4856 (push (cons kw (and key (string-to-char key))) kwsa)
4857 (and log (push log org-todo-log-states))
4859 (error "Invalid TODO keyword %s" x)))
4860 kws0)
4861 kwsa (if kwsa (append '((:startgroup))
4862 (nreverse kwsa)
4863 '((:endgroup))))
4864 hw (car kws1)
4865 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4866 tail (list inter hw (car dws) (org-last dws))))
4867 (add-to-list 'org-todo-heads hw 'append)
4868 (push kws1 org-todo-sets)
4869 (setq org-done-keywords (append org-done-keywords dws nil))
4870 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4871 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4872 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4873 (setq org-todo-sets (nreverse org-todo-sets)
4874 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4875 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4876 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4877 ;; Process the constants
4878 (when const
4879 (let (e cst)
4880 (while (setq e (pop const))
4881 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4882 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4883 (setq org-table-formula-constants-local cst)))
4885 ;; Process the tags.
4886 (when tags
4887 (let (e tgs)
4888 (while (setq e (pop tags))
4889 (cond
4890 ((equal e "{") (push '(:startgroup) tgs))
4891 ((equal e "}") (push '(:endgroup) tgs))
4892 ((equal e "\\n") (push '(:newline) tgs))
4893 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4894 (push (cons (match-string 1 e)
4895 (string-to-char (match-string 2 e)))
4896 tgs))
4897 (t (push (list e) tgs))))
4898 (org-set-local 'org-tag-alist nil)
4899 (while (setq e (pop tgs))
4900 (or (and (stringp (car e))
4901 (assoc (car e) org-tag-alist))
4902 (push e org-tag-alist)))))
4904 ;; Compute the regular expressions and other local variables.
4905 ;; Using `org-outline-regexp-bol' would complicate them much,
4906 ;; because of the fixed white space at the end of that string.
4907 (if (not org-done-keywords)
4908 (setq org-done-keywords (and org-todo-keywords-1
4909 (list (org-last org-todo-keywords-1)))))
4910 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4911 (length org-scheduled-string)
4912 (length org-clock-string)
4913 (length org-closed-string)))
4914 org-drawer-regexp
4915 (concat "^[ \t]*:\\("
4916 (mapconcat 'regexp-quote org-drawers "\\|")
4917 "\\):[ \t]*$")
4918 org-not-done-keywords
4919 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4920 org-todo-regexp
4921 (concat "\\("
4922 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4923 "\\)")
4924 org-not-done-regexp
4925 (concat "\\("
4926 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4927 "\\)")
4928 org-not-done-heading-regexp
4929 (format org-heading-keyword-regexp-format org-not-done-regexp)
4930 org-todo-line-regexp
4931 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4932 org-complex-heading-regexp
4933 (concat "^\\(\\*+\\)"
4934 "\\(?: +" org-todo-regexp "\\)?"
4935 "\\(?: +\\(\\[#.\\]\\)\\)?"
4936 "\\(?: +\\(.*?\\)\\)??"
4937 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4938 "[ \t]*$")
4939 org-complex-heading-regexp-format
4940 (concat "^\\(\\*+\\)"
4941 "\\(?: +" org-todo-regexp "\\)?"
4942 "\\(?: +\\(\\[#.\\]\\)\\)?"
4943 "\\(?: +"
4944 ;; Stats cookies can be stuck to body.
4945 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4946 "\\(%s\\)"
4947 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4948 "\\)"
4949 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4950 "[ \t]*$")
4951 org-todo-line-tags-regexp
4952 (concat "^\\(\\*+\\)"
4953 "\\(?: +" org-todo-regexp "\\)?"
4954 "\\(?: +\\(.*?\\)\\)??"
4955 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4956 "[ \t]*$")
4957 org-deadline-regexp (concat "\\<" org-deadline-string)
4958 org-deadline-time-regexp
4959 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4960 org-deadline-line-regexp
4961 (concat "\\<\\(" org-deadline-string "\\).*")
4962 org-scheduled-regexp
4963 (concat "\\<" org-scheduled-string)
4964 org-scheduled-time-regexp
4965 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4966 org-closed-time-regexp
4967 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4968 org-keyword-time-regexp
4969 (concat "\\<\\(" org-scheduled-string
4970 "\\|" org-deadline-string
4971 "\\|" org-closed-string
4972 "\\|" org-clock-string "\\)"
4973 " *[[<]\\([^]>]+\\)[]>]")
4974 org-keyword-time-not-clock-regexp
4975 (concat "\\<\\(" org-scheduled-string
4976 "\\|" org-deadline-string
4977 "\\|" org-closed-string
4978 "\\)"
4979 " *[[<]\\([^]>]+\\)[]>]")
4980 org-maybe-keyword-time-regexp
4981 (concat "\\(\\<\\(" org-scheduled-string
4982 "\\|" org-deadline-string
4983 "\\|" org-closed-string
4984 "\\|" org-clock-string "\\)\\)?"
4985 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4986 org-all-time-keywords
4987 (mapcar (lambda (w) (substring w 0 -1))
4988 (list org-scheduled-string org-deadline-string
4989 org-clock-string org-closed-string)))
4990 (org-set-font-lock-defaults))))
4992 (defun org-file-contents (file &optional noerror)
4993 "Return the contents of FILE, as a string."
4994 (if (or (not file)
4995 (not (file-readable-p file)))
4996 (if noerror
4997 (progn
4998 (message "Cannot read file \"%s\"" file)
4999 (ding) (sit-for 2)
5001 (error "Cannot read file \"%s\"" file))
5002 (with-temp-buffer
5003 (insert-file-contents file)
5004 (buffer-string))))
5006 (defun org-extract-log-state-settings (x)
5007 "Extract the log state setting from a TODO keyword string.
5008 This will extract info from a string like \"WAIT(w@/!)\"."
5009 (let (kw key log1 log2)
5010 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5011 (setq kw (match-string 1 x)
5012 key (and (match-end 2) (match-string 2 x))
5013 log1 (and (match-end 3) (match-string 3 x))
5014 log2 (and (match-end 4) (match-string 4 x)))
5015 (and (or log1 log2)
5016 (list kw
5017 (and log1 (if (equal log1 "!") 'time 'note))
5018 (and log2 (if (equal log2 "!") 'time 'note)))))))
5020 (defun org-remove-keyword-keys (list)
5021 "Remove a pair of parenthesis at the end of each string in LIST."
5022 (mapcar (lambda (x)
5023 (if (string-match "(.*)$" x)
5024 (substring x 0 (match-beginning 0))
5026 list))
5028 (defun org-assign-fast-keys (alist)
5029 "Assign fast keys to a keyword-key alist.
5030 Respect keys that are already there."
5031 (let (new e (alt ?0))
5032 (while (setq e (pop alist))
5033 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5034 (cdr e)) ;; Key already assigned.
5035 (push e new)
5036 (let ((clist (string-to-list (downcase (car e))))
5037 (used (append new alist)))
5038 (when (= (car clist) ?@)
5039 (pop clist))
5040 (while (and clist (rassoc (car clist) used))
5041 (pop clist))
5042 (unless clist
5043 (while (rassoc alt used)
5044 (incf alt)))
5045 (push (cons (car e) (or (car clist) alt)) new))))
5046 (nreverse new)))
5048 ;;; Some variables used in various places
5050 (defvar org-window-configuration nil
5051 "Used in various places to store a window configuration.")
5052 (defvar org-selected-window nil
5053 "Used in various places to store a window configuration.")
5054 (defvar org-finish-function nil
5055 "Function to be called when `C-c C-c' is used.
5056 This is for getting out of special buffers like capture.")
5059 ;; FIXME: Occasionally check by commenting these, to make sure
5060 ;; no other functions uses these, forgetting to let-bind them.
5061 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5062 (defvar org-last-state)
5063 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5065 ;; Defined somewhere in this file, but used before definition.
5066 (defvar org-entities) ;; defined in org-entities.el
5067 (defvar org-struct-menu)
5068 (defvar org-org-menu)
5069 (defvar org-tbl-menu)
5071 ;;;; Define the Org-mode
5073 ;; We use a before-change function to check if a table might need
5074 ;; an update.
5075 (defvar org-table-may-need-update t
5076 "Indicates that a table might need an update.
5077 This variable is set by `org-before-change-function'.
5078 `org-table-align' sets it back to nil.")
5079 (defun org-before-change-function (beg end)
5080 "Every change indicates that a table might need an update."
5081 (setq org-table-may-need-update t))
5082 (defvar org-mode-map)
5083 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5084 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5085 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5086 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5087 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5088 (defvar org-table-buffer-is-an nil)
5090 (defvar bidi-paragraph-direction)
5091 (defvar buffer-face-mode-face)
5093 (require 'outline)
5094 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5095 (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"))
5096 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5098 ;; Other stuff we need.
5099 (require 'time-date)
5100 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5101 (require 'easymenu)
5102 (require 'overlay)
5104 ;; (require 'org-macs) moved higher up in the file before it is first used
5105 (require 'org-entities)
5106 ;; (require 'org-compat) moved higher up in the file before it is first used
5107 (require 'org-faces)
5108 (require 'org-list)
5109 (require 'org-pcomplete)
5110 (require 'org-src)
5111 (require 'org-footnote)
5113 ;; babel
5114 (require 'ob)
5116 ;;;###autoload
5117 (define-derived-mode org-mode outline-mode "Org"
5118 "Outline-based notes management and organizer, alias
5119 \"Carsten's outline-mode for keeping track of everything.\"
5121 Org-mode develops organizational tasks around a NOTES file which
5122 contains information about projects as plain text. Org-mode is
5123 implemented on top of outline-mode, which is ideal to keep the content
5124 of large files well structured. It supports ToDo items, deadlines and
5125 time stamps, which magically appear in the diary listing of the Emacs
5126 calendar. Tables are easily created with a built-in table editor.
5127 Plain text URL-like links connect to websites, emails (VM), Usenet
5128 messages (Gnus), BBDB entries, and any files related to the project.
5129 For printing and sharing of notes, an Org-mode file (or a part of it)
5130 can be exported as a structured ASCII or HTML file.
5132 The following commands are available:
5134 \\{org-mode-map}"
5136 ;; Get rid of Outline menus, they are not needed
5137 ;; Need to do this here because define-derived-mode sets up
5138 ;; the keymap so late. Still, it is a waste to call this each time
5139 ;; we switch another buffer into org-mode.
5140 (if (featurep 'xemacs)
5141 (when (boundp 'outline-mode-menu-heading)
5142 ;; Assume this is Greg's port, it uses easymenu
5143 (easy-menu-remove outline-mode-menu-heading)
5144 (easy-menu-remove outline-mode-menu-show)
5145 (easy-menu-remove outline-mode-menu-hide))
5146 (define-key org-mode-map [menu-bar headings] 'undefined)
5147 (define-key org-mode-map [menu-bar hide] 'undefined)
5148 (define-key org-mode-map [menu-bar show] 'undefined))
5150 (org-load-modules-maybe)
5151 (easy-menu-add org-org-menu)
5152 (easy-menu-add org-tbl-menu)
5153 (org-install-agenda-files-menu)
5154 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5155 (add-to-invisibility-spec '(org-cwidth))
5156 (add-to-invisibility-spec '(org-hide-block . t))
5157 (when (featurep 'xemacs)
5158 (org-set-local 'line-move-ignore-invisible t))
5159 (org-set-local 'outline-regexp org-outline-regexp)
5160 (org-set-local 'outline-level 'org-outline-level)
5161 (setq bidi-paragraph-direction 'left-to-right)
5162 (when (and org-ellipsis
5163 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5164 (fboundp 'make-glyph-code))
5165 (unless org-display-table
5166 (setq org-display-table (make-display-table)))
5167 (set-display-table-slot
5168 org-display-table 4
5169 (vconcat (mapcar
5170 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5171 org-ellipsis)))
5172 (if (stringp org-ellipsis) org-ellipsis "..."))))
5173 (setq buffer-display-table org-display-table))
5174 (org-set-regexps-and-options)
5175 (when (and org-tag-faces (not org-tags-special-faces-re))
5176 ;; tag faces set outside customize.... force initialization.
5177 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5178 ;; Calc embedded
5179 (org-set-local 'calc-embedded-open-mode "# ")
5180 (modify-syntax-entry ?@ "w")
5181 (modify-syntax-entry ?\" "\"")
5182 (if org-startup-truncated (setq truncate-lines t))
5183 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5184 (org-set-local 'font-lock-unfontify-region-function
5185 'org-unfontify-region)
5186 ;; Activate before-change-function
5187 (org-set-local 'org-table-may-need-update t)
5188 (org-add-hook 'before-change-functions 'org-before-change-function nil
5189 'local)
5190 ;; Check for running clock before killing a buffer
5191 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5192 ;; Initialize macros templates.
5193 (org-macro-initialize-templates)
5194 ;; Initialize radio targets.
5195 (org-update-radio-target-regexp)
5196 ;; Indentation.
5197 (org-set-local 'indent-line-function 'org-indent-line)
5198 (org-set-local 'indent-region-function 'org-indent-region)
5199 ;; Filling and auto-filling.
5200 (org-setup-filling)
5201 ;; Comments.
5202 (org-setup-comments-handling)
5203 ;; Beginning/end of defun
5204 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5205 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5206 ;; Next error for sparse trees
5207 (org-set-local 'next-error-function 'org-occur-next-match)
5208 ;; Make sure dependence stuff works reliably, even for users who set it
5209 ;; too late :-(
5210 (if org-enforce-todo-dependencies
5211 (add-hook 'org-blocker-hook
5212 'org-block-todo-from-children-or-siblings-or-parent)
5213 (remove-hook 'org-blocker-hook
5214 'org-block-todo-from-children-or-siblings-or-parent))
5215 (if org-enforce-todo-checkbox-dependencies
5216 (add-hook 'org-blocker-hook
5217 'org-block-todo-from-checkboxes)
5218 (remove-hook 'org-blocker-hook
5219 'org-block-todo-from-checkboxes))
5221 ;; Align options lines
5222 (org-set-local
5223 'align-mode-rules-list
5224 '((org-in-buffer-settings
5225 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5226 (modes . '(org-mode)))))
5228 ;; Imenu
5229 (org-set-local 'imenu-create-index-function
5230 'org-imenu-get-tree)
5232 ;; Make isearch reveal context
5233 (if (or (featurep 'xemacs)
5234 (not (boundp 'outline-isearch-open-invisible-function)))
5235 ;; Emacs 21 and XEmacs make use of the hook
5236 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5237 ;; Emacs 22 deals with this through a special variable
5238 (org-set-local 'outline-isearch-open-invisible-function
5239 (lambda (&rest ignore) (org-show-context 'isearch))))
5241 ;; Setup the pcomplete hooks
5242 (set (make-local-variable 'pcomplete-command-completion-function)
5243 'org-pcomplete-initial)
5244 (set (make-local-variable 'pcomplete-command-name-function)
5245 'org-command-at-point)
5246 (set (make-local-variable 'pcomplete-default-completion-function)
5247 'ignore)
5248 (set (make-local-variable 'pcomplete-parse-arguments-function)
5249 'org-parse-arguments)
5250 (set (make-local-variable 'pcomplete-termination-string) "")
5251 (when (>= emacs-major-version 23)
5252 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5254 ;; If empty file that did not turn on org-mode automatically, make it to.
5255 (if (and org-insert-mode-line-in-empty-file
5256 (org-called-interactively-p 'any)
5257 (= (point-min) (point-max)))
5258 (insert "# -*- mode: org -*-\n\n"))
5259 (unless org-inhibit-startup
5260 (and org-startup-with-beamer-mode (org-beamer-mode))
5261 (when org-startup-align-all-tables
5262 (let ((bmp (buffer-modified-p)))
5263 (org-table-map-tables 'org-table-align 'quietly)
5264 (set-buffer-modified-p bmp)))
5265 (when org-startup-with-inline-images
5266 (org-display-inline-images))
5267 (unless org-inhibit-startup-visibility-stuff
5268 (org-set-startup-visibility)))
5269 ;; Try to set org-hide correctly
5270 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5272 (when (fboundp 'abbrev-table-put)
5273 (abbrev-table-put org-mode-abbrev-table
5274 :parents (list text-mode-abbrev-table)))
5276 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5279 (defun org-find-invisible-foreground ()
5280 (let ((candidates (remove
5281 "unspecified-bg"
5282 (nconc
5283 (list (face-background 'default)
5284 (face-background 'org-default))
5285 (mapcar
5286 (lambda (alist)
5287 (when (boundp alist)
5288 (cdr (assoc 'background-color (symbol-value alist)))))
5289 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5290 (list (face-foreground 'org-hide))))))
5291 (car (remove nil candidates))))
5293 (defun org-current-time (&optional rounding-minutes)
5294 "Current time, possibly rounded to ROUNDING-MINUTES.
5295 When ROUNDING-MINUTES is not an integer, fall back on the car of
5296 `org-time-stamp-rounding-minutes'."
5297 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5298 (car org-time-stamp-rounding-minutes)))
5299 (time (decode-time)))
5300 (if (> r 1)
5301 (apply 'encode-time
5302 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5303 (nthcdr 2 time)))
5304 (current-time))))
5306 (defun org-today ()
5307 "Return today date, considering `org-extend-today-until'."
5308 (time-to-days
5309 (time-subtract (current-time)
5310 (list 0 (* 3600 org-extend-today-until) 0))))
5312 ;;;; Font-Lock stuff, including the activators
5314 (defvar org-mouse-map (make-sparse-keymap))
5315 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5316 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5317 (when org-mouse-1-follows-link
5318 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5319 (when org-tab-follows-link
5320 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5321 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5323 (require 'font-lock)
5325 (defconst org-non-link-chars "]\t\n\r<>")
5326 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5327 "shell" "elisp" "doi" "message"))
5328 (defvar org-link-types-re nil
5329 "Matches a link that has a url-like prefix like \"http:\"")
5330 (defvar org-link-re-with-space nil
5331 "Matches a link with spaces, optional angular brackets around it.")
5332 (defvar org-link-re-with-space2 nil
5333 "Matches a link with spaces, optional angular brackets around it.")
5334 (defvar org-link-re-with-space3 nil
5335 "Matches a link with spaces, only for internal part in bracket links.")
5336 (defvar org-angle-link-re nil
5337 "Matches link with angular brackets, spaces are allowed.")
5338 (defvar org-plain-link-re nil
5339 "Matches plain link, without spaces.")
5340 (defvar org-bracket-link-regexp nil
5341 "Matches a link in double brackets.")
5342 (defvar org-bracket-link-analytic-regexp nil
5343 "Regular expression used to analyze links.
5344 Here is what the match groups contain after a match:
5345 1: http:
5346 2: http
5347 3: path
5348 4: [desc]
5349 5: desc")
5350 (defvar org-bracket-link-analytic-regexp++ nil
5351 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5352 (defvar org-any-link-re nil
5353 "Regular expression matching any link.")
5355 (defconst org-match-sexp-depth 3
5356 "Number of stacked braces for sub/superscript matching.")
5358 (defun org-create-multibrace-regexp (left right n)
5359 "Create a regular expression which will match a balanced sexp.
5360 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5361 as single character strings.
5362 The regexp returned will match the entire expression including the
5363 delimiters. It will also define a single group which contains the
5364 match except for the outermost delimiters. The maximum depth of
5365 stacked delimiters is N. Escaping delimiters is not possible."
5366 (let* ((nothing (concat "[^" left right "]*?"))
5367 (or "\\|")
5368 (re nothing)
5369 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5370 (while (> n 1)
5371 (setq n (1- n)
5372 re (concat re or next)
5373 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5374 (concat left "\\(" re "\\)" right)))
5376 (defvar org-match-substring-regexp
5377 (concat
5378 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5379 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5380 "\\|"
5381 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5382 "\\|"
5383 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5384 "The regular expression matching a sub- or superscript.")
5386 (defvar org-match-substring-with-braces-regexp
5387 (concat
5388 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5389 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5390 "\\)")
5391 "The regular expression matching a sub- or superscript, forcing braces.")
5393 (defun org-make-link-regexps ()
5394 "Update the link regular expressions.
5395 This should be called after the variable `org-link-types' has changed."
5396 (setq org-link-types-re
5397 (concat
5398 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5399 org-link-re-with-space
5400 (concat
5401 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5402 "\\([^" org-non-link-chars " ]"
5403 "[^" org-non-link-chars "]*"
5404 "[^" org-non-link-chars " ]\\)>?")
5405 org-link-re-with-space2
5406 (concat
5407 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5408 "\\([^" org-non-link-chars " ]"
5409 "[^\t\n\r]*"
5410 "[^" org-non-link-chars " ]\\)>?")
5411 org-link-re-with-space3
5412 (concat
5413 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5414 "\\([^" org-non-link-chars " ]"
5415 "[^\t\n\r]*\\)")
5416 org-angle-link-re
5417 (concat
5418 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5419 "\\([^" org-non-link-chars " ]"
5420 "[^" org-non-link-chars "]*"
5421 "\\)>")
5422 org-plain-link-re
5423 (concat
5424 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5425 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5426 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5427 org-bracket-link-regexp
5428 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5429 org-bracket-link-analytic-regexp
5430 (concat
5431 "\\[\\["
5432 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5433 "\\([^]]+\\)"
5434 "\\]"
5435 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5436 "\\]")
5437 org-bracket-link-analytic-regexp++
5438 (concat
5439 "\\[\\["
5440 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5441 "\\([^]]+\\)"
5442 "\\]"
5443 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5444 "\\]")
5445 org-any-link-re
5446 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5447 org-angle-link-re "\\)\\|\\("
5448 org-plain-link-re "\\)")))
5450 (org-make-link-regexps)
5452 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5453 "Regular expression for fast time stamp matching.")
5454 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5455 "Regular expression for fast time stamp matching.")
5456 (defconst org-ts-regexp0
5457 "\\(\\([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 This one does not require the space after the date, so it can be used
5460 on a string that terminates immediately after the date.")
5461 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5462 "Regular expression matching time strings for analysis.")
5463 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5464 "Regular expression matching time stamps, with groups.")
5465 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5466 "Regular expression matching time stamps (also [..]), with groups.")
5467 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5468 "Regular expression matching a time stamp range.")
5469 (defconst org-tr-regexp-both
5470 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5471 "Regular expression matching a time stamp range.")
5472 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5473 org-ts-regexp "\\)?")
5474 "Regular expression matching a time stamp or time stamp range.")
5475 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5476 org-ts-regexp-both "\\)?")
5477 "Regular expression matching a time stamp or time stamp range.
5478 The time stamps may be either active or inactive.")
5480 (defvar org-emph-face nil)
5482 (defun org-do-emphasis-faces (limit)
5483 "Run through the buffer and add overlays to emphasized strings."
5484 (let (rtn a)
5485 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5486 (if (not (= (char-after (match-beginning 3))
5487 (char-after (match-beginning 4))))
5488 (progn
5489 (setq rtn t)
5490 (setq a (assoc (match-string 3) org-emphasis-alist))
5491 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5492 'face
5493 (nth 1 a))
5494 (and (nth 4 a)
5495 (org-remove-flyspell-overlays-in
5496 (match-beginning 0) (match-end 0)))
5497 (add-text-properties (match-beginning 2) (match-end 2)
5498 '(font-lock-multiline t org-emphasis t))
5499 (when org-hide-emphasis-markers
5500 (add-text-properties (match-end 4) (match-beginning 5)
5501 '(invisible org-link))
5502 (add-text-properties (match-beginning 3) (match-end 3)
5503 '(invisible org-link)))))
5504 (backward-char 1))
5505 rtn))
5507 (defun org-emphasize (&optional char)
5508 "Insert or change an emphasis, i.e. a font like bold or italic.
5509 If there is an active region, change that region to a new emphasis.
5510 If there is no region, just insert the marker characters and position
5511 the cursor between them.
5512 CHAR should be either the marker character, or the first character of the
5513 HTML tag associated with that emphasis. If CHAR is a space, the means
5514 to remove the emphasis of the selected region.
5515 If char is not given (for example in an interactive call) it
5516 will be prompted for."
5517 (interactive)
5518 (let ((eal org-emphasis-alist) e det
5519 (erc org-emphasis-regexp-components)
5520 (prompt "")
5521 (string "") beg end move tag c s)
5522 (if (org-region-active-p)
5523 (setq beg (region-beginning) end (region-end)
5524 string (buffer-substring beg end))
5525 (setq move t))
5527 (while (setq e (pop eal))
5528 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5529 c (aref tag 0))
5530 (push (cons c (string-to-char (car e))) det)
5531 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5532 (substring tag 1)))))
5533 (setq det (nreverse det))
5534 (unless char
5535 (message "%s" (concat "Emphasis marker or tag:" prompt))
5536 (setq char (read-char-exclusive)))
5537 (setq char (or (cdr (assoc char det)) char))
5538 (if (equal char ?\ )
5539 (setq s "" move nil)
5540 (unless (assoc (char-to-string char) org-emphasis-alist)
5541 (error "No such emphasis marker: \"%c\"" char))
5542 (setq s (char-to-string char)))
5543 (while (and (> (length string) 1)
5544 (equal (substring string 0 1) (substring string -1))
5545 (assoc (substring string 0 1) org-emphasis-alist))
5546 (setq string (substring string 1 -1)))
5547 (setq string (concat s string s))
5548 (if beg (delete-region beg end))
5549 (unless (or (bolp)
5550 (string-match (concat "[" (nth 0 erc) "\n]")
5551 (char-to-string (char-before (point)))))
5552 (insert " "))
5553 (unless (or (eobp)
5554 (string-match (concat "[" (nth 1 erc) "\n]")
5555 (char-to-string (char-after (point)))))
5556 (insert " ") (backward-char 1))
5557 (insert string)
5558 (and move (backward-char 1))))
5560 (defconst org-nonsticky-props
5561 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5563 (defsubst org-rear-nonsticky-at (pos)
5564 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5566 (defun org-activate-plain-links (limit)
5567 "Run through the buffer and add overlays to links."
5568 (catch 'exit
5569 (let (f hl)
5570 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5571 (not (org-in-src-block-p)))
5572 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5573 (setq f (get-text-property (match-beginning 0) 'face))
5574 (setq hl (org-match-string-no-properties 0))
5575 (if (or (eq f 'org-tag)
5576 (and (listp f) (memq 'org-tag f)))
5578 (add-text-properties (match-beginning 0) (match-end 0)
5579 (list 'mouse-face 'highlight
5580 'face 'org-link
5581 'htmlize-link `(:uri ,hl)
5582 'keymap org-mouse-map))
5583 (org-rear-nonsticky-at (match-end 0)))
5584 t))))
5586 (defun org-activate-code (limit)
5587 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5588 (progn
5589 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5590 (remove-text-properties (match-beginning 0) (match-end 0)
5591 '(display t invisible t intangible t))
5592 t)))
5594 (defcustom org-src-fontify-natively nil
5595 "When non-nil, fontify code in code blocks."
5596 :type 'boolean
5597 :version "24.1"
5598 :group 'org-appearance
5599 :group 'org-babel)
5601 (defcustom org-allow-promoting-top-level-subtree nil
5602 "When non-nil, allow promoting a top level subtree.
5603 The leading star of the top level headline will be replaced
5604 by a #."
5605 :type 'boolean
5606 :version "24.1"
5607 :group 'org-appearance)
5609 (defun org-fontify-meta-lines-and-blocks (limit)
5610 (condition-case nil
5611 (org-fontify-meta-lines-and-blocks-1 limit)
5612 (error (message "org-mode fontification error"))))
5614 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5615 "Fontify #+ lines and blocks, in the correct ways."
5616 (let ((case-fold-search t))
5617 (if (re-search-forward
5618 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5619 limit t)
5620 (let ((beg (match-beginning 0))
5621 (block-start (match-end 0))
5622 (block-end nil)
5623 (lang (match-string 7))
5624 (beg1 (line-beginning-position 2))
5625 (dc1 (downcase (match-string 2)))
5626 (dc3 (downcase (match-string 3)))
5627 end end1 quoting block-type ovl)
5628 (cond
5629 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5630 ;; a single line of backend-specific content
5631 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5632 (remove-text-properties (match-beginning 0) (match-end 0)
5633 '(display t invisible t intangible t))
5634 (add-text-properties (match-beginning 1) (match-end 3)
5635 '(font-lock-fontified t face org-meta-line))
5636 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5637 '(font-lock-fontified t face org-block))
5638 ; for backend-specific code
5640 ((and (match-end 4) (equal dc3 "+begin"))
5641 ;; Truly a block
5642 (setq block-type (downcase (match-string 5))
5643 quoting (member block-type org-protecting-blocks))
5644 (when (re-search-forward
5645 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5646 nil t) ;; on purpose, we look further than LIMIT
5647 (setq end (min (point-max) (match-end 0))
5648 end1 (min (point-max) (1- (match-beginning 0))))
5649 (setq block-end (match-beginning 0))
5650 (when quoting
5651 (remove-text-properties beg end
5652 '(display t invisible t intangible t)))
5653 (add-text-properties
5654 beg end
5655 '(font-lock-fontified t font-lock-multiline t))
5656 (add-text-properties beg beg1 '(face org-meta-line))
5657 (add-text-properties end1 (min (point-max) (1+ end))
5658 '(face org-meta-line)) ; for end_src
5659 (cond
5660 ((and lang (not (string= lang "")) org-src-fontify-natively)
5661 (org-src-font-lock-fontify-block lang block-start block-end)
5662 ;; remove old background overlays
5663 (mapc (lambda (ov)
5664 (if (eq (overlay-get ov 'face) 'org-block-background)
5665 (delete-overlay ov)))
5666 (overlays-at (/ (+ beg1 block-end) 2)))
5667 ;; add a background overlay
5668 (setq ovl (make-overlay beg1 block-end))
5669 (overlay-put ovl 'face 'org-block-background)
5670 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5671 (quoting
5672 (add-text-properties beg1 (min (point-max) (1+ end1))
5673 '(face org-block))) ; end of source block
5674 ((not org-fontify-quote-and-verse-blocks))
5675 ((string= block-type "quote")
5676 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5677 ((string= block-type "verse")
5678 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5679 (add-text-properties beg beg1 '(face org-block-begin-line))
5680 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5681 '(face org-block-end-line))
5683 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5684 (add-text-properties
5685 beg (match-end 3)
5686 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5687 '(font-lock-fontified t invisible t)
5688 '(font-lock-fontified t face org-document-info-keyword)))
5689 (add-text-properties
5690 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5691 (if (string-equal dc1 "+title:")
5692 '(font-lock-fontified t face org-document-title)
5693 '(font-lock-fontified t face org-document-info))))
5694 ((or (equal dc1 "+results")
5695 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5696 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5697 "+call:" "+header:" "+headers:" "+name:"))
5698 (and (match-end 4) (equal dc3 "+attr")))
5699 (add-text-properties
5700 beg (match-end 0)
5701 '(font-lock-fontified t face org-meta-line))
5703 ((member dc3 '(" " ""))
5704 (add-text-properties
5705 beg (match-end 0)
5706 '(font-lock-fontified t face font-lock-comment-face)))
5707 ((not (member (char-after beg) '(?\ ?\t)))
5708 ;; just any other in-buffer setting, but not indented
5709 (add-text-properties
5710 beg (match-end 0)
5711 '(font-lock-fontified t face org-meta-line))
5713 (t nil))))))
5715 (defun org-activate-angle-links (limit)
5716 "Run through the buffer and add overlays to links."
5717 (if (and (re-search-forward org-angle-link-re limit t)
5718 (not (org-in-src-block-p)))
5719 (progn
5720 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5721 (add-text-properties (match-beginning 0) (match-end 0)
5722 (list 'mouse-face 'highlight
5723 'keymap org-mouse-map))
5724 (org-rear-nonsticky-at (match-end 0))
5725 t)))
5727 (defun org-activate-footnote-links (limit)
5728 "Run through the buffer and add overlays to footnotes."
5729 (let ((fn (org-footnote-next-reference-or-definition limit)))
5730 (when fn
5731 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5732 (org-remove-flyspell-overlays-in beg end)
5733 (add-text-properties beg end
5734 (list 'mouse-face 'highlight
5735 'keymap org-mouse-map
5736 'help-echo
5737 (if (= (point-at-bol) beg)
5738 "Footnote definition"
5739 "Footnote reference")
5740 'font-lock-fontified t
5741 'font-lock-multiline t
5742 'face 'org-footnote))))))
5744 (defun org-activate-bracket-links (limit)
5745 "Run through the buffer and add overlays to bracketed links."
5746 (if (and (re-search-forward org-bracket-link-regexp limit t)
5747 (not (org-in-src-block-p)))
5748 (let* ((hl (org-match-string-no-properties 1))
5749 (help (concat "LINK: " hl))
5750 ;; FIXME: Above we should remove the escapes. But that
5751 ;; requires another match, protecting match data, a lot
5752 ;; of overhead for font-lock.
5753 (ip (org-maybe-intangible
5754 (list 'invisible 'org-link
5755 'keymap org-mouse-map 'mouse-face 'highlight
5756 'font-lock-multiline t 'help-echo help
5757 'htmlize-link `(:uri ,hl))))
5758 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5759 'font-lock-multiline t 'help-echo help
5760 'htmlize-link `(:uri ,hl))))
5761 ;; We need to remove the invisible property here. Table narrowing
5762 ;; may have made some of this invisible.
5763 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5764 (remove-text-properties (match-beginning 0) (match-end 0)
5765 '(invisible nil))
5766 (if (match-end 3)
5767 (progn
5768 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5769 (org-rear-nonsticky-at (match-beginning 3))
5770 (add-text-properties (match-beginning 3) (match-end 3) vp)
5771 (org-rear-nonsticky-at (match-end 3))
5772 (add-text-properties (match-end 3) (match-end 0) ip)
5773 (org-rear-nonsticky-at (match-end 0)))
5774 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5775 (org-rear-nonsticky-at (match-beginning 1))
5776 (add-text-properties (match-beginning 1) (match-end 1) vp)
5777 (org-rear-nonsticky-at (match-end 1))
5778 (add-text-properties (match-end 1) (match-end 0) ip)
5779 (org-rear-nonsticky-at (match-end 0)))
5780 t)))
5782 (defun org-activate-dates (limit)
5783 "Run through the buffer and add overlays to dates."
5784 (if (re-search-forward org-tsr-regexp-both limit t)
5785 (progn
5786 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5787 (add-text-properties (match-beginning 0) (match-end 0)
5788 (list 'mouse-face 'highlight
5789 'keymap org-mouse-map))
5790 (org-rear-nonsticky-at (match-end 0))
5791 (when org-display-custom-times
5792 (if (match-end 3)
5793 (org-display-custom-time (match-beginning 3) (match-end 3)))
5794 (org-display-custom-time (match-beginning 1) (match-end 1)))
5795 t)))
5797 (defvar org-target-link-regexp nil
5798 "Regular expression matching radio targets in plain text.")
5799 (make-variable-buffer-local 'org-target-link-regexp)
5800 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5801 "Regular expression matching a link target.")
5802 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5803 "Regular expression matching a radio target.")
5804 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5805 "Regular expression matching any target.")
5807 (defun org-activate-target-links (limit)
5808 "Run through the buffer and add overlays to target matches."
5809 (when org-target-link-regexp
5810 (let ((case-fold-search t))
5811 (if (re-search-forward org-target-link-regexp limit t)
5812 (progn
5813 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5814 (add-text-properties (match-beginning 0) (match-end 0)
5815 (list 'mouse-face 'highlight
5816 'keymap org-mouse-map
5817 'help-echo "Radio target link"
5818 'org-linked-text t))
5819 (org-rear-nonsticky-at (match-end 0))
5820 t)))))
5822 (defun org-update-radio-target-regexp ()
5823 "Find all radio targets in this file and update the regular expression."
5824 (interactive)
5825 (when (memq 'radio org-activate-links)
5826 (setq org-target-link-regexp
5827 (org-make-target-link-regexp (org-all-targets 'radio)))
5828 (org-restart-font-lock)))
5830 (defun org-hide-wide-columns (limit)
5831 (let (s e)
5832 (setq s (text-property-any (point) (or limit (point-max))
5833 'org-cwidth t))
5834 (when s
5835 (setq e (next-single-property-change s 'org-cwidth))
5836 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5837 (goto-char e)
5838 t)))
5840 (defvar org-match-substring-regexp)
5841 (defvar org-match-substring-with-braces-regexp)
5843 (defun org-restart-font-lock ()
5844 "Restart `font-lock-mode', to force refontification."
5845 (when (and (boundp 'font-lock-mode) font-lock-mode)
5846 (font-lock-mode -1)
5847 (font-lock-mode 1)))
5849 (defun org-all-targets (&optional radio)
5850 "Return a list of all targets in this file.
5851 When optional argument RADIO is non-nil, only find radio
5852 targets."
5853 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5854 (save-excursion
5855 (goto-char (point-min))
5856 (while (re-search-forward re nil t)
5857 ;; Make sure point is really within the object.
5858 (backward-char)
5859 (let ((obj (org-element-context)))
5860 (when (memq (org-element-type obj) '(radio-target target))
5861 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5862 rtn)))
5864 (defun org-make-target-link-regexp (targets)
5865 "Make regular expression matching all strings in TARGETS.
5866 The regular expression finds the targets also if there is a line break
5867 between words."
5868 (and targets
5869 (concat
5870 "\\<\\("
5871 (mapconcat
5872 (lambda (x)
5873 (setq x (regexp-quote x))
5874 (while (string-match " +" x)
5875 (setq x (replace-match "\\s-+" t t x)))
5877 targets
5878 "\\|")
5879 "\\)\\>")))
5881 (defun org-activate-tags (limit)
5882 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5883 (progn
5884 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5885 (add-text-properties (match-beginning 1) (match-end 1)
5886 (list 'mouse-face 'highlight
5887 'keymap org-mouse-map))
5888 (org-rear-nonsticky-at (match-end 1))
5889 t)))
5891 (defun org-outline-level ()
5892 "Compute the outline level of the heading at point.
5893 If this is called at a normal headline, the level is the number of stars.
5894 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5895 (save-excursion
5896 (if (not (condition-case nil
5897 (org-back-to-heading t)
5898 (error nil)))
5900 (looking-at org-outline-regexp)
5901 (1- (- (match-end 0) (match-beginning 0))))))
5903 (defvar org-font-lock-keywords nil)
5905 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5906 "Regular expression matching a property line.")
5908 (defvar org-font-lock-hook nil
5909 "Functions to be called for special font lock stuff.")
5911 (defvar org-font-lock-set-keywords-hook nil
5912 "Functions that can manipulate `org-font-lock-extra-keywords'.
5913 This is called after `org-font-lock-extra-keywords' is defined, but before
5914 it is installed to be used by font lock. This can be useful if something
5915 needs to be inserted at a specific position in the font-lock sequence.")
5917 (defun org-font-lock-hook (limit)
5918 "Run `org-font-lock-hook' within LIMIT."
5919 (run-hook-with-args 'org-font-lock-hook limit))
5921 (defun org-set-font-lock-defaults ()
5922 "Set font lock defaults for the current buffer."
5923 (let* ((em org-fontify-emphasized-text)
5924 (lk org-activate-links)
5925 (org-font-lock-extra-keywords
5926 (list
5927 ;; Call the hook
5928 '(org-font-lock-hook)
5929 ;; Headlines
5930 `(,(if org-fontify-whole-heading-line
5931 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5932 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5933 (1 (org-get-level-face 1))
5934 (2 (org-get-level-face 2))
5935 (3 (org-get-level-face 3)))
5936 ;; Table lines
5937 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5938 (1 'org-table t))
5939 ;; Table internals
5940 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5941 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5942 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5943 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5944 ;; Drawers
5945 (list org-drawer-regexp '(0 'org-special-keyword t))
5946 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5947 ;; Properties
5948 (list org-property-re
5949 '(1 'org-special-keyword t)
5950 '(3 'org-property-value t))
5951 ;; Links
5952 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5953 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5954 (if (memq 'plain lk) '(org-activate-plain-links))
5955 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5956 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5957 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5958 (if (memq 'footnote lk) '(org-activate-footnote-links))
5959 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5960 '(org-hide-wide-columns (0 nil append))
5961 ;; TODO keyword
5962 (list (format org-heading-keyword-regexp-format
5963 org-todo-regexp)
5964 '(2 (org-get-todo-face 2) t))
5965 ;; DONE
5966 (if org-fontify-done-headline
5967 (list (format org-heading-keyword-regexp-format
5968 (concat
5969 "\\(?:"
5970 (mapconcat 'regexp-quote org-done-keywords "\\|")
5971 "\\)"))
5972 '(2 'org-headline-done t))
5973 nil)
5974 ;; Priorities
5975 '(org-font-lock-add-priority-faces)
5976 ;; Tags
5977 '(org-font-lock-add-tag-faces)
5978 ;; Special keywords
5979 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5980 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5981 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5982 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5983 ;; Emphasis
5984 (if em
5985 (if (featurep 'xemacs)
5986 '(org-do-emphasis-faces (0 nil append))
5987 '(org-do-emphasis-faces)))
5988 ;; Checkboxes
5989 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5990 1 'org-checkbox prepend)
5991 (if (cdr (assq 'checkbox org-list-automatic-rules))
5992 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5993 (0 (org-get-checkbox-statistics-face) t)))
5994 ;; Description list items
5995 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5996 1 'org-list-dt prepend)
5997 ;; ARCHIVEd headings
5998 (list (concat
5999 org-outline-regexp-bol
6000 "\\(.*:" org-archive-tag ":.*\\)")
6001 '(1 'org-archived prepend))
6002 ;; Specials
6003 '(org-fontify-entities)
6004 '(org-raise-scripts)
6005 ;; Code
6006 '(org-activate-code (1 'org-code t))
6007 ;; COMMENT
6008 (list (format org-heading-keyword-regexp-format
6009 (concat "\\("
6010 org-comment-string "\\|" org-quote-string
6011 "\\)"))
6012 '(2 'org-special-keyword t))
6013 ;; Blocks and meta lines
6014 '(org-fontify-meta-lines-and-blocks)
6016 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6017 (run-hooks 'org-font-lock-set-keywords-hook)
6018 ;; Now set the full font-lock-keywords
6019 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6020 (org-set-local 'font-lock-defaults
6021 '(org-font-lock-keywords t nil nil backward-paragraph))
6022 (kill-local-variable 'font-lock-keywords) nil))
6024 (defun org-toggle-pretty-entities ()
6025 "Toggle the composition display of entities as UTF8 characters."
6026 (interactive)
6027 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6028 (org-restart-font-lock)
6029 (if org-pretty-entities
6030 (message "Entities are displayed as UTF8 characters")
6031 (save-restriction
6032 (widen)
6033 (org-decompose-region (point-min) (point-max))
6034 (message "Entities are displayed plain"))))
6036 (defvar org-custom-properties-overlays nil
6037 "List of overlays used for custom properties.")
6038 (make-variable-buffer-local 'org-custom-properties-overlays)
6040 (defun org-toggle-custom-properties-visibility ()
6041 "Display or hide properties in `org-custom-properties'."
6042 (interactive)
6043 (if org-custom-properties-overlays
6044 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6045 (setq org-custom-properties-overlays nil))
6046 (unless (not org-custom-properties)
6047 (save-excursion
6048 (save-restriction
6049 (widen)
6050 (goto-char (point-min))
6051 (while (re-search-forward org-property-re nil t)
6052 (mapc (lambda(p)
6053 (when (equal p (substring (match-string 1) 1 -1))
6054 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6055 (overlay-put o 'invisible t)
6056 (overlay-put o 'org-custom-property t)
6057 (push o org-custom-properties-overlays))))
6058 org-custom-properties)))))))
6060 (defun org-fontify-entities (limit)
6061 "Find an entity to fontify."
6062 (let (ee)
6063 (when org-pretty-entities
6064 (catch 'match
6065 (while (re-search-forward
6066 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6067 limit t)
6068 (if (and (not (org-in-indented-comment-line))
6069 (setq ee (org-entity-get (match-string 1)))
6070 (= (length (nth 6 ee)) 1))
6071 (let*
6072 ((end (if (equal (match-string 2) "{}")
6073 (match-end 2)
6074 (match-end 1))))
6075 (add-text-properties
6076 (match-beginning 0) end
6077 (list 'font-lock-fontified t))
6078 (compose-region (match-beginning 0) end
6079 (nth 6 ee) nil)
6080 (backward-char 1)
6081 (throw 'match t))))
6082 nil))))
6084 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6085 "Fontify string S like in Org-mode."
6086 (with-temp-buffer
6087 (insert s)
6088 (let ((org-odd-levels-only odd-levels))
6089 (org-mode)
6090 (font-lock-fontify-buffer)
6091 (buffer-string))))
6093 (defvar org-m nil)
6094 (defvar org-l nil)
6095 (defvar org-f nil)
6096 (defun org-get-level-face (n)
6097 "Get the right face for match N in font-lock matching of headlines."
6098 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6099 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6100 (if org-cycle-level-faces
6101 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6102 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6103 (cond
6104 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6105 ((eq n 2) org-f)
6106 (t (if org-level-color-stars-only nil org-f))))
6109 (defun org-get-todo-face (kwd)
6110 "Get the right face for a TODO keyword KWD.
6111 If KWD is a number, get the corresponding match group."
6112 (if (numberp kwd) (setq kwd (match-string kwd)))
6113 (or (org-face-from-face-or-color
6114 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6115 (and (member kwd org-done-keywords) 'org-done)
6116 'org-todo))
6118 (defun org-face-from-face-or-color (context inherit face-or-color)
6119 "Create a face list that inherits INHERIT, but sets the foreground color.
6120 When FACE-OR-COLOR is not a string, just return it."
6121 (if (stringp face-or-color)
6122 (list :inherit inherit
6123 (cdr (assoc context org-faces-easy-properties))
6124 face-or-color)
6125 face-or-color))
6127 (defun org-font-lock-add-tag-faces (limit)
6128 "Add the special tag faces."
6129 (when (and org-tag-faces org-tags-special-faces-re)
6130 (while (re-search-forward org-tags-special-faces-re limit t)
6131 (add-text-properties (match-beginning 1) (match-end 1)
6132 (list 'face (org-get-tag-face 1)
6133 'font-lock-fontified t))
6134 (backward-char 1))))
6136 (defun org-font-lock-add-priority-faces (limit)
6137 "Add the special priority faces."
6138 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6139 (when (save-match-data (org-at-heading-p))
6140 (add-text-properties
6141 (match-beginning 0) (match-end 0)
6142 (list 'face (or (org-face-from-face-or-color
6143 'priority 'org-priority
6144 (cdr (assoc (char-after (match-beginning 1))
6145 org-priority-faces)))
6146 'org-priority)
6147 'font-lock-fontified t)))))
6149 (defun org-get-tag-face (kwd)
6150 "Get the right face for a TODO keyword KWD.
6151 If KWD is a number, get the corresponding match group."
6152 (if (numberp kwd) (setq kwd (match-string kwd)))
6153 (or (org-face-from-face-or-color
6154 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6155 'org-tag))
6157 (defun org-unfontify-region (beg end &optional maybe_loudly)
6158 "Remove fontification and activation overlays from links."
6159 (font-lock-default-unfontify-region beg end)
6160 (let* ((buffer-undo-list t)
6161 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6162 (inhibit-modification-hooks t)
6163 deactivate-mark buffer-file-name buffer-file-truename)
6164 (org-decompose-region beg end)
6165 (remove-text-properties beg end
6166 '(mouse-face t keymap t org-linked-text t
6167 invisible t intangible t
6168 org-no-flyspell t org-emphasis t))
6169 (org-remove-font-lock-display-properties beg end)))
6171 (defconst org-script-display '(((raise -0.3) (height 0.7))
6172 ((raise 0.3) (height 0.7))
6173 ((raise -0.5))
6174 ((raise 0.5)))
6175 "Display properties for showing superscripts and subscripts.")
6177 (defun org-remove-font-lock-display-properties (beg end)
6178 "Remove specific display properties that have been added by font lock.
6179 The will remove the raise properties that are used to show superscripts
6180 and subscripts."
6181 (let (next prop)
6182 (while (< beg end)
6183 (setq next (next-single-property-change beg 'display nil end)
6184 prop (get-text-property beg 'display))
6185 (if (member prop org-script-display)
6186 (put-text-property beg next 'display nil))
6187 (setq beg next))))
6189 (defun org-raise-scripts (limit)
6190 "Add raise properties to sub/superscripts."
6191 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6192 (if (re-search-forward
6193 (if (eq org-use-sub-superscripts t)
6194 org-match-substring-regexp
6195 org-match-substring-with-braces-regexp)
6196 limit t)
6197 (let* ((pos (point)) table-p comment-p
6198 (mpos (match-beginning 3))
6199 (emph-p (get-text-property mpos 'org-emphasis))
6200 (link-p (get-text-property mpos 'mouse-face))
6201 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6202 (goto-char (point-at-bol))
6203 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6204 comment-p (org-looking-at-p "[ \t]*#"))
6205 (goto-char pos)
6206 ;; FIXME: Should we go back one character here, for a_b^c
6207 ;; (goto-char (1- pos)) ;????????????????????
6208 (if (or comment-p emph-p link-p keyw-p)
6210 (put-text-property (match-beginning 3) (match-end 0)
6211 'display
6212 (if (equal (char-after (match-beginning 2)) ?^)
6213 (nth (if table-p 3 1) org-script-display)
6214 (nth (if table-p 2 0) org-script-display)))
6215 (add-text-properties (match-beginning 2) (match-end 2)
6216 (list 'invisible t
6217 'org-dwidth t 'org-dwidth-n 1))
6218 (if (and (eq (char-after (match-beginning 3)) ?{)
6219 (eq (char-before (match-end 3)) ?}))
6220 (progn
6221 (add-text-properties
6222 (match-beginning 3) (1+ (match-beginning 3))
6223 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6224 (add-text-properties
6225 (1- (match-end 3)) (match-end 3)
6226 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6227 t)))))
6229 ;;;; Visibility cycling, including org-goto and indirect buffer
6231 ;;; Cycling
6233 (defvar org-cycle-global-status nil)
6234 (make-variable-buffer-local 'org-cycle-global-status)
6235 (defvar org-cycle-subtree-status nil)
6236 (make-variable-buffer-local 'org-cycle-subtree-status)
6238 (defvar org-inlinetask-min-level)
6240 ;;;###autoload
6241 (defun org-cycle (&optional arg)
6242 "TAB-action and visibility cycling for Org-mode.
6244 This is the command invoked in Org-mode by the TAB key. Its main purpose
6245 is outline visibility cycling, but it also invokes other actions
6246 in special contexts.
6248 - When this function is called with a prefix argument, rotate the entire
6249 buffer through 3 states (global cycling)
6250 1. OVERVIEW: Show only top-level headlines.
6251 2. CONTENTS: Show all headlines of all levels, but no body text.
6252 3. SHOW ALL: Show everything.
6253 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6254 determined by the variable `org-startup-folded', and by any VISIBILITY
6255 properties in the buffer.
6256 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6257 including any drawers.
6259 - When inside a table, re-align the table and move to the next field.
6261 - When point is at the beginning of a headline, rotate the subtree started
6262 by this line through 3 different states (local cycling)
6263 1. FOLDED: Only the main headline is shown.
6264 2. CHILDREN: The main headline and the direct children are shown.
6265 From this state, you can move to one of the children
6266 and zoom in further.
6267 3. SUBTREE: Show the entire subtree, including body text.
6268 If there is no subtree, switch directly from CHILDREN to FOLDED.
6270 - When point is at the beginning of an empty headline and the variable
6271 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6272 of the headline by demoting and promoting it to likely levels. This
6273 speeds up creation document structure by pressing TAB once or several
6274 times right after creating a new headline.
6276 - When there is a numeric prefix, go up to a heading with level ARG, do
6277 a `show-subtree' and return to the previous cursor position. If ARG
6278 is negative, go up that many levels.
6280 - When point is not at the beginning of a headline, execute the global
6281 binding for TAB, which is re-indenting the line. See the option
6282 `org-cycle-emulate-tab' for details.
6284 - Special case: if point is at the beginning of the buffer and there is
6285 no headline in line 1, this function will act as if called with prefix arg
6286 (C-u TAB, same as S-TAB) also when called without prefix arg.
6287 But only if also the variable `org-cycle-global-at-bob' is t."
6288 (interactive "P")
6289 (org-load-modules-maybe)
6290 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6291 (and org-cycle-level-after-item/entry-creation
6292 (or (org-cycle-level)
6293 (org-cycle-item-indentation))))
6294 (let* (message-log-max ; Don't populate the *Messages* buffer
6295 (limit-level
6296 (or org-cycle-max-level
6297 (and (boundp 'org-inlinetask-min-level)
6298 org-inlinetask-min-level
6299 (1- org-inlinetask-min-level))))
6300 (nstars (and limit-level
6301 (if org-odd-levels-only
6302 (and limit-level (1- (* limit-level 2)))
6303 limit-level)))
6304 (org-outline-regexp
6305 (if (not (derived-mode-p 'org-mode))
6306 outline-regexp
6307 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6308 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6309 (not (looking-at org-outline-regexp))))
6310 (org-cycle-hook
6311 (if bob-special
6312 (delq 'org-optimize-window-after-visibility-change
6313 (copy-sequence org-cycle-hook))
6314 org-cycle-hook))
6315 (pos (point)))
6317 (if (or bob-special (equal arg '(4)))
6318 ;; special case: use global cycling
6319 (setq arg t))
6321 (cond
6323 ((equal arg '(16))
6324 (setq last-command 'dummy)
6325 (org-set-startup-visibility)
6326 (message "Startup visibility, plus VISIBILITY properties"))
6328 ((equal arg '(64))
6329 (show-all)
6330 (message "Entire buffer visible, including drawers"))
6332 ;; Table: enter it or move to the next field.
6333 ((org-at-table-p 'any)
6334 (if (org-at-table.el-p)
6335 (message "Use C-c ' to edit table.el tables")
6336 (if arg (org-table-edit-field t)
6337 (org-table-justify-field-maybe)
6338 (call-interactively 'org-table-next-field))))
6340 ((run-hook-with-args-until-success
6341 'org-tab-after-check-for-table-hook))
6343 ;; Global cycling: delegate to `org-cycle-internal-global'.
6344 ((eq arg t) (org-cycle-internal-global))
6346 ;; Drawers: delegate to `org-flag-drawer'.
6347 ((and org-drawers org-drawer-regexp
6348 (save-excursion
6349 (beginning-of-line 1)
6350 (looking-at org-drawer-regexp)))
6351 (org-flag-drawer ; toggle block visibility
6352 (not (get-char-property (match-end 0) 'invisible))))
6354 ;; Show-subtree, ARG levels up from here.
6355 ((integerp arg)
6356 (save-excursion
6357 (org-back-to-heading)
6358 (outline-up-heading (if (< arg 0) (- arg)
6359 (- (funcall outline-level) arg)))
6360 (org-show-subtree)))
6362 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6363 ((and (featurep 'org-inlinetask)
6364 (org-inlinetask-at-task-p)
6365 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6366 (org-inlinetask-toggle-visibility))
6368 ((org-try-cdlatex-tab))
6370 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6371 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6372 (save-excursion (beginning-of-line 1)
6373 (looking-at org-outline-regexp)))
6374 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6375 (org-cycle-internal-local))
6377 ;; From there: TAB emulation and template completion.
6378 (buffer-read-only (org-back-to-heading))
6380 ((run-hook-with-args-until-success
6381 'org-tab-after-check-for-cycling-hook))
6383 ((org-try-structure-completion))
6385 ((run-hook-with-args-until-success
6386 'org-tab-before-tab-emulation-hook))
6388 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6389 (or (not (bolp))
6390 (not (looking-at org-outline-regexp))))
6391 (call-interactively (global-key-binding "\t")))
6393 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6394 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6395 (or (and (eq org-cycle-emulate-tab 'white)
6396 (= (match-end 0) (point-at-eol)))
6397 (and (eq org-cycle-emulate-tab 'whitestart)
6398 (>= (match-end 0) pos))))
6400 (eq org-cycle-emulate-tab t))
6401 (call-interactively (global-key-binding "\t")))
6403 (t (save-excursion
6404 (org-back-to-heading)
6405 (org-cycle)))))))
6407 (defun org-cycle-internal-global ()
6408 "Do the global cycling action."
6409 ;; Hack to avoid display of messages for .org attachments in Gnus
6410 (let (message-log-max ; Don't populate the *Messages* buffer
6411 (ga (string-match "\\*fontification" (buffer-name))))
6412 (cond
6413 ((and (eq last-command this-command)
6414 (eq org-cycle-global-status 'overview))
6415 ;; We just created the overview - now do table of contents
6416 ;; This can be slow in very large buffers, so indicate action
6417 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6418 (unless ga (message "CONTENTS..."))
6419 (org-content)
6420 (unless ga (message "CONTENTS...done"))
6421 (setq org-cycle-global-status 'contents)
6422 (run-hook-with-args 'org-cycle-hook 'contents))
6424 ((and (eq last-command this-command)
6425 (eq org-cycle-global-status 'contents))
6426 ;; We just showed the table of contents - now show everything
6427 (run-hook-with-args 'org-pre-cycle-hook 'all)
6428 (show-all)
6429 (unless ga (message "SHOW ALL"))
6430 (setq org-cycle-global-status 'all)
6431 (run-hook-with-args 'org-cycle-hook 'all))
6434 ;; Default action: go to overview
6435 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6436 (org-overview)
6437 (unless ga (message "OVERVIEW"))
6438 (setq org-cycle-global-status 'overview)
6439 (run-hook-with-args 'org-cycle-hook 'overview)))))
6441 (defun org-cycle-internal-local ()
6442 "Do the local cycling action."
6443 (let (message-log-max ; Don't populate the *Messages* buffer
6444 (goal-column 0) eoh eol eos has-children children-skipped struct)
6445 ;; First, determine end of headline (EOH), end of subtree or item
6446 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6447 (save-excursion
6448 (if (org-at-item-p)
6449 (progn
6450 (beginning-of-line)
6451 (setq struct (org-list-struct))
6452 (setq eoh (point-at-eol))
6453 (setq eos (org-list-get-item-end-before-blank (point) struct))
6454 (setq has-children (org-list-has-child-p (point) struct)))
6455 (org-back-to-heading)
6456 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6457 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6458 (setq has-children
6459 (or (save-excursion
6460 (let ((level (funcall outline-level)))
6461 (outline-next-heading)
6462 (and (org-at-heading-p t)
6463 (> (funcall outline-level) level))))
6464 (save-excursion
6465 (org-list-search-forward (org-item-beginning-re) eos t)))))
6466 ;; Determine end invisible part of buffer (EOL)
6467 (beginning-of-line 2)
6468 ;; XEmacs doesn't have `next-single-char-property-change'
6469 (if (featurep 'xemacs)
6470 (while (and (not (eobp)) ;; this is like `next-line'
6471 (get-char-property (1- (point)) 'invisible))
6472 (beginning-of-line 2))
6473 (while (and (not (eobp)) ;; this is like `next-line'
6474 (get-char-property (1- (point)) 'invisible))
6475 (goto-char (next-single-char-property-change (point) 'invisible))
6476 (and (eolp) (beginning-of-line 2))))
6477 (setq eol (point)))
6478 ;; Find out what to do next and set `this-command'
6479 (cond
6480 ((= eos eoh)
6481 ;; Nothing is hidden behind this heading
6482 (unless (org-before-first-heading-p)
6483 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6484 (message "EMPTY ENTRY")
6485 (setq org-cycle-subtree-status nil)
6486 (save-excursion
6487 (goto-char eos)
6488 (outline-next-heading)
6489 (if (outline-invisible-p) (org-flag-heading nil))))
6490 ((and (or (>= eol eos)
6491 (not (string-match "\\S-" (buffer-substring eol eos))))
6492 (or has-children
6493 (not (setq children-skipped
6494 org-cycle-skip-children-state-if-no-children))))
6495 ;; Entire subtree is hidden in one line: children view
6496 (unless (org-before-first-heading-p)
6497 (run-hook-with-args 'org-pre-cycle-hook 'children))
6498 (if (org-at-item-p)
6499 (org-list-set-item-visibility (point-at-bol) struct 'children)
6500 (org-show-entry)
6501 (org-with-limited-levels (show-children))
6502 ;; FIXME: This slows down the func way too much.
6503 ;; How keep drawers hidden in subtree anyway?
6504 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6505 ;; (org-cycle-hide-drawers 'subtree))
6507 ;; Fold every list in subtree to top-level items.
6508 (when (eq org-cycle-include-plain-lists 'integrate)
6509 (save-excursion
6510 (org-back-to-heading)
6511 (while (org-list-search-forward (org-item-beginning-re) eos t)
6512 (beginning-of-line 1)
6513 (let* ((struct (org-list-struct))
6514 (prevs (org-list-prevs-alist struct))
6515 (end (org-list-get-bottom-point struct)))
6516 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6517 (org-list-get-all-items (point) struct prevs))
6518 (goto-char end))))))
6519 (message "CHILDREN")
6520 (save-excursion
6521 (goto-char eos)
6522 (outline-next-heading)
6523 (if (outline-invisible-p) (org-flag-heading nil)))
6524 (setq org-cycle-subtree-status 'children)
6525 (unless (org-before-first-heading-p)
6526 (run-hook-with-args 'org-cycle-hook 'children)))
6527 ((or children-skipped
6528 (and (eq last-command this-command)
6529 (eq org-cycle-subtree-status 'children)))
6530 ;; We just showed the children, or no children are there,
6531 ;; now show everything.
6532 (unless (org-before-first-heading-p)
6533 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6534 (outline-flag-region eoh eos nil)
6535 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6536 (setq org-cycle-subtree-status 'subtree)
6537 (unless (org-before-first-heading-p)
6538 (run-hook-with-args 'org-cycle-hook 'subtree)))
6540 ;; Default action: hide the subtree.
6541 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6542 (outline-flag-region eoh eos t)
6543 (message "FOLDED")
6544 (setq org-cycle-subtree-status 'folded)
6545 (unless (org-before-first-heading-p)
6546 (run-hook-with-args 'org-cycle-hook 'folded))))))
6548 ;;;###autoload
6549 (defun org-global-cycle (&optional arg)
6550 "Cycle the global visibility. For details see `org-cycle'.
6551 With \\[universal-argument] prefix arg, switch to startup visibility.
6552 With a numeric prefix, show all headlines up to that level."
6553 (interactive "P")
6554 (let ((org-cycle-include-plain-lists
6555 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6556 (cond
6557 ((integerp arg)
6558 (show-all)
6559 (hide-sublevels arg)
6560 (setq org-cycle-global-status 'contents))
6561 ((equal arg '(4))
6562 (org-set-startup-visibility)
6563 (message "Startup visibility, plus VISIBILITY properties."))
6565 (org-cycle '(4))))))
6567 (defun org-set-startup-visibility ()
6568 "Set the visibility required by startup options and properties."
6569 (cond
6570 ((eq org-startup-folded t)
6571 (org-cycle '(4)))
6572 ((eq org-startup-folded 'content)
6573 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6574 (org-cycle '(4)) (org-cycle '(4)))))
6575 (unless (eq org-startup-folded 'showeverything)
6576 (if org-hide-block-startup (org-hide-block-all))
6577 (org-set-visibility-according-to-property 'no-cleanup)
6578 (org-cycle-hide-archived-subtrees 'all)
6579 (org-cycle-hide-drawers 'all)
6580 (org-cycle-show-empty-lines t)))
6582 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6583 "Switch subtree visibilities according to :VISIBILITY: property."
6584 (interactive)
6585 (let (org-show-entry-below state)
6586 (save-excursion
6587 (goto-char (point-min))
6588 (while (re-search-forward
6589 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6590 nil t)
6591 (setq state (match-string 1))
6592 (save-excursion
6593 (org-back-to-heading t)
6594 (hide-subtree)
6595 (org-reveal)
6596 (cond
6597 ((equal state '("fold" "folded"))
6598 (hide-subtree))
6599 ((equal state "children")
6600 (org-show-hidden-entry)
6601 (show-children))
6602 ((equal state "content")
6603 (save-excursion
6604 (save-restriction
6605 (org-narrow-to-subtree)
6606 (org-content))))
6607 ((member state '("all" "showall"))
6608 (show-subtree)))))
6609 (unless no-cleanup
6610 (org-cycle-hide-archived-subtrees 'all)
6611 (org-cycle-hide-drawers 'all)
6612 (org-cycle-show-empty-lines 'all)))))
6614 ;; This function uses outline-regexp instead of the more fundamental
6615 ;; org-outline-regexp so that org-cycle-global works outside of Org
6616 ;; buffers, where outline-regexp is needed.
6617 (defun org-overview ()
6618 "Switch to overview mode, showing only top-level headlines.
6619 Really, this shows all headlines with level equal or greater than the level
6620 of the first headline in the buffer. This is important, because if the
6621 first headline is not level one, then (hide-sublevels 1) gives confusing
6622 results."
6623 (interactive)
6624 (let ((level (save-excursion
6625 (goto-char (point-min))
6626 (if (re-search-forward (concat "^" outline-regexp) nil t)
6627 (progn
6628 (goto-char (match-beginning 0))
6629 (funcall outline-level))))))
6630 (and level (hide-sublevels level))))
6632 (defun org-content (&optional arg)
6633 "Show all headlines in the buffer, like a table of contents.
6634 With numerical argument N, show content up to level N."
6635 (interactive "P")
6636 (save-excursion
6637 ;; Visit all headings and show their offspring
6638 (and (integerp arg) (org-overview))
6639 (goto-char (point-max))
6640 (catch 'exit
6641 (while (and (progn (condition-case nil
6642 (outline-previous-visible-heading 1)
6643 (error (goto-char (point-min))))
6645 (looking-at org-outline-regexp))
6646 (if (integerp arg)
6647 (show-children (1- arg))
6648 (show-branches))
6649 (if (bobp) (throw 'exit nil))))))
6652 (defun org-optimize-window-after-visibility-change (state)
6653 "Adjust the window after a change in outline visibility.
6654 This function is the default value of the hook `org-cycle-hook'."
6655 (when (get-buffer-window (current-buffer))
6656 (cond
6657 ((eq state 'content) nil)
6658 ((eq state 'all) nil)
6659 ((eq state 'folded) nil)
6660 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6661 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6663 (defun org-remove-empty-overlays-at (pos)
6664 "Remove outline overlays that do not contain non-white stuff."
6665 (mapc
6666 (lambda (o)
6667 (and (eq 'outline (overlay-get o 'invisible))
6668 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6669 (overlay-end o))))
6670 (delete-overlay o)))
6671 (overlays-at pos)))
6673 (defun org-clean-visibility-after-subtree-move ()
6674 "Fix visibility issues after moving a subtree."
6675 ;; First, find a reasonable region to look at:
6676 ;; Start two siblings above, end three below
6677 (let* ((beg (save-excursion
6678 (and (org-get-last-sibling)
6679 (org-get-last-sibling))
6680 (point)))
6681 (end (save-excursion
6682 (and (org-get-next-sibling)
6683 (org-get-next-sibling)
6684 (org-get-next-sibling))
6685 (if (org-at-heading-p)
6686 (point-at-eol)
6687 (point))))
6688 (level (looking-at "\\*+"))
6689 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6690 (save-excursion
6691 (save-restriction
6692 (narrow-to-region beg end)
6693 (when re
6694 ;; Properly fold already folded siblings
6695 (goto-char (point-min))
6696 (while (re-search-forward re nil t)
6697 (if (and (not (outline-invisible-p))
6698 (save-excursion
6699 (goto-char (point-at-eol)) (outline-invisible-p)))
6700 (hide-entry))))
6701 (org-cycle-show-empty-lines 'overview)
6702 (org-cycle-hide-drawers 'overview)))))
6704 (defun org-cycle-show-empty-lines (state)
6705 "Show empty lines above all visible headlines.
6706 The region to be covered depends on STATE when called through
6707 `org-cycle-hook'. Lisp program can use t for STATE to get the
6708 entire buffer covered. Note that an empty line is only shown if there
6709 are at least `org-cycle-separator-lines' empty lines before the headline."
6710 (when (not (= org-cycle-separator-lines 0))
6711 (save-excursion
6712 (let* ((n (abs org-cycle-separator-lines))
6713 (re (cond
6714 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6715 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6716 (t (let ((ns (number-to-string (- n 2))))
6717 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6718 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6719 beg end b e)
6720 (cond
6721 ((memq state '(overview contents t))
6722 (setq beg (point-min) end (point-max)))
6723 ((memq state '(children folded))
6724 (setq beg (point) end (progn (org-end-of-subtree t t)
6725 (beginning-of-line 2)
6726 (point)))))
6727 (when beg
6728 (goto-char beg)
6729 (while (re-search-forward re end t)
6730 (unless (get-char-property (match-end 1) 'invisible)
6731 (setq e (match-end 1))
6732 (if (< org-cycle-separator-lines 0)
6733 (setq b (save-excursion
6734 (goto-char (match-beginning 0))
6735 (org-back-over-empty-lines)
6736 (if (save-excursion
6737 (goto-char (max (point-min) (1- (point))))
6738 (org-at-heading-p))
6739 (1- (point))
6740 (point))))
6741 (setq b (match-beginning 1)))
6742 (outline-flag-region b e nil)))))))
6743 ;; Never hide empty lines at the end of the file.
6744 (save-excursion
6745 (goto-char (point-max))
6746 (outline-previous-heading)
6747 (outline-end-of-heading)
6748 (if (and (looking-at "[ \t\n]+")
6749 (= (match-end 0) (point-max)))
6750 (outline-flag-region (point) (match-end 0) nil))))
6752 (defun org-show-empty-lines-in-parent ()
6753 "Move to the parent and re-show empty lines before visible headlines."
6754 (save-excursion
6755 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6756 (org-cycle-show-empty-lines context))))
6758 (defun org-files-list ()
6759 "Return `org-agenda-files' list, plus all open org-mode files.
6760 This is useful for operations that need to scan all of a user's
6761 open and agenda-wise Org files."
6762 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6763 (dolist (buf (buffer-list))
6764 (with-current-buffer buf
6765 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6766 (let ((file (expand-file-name (buffer-file-name))))
6767 (unless (member file files)
6768 (push file files))))))
6769 files))
6771 (defsubst org-entry-beginning-position ()
6772 "Return the beginning position of the current entry."
6773 (save-excursion (outline-back-to-heading t) (point)))
6775 (defsubst org-entry-end-position ()
6776 "Return the end position of the current entry."
6777 (save-excursion (outline-next-heading) (point)))
6779 (defun org-cycle-hide-drawers (state)
6780 "Re-hide all drawers after a visibility state change."
6781 (when (and (derived-mode-p 'org-mode)
6782 (not (memq state '(overview folded contents))))
6783 (save-excursion
6784 (let* ((globalp (memq state '(contents all)))
6785 (beg (if globalp (point-min) (point)))
6786 (end (if globalp (point-max)
6787 (if (eq state 'children)
6788 (save-excursion (outline-next-heading) (point))
6789 (org-end-of-subtree t)))))
6790 (goto-char beg)
6791 (while (re-search-forward org-drawer-regexp end t)
6792 (org-flag-drawer t))))))
6794 (defun org-cycle-hide-inline-tasks (state)
6795 "Re-hide inline task when switching to 'contents visibility state."
6796 (when (and (eq state 'contents)
6797 (boundp 'org-inlinetask-min-level)
6798 org-inlinetask-min-level)
6799 (hide-sublevels (1- org-inlinetask-min-level))))
6801 (defun org-flag-drawer (flag)
6802 "When FLAG is non-nil, hide the drawer we are within.
6803 Otherwise make it visible."
6804 (save-excursion
6805 (beginning-of-line 1)
6806 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6807 (let ((b (match-end 0)))
6808 (if (re-search-forward
6809 "^[ \t]*:END:"
6810 (save-excursion (outline-next-heading) (point)) t)
6811 (outline-flag-region b (point-at-eol) flag)
6812 (error ":END: line missing at position %s" b))))))
6814 (defun org-subtree-end-visible-p ()
6815 "Is the end of the current subtree visible?"
6816 (pos-visible-in-window-p
6817 (save-excursion (org-end-of-subtree t) (point))))
6819 (defun org-first-headline-recenter (&optional N)
6820 "Move cursor to the first headline and recenter the headline.
6821 Optional argument N means put the headline into the Nth line of the window."
6822 (goto-char (point-min))
6823 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6824 (beginning-of-line)
6825 (recenter (prefix-numeric-value N))))
6827 ;;; Saving and restoring visibility
6829 (defun org-outline-overlay-data (&optional use-markers)
6830 "Return a list of the locations of all outline overlays.
6831 These are overlays with the `invisible' property value `outline'.
6832 The return value is a list of cons cells, with start and stop
6833 positions for each overlay.
6834 If USE-MARKERS is set, return the positions as markers."
6835 (let (beg end)
6836 (save-excursion
6837 (save-restriction
6838 (widen)
6839 (delq nil
6840 (mapcar (lambda (o)
6841 (when (eq (overlay-get o 'invisible) 'outline)
6842 (setq beg (overlay-start o)
6843 end (overlay-end o))
6844 (and beg end (> end beg)
6845 (if use-markers
6846 (cons (move-marker (make-marker) beg)
6847 (move-marker (make-marker) end))
6848 (cons beg end)))))
6849 (overlays-in (point-min) (point-max))))))))
6851 (defun org-set-outline-overlay-data (data)
6852 "Create visibility overlays for all positions in DATA.
6853 DATA should have been made by `org-outline-overlay-data'."
6854 (let (o)
6855 (save-excursion
6856 (save-restriction
6857 (widen)
6858 (show-all)
6859 (mapc (lambda (c)
6860 (outline-flag-region (car c) (cdr c) t))
6861 data)))))
6863 ;;; Folding of blocks
6865 (defvar org-hide-block-overlays nil
6866 "Overlays hiding blocks.")
6867 (make-variable-buffer-local 'org-hide-block-overlays)
6869 (defun org-block-map (function &optional start end)
6870 "Call FUNCTION at the head of all source blocks in the current buffer.
6871 Optional arguments START and END can be used to limit the range."
6872 (let ((start (or start (point-min)))
6873 (end (or end (point-max))))
6874 (save-excursion
6875 (goto-char start)
6876 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6877 (save-excursion
6878 (save-match-data
6879 (goto-char (match-beginning 0))
6880 (funcall function)))))))
6882 (defun org-hide-block-toggle-all ()
6883 "Toggle the visibility of all blocks in the current buffer."
6884 (org-block-map #'org-hide-block-toggle))
6886 (defun org-hide-block-all ()
6887 "Fold all blocks in the current buffer."
6888 (interactive)
6889 (org-show-block-all)
6890 (org-block-map #'org-hide-block-toggle-maybe))
6892 (defun org-show-block-all ()
6893 "Unfold all blocks in the current buffer."
6894 (interactive)
6895 (mapc 'delete-overlay org-hide-block-overlays)
6896 (setq org-hide-block-overlays nil))
6898 (defun org-hide-block-toggle-maybe ()
6899 "Toggle visibility of block at point."
6900 (interactive)
6901 (let ((case-fold-search t))
6902 (if (save-excursion
6903 (beginning-of-line 1)
6904 (looking-at org-block-regexp))
6905 (progn (org-hide-block-toggle)
6906 t) ;; to signal that we took action
6907 nil))) ;; to signal that we did not
6909 (defun org-hide-block-toggle (&optional force)
6910 "Toggle the visibility of the current block."
6911 (interactive)
6912 (save-excursion
6913 (beginning-of-line)
6914 (if (re-search-forward org-block-regexp nil t)
6915 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6916 (end (match-end 0)) ;; end of entire body
6918 (if (memq t (mapcar (lambda (overlay)
6919 (eq (overlay-get overlay 'invisible)
6920 'org-hide-block))
6921 (overlays-at start)))
6922 (if (or (not force) (eq force 'off))
6923 (mapc (lambda (ov)
6924 (when (member ov org-hide-block-overlays)
6925 (setq org-hide-block-overlays
6926 (delq ov org-hide-block-overlays)))
6927 (when (eq (overlay-get ov 'invisible)
6928 'org-hide-block)
6929 (delete-overlay ov)))
6930 (overlays-at start)))
6931 (setq ov (make-overlay start end))
6932 (overlay-put ov 'invisible 'org-hide-block)
6933 ;; make the block accessible to isearch
6934 (overlay-put
6935 ov 'isearch-open-invisible
6936 (lambda (ov)
6937 (when (member ov org-hide-block-overlays)
6938 (setq org-hide-block-overlays
6939 (delq ov org-hide-block-overlays)))
6940 (when (eq (overlay-get ov 'invisible)
6941 'org-hide-block)
6942 (delete-overlay ov))))
6943 (push ov org-hide-block-overlays)))
6944 (error "Not looking at a source block"))))
6946 ;; org-tab-after-check-for-cycling-hook
6947 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6948 ;; Remove overlays when changing major mode
6949 (add-hook 'org-mode-hook
6950 (lambda () (org-add-hook 'change-major-mode-hook
6951 'org-show-block-all 'append 'local)))
6953 ;;; Org-goto
6955 (defvar org-goto-window-configuration nil)
6956 (defvar org-goto-marker nil)
6957 (defvar org-goto-map)
6958 (defun org-goto-map ()
6959 "Set the keymap `org-goto'."
6960 (setq org-goto-map
6961 (let ((map (make-sparse-keymap)))
6962 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6963 mouse-drag-region universal-argument org-occur))
6964 cmd)
6965 (while (setq cmd (pop cmds))
6966 (substitute-key-definition cmd cmd map global-map)))
6967 (suppress-keymap map)
6968 (org-defkey map "\C-m" 'org-goto-ret)
6969 (org-defkey map [(return)] 'org-goto-ret)
6970 (org-defkey map [(left)] 'org-goto-left)
6971 (org-defkey map [(right)] 'org-goto-right)
6972 (org-defkey map [(control ?g)] 'org-goto-quit)
6973 (org-defkey map "\C-i" 'org-cycle)
6974 (org-defkey map [(tab)] 'org-cycle)
6975 (org-defkey map [(down)] 'outline-next-visible-heading)
6976 (org-defkey map [(up)] 'outline-previous-visible-heading)
6977 (if org-goto-auto-isearch
6978 (if (fboundp 'define-key-after)
6979 (define-key-after map [t] 'org-goto-local-auto-isearch)
6980 nil)
6981 (org-defkey map "q" 'org-goto-quit)
6982 (org-defkey map "n" 'outline-next-visible-heading)
6983 (org-defkey map "p" 'outline-previous-visible-heading)
6984 (org-defkey map "f" 'outline-forward-same-level)
6985 (org-defkey map "b" 'outline-backward-same-level)
6986 (org-defkey map "u" 'outline-up-heading))
6987 (org-defkey map "/" 'org-occur)
6988 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6989 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6990 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6991 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6992 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6993 map)))
6995 (defconst org-goto-help
6996 "Browse buffer copy, to find location or copy text.%s
6997 RET=jump to location C-g=quit and return to previous location
6998 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7000 (defvar org-goto-start-pos) ; dynamically scoped parameter
7002 ;; FIXME: Docstring does not mention both interfaces
7003 (defun org-goto (&optional alternative-interface)
7004 "Look up a different location in the current file, keeping current visibility.
7006 When you want look-up or go to a different location in a
7007 document, the fastest way is often to fold the entire buffer and
7008 then dive into the tree. This method has the disadvantage, that
7009 the previous location will be folded, which may not be what you
7010 want.
7012 This command works around this by showing a copy of the current
7013 buffer in an indirect buffer, in overview mode. You can dive
7014 into the tree in that copy, use org-occur and incremental search
7015 to find a location. When pressing RET or `Q', the command
7016 returns to the original buffer in which the visibility is still
7017 unchanged. After RET it will also jump to the location selected
7018 in the indirect buffer and expose the headline hierarchy above.
7020 With a prefix argument, use the alternative interface: e.g. if
7021 `org-goto-interface' is 'outline use 'outline-path-completion."
7022 (interactive "P")
7023 (org-goto-map)
7024 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7025 (org-refile-use-outline-path t)
7026 (org-refile-target-verify-function nil)
7027 (interface
7028 (if (not alternative-interface)
7029 org-goto-interface
7030 (if (eq org-goto-interface 'outline)
7031 'outline-path-completion
7032 'outline)))
7033 (org-goto-start-pos (point))
7034 (selected-point
7035 (if (eq interface 'outline)
7036 (car (org-get-location (current-buffer) org-goto-help))
7037 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7038 (org-refile-check-position pa)
7039 (nth 3 pa)))))
7040 (if selected-point
7041 (progn
7042 (org-mark-ring-push org-goto-start-pos)
7043 (goto-char selected-point)
7044 (if (or (outline-invisible-p) (org-invisible-p2))
7045 (org-show-context 'org-goto)))
7046 (message "Quit"))))
7048 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7049 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7050 (defvar org-goto-local-auto-isearch-map) ; defined below
7052 (defun org-get-location (buf help)
7053 "Let the user select a location in the Org-mode buffer BUF.
7054 This function uses a recursive edit. It returns the selected position
7055 or nil."
7056 (org-no-popups
7057 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7058 (isearch-hide-immediately nil)
7059 (isearch-search-fun-function
7060 (lambda () 'org-goto-local-search-headings))
7061 (org-goto-selected-point org-goto-exit-command))
7062 (save-excursion
7063 (save-window-excursion
7064 (delete-other-windows)
7065 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7066 (org-pop-to-buffer-same-window
7067 (condition-case nil
7068 (make-indirect-buffer (current-buffer) "*org-goto*")
7069 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7070 (with-output-to-temp-buffer "*Org Help*"
7071 (princ (format help (if org-goto-auto-isearch
7072 " Just type for auto-isearch."
7073 " n/p/f/b/u to navigate, q to quit."))))
7074 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7075 (setq buffer-read-only nil)
7076 (let ((org-startup-truncated t)
7077 (org-startup-folded nil)
7078 (org-startup-align-all-tables nil))
7079 (org-mode)
7080 (org-overview))
7081 (setq buffer-read-only t)
7082 (if (and (boundp 'org-goto-start-pos)
7083 (integer-or-marker-p org-goto-start-pos))
7084 (let ((org-show-hierarchy-above t)
7085 (org-show-siblings t)
7086 (org-show-following-heading t))
7087 (goto-char org-goto-start-pos)
7088 (and (outline-invisible-p) (org-show-context)))
7089 (goto-char (point-min)))
7090 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7091 (message "Select location and press RET")
7092 (use-local-map org-goto-map)
7093 (recursive-edit)))
7094 (kill-buffer "*org-goto*")
7095 (cons org-goto-selected-point org-goto-exit-command))))
7097 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7098 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7099 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7100 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7102 (defun org-goto-local-search-headings (string bound noerror)
7103 "Search and make sure that any matches are in headlines."
7104 (catch 'return
7105 (while (if isearch-forward
7106 (search-forward string bound noerror)
7107 (search-backward string bound noerror))
7108 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7109 (and (member :headline context)
7110 (not (member :tags context))))
7111 (throw 'return (point))))))
7113 (defun org-goto-local-auto-isearch ()
7114 "Start isearch."
7115 (interactive)
7116 (goto-char (point-min))
7117 (let ((keys (this-command-keys)))
7118 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7119 (isearch-mode t)
7120 (isearch-process-search-char (string-to-char keys)))))
7122 (defun org-goto-ret (&optional arg)
7123 "Finish `org-goto' by going to the new location."
7124 (interactive "P")
7125 (setq org-goto-selected-point (point)
7126 org-goto-exit-command 'return)
7127 (throw 'exit nil))
7129 (defun org-goto-left ()
7130 "Finish `org-goto' by going to the new location."
7131 (interactive)
7132 (if (org-at-heading-p)
7133 (progn
7134 (beginning-of-line 1)
7135 (setq org-goto-selected-point (point)
7136 org-goto-exit-command 'left)
7137 (throw 'exit nil))
7138 (error "Not on a heading")))
7140 (defun org-goto-right ()
7141 "Finish `org-goto' by going to the new location."
7142 (interactive)
7143 (if (org-at-heading-p)
7144 (progn
7145 (setq org-goto-selected-point (point)
7146 org-goto-exit-command 'right)
7147 (throw 'exit nil))
7148 (error "Not on a heading")))
7150 (defun org-goto-quit ()
7151 "Finish `org-goto' without cursor motion."
7152 (interactive)
7153 (setq org-goto-selected-point nil)
7154 (setq org-goto-exit-command 'quit)
7155 (throw 'exit nil))
7157 ;;; Indirect buffer display of subtrees
7159 (defvar org-indirect-dedicated-frame nil
7160 "This is the frame being used for indirect tree display.")
7161 (defvar org-last-indirect-buffer nil)
7163 (defun org-tree-to-indirect-buffer (&optional arg)
7164 "Create indirect buffer and narrow it to current subtree.
7165 With a numerical prefix ARG, go up to this level and then take that tree.
7166 If ARG is negative, go up that many levels.
7168 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7169 indirect buffer previously made with this command, to avoid proliferation of
7170 indirect buffers. However, when you call the command with a \
7171 \\[universal-argument] prefix, or
7172 when `org-indirect-buffer-display' is `new-frame', the last buffer
7173 is kept so that you can work with several indirect buffers at the same time.
7174 If `org-indirect-buffer-display' is `dedicated-frame', the \
7175 \\[universal-argument] prefix also
7176 requests that a new frame be made for the new buffer, so that the dedicated
7177 frame is not changed."
7178 (interactive "P")
7179 (let ((cbuf (current-buffer))
7180 (cwin (selected-window))
7181 (pos (point))
7182 beg end level heading ibuf)
7183 (save-excursion
7184 (org-back-to-heading t)
7185 (when (numberp arg)
7186 (setq level (org-outline-level))
7187 (if (< arg 0) (setq arg (+ level arg)))
7188 (while (> (setq level (org-outline-level)) arg)
7189 (org-up-heading-safe)))
7190 (setq beg (point)
7191 heading (org-get-heading))
7192 (org-end-of-subtree t t)
7193 (if (org-at-heading-p) (backward-char 1))
7194 (setq end (point)))
7195 (if (and (buffer-live-p org-last-indirect-buffer)
7196 (not (eq org-indirect-buffer-display 'new-frame))
7197 (not arg))
7198 (kill-buffer org-last-indirect-buffer))
7199 (setq ibuf (org-get-indirect-buffer cbuf)
7200 org-last-indirect-buffer ibuf)
7201 (cond
7202 ((or (eq org-indirect-buffer-display 'new-frame)
7203 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7204 (select-frame (make-frame))
7205 (delete-other-windows)
7206 (org-pop-to-buffer-same-window ibuf)
7207 (org-set-frame-title heading))
7208 ((eq org-indirect-buffer-display 'dedicated-frame)
7209 (raise-frame
7210 (select-frame (or (and org-indirect-dedicated-frame
7211 (frame-live-p org-indirect-dedicated-frame)
7212 org-indirect-dedicated-frame)
7213 (setq org-indirect-dedicated-frame (make-frame)))))
7214 (delete-other-windows)
7215 (org-pop-to-buffer-same-window ibuf)
7216 (org-set-frame-title (concat "Indirect: " heading)))
7217 ((eq org-indirect-buffer-display 'current-window)
7218 (org-pop-to-buffer-same-window ibuf))
7219 ((eq org-indirect-buffer-display 'other-window)
7220 (pop-to-buffer ibuf))
7221 (t (error "Invalid value")))
7222 (if (featurep 'xemacs)
7223 (save-excursion (org-mode) (turn-on-font-lock)))
7224 (narrow-to-region beg end)
7225 (show-all)
7226 (goto-char pos)
7227 (run-hook-with-args 'org-cycle-hook 'all)
7228 (and (window-live-p cwin) (select-window cwin))))
7230 (defun org-get-indirect-buffer (&optional buffer)
7231 (setq buffer (or buffer (current-buffer)))
7232 (let ((n 1) (base (buffer-name buffer)) bname)
7233 (while (buffer-live-p
7234 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7235 (setq n (1+ n)))
7236 (condition-case nil
7237 (make-indirect-buffer buffer bname 'clone)
7238 (error (make-indirect-buffer buffer bname)))))
7240 (defun org-set-frame-title (title)
7241 "Set the title of the current frame to the string TITLE."
7242 ;; FIXME: how to name a single frame in XEmacs???
7243 (unless (featurep 'xemacs)
7244 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7246 ;;;; Structure editing
7248 ;;; Inserting headlines
7250 (defun org-previous-line-empty-p ()
7251 (save-excursion
7252 (and (not (bobp))
7253 (or (beginning-of-line 0) t)
7254 (save-match-data
7255 (looking-at "[ \t]*$")))))
7257 (defun org-insert-heading (&optional force-heading invisible-ok)
7258 "Insert a new heading or item with same depth at point.
7259 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7260 If point is at the beginning of a headline, insert a sibling before the
7261 current headline. If point is not at the beginning, split the line,
7262 create the new headline with the text in the current line after point
7263 \(but see also the variable `org-M-RET-may-split-line').
7265 With a double prefix arg, force the heading to be inserted at the
7266 end of the parent subtree.
7268 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7269 This is important for non-interactive uses of the command."
7270 (interactive "P")
7271 (if (or (= (buffer-size) 0)
7272 (and (not (save-excursion
7273 (and (ignore-errors (org-back-to-heading invisible-ok))
7274 (org-at-heading-p))))
7275 (or force-heading (not (org-in-item-p)))))
7276 (progn
7277 (insert "\n* ")
7278 (run-hooks 'org-insert-heading-hook))
7279 (when (or force-heading (not (org-insert-item)))
7280 (let* ((empty-line-p nil)
7281 (level nil)
7282 (on-heading (org-at-heading-p))
7283 (head (save-excursion
7284 (condition-case nil
7285 (progn
7286 (org-back-to-heading invisible-ok)
7287 (when (and (not on-heading)
7288 (featurep 'org-inlinetask)
7289 (integerp org-inlinetask-min-level)
7290 (>= (length (match-string 0))
7291 org-inlinetask-min-level))
7292 ;; Find a heading level before the inline task
7293 (while (and (setq level (org-up-heading-safe))
7294 (>= level org-inlinetask-min-level)))
7295 (if (org-at-heading-p)
7296 (org-back-to-heading invisible-ok)
7297 (error "This should not happen")))
7298 (setq empty-line-p (org-previous-line-empty-p))
7299 (match-string 0))
7300 (error "*"))))
7301 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7302 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7303 pos hide-previous previous-pos)
7304 (cond
7305 ((and (org-at-heading-p) (bolp)
7306 (or (bobp)
7307 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7308 ;; insert before the current line
7309 (open-line (if blank 2 1)))
7310 ((and (bolp)
7311 (not org-insert-heading-respect-content)
7312 (or (bobp)
7313 (save-excursion
7314 (backward-char 1) (not (outline-invisible-p)))))
7315 ;; insert right here
7316 nil)
7318 ;; somewhere in the line
7319 (save-excursion
7320 (setq previous-pos (point-at-bol))
7321 (end-of-line)
7322 (setq hide-previous (outline-invisible-p)))
7323 (and org-insert-heading-respect-content (org-show-subtree))
7324 (let ((split
7325 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7326 (save-excursion
7327 (let ((p (point)))
7328 (goto-char (point-at-bol))
7329 (and (looking-at org-complex-heading-regexp)
7330 (match-beginning 4)
7331 (> p (match-beginning 4)))))))
7332 tags pos)
7333 (cond
7334 (org-insert-heading-respect-content
7335 (if (not (equal force-heading '(16)))
7336 (org-end-of-subtree nil t)
7337 (org-up-heading-safe)
7338 (org-end-of-subtree nil t))
7339 (when (featurep 'org-inlinetask)
7340 (while (and (not (eobp))
7341 (looking-at "\\(\\*+\\)[ \t]+")
7342 (>= (length (match-string 1))
7343 org-inlinetask-min-level))
7344 (org-end-of-subtree nil t)))
7345 (or (bolp) (newline))
7346 (or (org-previous-line-empty-p)
7347 (and blank (newline)))
7348 (open-line 1))
7349 ((org-at-heading-p)
7350 (when hide-previous
7351 (show-children)
7352 (org-show-entry))
7353 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7354 (setq tags (and (match-end 2) (match-string 2)))
7355 (and (match-end 1)
7356 (delete-region (match-beginning 1) (match-end 1)))
7357 (setq pos (point-at-bol))
7358 (or split (end-of-line 1))
7359 (delete-horizontal-space)
7360 (if (string-match "\\`\\*+\\'"
7361 (buffer-substring (point-at-bol) (point)))
7362 (insert " "))
7363 (newline (if blank 2 1))
7364 (when tags
7365 (save-excursion
7366 (goto-char pos)
7367 (end-of-line 1)
7368 (insert " " tags)
7369 (org-set-tags nil 'align))))
7371 (or split (end-of-line 1))
7372 (newline (if blank 2 1)))))))
7373 (insert head) (just-one-space)
7374 (setq pos (point))
7375 (end-of-line 1)
7376 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7377 (when (and org-insert-heading-respect-content hide-previous)
7378 (save-excursion
7379 (goto-char previous-pos)
7380 (hide-subtree)))
7381 (run-hooks 'org-insert-heading-hook)))))
7383 (defun org-get-heading (&optional no-tags no-todo)
7384 "Return the heading of the current entry, without the stars.
7385 When NO-TAGS is non-nil, don't include tags.
7386 When NO-TODO is non-nil, don't include TODO keywords."
7387 (save-excursion
7388 (org-back-to-heading t)
7389 (cond
7390 ((and no-tags no-todo)
7391 (looking-at org-complex-heading-regexp)
7392 (match-string 4))
7393 (no-tags
7394 (looking-at (concat org-outline-regexp
7395 "\\(.*?\\)"
7396 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7397 (match-string 1))
7398 (no-todo
7399 (looking-at org-todo-line-regexp)
7400 (match-string 3))
7401 (t (looking-at org-heading-regexp)
7402 (match-string 2)))))
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) (looking-at org-complex-heading-regexp))
7416 (list (length (match-string 1))
7417 (org-reduced-level (length (match-string 1)))
7418 (org-match-string-no-properties 2)
7419 (and (match-end 3) (aref (match-string 3) 2))
7420 (org-match-string-no-properties 4)
7421 (org-match-string-no-properties 5)))))
7423 (defun org-get-entry ()
7424 "Get the entry text, after heading, entire subtree."
7425 (save-excursion
7426 (org-back-to-heading t)
7427 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7429 (defun org-insert-heading-after-current ()
7430 "Insert a new heading with same level as current, after current subtree."
7431 (interactive)
7432 (org-back-to-heading)
7433 (org-insert-heading)
7434 (org-move-subtree-down)
7435 (end-of-line 1))
7437 (defun org-insert-heading-respect-content ()
7438 (interactive)
7439 (let ((org-insert-heading-respect-content t))
7440 (org-insert-heading t)))
7442 (defun org-insert-todo-heading-respect-content (&optional force-state)
7443 (interactive "P")
7444 (let ((org-insert-heading-respect-content t))
7445 (org-insert-todo-heading force-state t)))
7447 (defun org-insert-todo-heading (arg &optional force-heading)
7448 "Insert a new heading with the same level and TODO state as current heading.
7449 If the heading has no TODO state, or if the state is DONE, use the first
7450 state (TODO by default). Also one prefix arg, force first state. With two
7451 prefix args, force inserting at the end of the parent subtree."
7452 (interactive "P")
7453 (when (or force-heading (not (org-insert-item 'checkbox)))
7454 (org-insert-heading (or (and (equal arg '(16)) '(16))
7455 force-heading))
7456 (save-excursion
7457 (org-back-to-heading)
7458 (outline-previous-heading)
7459 (looking-at org-todo-line-regexp))
7460 (let*
7461 ((new-mark-x
7462 (if (or arg
7463 (not (match-beginning 2))
7464 (member (match-string 2) org-done-keywords))
7465 (car org-todo-keywords-1)
7466 (match-string 2)))
7467 (new-mark
7469 (run-hook-with-args-until-success
7470 'org-todo-get-default-hook new-mark-x nil)
7471 new-mark-x)))
7472 (beginning-of-line 1)
7473 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7474 (if org-treat-insert-todo-heading-as-state-change
7475 (org-todo new-mark)
7476 (insert new-mark " "))))
7477 (when org-provide-todo-statistics
7478 (org-update-parent-todo-statistics))))
7480 (defun org-insert-subheading (arg)
7481 "Insert a new subheading and demote it.
7482 Works for outline headings and for plain lists alike."
7483 (interactive "P")
7484 (org-insert-heading arg)
7485 (cond
7486 ((org-at-heading-p) (org-do-demote))
7487 ((org-at-item-p) (org-indent-item))))
7489 (defun org-insert-todo-subheading (arg)
7490 "Insert a new subheading with TODO keyword or checkbox and demote it.
7491 Works for outline headings and for plain lists alike."
7492 (interactive "P")
7493 (org-insert-todo-heading arg)
7494 (cond
7495 ((org-at-heading-p) (org-do-demote))
7496 ((org-at-item-p) (org-indent-item))))
7498 ;;; Promotion and Demotion
7500 (defvar org-after-demote-entry-hook nil
7501 "Hook run after an entry has been demoted.
7502 The cursor will be at the beginning of the entry.
7503 When a subtree is being demoted, the hook will be called for each node.")
7505 (defvar org-after-promote-entry-hook nil
7506 "Hook run after an entry has been promoted.
7507 The cursor will be at the beginning of the entry.
7508 When a subtree is being promoted, the hook will be called for each node.")
7510 (defun org-promote-subtree ()
7511 "Promote the entire subtree.
7512 See also `org-promote'."
7513 (interactive)
7514 (save-excursion
7515 (org-with-limited-levels (org-map-tree 'org-promote)))
7516 (org-fix-position-after-promote))
7518 (defun org-demote-subtree ()
7519 "Demote the entire subtree. See `org-demote'.
7520 See also `org-promote'."
7521 (interactive)
7522 (save-excursion
7523 (org-with-limited-levels (org-map-tree 'org-demote)))
7524 (org-fix-position-after-promote))
7527 (defun org-do-promote ()
7528 "Promote the current heading higher up the tree.
7529 If the region is active in `transient-mark-mode', promote all headings
7530 in the region."
7531 (interactive)
7532 (save-excursion
7533 (if (org-region-active-p)
7534 (org-map-region 'org-promote (region-beginning) (region-end))
7535 (org-promote)))
7536 (org-fix-position-after-promote))
7538 (defun org-do-demote ()
7539 "Demote the current heading lower down the tree.
7540 If the region is active in `transient-mark-mode', demote all headings
7541 in the region."
7542 (interactive)
7543 (save-excursion
7544 (if (org-region-active-p)
7545 (org-map-region 'org-demote (region-beginning) (region-end))
7546 (org-demote)))
7547 (org-fix-position-after-promote))
7549 (defun org-fix-position-after-promote ()
7550 "Make sure that after pro/demotion cursor position is right."
7551 (let ((pos (point)))
7552 (when (save-excursion
7553 (beginning-of-line 1)
7554 (looking-at org-todo-line-regexp)
7555 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7556 (cond ((eobp) (insert " "))
7557 ((eolp) (insert " "))
7558 ((equal (char-after) ?\ ) (forward-char 1))))))
7560 (defun org-current-level ()
7561 "Return the level of the current entry, or nil if before the first headline.
7562 The level is the number of stars at the beginning of the headline."
7563 (save-excursion
7564 (org-with-limited-levels
7565 (if (ignore-errors (org-back-to-heading t))
7566 (funcall outline-level)))))
7568 (defun org-get-previous-line-level ()
7569 "Return the outline depth of the last headline before the current line.
7570 Returns 0 for the first headline in the buffer, and nil if before the
7571 first headline."
7572 (let ((current-level (org-current-level))
7573 (prev-level (when (> (line-number-at-pos) 1)
7574 (save-excursion
7575 (beginning-of-line 0)
7576 (org-current-level)))))
7577 (cond ((null current-level) nil) ; Before first headline
7578 ((null prev-level) 0) ; At first headline
7579 (prev-level))))
7581 (defun org-reduced-level (l)
7582 "Compute the effective level of a heading.
7583 This takes into account the setting of `org-odd-levels-only'."
7584 (cond
7585 ((zerop l) 0)
7586 (org-odd-levels-only (1+ (floor (/ l 2))))
7587 (t l)))
7589 (defun org-level-increment ()
7590 "Return the number of stars that will be added or removed at a
7591 time to headlines when structure editing, based on the value of
7592 `org-odd-levels-only'."
7593 (if org-odd-levels-only 2 1))
7595 (defun org-get-valid-level (level &optional change)
7596 "Rectify a level change under the influence of `org-odd-levels-only'
7597 LEVEL is a current level, CHANGE is by how much the level should be
7598 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7599 even level numbers will become the next higher odd number."
7600 (if org-odd-levels-only
7601 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7602 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7603 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7604 (max 1 (+ level (or change 0)))))
7606 (if (boundp 'define-obsolete-function-alias)
7607 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7608 (define-obsolete-function-alias 'org-get-legal-level
7609 'org-get-valid-level)
7610 (define-obsolete-function-alias 'org-get-legal-level
7611 'org-get-valid-level "23.1")))
7613 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7614 ;; ̀org-with-limited-levels'
7615 (defun org-promote ()
7616 "Promote the current heading higher up the tree.
7617 If the region is active in `transient-mark-mode', promote all headings
7618 in the region."
7619 (org-back-to-heading t)
7620 (let* ((level (save-match-data (funcall outline-level)))
7621 (after-change-functions (remove 'flyspell-after-change-function
7622 after-change-functions))
7623 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7624 (diff (abs (- level (length up-head) -1))))
7625 (cond ((and (= level 1) org-called-with-limited-levels
7626 org-allow-promoting-top-level-subtree)
7627 (replace-match "# " nil t))
7628 ((= level 1)
7629 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7630 (t (replace-match up-head nil t)))
7631 ;; Fixup tag positioning
7632 (unless (= level 1)
7633 (and org-auto-align-tags (org-set-tags nil t))
7634 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7635 (run-hooks 'org-after-promote-entry-hook)))
7637 (defun org-demote ()
7638 "Demote the current heading lower down the tree.
7639 If the region is active in `transient-mark-mode', demote all headings
7640 in the region."
7641 (org-back-to-heading t)
7642 (let* ((level (save-match-data (funcall outline-level)))
7643 (after-change-functions (remove 'flyspell-after-change-function
7644 after-change-functions))
7645 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7646 (diff (abs (- level (length down-head) -1))))
7647 (replace-match down-head nil t)
7648 ;; Fixup tag positioning
7649 (and org-auto-align-tags (org-set-tags nil t))
7650 (if org-adapt-indentation (org-fixup-indentation diff))
7651 (run-hooks 'org-after-demote-entry-hook)))
7653 (defun org-cycle-level ()
7654 "Cycle the level of an empty headline through possible states.
7655 This goes first to child, then to parent, level, then up the hierarchy.
7656 After top level, it switches back to sibling level."
7657 (interactive)
7658 (let ((org-adapt-indentation nil))
7659 (when (org-point-at-end-of-empty-headline)
7660 (setq this-command 'org-cycle-level) ; Only needed for caching
7661 (let ((cur-level (org-current-level))
7662 (prev-level (org-get-previous-line-level)))
7663 (cond
7664 ;; If first headline in file, promote to top-level.
7665 ((= prev-level 0)
7666 (loop repeat (/ (- cur-level 1) (org-level-increment))
7667 do (org-do-promote)))
7668 ;; If same level as prev, demote one.
7669 ((= prev-level cur-level)
7670 (org-do-demote))
7671 ;; If parent is top-level, promote to top level if not already.
7672 ((= prev-level 1)
7673 (loop repeat (/ (- cur-level 1) (org-level-increment))
7674 do (org-do-promote)))
7675 ;; If top-level, return to prev-level.
7676 ((= cur-level 1)
7677 (loop repeat (/ (- prev-level 1) (org-level-increment))
7678 do (org-do-demote)))
7679 ;; If less than prev-level, promote one.
7680 ((< cur-level prev-level)
7681 (org-do-promote))
7682 ;; If deeper than prev-level, promote until higher than
7683 ;; prev-level.
7684 ((> cur-level prev-level)
7685 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7686 do (org-do-promote))))
7687 t))))
7689 (defun org-map-tree (fun)
7690 "Call FUN for every heading underneath the current one."
7691 (org-back-to-heading)
7692 (let ((level (funcall outline-level)))
7693 (save-excursion
7694 (funcall fun)
7695 (while (and (progn
7696 (outline-next-heading)
7697 (> (funcall outline-level) level))
7698 (not (eobp)))
7699 (funcall fun)))))
7701 (defun org-map-region (fun beg end)
7702 "Call FUN for every heading between BEG and END."
7703 (let ((org-ignore-region t))
7704 (save-excursion
7705 (setq end (copy-marker end))
7706 (goto-char beg)
7707 (if (and (re-search-forward org-outline-regexp-bol nil t)
7708 (< (point) end))
7709 (funcall fun))
7710 (while (and (progn
7711 (outline-next-heading)
7712 (< (point) end))
7713 (not (eobp)))
7714 (funcall fun)))))
7716 (defvar org-property-end-re) ; silence byte-compiler
7717 (defun org-fixup-indentation (diff)
7718 "Change the indentation in the current entry by DIFF.
7719 However, if any line in the current entry has no indentation, or if it
7720 would end up with no indentation after the change, nothing at all is done."
7721 (save-excursion
7722 (let ((end (save-excursion (outline-next-heading)
7723 (point-marker)))
7724 (prohibit (if (> diff 0)
7725 "^\\S-"
7726 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7727 col)
7728 (unless (save-excursion (end-of-line 1)
7729 (re-search-forward prohibit end t))
7730 (while (and (< (point) end)
7731 (re-search-forward "^[ \t]+" end t))
7732 (goto-char (match-end 0))
7733 (setq col (current-column))
7734 (if (< diff 0) (replace-match ""))
7735 (org-indent-to-column (+ diff col))))
7736 (move-marker end nil))))
7738 (defun org-convert-to-odd-levels ()
7739 "Convert an org-mode file with all levels allowed to one with odd levels.
7740 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7741 level 5 etc."
7742 (interactive)
7743 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7744 (let ((outline-level 'org-outline-level)
7745 (org-odd-levels-only nil) n)
7746 (save-excursion
7747 (goto-char (point-min))
7748 (while (re-search-forward "^\\*\\*+ " nil t)
7749 (setq n (- (length (match-string 0)) 2))
7750 (while (>= (setq n (1- n)) 0)
7751 (org-demote))
7752 (end-of-line 1))))))
7754 (defun org-convert-to-oddeven-levels ()
7755 "Convert an org-mode file with only odd levels to one with odd/even levels.
7756 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7757 file contains a section with an even level, conversion would
7758 destroy the structure of the file. An error is signaled in this
7759 case."
7760 (interactive)
7761 (goto-char (point-min))
7762 ;; First check if there are no even levels
7763 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7764 (org-show-context t)
7765 (error "Not all levels are odd in this file. Conversion not possible"))
7766 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7767 (let ((outline-regexp org-outline-regexp)
7768 (outline-level 'org-outline-level)
7769 (org-odd-levels-only nil) n)
7770 (save-excursion
7771 (goto-char (point-min))
7772 (while (re-search-forward "^\\*\\*+ " nil t)
7773 (setq n (/ (1- (length (match-string 0))) 2))
7774 (while (>= (setq n (1- n)) 0)
7775 (org-promote))
7776 (end-of-line 1))))))
7778 (defun org-tr-level (n)
7779 "Make N odd if required."
7780 (if org-odd-levels-only (1+ (/ n 2)) n))
7782 ;;; Vertical tree motion, cutting and pasting of subtrees
7784 (defun org-move-subtree-up (&optional arg)
7785 "Move the current subtree up past ARG headlines of the same level."
7786 (interactive "p")
7787 (org-move-subtree-down (- (prefix-numeric-value arg))))
7789 (defun org-move-subtree-down (&optional arg)
7790 "Move the current subtree down past ARG headlines of the same level."
7791 (interactive "p")
7792 (setq arg (prefix-numeric-value arg))
7793 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7794 'org-get-last-sibling))
7795 (ins-point (make-marker))
7796 (cnt (abs arg))
7797 (col (current-column))
7798 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7799 ;; Select the tree
7800 (org-back-to-heading)
7801 (setq beg0 (point))
7802 (save-excursion
7803 (setq ne-beg (org-back-over-empty-lines))
7804 (setq beg (point)))
7805 (save-match-data
7806 (save-excursion (outline-end-of-heading)
7807 (setq folded (outline-invisible-p)))
7808 (outline-end-of-subtree))
7809 (outline-next-heading)
7810 (setq ne-end (org-back-over-empty-lines))
7811 (setq end (point))
7812 (goto-char beg0)
7813 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7814 ;; include less whitespace
7815 (save-excursion
7816 (goto-char beg)
7817 (forward-line (- ne-beg ne-end))
7818 (setq beg (point))))
7819 ;; Find insertion point, with error handling
7820 (while (> cnt 0)
7821 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7822 (progn (goto-char beg0)
7823 (error "Cannot move past superior level or buffer limit")))
7824 (setq cnt (1- cnt)))
7825 (if (> arg 0)
7826 ;; Moving forward - still need to move over subtree
7827 (progn (org-end-of-subtree t t)
7828 (save-excursion
7829 (org-back-over-empty-lines)
7830 (or (bolp) (newline)))))
7831 (setq ne-ins (org-back-over-empty-lines))
7832 (move-marker ins-point (point))
7833 (setq txt (buffer-substring beg end))
7834 (org-save-markers-in-region beg end)
7835 (delete-region beg end)
7836 (org-remove-empty-overlays-at beg)
7837 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7838 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7839 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7840 (let ((bbb (point)))
7841 (insert-before-markers txt)
7842 (org-reinstall-markers-in-region bbb)
7843 (move-marker ins-point bbb))
7844 (or (bolp) (insert "\n"))
7845 (setq ins-end (point))
7846 (goto-char ins-point)
7847 (org-skip-whitespace)
7848 (when (and (< arg 0)
7849 (org-first-sibling-p)
7850 (> ne-ins ne-beg))
7851 ;; Move whitespace back to beginning
7852 (save-excursion
7853 (goto-char ins-end)
7854 (let ((kill-whole-line t))
7855 (kill-line (- ne-ins ne-beg)) (point)))
7856 (insert (make-string (- ne-ins ne-beg) ?\n)))
7857 (move-marker ins-point nil)
7858 (if folded
7859 (hide-subtree)
7860 (org-show-entry)
7861 (show-children)
7862 (org-cycle-hide-drawers 'children))
7863 (org-clean-visibility-after-subtree-move)
7864 ;; move back to the initial column we were at
7865 (move-to-column col)))
7867 (defvar org-subtree-clip ""
7868 "Clipboard for cut and paste of subtrees.
7869 This is actually only a copy of the kill, because we use the normal kill
7870 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7872 (defvar org-subtree-clip-folded nil
7873 "Was the last copied subtree folded?
7874 This is used to fold the tree back after pasting.")
7876 (defun org-cut-subtree (&optional n)
7877 "Cut the current subtree into the clipboard.
7878 With prefix arg N, cut this many sequential subtrees.
7879 This is a short-hand for marking the subtree and then cutting it."
7880 (interactive "p")
7881 (org-copy-subtree n 'cut))
7883 (defun org-copy-subtree (&optional n cut force-store-markers)
7884 "Cut the current subtree into the clipboard.
7885 With prefix arg N, cut this many sequential subtrees.
7886 This is a short-hand for marking the subtree and then copying it.
7887 If CUT is non-nil, actually cut the subtree.
7888 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7889 of some markers in the region, even if CUT is non-nil. This is
7890 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7891 (interactive "p")
7892 (let (beg end folded (beg0 (point)))
7893 (if (org-called-interactively-p 'any)
7894 (org-back-to-heading nil) ; take what looks like a subtree
7895 (org-back-to-heading t)) ; take what is really there
7896 (setq beg (point))
7897 (skip-chars-forward " \t\r\n")
7898 (save-match-data
7899 (save-excursion (outline-end-of-heading)
7900 (setq folded (outline-invisible-p)))
7901 (condition-case nil
7902 (org-forward-heading-same-level (1- n) t)
7903 (error nil))
7904 (org-end-of-subtree t t))
7905 (setq end (point))
7906 (goto-char beg0)
7907 (when (> end beg)
7908 (setq org-subtree-clip-folded folded)
7909 (when (or cut force-store-markers)
7910 (org-save-markers-in-region beg end))
7911 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7912 (setq org-subtree-clip (current-kill 0))
7913 (message "%s: Subtree(s) with %d characters"
7914 (if cut "Cut" "Copied")
7915 (length org-subtree-clip)))))
7917 (defun org-paste-subtree (&optional level tree for-yank)
7918 "Paste the clipboard as a subtree, with modification of headline level.
7919 The entire subtree is promoted or demoted in order to match a new headline
7920 level.
7922 If the cursor is at the beginning of a headline, the same level as
7923 that headline is used to paste the tree.
7925 If not, the new level is derived from the *visible* headings
7926 before and after the insertion point, and taken to be the inferior headline
7927 level of the two. So if the previous visible heading is level 3 and the
7928 next is level 4 (or vice versa), level 4 will be used for insertion.
7929 This makes sure that the subtree remains an independent subtree and does
7930 not swallow low level entries.
7932 You can also force a different level, either by using a numeric prefix
7933 argument, or by inserting the heading marker by hand. For example, if the
7934 cursor is after \"*****\", then the tree will be shifted to level 5.
7936 If optional TREE is given, use this text instead of the kill ring.
7938 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7939 move back over whitespace before inserting, and move point to the end of
7940 the inserted text when done."
7941 (interactive "P")
7942 (setq tree (or tree (and kill-ring (current-kill 0))))
7943 (unless (org-kill-is-subtree-p tree)
7944 (error "%s"
7945 (substitute-command-keys
7946 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7947 (org-with-limited-levels
7948 (let* ((visp (not (outline-invisible-p)))
7949 (txt tree)
7950 (^re_ "\\(\\*+\\)[ \t]*")
7951 (old-level (if (string-match org-outline-regexp-bol txt)
7952 (- (match-end 0) (match-beginning 0) 1)
7953 -1))
7954 (force-level (cond (level (prefix-numeric-value level))
7955 ((and (looking-at "[ \t]*$")
7956 (string-match
7957 "^\\*+$" (buffer-substring
7958 (point-at-bol) (point))))
7959 (- (match-end 1) (match-beginning 1)))
7960 ((and (bolp)
7961 (looking-at org-outline-regexp))
7962 (- (match-end 0) (point) 1))))
7963 (previous-level (save-excursion
7964 (condition-case nil
7965 (progn
7966 (outline-previous-visible-heading 1)
7967 (if (looking-at ^re_)
7968 (- (match-end 0) (match-beginning 0) 1)
7970 (error 1))))
7971 (next-level (save-excursion
7972 (condition-case nil
7973 (progn
7974 (or (looking-at org-outline-regexp)
7975 (outline-next-visible-heading 1))
7976 (if (looking-at ^re_)
7977 (- (match-end 0) (match-beginning 0) 1)
7979 (error 1))))
7980 (new-level (or force-level (max previous-level next-level)))
7981 (shift (if (or (= old-level -1)
7982 (= new-level -1)
7983 (= old-level new-level))
7985 (- new-level old-level)))
7986 (delta (if (> shift 0) -1 1))
7987 (func (if (> shift 0) 'org-demote 'org-promote))
7988 (org-odd-levels-only nil)
7989 beg end newend)
7990 ;; Remove the forced level indicator
7991 (if force-level
7992 (delete-region (point-at-bol) (point)))
7993 ;; Paste
7994 (beginning-of-line (if (bolp) 1 2))
7995 (setq beg (point))
7996 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7997 (insert-before-markers txt)
7998 (unless (string-match "\n\\'" txt) (insert "\n"))
7999 (setq newend (point))
8000 (org-reinstall-markers-in-region beg)
8001 (setq end (point))
8002 (goto-char beg)
8003 (skip-chars-forward " \t\n\r")
8004 (setq beg (point))
8005 (if (and (outline-invisible-p) visp)
8006 (save-excursion (outline-show-heading)))
8007 ;; Shift if necessary
8008 (unless (= shift 0)
8009 (save-restriction
8010 (narrow-to-region beg end)
8011 (while (not (= shift 0))
8012 (org-map-region func (point-min) (point-max))
8013 (setq shift (+ delta shift)))
8014 (goto-char (point-min))
8015 (setq newend (point-max))))
8016 (when (or (org-called-interactively-p 'interactive) for-yank)
8017 (message "Clipboard pasted as level %d subtree" new-level))
8018 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8019 kill-ring
8020 (eq org-subtree-clip (current-kill 0))
8021 org-subtree-clip-folded)
8022 ;; The tree was folded before it was killed/copied
8023 (hide-subtree))
8024 (and for-yank (goto-char newend)))))
8026 (defun org-kill-is-subtree-p (&optional txt)
8027 "Check if the current kill is an outline subtree, or a set of trees.
8028 Returns nil if kill does not start with a headline, or if the first
8029 headline level is not the largest headline level in the tree.
8030 So this will actually accept several entries of equal levels as well,
8031 which is OK for `org-paste-subtree'.
8032 If optional TXT is given, check this string instead of the current kill."
8033 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8034 (re (org-get-limited-outline-regexp))
8035 (^re (concat "^" re))
8036 (start-level (and kill
8037 (string-match
8038 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8039 kill)
8040 (- (match-end 2) (match-beginning 2) 1)))
8041 (start (1+ (or (match-beginning 2) -1))))
8042 (if (not start-level)
8043 (progn
8044 nil) ;; does not even start with a heading
8045 (catch 'exit
8046 (while (setq start (string-match ^re kill (1+ start)))
8047 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8048 (throw 'exit nil)))
8049 t))))
8051 (defvar org-markers-to-move nil
8052 "Markers that should be moved with a cut-and-paste operation.
8053 Those markers are stored together with their positions relative to
8054 the start of the region.")
8056 (defun org-save-markers-in-region (beg end)
8057 "Check markers in region.
8058 If these markers are between BEG and END, record their position relative
8059 to BEG, so that after moving the block of text, we can put the markers back
8060 into place.
8061 This function gets called just before an entry or tree gets cut from the
8062 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8063 called immediately, to move the markers with the entries."
8064 (setq org-markers-to-move nil)
8065 (when (featurep 'org-clock)
8066 (org-clock-save-markers-for-cut-and-paste beg end))
8067 (when (featurep 'org-agenda)
8068 (org-agenda-save-markers-for-cut-and-paste beg end)))
8070 (defun org-check-and-save-marker (marker beg end)
8071 "Check if MARKER is between BEG and END.
8072 If yes, remember the marker and the distance to BEG."
8073 (when (and (marker-buffer marker)
8074 (equal (marker-buffer marker) (current-buffer)))
8075 (if (and (>= marker beg) (< marker end))
8076 (push (cons marker (- marker beg)) org-markers-to-move))))
8078 (defun org-reinstall-markers-in-region (beg)
8079 "Move all remembered markers to their position relative to BEG."
8080 (mapc (lambda (x)
8081 (move-marker (car x) (+ beg (cdr x))))
8082 org-markers-to-move)
8083 (setq org-markers-to-move nil))
8085 (defun org-narrow-to-subtree ()
8086 "Narrow buffer to the current subtree."
8087 (interactive)
8088 (save-excursion
8089 (save-match-data
8090 (org-with-limited-levels
8091 (narrow-to-region
8092 (progn (org-back-to-heading t) (point))
8093 (progn (org-end-of-subtree t t)
8094 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8095 (point)))))))
8097 (defun org-narrow-to-block ()
8098 "Narrow buffer to the current block."
8099 (interactive)
8100 (let* ((case-fold-search t)
8101 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8102 "^[ \t]*#\\+end_.*")))
8103 (if blockp
8104 (narrow-to-region (car blockp) (cdr blockp))
8105 (error "Not in a block"))))
8107 (eval-when-compile
8108 (defvar org-property-drawer-re))
8110 (defvar org-property-start-re) ;; defined below
8111 (defun org-clone-subtree-with-time-shift (n &optional shift)
8112 "Clone the task (subtree) at point N times.
8113 The clones will be inserted as siblings.
8115 In interactive use, the user will be prompted for the number of
8116 clones to be produced, and for a time SHIFT, which may be a
8117 repeater as used in time stamps, for example `+3d'.
8119 When a valid repeater is given and the entry contains any time
8120 stamps, the clones will become a sequence in time, with time
8121 stamps in the subtree shifted for each clone produced. If SHIFT
8122 is nil or the empty string, time stamps will be left alone. The
8123 ID property of the original subtree is removed.
8125 If the original subtree did contain time stamps with a repeater,
8126 the following will happen:
8127 - the repeater will be removed in each clone
8128 - an additional clone will be produced, with the current, unshifted
8129 date(s) in the entry.
8130 - the original entry will be placed *after* all the clones, with
8131 repeater intact.
8132 - the start days in the repeater in the original entry will be shifted
8133 to past the last clone.
8134 In this way you can spell out a number of instances of a repeating task,
8135 and still retain the repeater to cover future instances of the task."
8136 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8137 (let (beg end template task idprop
8138 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8139 (drawer-re org-drawer-regexp))
8140 (if (not (and (integerp n) (> n 0)))
8141 (error "Invalid number of replications %s" n))
8142 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8143 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8144 shift)))
8145 (error "Invalid shift specification %s" shift))
8146 (when doshift
8147 (setq shift-n (string-to-number (match-string 1 shift))
8148 shift-what (cdr (assoc (match-string 2 shift)
8149 '(("d" . day) ("w" . week)
8150 ("m" . month) ("y" . year))))))
8151 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8152 (setq nmin 1 nmax n)
8153 (org-back-to-heading t)
8154 (setq beg (point))
8155 (setq idprop (org-entry-get nil "ID"))
8156 (org-end-of-subtree t t)
8157 (or (bolp) (insert "\n"))
8158 (setq end (point))
8159 (setq template (buffer-substring beg end))
8160 (when (and doshift
8161 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8162 (delete-region beg end)
8163 (setq end beg)
8164 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8165 (goto-char end)
8166 (loop for n from nmin to nmax do
8167 ;; prepare clone
8168 (with-temp-buffer
8169 (insert template)
8170 (org-mode)
8171 (goto-char (point-min))
8172 (org-show-subtree)
8173 (and idprop (if org-clone-delete-id
8174 (org-entry-delete nil "ID")
8175 (org-id-get-create t)))
8176 (unless (= n 0)
8177 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8178 (kill-whole-line))
8179 (goto-char (point-min))
8180 (while (re-search-forward drawer-re nil t)
8181 (mapc (lambda (d)
8182 (org-remove-empty-drawer-at d (point))) org-drawers)))
8183 (goto-char (point-min))
8184 (when doshift
8185 (while (re-search-forward org-ts-regexp-both nil t)
8186 (org-timestamp-change (* n shift-n) shift-what))
8187 (unless (= n n-no-remove)
8188 (goto-char (point-min))
8189 (while (re-search-forward org-ts-regexp nil t)
8190 (save-excursion
8191 (goto-char (match-beginning 0))
8192 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8193 (delete-region (match-beginning 1) (match-end 1)))))))
8194 (setq task (buffer-string)))
8195 (insert task))
8196 (goto-char beg)))
8198 ;;; Outline Sorting
8200 (defun org-sort (with-case)
8201 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8202 Optional argument WITH-CASE means sort case-sensitively."
8203 (interactive "P")
8204 (cond
8205 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8206 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8208 (org-call-with-arg 'org-sort-entries with-case))))
8210 (defun org-sort-remove-invisible (s)
8211 (remove-text-properties 0 (length s) org-rm-props s)
8212 (while (string-match org-bracket-link-regexp s)
8213 (setq s (replace-match (if (match-end 2)
8214 (match-string 3 s)
8215 (match-string 1 s)) t t s)))
8218 (defvar org-priority-regexp) ; defined later in the file
8220 (defvar org-after-sorting-entries-or-items-hook nil
8221 "Hook that is run after a bunch of entries or items have been sorted.
8222 When children are sorted, the cursor is in the parent line when this
8223 hook gets called. When a region or a plain list is sorted, the cursor
8224 will be in the first entry of the sorted region/list.")
8226 (defun org-sort-entries
8227 (&optional with-case sorting-type getkey-func compare-func property)
8228 "Sort entries on a certain level of an outline tree.
8229 If there is an active region, the entries in the region are sorted.
8230 Else, if the cursor is before the first entry, sort the top-level items.
8231 Else, the children of the entry at point are sorted.
8233 Sorting can be alphabetically, numerically, by date/time as given by
8234 a time stamp, by a property or by priority.
8236 The command prompts for the sorting type unless it has been given to the
8237 function through the SORTING-TYPE argument, which needs to be a character,
8238 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8239 precise meaning of each character:
8241 n Numerically, by converting the beginning of the entry/item to a number.
8242 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8243 o By order of TODO keywords.
8244 t By date/time, either the first active time stamp in the entry, or, if
8245 none exist, by the first inactive one.
8246 s By the scheduled date/time.
8247 d By deadline date/time.
8248 c By creation time, which is assumed to be the first inactive time stamp
8249 at the beginning of a line.
8250 p By priority according to the cookie.
8251 r By the value of a property.
8253 Capital letters will reverse the sort order.
8255 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8256 called with point at the beginning of the record. It must return either
8257 a string or a number that should serve as the sorting key for that record.
8259 Comparing entries ignores case by default. However, with an optional argument
8260 WITH-CASE, the sorting considers case as well."
8261 (interactive "P")
8262 (let ((case-func (if with-case 'identity 'downcase))
8263 (cmstr
8264 ;; The clock marker is lost when using `sort-subr', let's
8265 ;; store the clocking string.
8266 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8267 (save-excursion
8268 (goto-char org-clock-marker)
8269 (looking-back "^.*") (match-string-no-properties 0))))
8270 start beg end stars re re2
8271 txt what tmp)
8272 ;; Find beginning and end of region to sort
8273 (cond
8274 ((org-region-active-p)
8275 ;; we will sort the region
8276 (setq end (region-end)
8277 what "region")
8278 (goto-char (region-beginning))
8279 (if (not (org-at-heading-p)) (outline-next-heading))
8280 (setq start (point)))
8281 ((or (org-at-heading-p)
8282 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8283 ;; we will sort the children of the current headline
8284 (org-back-to-heading)
8285 (setq start (point)
8286 end (progn (org-end-of-subtree t t)
8287 (or (bolp) (insert "\n"))
8288 (org-back-over-empty-lines)
8289 (point))
8290 what "children")
8291 (goto-char start)
8292 (show-subtree)
8293 (outline-next-heading))
8295 ;; we will sort the top-level entries in this file
8296 (goto-char (point-min))
8297 (or (org-at-heading-p) (outline-next-heading))
8298 (setq start (point))
8299 (goto-char (point-max))
8300 (beginning-of-line 1)
8301 (when (looking-at ".*?\\S-")
8302 ;; File ends in a non-white line
8303 (end-of-line 1)
8304 (insert "\n"))
8305 (setq end (point-max))
8306 (setq what "top-level")
8307 (goto-char start)
8308 (show-all)))
8310 (setq beg (point))
8311 (if (>= beg end) (error "Nothing to sort"))
8313 (looking-at "\\(\\*+\\)")
8314 (setq stars (match-string 1)
8315 re (concat "^" (regexp-quote stars) " +")
8316 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8317 txt (buffer-substring beg end))
8318 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8319 (if (and (not (equal stars "*")) (string-match re2 txt))
8320 (error "Region to sort contains a level above the first entry"))
8322 (unless sorting-type
8323 (message
8324 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8325 [t]ime [s]cheduled [d]eadline [c]reated
8326 A/N/P/R/O/F/T/S/D/C means reversed:"
8327 what)
8328 (setq sorting-type (read-char-exclusive))
8330 (unless getkey-func
8331 (and (= (downcase sorting-type) ?f)
8332 (setq getkey-func
8333 (org-icompleting-read "Sort using function: "
8334 obarray 'fboundp t nil nil))
8335 (setq getkey-func (intern getkey-func))))
8337 (and (= (downcase sorting-type) ?r)
8338 (not property)
8339 (setq property
8340 (org-icompleting-read "Property: "
8341 (mapcar 'list (org-buffer-property-keys t))
8342 nil t))))
8344 (message "Sorting entries...")
8346 (save-restriction
8347 (narrow-to-region start end)
8348 (let ((dcst (downcase sorting-type))
8349 (case-fold-search nil)
8350 (now (current-time)))
8351 (sort-subr
8352 (/= dcst sorting-type)
8353 ;; This function moves to the beginning character of the "record" to
8354 ;; be sorted.
8355 (lambda nil
8356 (if (re-search-forward re nil t)
8357 (goto-char (match-beginning 0))
8358 (goto-char (point-max))))
8359 ;; This function moves to the last character of the "record" being
8360 ;; sorted.
8361 (lambda nil
8362 (save-match-data
8363 (condition-case nil
8364 (outline-forward-same-level 1)
8365 (error
8366 (goto-char (point-max))))))
8367 ;; This function returns the value that gets sorted against.
8368 (lambda nil
8369 (cond
8370 ((= dcst ?n)
8371 (if (looking-at org-complex-heading-regexp)
8372 (string-to-number (match-string 4))
8373 nil))
8374 ((= dcst ?a)
8375 (if (looking-at org-complex-heading-regexp)
8376 (funcall case-func (match-string 4))
8377 nil))
8378 ((= dcst ?t)
8379 (let ((end (save-excursion (outline-next-heading) (point))))
8380 (if (or (re-search-forward org-ts-regexp end t)
8381 (re-search-forward org-ts-regexp-both end t))
8382 (org-time-string-to-seconds (match-string 0))
8383 (org-float-time now))))
8384 ((= dcst ?c)
8385 (let ((end (save-excursion (outline-next-heading) (point))))
8386 (if (re-search-forward
8387 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8388 end t)
8389 (org-time-string-to-seconds (match-string 0))
8390 (org-float-time now))))
8391 ((= dcst ?s)
8392 (let ((end (save-excursion (outline-next-heading) (point))))
8393 (if (re-search-forward org-scheduled-time-regexp end t)
8394 (org-time-string-to-seconds (match-string 1))
8395 (org-float-time now))))
8396 ((= dcst ?d)
8397 (let ((end (save-excursion (outline-next-heading) (point))))
8398 (if (re-search-forward org-deadline-time-regexp end t)
8399 (org-time-string-to-seconds (match-string 1))
8400 (org-float-time now))))
8401 ((= dcst ?p)
8402 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8403 (string-to-char (match-string 2))
8404 org-default-priority))
8405 ((= dcst ?r)
8406 (or (org-entry-get nil property) ""))
8407 ((= dcst ?o)
8408 (if (looking-at org-complex-heading-regexp)
8409 (- 9999 (length (member (match-string 2)
8410 org-todo-keywords-1)))))
8411 ((= dcst ?f)
8412 (if getkey-func
8413 (progn
8414 (setq tmp (funcall getkey-func))
8415 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8416 tmp)
8417 (error "Invalid key function `%s'" getkey-func)))
8418 (t (error "Invalid sorting type `%c'" sorting-type))))
8420 (cond
8421 ((= dcst ?a) 'string<)
8422 ((= dcst ?f) compare-func)
8423 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8424 (run-hooks 'org-after-sorting-entries-or-items-hook)
8425 ;; Reset the clock marker if needed
8426 (when cmstr
8427 (save-excursion
8428 (goto-char start)
8429 (search-forward cmstr nil t)
8430 (move-marker org-clock-marker (point))))
8431 (message "Sorting entries...done")))
8433 (defun org-do-sort (table what &optional with-case sorting-type)
8434 "Sort TABLE of WHAT according to SORTING-TYPE.
8435 The user will be prompted for the SORTING-TYPE if the call to this
8436 function does not specify it. WHAT is only for the prompt, to indicate
8437 what is being sorted. The sorting key will be extracted from
8438 the car of the elements of the table.
8439 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8440 (unless sorting-type
8441 (message
8442 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8443 what)
8444 (setq sorting-type (read-char-exclusive)))
8445 (let ((dcst (downcase sorting-type))
8446 extractfun comparefun)
8447 ;; Define the appropriate functions
8448 (cond
8449 ((= dcst ?n)
8450 (setq extractfun 'string-to-number
8451 comparefun (if (= dcst sorting-type) '< '>)))
8452 ((= dcst ?a)
8453 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8454 (lambda(x) (downcase (org-sort-remove-invisible x))))
8455 comparefun (if (= dcst sorting-type)
8456 'string<
8457 (lambda (a b) (and (not (string< a b))
8458 (not (string= a b)))))))
8459 ((= dcst ?t)
8460 (setq extractfun
8461 (lambda (x)
8462 (if (or (string-match org-ts-regexp x)
8463 (string-match org-ts-regexp-both x))
8464 (org-float-time
8465 (org-time-string-to-time (match-string 0 x)))
8467 comparefun (if (= dcst sorting-type) '< '>)))
8468 (t (error "Invalid sorting type `%c'" sorting-type)))
8470 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8471 table)
8472 (lambda (a b) (funcall comparefun (car a) (car b))))))
8475 ;;; The orgstruct minor mode
8477 ;; Define a minor mode which can be used in other modes in order to
8478 ;; integrate the org-mode structure editing commands.
8480 ;; This is really a hack, because the org-mode structure commands use
8481 ;; keys which normally belong to the major mode. Here is how it
8482 ;; works: The minor mode defines all the keys necessary to operate the
8483 ;; structure commands, but wraps the commands into a function which
8484 ;; tests if the cursor is currently at a headline or a plain list
8485 ;; item. If that is the case, the structure command is used,
8486 ;; temporarily setting many Org-mode variables like regular
8487 ;; expressions for filling etc. However, when any of those keys is
8488 ;; used at a different location, function uses `key-binding' to look
8489 ;; up if the key has an associated command in another currently active
8490 ;; keymap (minor modes, major mode, global), and executes that
8491 ;; command. There might be problems if any of the keys is otherwise
8492 ;; used as a prefix key.
8494 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8495 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8496 ;; addresses this by checking explicitly for both bindings.
8498 (defvar orgstruct-mode-map (make-sparse-keymap)
8499 "Keymap for the minor `orgstruct-mode'.")
8501 (defvar org-local-vars nil
8502 "List of local variables, for use by `orgstruct-mode'.")
8504 ;;;###autoload
8505 (define-minor-mode orgstruct-mode
8506 "Toggle the minor mode `orgstruct-mode'.
8507 This mode is for using Org-mode structure commands in other
8508 modes. The following keys behave as if Org-mode were active, if
8509 the cursor is on a headline, or on a plain list item (both as
8510 defined by Org-mode).
8512 M-up Move entry/item up
8513 M-down Move entry/item down
8514 M-left Promote
8515 M-right Demote
8516 M-S-up Move entry/item up
8517 M-S-down Move entry/item down
8518 M-S-left Promote subtree
8519 M-S-right Demote subtree
8520 M-q Fill paragraph and items like in Org-mode
8521 C-c ^ Sort entries
8522 C-c - Cycle list bullet
8523 TAB Cycle item visibility
8524 M-RET Insert new heading/item
8525 S-M-RET Insert new TODO heading / Checkbox item
8526 C-c C-c Set tags / toggle checkbox"
8527 nil " OrgStruct" nil
8528 (org-load-modules-maybe)
8529 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8531 ;;;###autoload
8532 (defun turn-on-orgstruct ()
8533 "Unconditionally turn on `orgstruct-mode'."
8534 (orgstruct-mode 1))
8536 (defvar org-fb-vars nil)
8537 (make-variable-buffer-local 'org-fb-vars)
8538 (defun orgstruct++-mode (&optional arg)
8539 "Toggle `orgstruct-mode', the enhanced version of it.
8540 In addition to setting orgstruct-mode, this also exports all
8541 indentation and autofilling variables from org-mode into the
8542 buffer. It will also recognize item context in multiline items."
8543 (interactive "P")
8544 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8545 (if (< arg 1)
8546 (progn (orgstruct-mode -1)
8547 (mapc (lambda(v)
8548 (org-set-local (car v)
8549 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8550 org-fb-vars))
8551 (orgstruct-mode 1)
8552 (setq org-fb-vars nil)
8553 (let (var val)
8554 (mapc
8555 (lambda (x)
8556 (when (string-match
8557 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8558 (symbol-name (car x)))
8559 (setq var (car x) val (nth 1 x))
8560 (push (list var `(quote ,(eval var))) org-fb-vars)
8561 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8562 org-local-vars)
8563 (org-set-local 'orgstruct-is-++ t))))
8565 (defvar orgstruct-is-++ nil
8566 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8567 (make-variable-buffer-local 'orgstruct-is-++)
8569 ;;;###autoload
8570 (defun turn-on-orgstruct++ ()
8571 "Unconditionally turn on `orgstruct++-mode'."
8572 (orgstruct++-mode 1))
8574 (defun orgstruct-error ()
8575 "Error when there is no default binding for a structure key."
8576 (interactive)
8577 (error "This key has no function outside structure elements"))
8579 (defun orgstruct-setup ()
8580 "Setup orgstruct keymaps."
8581 (let ((nfunc 0)
8582 (bindings
8583 (list
8584 '([(meta up)] org-metaup)
8585 '([(meta down)] org-metadown)
8586 '([(meta left)] org-metaleft)
8587 '([(meta right)] org-metaright)
8588 '([(meta shift up)] org-shiftmetaup)
8589 '([(meta shift down)] org-shiftmetadown)
8590 '([(meta shift left)] org-shiftmetaleft)
8591 '([(meta shift right)] org-shiftmetaright)
8592 '([?\e (up)] org-metaup)
8593 '([?\e (down)] org-metadown)
8594 '([?\e (left)] org-metaleft)
8595 '([?\e (right)] org-metaright)
8596 '([?\e (shift up)] org-shiftmetaup)
8597 '([?\e (shift down)] org-shiftmetadown)
8598 '([?\e (shift left)] org-shiftmetaleft)
8599 '([?\e (shift right)] org-shiftmetaright)
8600 '([(shift up)] org-shiftup)
8601 '([(shift down)] org-shiftdown)
8602 '([(shift left)] org-shiftleft)
8603 '([(shift right)] org-shiftright)
8604 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8605 '("\M-q" fill-paragraph)
8606 '("\C-c^" org-sort)
8607 '("\C-c-" org-cycle-list-bullet)))
8608 elt key fun cmd)
8609 (while (setq elt (pop bindings))
8610 (setq nfunc (1+ nfunc))
8611 (setq key (org-key (car elt))
8612 fun (nth 1 elt)
8613 cmd (orgstruct-make-binding fun nfunc key))
8614 (org-defkey orgstruct-mode-map key cmd))
8616 ;; Prevent an error for users who forgot to make autoloads
8617 (require 'org-element)
8619 ;; Special treatment needed for TAB and RET
8620 (org-defkey orgstruct-mode-map [(tab)]
8621 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8622 (org-defkey orgstruct-mode-map "\C-i"
8623 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8625 (org-defkey orgstruct-mode-map "\M-\C-m"
8626 (orgstruct-make-binding 'org-insert-heading 105
8627 "\M-\C-m" [(meta return)]))
8628 (org-defkey orgstruct-mode-map [(meta return)]
8629 (orgstruct-make-binding 'org-insert-heading 106
8630 [(meta return)] "\M-\C-m"))
8632 (org-defkey orgstruct-mode-map [(shift meta return)]
8633 (orgstruct-make-binding 'org-insert-todo-heading 107
8634 [(meta return)] "\M-\C-m"))
8636 (org-defkey orgstruct-mode-map "\e\C-m"
8637 (orgstruct-make-binding 'org-insert-heading 108
8638 "\e\C-m" [?\e (return)]))
8639 (org-defkey orgstruct-mode-map [?\e (return)]
8640 (orgstruct-make-binding 'org-insert-heading 109
8641 [?\e (return)] "\e\C-m"))
8642 (org-defkey orgstruct-mode-map [?\e (shift return)]
8643 (orgstruct-make-binding 'org-insert-todo-heading 110
8644 [?\e (return)] "\e\C-m"))
8646 (unless org-local-vars
8647 (setq org-local-vars (org-get-local-variables)))
8651 (defun orgstruct-make-binding (fun n &rest keys)
8652 "Create a function for binding in the structure minor mode.
8653 FUN is the command to call inside a table. N is used to create a unique
8654 command name. KEYS are keys that should be checked in for a command
8655 to execute outside of tables."
8656 (eval
8657 (list 'defun
8658 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8659 '(arg)
8660 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8661 "Outside of structure, run the binding of `"
8662 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8663 "'.")
8664 '(interactive "p")
8665 (list 'if
8666 `(org-context-p 'headline 'item
8667 (and orgstruct-is-++
8668 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8669 'item-body))
8670 (list 'org-run-like-in-org-mode (list 'quote fun))
8671 (list 'let '(orgstruct-mode)
8672 (list 'call-interactively
8673 (append '(or)
8674 (mapcar (lambda (k)
8675 (list 'key-binding k))
8676 keys)
8677 '('orgstruct-error))))))))
8679 (defun org-contextualize-keys (alist contexts)
8680 "Return valid elements in ALIST depending on CONTEXTS.
8682 `org-agenda-custom-commands' or `org-capture-templates' are the
8683 values used for ALIST, and `org-agenda-custom-commands-contexts'
8684 or `org-capture-templates-contexts' are the associated contexts
8685 definitions."
8686 (let ((contexts
8687 ;; normalize contexts
8688 (mapcar
8689 (lambda(c) (cond ((listp (cadr c))
8690 (list (car c) (car c) (cadr c)))
8691 ((string= "" (cadr c))
8692 (list (car c) (car c) (caddr c)))
8693 (t c))) contexts))
8694 (a alist) c r s)
8695 ;; loop over all commands or templates
8696 (while (setq c (pop a))
8697 (let (vrules repl)
8698 (cond
8699 ((not (assoc (car c) contexts))
8700 (push c r))
8701 ((and (assoc (car c) contexts)
8702 (setq vrules (org-contextualize-validate-key
8703 (car c) contexts)))
8704 (mapc (lambda (vr)
8705 (when (not (equal (car vr) (cadr vr)))
8706 (setq repl vr))) vrules)
8707 (if (not repl) (push c r)
8708 (push (cadr repl) s)
8709 (push
8710 (cons (car c)
8711 (cdr (or (assoc (cadr repl) alist)
8712 (error "Undefined key `%s' as contextual replacement for `%s'"
8713 (cadr repl) (car c)))))
8714 r))))))
8715 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8716 (delq
8718 (delete-dups
8719 (mapcar (lambda (x)
8720 (let ((tpl (car x)))
8721 (when (not (delq
8723 (mapcar (lambda(y)
8724 (equal y tpl)) s))) x)))
8725 (reverse r))))))
8727 (defun org-contextualize-validate-key (key contexts)
8728 "Check CONTEXTS for agenda or capture KEY."
8729 (let (r rr res)
8730 (while (setq r (pop contexts))
8731 (mapc
8732 (lambda (rr)
8733 (when
8734 (and (equal key (car r))
8735 (if (functionp rr) (funcall rr)
8736 (or (and (eq (car rr) 'in-file)
8737 (buffer-file-name)
8738 (string-match (cdr rr) (buffer-file-name)))
8739 (and (eq (car rr) 'in-mode)
8740 (string-match (cdr rr) (symbol-name major-mode)))
8741 (and (eq (car rr) 'in-buffer)
8742 (string-match (cdr rr) (buffer-name)))
8743 (when (and (eq (car rr) 'not-in-file)
8744 (buffer-file-name))
8745 (not (string-match (cdr rr) (buffer-file-name))))
8746 (when (eq (car rr) 'not-in-mode)
8747 (not (string-match (cdr rr) (symbol-name major-mode))))
8748 (when (eq (car rr) 'not-in-buffer)
8749 (not (string-match (cdr rr) (buffer-name)))))))
8750 (push r res)))
8751 (car (last r))))
8752 (delete-dups (delq nil res))))
8754 (defun org-context-p (&rest contexts)
8755 "Check if local context is any of CONTEXTS.
8756 Possible values in the list of contexts are `table', `headline', and `item'."
8757 (let ((pos (point)))
8758 (goto-char (point-at-bol))
8759 (prog1 (or (and (memq 'table contexts)
8760 (looking-at "[ \t]*|"))
8761 (and (memq 'headline contexts)
8762 (looking-at org-outline-regexp))
8763 (and (memq 'item contexts)
8764 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8765 (and (memq 'item-body contexts)
8766 (org-in-item-p)))
8767 (goto-char pos))))
8769 (defun org-get-local-variables ()
8770 "Return a list of all local variables in an Org mode buffer."
8771 (let (varlist)
8772 (with-current-buffer (get-buffer-create "*Org tmp*")
8773 (erase-buffer)
8774 (org-mode)
8775 (setq varlist (buffer-local-variables)))
8776 (kill-buffer "*Org tmp*")
8777 (delq nil
8778 (mapcar
8779 (lambda (x)
8780 (setq x
8781 (if (symbolp x)
8782 (list x)
8783 (list (car x) (list 'quote (cdr x)))))
8784 (if (string-match
8785 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8786 (symbol-name (car x)))
8787 x nil))
8788 varlist))))
8790 (defun org-clone-local-variables (from-buffer &optional regexp)
8791 "Clone local variables from FROM-BUFFER.
8792 Optional argument REGEXP selects variables to clone."
8793 (mapc
8794 (lambda (pair)
8795 (and (symbolp (car pair))
8796 (or (null regexp)
8797 (string-match regexp (symbol-name (car pair))))
8798 (set (make-local-variable (car pair))
8799 (cdr pair))))
8800 (buffer-local-variables from-buffer)))
8802 ;;;###autoload
8803 (defun org-run-like-in-org-mode (cmd)
8804 "Run a command, pretending that the current buffer is in Org-mode.
8805 This will temporarily bind local variables that are typically bound in
8806 Org-mode to the values they have in Org-mode, and then interactively
8807 call CMD."
8808 (org-load-modules-maybe)
8809 (unless org-local-vars
8810 (setq org-local-vars (org-get-local-variables)))
8811 (eval (list 'let org-local-vars
8812 (list 'call-interactively (list 'quote cmd)))))
8814 ;;;; Archiving
8816 (defun org-get-category (&optional pos force-refresh)
8817 "Get the category applying to position POS."
8818 (save-match-data
8819 (if force-refresh (org-refresh-category-properties))
8820 (let ((pos (or pos (point))))
8821 (or (get-text-property pos 'org-category)
8822 (progn (org-refresh-category-properties)
8823 (get-text-property pos 'org-category))))))
8825 (defun org-refresh-category-properties ()
8826 "Refresh category text properties in the buffer."
8827 (let ((case-fold-search t)
8828 (inhibit-read-only t)
8829 (def-cat (cond
8830 ((null org-category)
8831 (if buffer-file-name
8832 (file-name-sans-extension
8833 (file-name-nondirectory buffer-file-name))
8834 "???"))
8835 ((symbolp org-category) (symbol-name org-category))
8836 (t org-category)))
8837 beg end cat pos optionp)
8838 (org-unmodified
8839 (save-excursion
8840 (save-restriction
8841 (widen)
8842 (goto-char (point-min))
8843 (put-text-property (point) (point-max) 'org-category def-cat)
8844 (while (re-search-forward
8845 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8846 (setq pos (match-end 0)
8847 optionp (equal (char-after (match-beginning 0)) ?#)
8848 cat (org-trim (match-string 2)))
8849 (if optionp
8850 (setq beg (point-at-bol) end (point-max))
8851 (org-back-to-heading t)
8852 (setq beg (point) end (org-end-of-subtree t t)))
8853 (put-text-property beg end 'org-category cat)
8854 (put-text-property beg end 'org-category-position beg)
8855 (goto-char pos)))))))
8857 (defun org-refresh-properties (dprop tprop)
8858 "Refresh buffer text properties.
8859 DPROP is the drawer property and TPROP is the corresponding text
8860 property to set."
8861 (let ((case-fold-search t)
8862 (inhibit-read-only t) p)
8863 (org-unmodified
8864 (save-excursion
8865 (save-restriction
8866 (widen)
8867 (goto-char (point-min))
8868 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8869 (setq p (org-match-string-no-properties 1))
8870 (save-excursion
8871 (org-back-to-heading t)
8872 (put-text-property
8873 (point-at-bol) (point-at-eol) tprop p))))))))
8876 ;;;; Link Stuff
8878 ;;; Link abbreviations
8880 (defun org-link-expand-abbrev (link)
8881 "Apply replacements as defined in `org-link-abbrev-alist'."
8882 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8883 (let* ((key (match-string 1 link))
8884 (as (or (assoc key org-link-abbrev-alist-local)
8885 (assoc key org-link-abbrev-alist)))
8886 (tag (and (match-end 2) (match-string 3 link)))
8887 rpl)
8888 (if (not as)
8889 link
8890 (setq rpl (cdr as))
8891 (cond
8892 ((symbolp rpl) (funcall rpl tag))
8893 ((string-match "%(\\([^)]+\\))" rpl)
8894 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8895 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8896 ((string-match "%h" rpl)
8897 (replace-match (url-hexify-string (or tag "")) t t rpl))
8898 (t (concat rpl tag)))))
8899 link))
8901 ;;; Storing and inserting links
8903 (defvar org-insert-link-history nil
8904 "Minibuffer history for links inserted with `org-insert-link'.")
8906 (defvar org-stored-links nil
8907 "Contains the links stored with `org-store-link'.")
8909 (defvar org-store-link-plist nil
8910 "Plist with info about the most recently link created with `org-store-link'.")
8912 (defvar org-link-protocols nil
8913 "Link protocols added to Org-mode using `org-add-link-type'.")
8915 (defvar org-store-link-functions nil
8916 "List of functions that are called to create and store a link.
8917 Each function will be called in turn until one returns a non-nil
8918 value. Each function should check if it is responsible for creating
8919 this link (for example by looking at the major mode).
8920 If not, it must exit and return nil.
8921 If yes, it should return a non-nil value after a calling
8922 `org-store-link-props' with a list of properties and values.
8923 Special properties are:
8925 :type The link prefix, like \"http\". This must be given.
8926 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8927 This is obligatory as well.
8928 :description Optional default description for the second pair
8929 of brackets in an Org-mode link. The user can still change
8930 this when inserting this link into an Org-mode buffer.
8932 In addition to these, any additional properties can be specified
8933 and then used in capture templates.")
8935 (defun org-add-link-type (type &optional follow export)
8936 "Add TYPE to the list of `org-link-types'.
8937 Re-compute all regular expressions depending on `org-link-types'
8939 FOLLOW and EXPORT are two functions.
8941 FOLLOW should take the link path as the single argument and do whatever
8942 is necessary to follow the link, for example find a file or display
8943 a mail message.
8945 EXPORT should format the link path for export to one of the export formats.
8946 It should be a function accepting three arguments:
8948 path the path of the link, the text after the prefix (like \"http:\")
8949 desc the description of the link, if any, or a description added by
8950 org-export-normalize-links if there is none
8951 format the export format, a symbol like `html' or `latex' or `ascii'..
8953 The function may use the FORMAT information to return different values
8954 depending on the format. The return value will be put literally into
8955 the exported file. If the return value is nil, this means Org should
8956 do what it normally does with links which do not have EXPORT defined.
8958 Org-mode has a built-in default for exporting links. If you are happy with
8959 this default, there is no need to define an export function for the link
8960 type. For a simple example of an export function, see `org-bbdb.el'."
8961 (add-to-list 'org-link-types type t)
8962 (org-make-link-regexps)
8963 (if (assoc type org-link-protocols)
8964 (setcdr (assoc type org-link-protocols) (list follow export))
8965 (push (list type follow export) org-link-protocols)))
8967 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8968 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8970 ;;;###autoload
8971 (defun org-store-link (arg)
8972 "\\<org-mode-map>Store an org-link to the current location.
8973 This link is added to `org-stored-links' and can later be inserted
8974 into an org-buffer with \\[org-insert-link].
8976 For some link types, a prefix arg is interpreted.
8977 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8978 For file links, arg negates `org-context-in-file-links'.
8980 A double prefix arg force skipping storing functions that are not
8981 part of Org's core."
8982 (interactive "P")
8983 (org-load-modules-maybe)
8984 (setq org-store-link-plist nil) ; reset
8985 (org-with-limited-levels
8986 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
8987 (cond
8988 ((and (not (equal arg '(16)))
8989 (setq sfuns
8990 (delq
8991 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
8992 org-store-link-functions))
8993 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
8994 (or (and (cdr sfuns)
8995 (funcall (intern
8996 (completing-read "Which function for creating the link? "
8997 sfunsn t (car sfunsn)))))
8998 (funcall (caar sfuns)))
8999 (setq link (plist-get org-store-link-plist :link)
9000 desc (or (plist-get org-store-link-plist :description) link))))
9001 ((org-src-edit-buffer-p)
9002 (let (label gc)
9003 (while (or (not label)
9004 (save-excursion
9005 (save-restriction
9006 (widen)
9007 (goto-char (point-min))
9008 (re-search-forward
9009 (regexp-quote (format org-coderef-label-format label))
9010 nil t))))
9011 (when label (message "Label exists already") (sit-for 2))
9012 (setq label (read-string "Code line label: " label)))
9013 (end-of-line 1)
9014 (setq link (format org-coderef-label-format label))
9015 (setq gc (- 79 (length link)))
9016 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9017 (insert link)
9018 (setq link (concat "(" label ")") desc nil)))
9020 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9021 ;; We are in the agenda, link to referenced location
9022 (let ((m (or (get-text-property (point) 'org-hd-marker)
9023 (get-text-property (point) 'org-marker))))
9024 (when m
9025 (org-with-point-at m
9026 (setq agenda-link
9027 (if (org-called-interactively-p 'any)
9028 (call-interactively 'org-store-link)
9029 (org-store-link nil)))))))
9031 ((eq major-mode 'calendar-mode)
9032 (let ((cd (calendar-cursor-to-date)))
9033 (setq link
9034 (format-time-string
9035 (car org-time-stamp-formats)
9036 (apply 'encode-time
9037 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9038 nil nil nil))))
9039 (org-store-link-props :type "calendar" :date cd)))
9041 ((eq major-mode 'help-mode)
9042 (setq link (concat "help:" (save-excursion
9043 (goto-char (point-min))
9044 (looking-at "^[^ ]+")
9045 (match-string 0))))
9046 (org-store-link-props :type "help"))
9048 ((eq major-mode 'w3-mode)
9049 (setq cpltxt (if (and (buffer-name)
9050 (not (string-match "Untitled" (buffer-name))))
9051 (buffer-name)
9052 (url-view-url t))
9053 link (url-view-url t))
9054 (org-store-link-props :type "w3" :url (url-view-url t)))
9056 ((setq search (run-hook-with-args-until-success
9057 'org-create-file-search-functions))
9058 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9059 "::" search))
9060 (setq cpltxt (or description link)))
9062 ((eq major-mode 'image-mode)
9063 (setq cpltxt (concat "file:"
9064 (abbreviate-file-name buffer-file-name))
9065 link cpltxt)
9066 (org-store-link-props :type "image" :file buffer-file-name))
9068 ((eq major-mode 'dired-mode)
9069 ;; link to the file in the current line
9070 (let ((file (dired-get-filename nil t)))
9071 (setq file (if file
9072 (abbreviate-file-name
9073 (expand-file-name (dired-get-filename nil t)))
9074 ;; otherwise, no file so use current directory.
9075 default-directory))
9076 (setq cpltxt (concat "file:" file)
9077 link cpltxt)))
9079 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9080 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9081 (cond
9082 ((org-in-regexp "<<\\(.*?\\)>>")
9083 (setq cpltxt
9084 (concat "file:"
9085 (abbreviate-file-name
9086 (buffer-file-name (buffer-base-buffer)))
9087 "::" (match-string 1))
9088 link cpltxt))
9089 ((and (featurep 'org-id)
9090 (or (eq org-id-link-to-org-use-id t)
9091 (and (org-called-interactively-p 'any)
9092 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9093 (and (eq org-id-link-to-org-use-id
9094 'create-if-interactive-and-no-custom-id)
9095 (not custom-id))))
9096 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9097 ;; We can make a link using the ID.
9098 (setq link (condition-case nil
9099 (prog1 (org-id-store-link)
9100 (setq desc (plist-get org-store-link-plist :description)))
9101 (error
9102 ;; probably before first headline, link to file only
9103 (concat "file:"
9104 (abbreviate-file-name
9105 (buffer-file-name (buffer-base-buffer))))))))
9107 ;; Just link to current headline
9108 (setq cpltxt (concat "file:"
9109 (abbreviate-file-name
9110 (buffer-file-name (buffer-base-buffer)))))
9111 ;; Add a context search string
9112 (when (org-xor org-context-in-file-links arg)
9113 (let* ((ee (org-element-at-point))
9114 (et (org-element-type ee))
9115 (ev (plist-get (cadr ee) :value)))
9116 (setq txt (cond
9117 ((org-at-heading-p) nil)
9118 ((eq et 'keyword) ev)
9119 ((org-region-active-p)
9120 (buffer-substring (region-beginning) (region-end)))))
9121 (when (or (null txt) (string-match "\\S-" txt))
9122 (setq cpltxt
9123 (concat cpltxt "::"
9124 (condition-case nil
9125 (org-make-org-heading-search-string txt)
9126 (error "")))
9127 desc (or (and (eq et 'keyword) ev)
9128 (nth 4 (ignore-errors (org-heading-components)))
9129 "NONE")))))
9130 (if (string-match "::\\'" cpltxt)
9131 (setq cpltxt (substring cpltxt 0 -2)))
9132 (setq link cpltxt))))
9134 ((buffer-file-name (buffer-base-buffer))
9135 ;; Just link to this file here.
9136 (setq cpltxt (concat "file:"
9137 (abbreviate-file-name
9138 (buffer-file-name (buffer-base-buffer)))))
9139 ;; Add a context string
9140 (when (org-xor org-context-in-file-links arg)
9141 (setq txt (if (org-region-active-p)
9142 (buffer-substring (region-beginning) (region-end))
9143 (buffer-substring (point-at-bol) (point-at-eol))))
9144 ;; Only use search option if there is some text.
9145 (when (string-match "\\S-" txt)
9146 (setq cpltxt
9147 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9148 desc "NONE")))
9149 (setq link cpltxt))
9151 ((org-called-interactively-p 'interactive)
9152 (user-error "No method for storing a link from this buffer"))
9154 (t (setq link nil)))
9156 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9157 (setq link (or link cpltxt)
9158 desc (or desc cpltxt))
9159 (cond ((equal desc "NONE") (setq desc nil))
9160 ((string-match org-bracket-link-regexp desc)
9161 (setq desc (replace-regexp-in-string
9162 org-bracket-link-regexp
9163 (concat "\\3" (if (equal (length (match-string 0 desc))
9164 (length desc)) "*" "")) desc))))
9166 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9167 (progn
9168 (setq org-stored-links
9169 (cons (list link desc) org-stored-links))
9170 (message "Stored: %s" (or desc link))
9171 (when custom-id
9172 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9173 "::#" custom-id))
9174 (setq org-stored-links
9175 (cons (list link desc) org-stored-links))))
9176 (or agenda-link (and link (org-make-link-string link desc)))))))
9178 (defun org-store-link-props (&rest plist)
9179 "Store link properties, extract names and addresses."
9180 (let (x adr)
9181 (when (setq x (plist-get plist :from))
9182 (setq adr (mail-extract-address-components x))
9183 (setq plist (plist-put plist :fromname (car adr)))
9184 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9185 (when (setq x (plist-get plist :to))
9186 (setq adr (mail-extract-address-components x))
9187 (setq plist (plist-put plist :toname (car adr)))
9188 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9189 (let ((from (plist-get plist :from))
9190 (to (plist-get plist :to)))
9191 (when (and from to org-from-is-user-regexp)
9192 (setq plist
9193 (plist-put plist :fromto
9194 (if (string-match org-from-is-user-regexp from)
9195 (concat "to %t")
9196 (concat "from %f"))))))
9197 (setq org-store-link-plist plist))
9199 (defun org-add-link-props (&rest plist)
9200 "Add these properties to the link property list."
9201 (let (key value)
9202 (while plist
9203 (setq key (pop plist) value (pop plist))
9204 (setq org-store-link-plist
9205 (plist-put org-store-link-plist key value)))))
9207 (defun org-email-link-description (&optional fmt)
9208 "Return the description part of an email link.
9209 This takes information from `org-store-link-plist' and formats it
9210 according to FMT (default from `org-email-link-description-format')."
9211 (setq fmt (or fmt org-email-link-description-format))
9212 (let* ((p org-store-link-plist)
9213 (to (plist-get p :toaddress))
9214 (from (plist-get p :fromaddress))
9215 (table
9216 (list
9217 (cons "%c" (plist-get p :fromto))
9218 (cons "%F" (plist-get p :from))
9219 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9220 (cons "%T" (plist-get p :to))
9221 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9222 (cons "%s" (plist-get p :subject))
9223 (cons "%d" (plist-get p :date))
9224 (cons "%m" (plist-get p :message-id)))))
9225 (when (string-match "%c" fmt)
9226 ;; Check if the user wrote this message
9227 (if (and org-from-is-user-regexp from to
9228 (save-match-data (string-match org-from-is-user-regexp from)))
9229 (setq fmt (replace-match "to %t" t t fmt))
9230 (setq fmt (replace-match "from %f" t t fmt))))
9231 (org-replace-escapes fmt table)))
9233 (defun org-make-org-heading-search-string (&optional string)
9234 "Make search string for the current headline or STRING."
9235 (let ((s (or string
9236 (and (derived-mode-p 'org-mode)
9237 (save-excursion
9238 (org-back-to-heading t)
9239 (plist-get (cadr (org-element-at-point))
9240 :raw-value)))))
9241 (lines org-context-in-file-links))
9242 (or string (setq s (concat "*" s))) ; Add * for headlines
9243 (when (and string (integerp lines) (> lines 0))
9244 (let ((slines (org-split-string s "\n")))
9245 (when (< lines (length slines))
9246 (setq s (mapconcat
9247 'identity
9248 (reverse (nthcdr (- (length slines) lines)
9249 (reverse slines))) "\n")))))
9250 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9252 (defun org-make-link-string (link &optional description)
9253 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9254 (unless (string-match "\\S-" link)
9255 (error "Empty link"))
9256 (when (and description
9257 (stringp description)
9258 (not (string-match "\\S-" description)))
9259 (setq description nil))
9260 (when (stringp description)
9261 ;; Remove brackets from the description, they are fatal.
9262 (while (string-match "\\[" description)
9263 (setq description (replace-match "{" t t description)))
9264 (while (string-match "\\]" description)
9265 (setq description (replace-match "}" t t description))))
9266 (when (equal link description)
9267 ;; No description needed, it is identical
9268 (setq description nil))
9269 (when (and (not description)
9270 (not (string-match (org-image-file-name-regexp) link))
9271 (not (equal link (org-link-escape link))))
9272 (setq description (org-extract-attributes link)))
9273 (setq link
9274 (cond ((string-match (org-image-file-name-regexp) link) link)
9275 ((string-match org-link-types-re link)
9276 (concat (match-string 1 link)
9277 (org-link-escape (substring link (match-end 1)))))
9278 (t (org-link-escape link))))
9279 (concat "[[" link "]"
9280 (if description (concat "[" description "]") "")
9281 "]"))
9283 (defconst org-link-escape-chars
9284 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9285 "List of characters that should be escaped in link.
9286 This is the list that is used for internal purposes.")
9288 (defconst org-link-escape-chars-browser
9289 '(?\ )
9290 "List of escapes for characters that are problematic in links.
9291 This is the list that is used before handing over to the browser.")
9293 (defun org-link-escape (text &optional table merge)
9294 "Return percent escaped representation of TEXT.
9295 TEXT is a string with the text to escape.
9296 Optional argument TABLE is a list with characters that should be
9297 escaped. When nil, `org-link-escape-chars' is used.
9298 If optional argument MERGE is set, merge TABLE into
9299 `org-link-escape-chars'."
9300 (cond
9301 ((and table merge)
9302 (mapc (lambda (defchr)
9303 (unless (member defchr table)
9304 (setq table (cons defchr table)))) org-link-escape-chars))
9305 ((null table)
9306 (setq table org-link-escape-chars)))
9307 (mapconcat
9308 (lambda (char)
9309 (if (or (member char table)
9310 (and (or (< char 32) (= char 37) (> char 126))
9311 org-url-hexify-p))
9312 (mapconcat (lambda (sequence-element)
9313 (format "%%%.2X" sequence-element))
9314 (or (encode-coding-char char 'utf-8)
9315 (error "Unable to percent escape character: %s"
9316 (char-to-string char))) "")
9317 (char-to-string char))) text ""))
9319 (defun org-link-unescape (str)
9320 "Unhex hexified Unicode strings as returned from the JavaScript function
9321 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9322 (unless (and (null str) (string= "" str))
9323 (let ((pos 0) (case-fold-search t) unhexed)
9324 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9325 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9326 (setq str (replace-match unhexed t t str))
9327 (setq pos (+ pos (length unhexed))))))
9328 str)
9330 (defun org-link-unescape-compound (hex)
9331 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9332 Note: this function also decodes single byte encodings like
9333 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9334 (save-match-data
9335 (let* ((bytes (cdr (split-string hex "%")))
9336 (ret "")
9337 (eat 0)
9338 (sum 0))
9339 (while bytes
9340 (let* ((val (string-to-number (pop bytes) 16))
9341 (shift-xor
9342 (if (= 0 eat)
9343 (cond
9344 ((>= val 252) (cons 6 252))
9345 ((>= val 248) (cons 5 248))
9346 ((>= val 240) (cons 4 240))
9347 ((>= val 224) (cons 3 224))
9348 ((>= val 192) (cons 2 192))
9349 (t (cons 0 0)))
9350 (cons 6 128))))
9351 (if (>= val 192) (setq eat (car shift-xor)))
9352 (setq val (logxor val (cdr shift-xor)))
9353 (setq sum (+ (lsh sum (car shift-xor)) val))
9354 (if (> eat 0) (setq eat (- eat 1)))
9355 (cond
9356 ((= 0 eat) ;multi byte
9357 (setq ret (concat ret (org-char-to-string sum)))
9358 (setq sum 0))
9359 ((not bytes) ; single byte(s)
9360 (setq ret (org-link-unescape-single-byte-sequence hex))))
9361 )) ;; end (while bytes
9362 ret )))
9364 (defun org-link-unescape-single-byte-sequence (hex)
9365 "Unhexify hex-encoded single byte character sequences."
9366 (mapconcat (lambda (byte)
9367 (char-to-string (string-to-number byte 16)))
9368 (cdr (split-string hex "%")) ""))
9370 (defun org-xor (a b)
9371 "Exclusive or."
9372 (if a (not b) b))
9374 (defun org-fixup-message-id-for-http (s)
9375 "Replace special characters in a message id, so it can be used in an http query."
9376 (when (string-match "%" s)
9377 (setq s (mapconcat (lambda (c)
9378 (if (eq c ?%)
9379 "%25"
9380 (char-to-string c)))
9381 s "")))
9382 (while (string-match "<" s)
9383 (setq s (replace-match "%3C" t t s)))
9384 (while (string-match ">" s)
9385 (setq s (replace-match "%3E" t t s)))
9386 (while (string-match "@" s)
9387 (setq s (replace-match "%40" t t s)))
9390 (defun org-link-prettify (link)
9391 "Return a human-readable representation of LINK.
9392 The car of LINK must be a raw link the cdr of LINK must be either
9393 a link description or nil."
9394 (let ((desc (or (cadr link) "<no description>")))
9395 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9396 "<" (car link) ">")))
9398 ;;;###autoload
9399 (defun org-insert-link-global ()
9400 "Insert a link like Org-mode does.
9401 This command can be called in any mode to insert a link in Org-mode syntax."
9402 (interactive)
9403 (org-load-modules-maybe)
9404 (org-run-like-in-org-mode 'org-insert-link))
9406 (defun org-insert-all-links (&optional keep)
9407 "Insert all links in `org-stored-links'."
9408 (interactive "P")
9409 (let ((links (copy-sequence org-stored-links)) l)
9410 (while (setq l (if keep (pop links) (pop org-stored-links)))
9411 (insert "- ")
9412 (org-insert-link nil (car l) (cadr l))
9413 (insert "\n"))))
9415 (defun org-link-fontify-links-to-this-file ()
9416 "Fontify links to the current file in `org-stored-links'."
9417 (let ((f (buffer-file-name)) a b)
9418 (setq a (mapcar (lambda(l)
9419 (let ((ll (car l)))
9420 (when (and (string-match "^file:\\(.+\\)::" ll)
9421 (equal f (expand-file-name (match-string 1 ll))))
9422 ll)))
9423 org-stored-links))
9424 (when (featurep 'org-id)
9425 (setq b (mapcar (lambda(l)
9426 (let ((ll (car l)))
9427 (when (and (string-match "^id:\\(.+\\)$" ll)
9428 (equal f (expand-file-name
9429 (or (org-id-find-id-file
9430 (match-string 1 ll)) ""))))
9431 ll)))
9432 org-stored-links)))
9433 (mapcar (lambda(l)
9434 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9435 (delq nil (append a b)))))
9437 (defvar org-link-links-in-this-file nil)
9438 (defun org-insert-link (&optional complete-file link-location default-description)
9439 "Insert a link. At the prompt, enter the link.
9441 Completion can be used to insert any of the link protocol prefixes like
9442 http or ftp in use.
9444 The history can be used to select a link previously stored with
9445 `org-store-link'. When the empty string is entered (i.e. if you just
9446 press RET at the prompt), the link defaults to the most recently
9447 stored link. As SPC triggers completion in the minibuffer, you need to
9448 use M-SPC or C-q SPC to force the insertion of a space character.
9450 You will also be prompted for a description, and if one is given, it will
9451 be displayed in the buffer instead of the link.
9453 If there is already a link at point, this command will allow you to edit link
9454 and description parts.
9456 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9457 be selected using completion. The path to the file will be relative to the
9458 current directory if the file is in the current directory or a subdirectory.
9459 Otherwise, the link will be the absolute path as completed in the minibuffer
9460 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9461 option `org-link-file-path-type'.
9463 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9464 the current directory or below.
9466 With three \\[universal-argument] prefixes, negate the meaning of
9467 `org-keep-stored-link-after-insertion'.
9469 If `org-make-link-description-function' is non-nil, this function will be
9470 called with the link target, and the result will be the default
9471 link description.
9473 If the LINK-LOCATION parameter is non-nil, this value will be
9474 used as the link location instead of reading one interactively.
9476 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9477 be used as the default description."
9478 (interactive "P")
9479 (let* ((wcf (current-window-configuration))
9480 (origbuf (current-buffer))
9481 (region (if (org-region-active-p)
9482 (buffer-substring (region-beginning) (region-end))))
9483 (remove (and region (list (region-beginning) (region-end))))
9484 (desc region)
9485 tmphist ; byte-compile incorrectly complains about this
9486 (link link-location)
9487 (abbrevs org-link-abbrev-alist-local)
9488 entry file all-prefixes auto-desc)
9489 (cond
9490 (link-location) ; specified by arg, just use it.
9491 ((org-in-regexp org-bracket-link-regexp 1)
9492 ;; We do have a link at point, and we are going to edit it.
9493 (setq remove (list (match-beginning 0) (match-end 0)))
9494 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9495 (setq link (read-string "Link: "
9496 (org-link-unescape
9497 (org-match-string-no-properties 1)))))
9498 ((or (org-in-regexp org-angle-link-re)
9499 (org-in-regexp org-plain-link-re))
9500 ;; Convert to bracket link
9501 (setq remove (list (match-beginning 0) (match-end 0))
9502 link (read-string "Link: "
9503 (org-remove-angle-brackets (match-string 0)))))
9504 ((member complete-file '((4) (16)))
9505 ;; Completing read for file names.
9506 (setq link (org-file-complete-link complete-file)))
9508 ;; Read link, with completion for stored links.
9509 (org-link-fontify-links-to-this-file)
9510 (org-switch-to-buffer-other-window "*Org Links*")
9511 (with-current-buffer "*Org Links*"
9512 (erase-buffer)
9513 (insert "Insert a link.
9514 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9515 (when org-stored-links
9516 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9517 (insert (mapconcat 'org-link-prettify
9518 (reverse org-stored-links) "\n")))
9519 (goto-char (point-min)))
9520 (let ((cw (selected-window)))
9521 (select-window (get-buffer-window "*Org Links*" 'visible))
9522 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9523 (unless (pos-visible-in-window-p (point-max))
9524 (org-fit-window-to-buffer))
9525 (and (window-live-p cw) (select-window cw)))
9526 ;; Fake a link history, containing the stored links.
9527 (setq tmphist (append (mapcar 'car org-stored-links)
9528 org-insert-link-history))
9529 (setq all-prefixes (append (mapcar 'car abbrevs)
9530 (mapcar 'car org-link-abbrev-alist)
9531 org-link-types))
9532 (unwind-protect
9533 (progn
9534 (setq link
9535 (org-completing-read
9536 "Link: "
9537 (append
9538 (mapcar (lambda (x) (concat x ":"))
9539 all-prefixes)
9540 (mapcar 'car org-stored-links))
9541 nil nil nil
9542 'tmphist
9543 (caar org-stored-links)))
9544 (if (not (string-match "\\S-" link))
9545 (error "No link selected"))
9546 (mapc (lambda(l)
9547 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9548 org-stored-links)
9549 (if (or (member link all-prefixes)
9550 (and (equal ":" (substring link -1))
9551 (member (substring link 0 -1) all-prefixes)
9552 (setq link (substring link 0 -1))))
9553 (setq link (with-current-buffer origbuf
9554 (org-link-try-special-completion link)))))
9555 (set-window-configuration wcf)
9556 (kill-buffer "*Org Links*"))
9557 (setq entry (assoc link org-stored-links))
9558 (or entry (push link org-insert-link-history))
9559 (setq desc (or desc (nth 1 entry)))))
9561 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9562 (not org-keep-stored-link-after-insertion))
9563 (setq org-stored-links (delq (assoc link org-stored-links)
9564 org-stored-links)))
9566 (if (string-match org-plain-link-re link)
9567 ;; URL-like link, normalize the use of angular brackets.
9568 (setq link (org-remove-angle-brackets link)))
9570 ;; Check if we are linking to the current file with a search
9571 ;; option If yes, simplify the link by using only the search
9572 ;; option.
9573 (when (and buffer-file-name
9574 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9575 (let* ((path (match-string 1 link))
9576 (case-fold-search nil)
9577 (search (match-string 2 link)))
9578 (save-match-data
9579 (if (equal (file-truename buffer-file-name) (file-truename path))
9580 ;; We are linking to this same file, with a search option
9581 (setq link search)))))
9583 ;; Check if we can/should use a relative path. If yes, simplify the link
9584 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9585 (let* ((type (match-string 1 link))
9586 (path (match-string 2 link))
9587 (origpath path)
9588 (case-fold-search nil))
9589 (cond
9590 ((or (eq org-link-file-path-type 'absolute)
9591 (equal complete-file '(16)))
9592 (setq path (abbreviate-file-name (expand-file-name path))))
9593 ((eq org-link-file-path-type 'noabbrev)
9594 (setq path (expand-file-name path)))
9595 ((eq org-link-file-path-type 'relative)
9596 (setq path (file-relative-name path)))
9598 (save-match-data
9599 (if (string-match (concat "^" (regexp-quote
9600 (expand-file-name
9601 (file-name-as-directory
9602 default-directory))))
9603 (expand-file-name path))
9604 ;; We are linking a file with relative path name.
9605 (setq path (substring (expand-file-name path)
9606 (match-end 0)))
9607 (setq path (abbreviate-file-name (expand-file-name path)))))))
9608 (setq link (concat type path))
9609 (if (equal desc origpath)
9610 (setq desc path))))
9612 (if org-make-link-description-function
9613 (setq desc
9614 (or (condition-case nil
9615 (funcall org-make-link-description-function link desc)
9616 (error (progn (message "Can't get link description from `%s'"
9617 (symbol-name org-make-link-description-function))
9618 (sit-for 2) nil)))
9619 (read-string "Description: " default-description)))
9620 (if default-description (setq desc default-description)
9621 (setq desc (or (and auto-desc desc)
9622 (read-string "Description: " desc)))))
9624 (unless (string-match "\\S-" desc) (setq desc nil))
9625 (if remove (apply 'delete-region remove))
9626 (insert (org-make-link-string link desc))))
9628 (defun org-link-try-special-completion (type)
9629 "If there is completion support for link type TYPE, offer it."
9630 (let ((fun (intern (concat "org-" type "-complete-link"))))
9631 (if (functionp fun)
9632 (funcall fun)
9633 (read-string "Link (no completion support): " (concat type ":")))))
9635 (defun org-file-complete-link (&optional arg)
9636 "Create a file link using completion."
9637 (let (file link)
9638 (setq file (org-iread-file-name "File: "))
9639 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9640 (pwd1 (file-name-as-directory (abbreviate-file-name
9641 (expand-file-name ".")))))
9642 (cond
9643 ((equal arg '(16))
9644 (setq link (concat
9645 "file:"
9646 (abbreviate-file-name (expand-file-name file)))))
9647 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9648 (setq link (concat "file:" (match-string 1 file))))
9649 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9650 (expand-file-name file))
9651 (setq link (concat
9652 "file:" (match-string 1 (expand-file-name file)))))
9653 (t (setq link (concat "file:" file)))))
9654 link))
9656 (defun org-iread-file-name (&rest args)
9657 "Read-file-name using `ido-mode' speedup if available.
9658 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9659 See `read-file-name' for a description of parameters."
9660 (org-without-partial-completion
9661 (if (and org-completion-use-ido
9662 (fboundp 'ido-read-file-name)
9663 (boundp 'ido-mode) ido-mode
9664 (listp (second args)))
9665 (let ((ido-enter-matching-directory nil))
9666 (apply 'ido-read-file-name args))
9667 (apply 'read-file-name args))))
9669 (defun org-completing-read (&rest args)
9670 "Completing-read with SPACE being a normal character."
9671 (let ((enable-recursive-minibuffers t)
9672 (minibuffer-local-completion-map
9673 (copy-keymap minibuffer-local-completion-map)))
9674 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9675 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9676 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9677 (apply 'org-icompleting-read args)))
9679 (defun org-completing-read-no-i (&rest args)
9680 (let (org-completion-use-ido org-completion-use-iswitchb)
9681 (apply 'org-completing-read args)))
9683 (defun org-iswitchb-completing-read (prompt choices &rest args)
9684 "Use iswitch as a completing-read replacement to choose from choices.
9685 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9686 from."
9687 (let* ((iswitchb-use-virtual-buffers nil)
9688 (iswitchb-make-buflist-hook
9689 (lambda ()
9690 (setq iswitchb-temp-buflist choices))))
9691 (iswitchb-read-buffer prompt)))
9693 (defun org-icompleting-read (&rest args)
9694 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9695 (org-without-partial-completion
9696 (if (and org-completion-use-ido
9697 (fboundp 'ido-completing-read)
9698 (boundp 'ido-mode) ido-mode
9699 (listp (second args)))
9700 (let ((ido-enter-matching-directory nil))
9701 (apply 'ido-completing-read (concat (car args))
9702 (if (consp (car (nth 1 args)))
9703 (mapcar 'car (nth 1 args))
9704 (nth 1 args))
9705 (cddr args)))
9706 (if (and org-completion-use-iswitchb
9707 (boundp 'iswitchb-mode) iswitchb-mode
9708 (listp (second args)))
9709 (apply 'org-iswitchb-completing-read (concat (car args))
9710 (if (consp (car (nth 1 args)))
9711 (mapcar 'car (nth 1 args))
9712 (nth 1 args))
9713 (cddr args))
9714 (apply 'completing-read args)))))
9716 (defun org-extract-attributes (s)
9717 "Extract the attributes cookie from a string and set as text property."
9718 (let (a attr (start 0) key value)
9719 (save-match-data
9720 (when (string-match "{{\\([^}]+\\)}}$" s)
9721 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9722 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9723 (setq key (match-string 1 a) value (match-string 2 a)
9724 start (match-end 0)
9725 attr (plist-put attr (intern key) value))))
9726 (org-add-props s nil 'org-attr attr))
9729 (defun org-extract-attributes-from-string (tag)
9730 (let (key value attr)
9731 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9732 (setq key (match-string 1 tag) value (match-string 2 tag)
9733 tag (replace-match "" t t tag)
9734 attr (plist-put attr (intern key) value)))
9735 (cons tag attr)))
9737 (defun org-attributes-to-string (plist)
9738 "Format a property list into an HTML attribute list."
9739 (let ((s "") key value)
9740 (while plist
9741 (setq key (pop plist) value (pop plist))
9742 (and value
9743 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9746 ;;; Opening/following a link
9748 (defvar org-link-search-failed nil)
9750 (defvar org-open-link-functions nil
9751 "Hook for functions finding a plain text link.
9752 These functions must take a single argument, the link content.
9753 They will be called for links that look like [[link text][description]]
9754 when LINK TEXT does not have a protocol like \"http:\" and does not look
9755 like a filename (e.g. \"./blue.png\").
9757 These functions will be called *before* Org attempts to resolve the
9758 link by doing text searches in the current buffer - so if you want a
9759 link \"[[target]]\" to still find \"<<target>>\", your function should
9760 handle this as a special case.
9762 When the function does handle the link, it must return a non-nil value.
9763 If it decides that it is not responsible for this link, it must return
9764 nil to indicate that that Org-mode can continue with other options
9765 like exact and fuzzy text search.")
9767 (defun org-next-link ()
9768 "Move forward to the next link.
9769 If the link is in hidden text, expose it."
9770 (interactive)
9771 (when (and org-link-search-failed (eq this-command last-command))
9772 (goto-char (point-min))
9773 (message "Link search wrapped back to beginning of buffer"))
9774 (setq org-link-search-failed nil)
9775 (let* ((pos (point))
9776 (ct (org-context))
9777 (a (assoc :link ct)))
9778 (if a (goto-char (nth 2 a)))
9779 (if (re-search-forward org-any-link-re nil t)
9780 (progn
9781 (goto-char (match-beginning 0))
9782 (if (outline-invisible-p) (org-show-context)))
9783 (goto-char pos)
9784 (setq org-link-search-failed t)
9785 (error "No further link found"))))
9787 (defun org-previous-link ()
9788 "Move backward to the previous link.
9789 If the link is in hidden text, expose it."
9790 (interactive)
9791 (when (and org-link-search-failed (eq this-command last-command))
9792 (goto-char (point-max))
9793 (message "Link search wrapped back to end of buffer"))
9794 (setq org-link-search-failed nil)
9795 (let* ((pos (point))
9796 (ct (org-context))
9797 (a (assoc :link ct)))
9798 (if a (goto-char (nth 1 a)))
9799 (if (re-search-backward org-any-link-re nil t)
9800 (progn
9801 (goto-char (match-beginning 0))
9802 (if (outline-invisible-p) (org-show-context)))
9803 (goto-char pos)
9804 (setq org-link-search-failed t)
9805 (error "No further link found"))))
9807 (defun org-translate-link (s)
9808 "Translate a link string if a translation function has been defined."
9809 (if (and org-link-translation-function
9810 (fboundp org-link-translation-function)
9811 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9812 (progn
9813 (setq s (funcall org-link-translation-function
9814 (match-string 1 s) (match-string 2 s)))
9815 (concat (car s) ":" (cdr s)))
9818 (defun org-translate-link-from-planner (type path)
9819 "Translate a link from Emacs Planner syntax so that Org can follow it.
9820 This is still an experimental function, your mileage may vary."
9821 (cond
9822 ((member type '("http" "https" "news" "ftp"))
9823 ;; standard Internet links are the same.
9824 nil)
9825 ((and (equal type "irc") (string-match "^//" path))
9826 ;; Planner has two / at the beginning of an irc link, we have 1.
9827 ;; We should have zero, actually....
9828 (setq path (substring path 1)))
9829 ((and (equal type "lisp") (string-match "^/" path))
9830 ;; Planner has a slash, we do not.
9831 (setq type "elisp" path (substring path 1)))
9832 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9833 ;; A typical message link. Planner has the id after the final slash,
9834 ;; we separate it with a hash mark
9835 (setq path (concat (match-string 1 path) "#"
9836 (org-remove-angle-brackets (match-string 2 path)))))
9838 (cons type path))
9840 (defun org-find-file-at-mouse (ev)
9841 "Open file link or URL at mouse."
9842 (interactive "e")
9843 (mouse-set-point ev)
9844 (org-open-at-point 'in-emacs))
9846 (defun org-open-at-mouse (ev)
9847 "Open file link or URL at mouse.
9848 See the docstring of `org-open-file' for details."
9849 (interactive "e")
9850 (mouse-set-point ev)
9851 (if (eq major-mode 'org-agenda-mode)
9852 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9853 (org-open-at-point))
9855 (defvar org-window-config-before-follow-link nil
9856 "The window configuration before following a link.
9857 This is saved in case the need arises to restore it.")
9859 (defvar org-open-link-marker (make-marker)
9860 "Marker pointing to the location where `org-open-at-point; was called.")
9862 ;;;###autoload
9863 (defun org-open-at-point-global ()
9864 "Follow a link like Org-mode does.
9865 This command can be called in any mode to follow a link that has
9866 Org-mode syntax."
9867 (interactive)
9868 (org-run-like-in-org-mode 'org-open-at-point))
9870 ;;;###autoload
9871 (defun org-open-link-from-string (s &optional arg reference-buffer)
9872 "Open a link in the string S, as if it was in Org-mode."
9873 (interactive "sLink: \nP")
9874 (let ((reference-buffer (or reference-buffer (current-buffer))))
9875 (with-temp-buffer
9876 (let ((org-inhibit-startup (not reference-buffer)))
9877 (org-mode)
9878 (insert s)
9879 (goto-char (point-min))
9880 (when reference-buffer
9881 (setq org-link-abbrev-alist-local
9882 (with-current-buffer reference-buffer
9883 org-link-abbrev-alist-local)))
9884 (org-open-at-point arg reference-buffer)))))
9886 (defvar org-open-at-point-functions nil
9887 "Hook that is run when following a link at point.
9889 Functions in this hook must return t if they identify and follow
9890 a link at point. If they don't find anything interesting at point,
9891 they must return nil.")
9893 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9894 (defun org-open-at-point (&optional arg reference-buffer)
9895 "Open link at or after point.
9896 If there is no link at point, this function will search forward up to
9897 the end of the current line.
9898 Normally, files will be opened by an appropriate application. If the
9899 optional prefix argument ARG is non-nil, Emacs will visit the file.
9900 With a double prefix argument, try to open outside of Emacs, in the
9901 application the system uses for this file type."
9902 (interactive "P")
9903 ;; if in a code block, then open the block's results
9904 (unless (call-interactively #'org-babel-open-src-block-result)
9905 (org-load-modules-maybe)
9906 (move-marker org-open-link-marker (point))
9907 (setq org-window-config-before-follow-link (current-window-configuration))
9908 (org-remove-occur-highlights nil nil t)
9909 (cond
9910 ((and (org-at-heading-p)
9911 (not (org-at-timestamp-p t))
9912 (not (org-in-regexp
9913 (concat org-plain-link-re "\\|"
9914 org-bracket-link-regexp "\\|"
9915 org-angle-link-re "\\|"
9916 "[ \t]:[^ \t\n]+:[ \t]*$")))
9917 (not (get-text-property (point) 'org-linked-text)))
9918 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9919 (lk0 (car lkall))
9920 (lk (if (stringp lk0) (list lk0) lk0))
9921 (lkend (cdr lkall)))
9922 (mapcar (lambda(l)
9923 (search-forward l nil lkend)
9924 (goto-char (match-beginning 0))
9925 (org-open-at-point))
9926 lk))
9927 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9928 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9929 ((and (org-at-timestamp-p t)
9930 (not (org-in-regexp org-bracket-link-regexp)))
9931 (org-follow-timestamp-link))
9932 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9933 (not (org-in-regexp org-any-link-re)))
9934 (org-footnote-action))
9936 (let (type path link line search (pos (point)))
9937 (catch 'match
9938 (save-excursion
9939 (skip-chars-forward "^]\n\r")
9940 (when (org-in-regexp org-bracket-link-regexp 1)
9941 (setq link (org-extract-attributes
9942 (org-link-unescape (org-match-string-no-properties 1))))
9943 (while (string-match " *\n *" link)
9944 (setq link (replace-match " " t t link)))
9945 (setq link (org-link-expand-abbrev link))
9946 (cond
9947 ((or (file-name-absolute-p link)
9948 (string-match "^\\.\\.?/" link))
9949 (setq type "file" path link))
9950 ((string-match org-link-re-with-space3 link)
9951 (setq type (match-string 1 link) path (match-string 2 link)))
9952 ((string-match "^help:+\\(.+\\)" link)
9953 (setq type "help" path (match-string 1 link)))
9954 (t (setq type "thisfile" path link)))
9955 (throw 'match t)))
9957 (when (get-text-property (point) 'org-linked-text)
9958 (setq type "thisfile"
9959 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9960 (1+ (point)) (point))
9961 path (buffer-substring
9962 (or (previous-single-property-change pos 'org-linked-text)
9963 (point-min))
9964 (or (next-single-property-change pos 'org-linked-text)
9965 (point-max))))
9966 (throw 'match t))
9968 (save-excursion
9969 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9970 (when (or (org-in-regexp org-angle-link-re)
9971 (and plinkpos (goto-char (car plinkpos))
9972 (save-match-data (not (looking-back "\\[\\[")))))
9973 (setq type (match-string 1)
9974 path (org-link-unescape (match-string 2)))
9975 (throw 'match t))))
9976 (save-excursion
9977 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9978 (setq type "tags"
9979 path (match-string 1))
9980 (while (string-match ":" path)
9981 (setq path (replace-match "+" t t path)))
9982 (throw 'match t)))
9983 (when (org-in-regexp "<\\([^><\n]+\\)>")
9984 (setq type "tree-match"
9985 path (match-string 1))
9986 (throw 'match t)))
9987 (unless path
9988 (user-error "No link found"))
9990 ;; switch back to reference buffer
9991 ;; needed when if called in a temporary buffer through
9992 ;; org-open-link-from-string
9993 (with-current-buffer (or reference-buffer (current-buffer))
9995 ;; Remove any trailing spaces in path
9996 (if (string-match " +\\'" path)
9997 (setq path (replace-match "" t t path)))
9998 (if (and org-link-translation-function
9999 (fboundp org-link-translation-function))
10000 ;; Check if we need to translate the link
10001 (let ((tmp (funcall org-link-translation-function type path)))
10002 (setq type (car tmp) path (cdr tmp))))
10004 (cond
10006 ((assoc type org-link-protocols)
10007 (funcall (nth 1 (assoc type org-link-protocols)) path))
10009 ((equal type "help")
10010 (let ((f-or-v (intern path)))
10011 (cond ((fboundp f-or-v)
10012 (describe-function f-or-v))
10013 ((boundp f-or-v)
10014 (describe-variable f-or-v))
10015 (t (error "Not a known function or variable")))))
10017 ((equal type "mailto")
10018 (let ((cmd (car org-link-mailto-program))
10019 (args (cdr org-link-mailto-program)) args1
10020 (address path) (subject "") a)
10021 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10022 (setq address (match-string 1 path)
10023 subject (org-link-escape (match-string 2 path))))
10024 (while args
10025 (cond
10026 ((not (stringp (car args))) (push (pop args) args1))
10027 (t (setq a (pop args))
10028 (if (string-match "%a" a)
10029 (setq a (replace-match address t t a)))
10030 (if (string-match "%s" a)
10031 (setq a (replace-match subject t t a)))
10032 (push a args1))))
10033 (apply cmd (nreverse args1))))
10035 ((member type '("http" "https" "ftp" "news"))
10036 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10037 (org-link-escape
10038 path org-link-escape-chars-browser)
10039 path))))
10041 ((string= type "doi")
10042 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10043 (org-link-escape
10044 path org-link-escape-chars-browser)
10045 path))))
10047 ((member type '("message"))
10048 (browse-url (concat type ":" path)))
10050 ((string= type "tags")
10051 (org-tags-view arg path))
10053 ((string= type "tree-match")
10054 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10056 ((string= type "file")
10057 (if (string-match "::\\([0-9]+\\)\\'" path)
10058 (setq line (string-to-number (match-string 1 path))
10059 path (substring path 0 (match-beginning 0)))
10060 (if (string-match "::\\(.+\\)\\'" path)
10061 (setq search (match-string 1 path)
10062 path (substring path 0 (match-beginning 0)))))
10063 (if (string-match "[*?{]" (file-name-nondirectory path))
10064 (dired path)
10065 (org-open-file path arg line search)))
10067 ((string= type "shell")
10068 (let ((buf (generate-new-buffer "*Org Shell Output"))
10069 (cmd path))
10070 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10071 (string-match org-confirm-shell-link-not-regexp cmd))
10072 (not org-confirm-shell-link-function)
10073 (funcall org-confirm-shell-link-function
10074 (format "Execute \"%s\" in shell? "
10075 (org-add-props cmd nil
10076 'face 'org-warning))))
10077 (progn
10078 (message "Executing %s" cmd)
10079 (shell-command cmd buf)
10080 (if (featurep 'midnight)
10081 (setq clean-buffer-list-kill-buffer-names
10082 (cons buf clean-buffer-list-kill-buffer-names))))
10083 (error "Abort"))))
10085 ((string= type "elisp")
10086 (let ((cmd path))
10087 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10088 (string-match org-confirm-elisp-link-not-regexp cmd))
10089 (not org-confirm-elisp-link-function)
10090 (funcall org-confirm-elisp-link-function
10091 (format "Execute \"%s\" as elisp? "
10092 (org-add-props cmd nil
10093 'face 'org-warning))))
10094 (message "%s => %s" cmd
10095 (if (equal (string-to-char cmd) ?\()
10096 (eval (read cmd))
10097 (call-interactively (read cmd))))
10098 (error "Abort"))))
10100 ((and (string= type "thisfile")
10101 (run-hook-with-args-until-success
10102 'org-open-link-functions path)))
10104 ((string= type "thisfile")
10105 (if arg
10106 (switch-to-buffer-other-window
10107 (org-get-buffer-for-internal-link (current-buffer)))
10108 (org-mark-ring-push))
10109 (let ((cmd `(org-link-search
10110 ,path
10111 ,(cond ((equal arg '(4)) ''occur)
10112 ((equal arg '(16)) ''org-occur))
10113 ,pos)))
10114 (condition-case nil (let ((org-link-search-inhibit-query t))
10115 (eval cmd))
10116 (error (progn (widen) (eval cmd))))))
10118 (t (browse-url-at-point)))))))
10119 (move-marker org-open-link-marker nil)
10120 (run-hook-with-args 'org-follow-link-hook)))
10122 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10123 "Offer links in the current entry and return the selected link.
10124 If there is only one link, return it.
10125 If NTH is an integer, return the NTH link found.
10126 If ZERO is a string, check also this string for a link, and if
10127 there is one, return it."
10128 (with-current-buffer buffer
10129 (save-excursion
10130 (save-restriction
10131 (widen)
10132 (goto-char marker)
10133 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10134 "\\(" org-angle-link-re "\\)\\|"
10135 "\\(" org-plain-link-re "\\)"))
10136 (cnt ?0)
10137 (in-emacs (if (integerp nth) nil nth))
10138 have-zero end links link c)
10139 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10140 (push (match-string 0 zero) links)
10141 (setq cnt (1- cnt) have-zero t))
10142 (save-excursion
10143 (org-back-to-heading t)
10144 (setq end (save-excursion (outline-next-heading) (point)))
10145 (while (re-search-forward re end t)
10146 (push (match-string 0) links))
10147 (setq links (org-uniquify (reverse links))))
10148 (cond
10149 ((null links)
10150 (message "No links"))
10151 ((equal (length links) 1)
10152 (setq link (car links)))
10153 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10154 (setq link (nth (if have-zero nth (1- nth)) links)))
10155 (t ; we have to select a link
10156 (save-excursion
10157 (save-window-excursion
10158 (delete-other-windows)
10159 (with-output-to-temp-buffer "*Select Link*"
10160 (mapc (lambda (l)
10161 (if (not (string-match org-bracket-link-regexp l))
10162 (princ (format "[%c] %s\n" (incf cnt)
10163 (org-remove-angle-brackets l)))
10164 (if (match-end 3)
10165 (princ (format "[%c] %s (%s)\n" (incf cnt)
10166 (match-string 3 l) (match-string 1 l)))
10167 (princ (format "[%c] %s\n" (incf cnt)
10168 (match-string 1 l))))))
10169 links))
10170 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10171 (message "Select link to open, RET to open all:")
10172 (setq c (read-char-exclusive))
10173 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10174 (when (equal c ?q) (error "Abort"))
10175 (if (equal c ?\C-m)
10176 (setq link links)
10177 (setq nth (- c ?0))
10178 (if have-zero (setq nth (1+ nth)))
10179 (unless (and (integerp nth) (>= (length links) nth))
10180 (error "Invalid link selection"))
10181 (setq link (nth (1- nth) links)))))
10182 (cons link end))))))
10184 ;; Add special file links that specify the way of opening
10186 (org-add-link-type "file+sys" 'org-open-file-with-system)
10187 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10188 (defun org-open-file-with-system (path)
10189 "Open file at PATH using the system way of opening it."
10190 (org-open-file path 'system))
10191 (defun org-open-file-with-emacs (path)
10192 "Open file at PATH in Emacs."
10193 (org-open-file path 'emacs))
10196 ;;; File search
10198 (defvar org-create-file-search-functions nil
10199 "List of functions to construct the right search string for a file link.
10200 These functions are called in turn with point at the location to
10201 which the link should point.
10203 A function in the hook should first test if it would like to
10204 handle this file type, for example by checking the `major-mode'
10205 or the file extension. If it decides not to handle this file, it
10206 should just return nil to give other functions a chance. If it
10207 does handle the file, it must return the search string to be used
10208 when following the link. The search string will be part of the
10209 file link, given after a double colon, and `org-open-at-point'
10210 will automatically search for it. If special measures must be
10211 taken to make the search successful, another function should be
10212 added to the companion hook `org-execute-file-search-functions',
10213 which see.
10215 A function in this hook may also use `setq' to set the variable
10216 `description' to provide a suggestion for the descriptive text to
10217 be used for this link when it gets inserted into an Org-mode
10218 buffer with \\[org-insert-link].")
10220 (defvar org-execute-file-search-functions nil
10221 "List of functions to execute a file search triggered by a link.
10223 Functions added to this hook must accept a single argument, the
10224 search string that was part of the file link, the part after the
10225 double colon. The function must first check if it would like to
10226 handle this search, for example by checking the `major-mode' or
10227 the file extension. If it decides not to handle this search, it
10228 should just return nil to give other functions a chance. If it
10229 does handle the search, it must return a non-nil value to keep
10230 other functions from trying.
10232 Each function can access the current prefix argument through the
10233 variable `current-prefix-argument'. Note that a single prefix is
10234 used to force opening a link in Emacs, so it may be good to only
10235 use a numeric or double prefix to guide the search function.
10237 In case this is needed, a function in this hook can also restore
10238 the window configuration before `org-open-at-point' was called using:
10240 (set-window-configuration org-window-config-before-follow-link)")
10242 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10243 (defun org-link-search (s &optional type avoid-pos stealth)
10244 "Search for a link search option.
10245 If S is surrounded by forward slashes, it is interpreted as a
10246 regular expression. In org-mode files, this will create an `org-occur'
10247 sparse tree. In ordinary files, `occur' will be used to list matches.
10248 If the current buffer is in `dired-mode', grep will be used to search
10249 in all files. If AVOID-POS is given, ignore matches near that position.
10251 When optional argument STEALTH is non-nil, do not modify
10252 visibility around point, thus ignoring
10253 `org-show-hierarchy-above', `org-show-following-heading' and
10254 `org-show-siblings' variables."
10255 (let ((case-fold-search t)
10256 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10257 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10258 (append '(("") (" ") ("\t") ("\n"))
10259 org-emphasis-alist)
10260 "\\|") "\\)"))
10261 (pos (point))
10262 (pre nil) (post nil)
10263 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10264 (cond
10265 ;; First check if there are any special search functions
10266 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10267 ;; Now try the builtin stuff
10268 ((and (equal (string-to-char s0) ?#)
10269 (> (length s0) 1)
10270 (save-excursion
10271 (goto-char (point-min))
10272 (and
10273 (re-search-forward
10274 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10275 (setq type 'dedicated
10276 pos (match-beginning 0))))
10277 ;; There is an exact target for this
10278 (goto-char pos)
10279 (org-back-to-heading t)))
10280 ((save-excursion
10281 (goto-char (point-min))
10282 (and
10283 (re-search-forward
10284 (concat "<<" (regexp-quote s0) ">>") nil t)
10285 (setq type 'dedicated
10286 pos (match-beginning 0))))
10287 ;; There is an exact target for this
10288 (goto-char pos))
10289 ((save-excursion
10290 (goto-char (point-min))
10291 (and
10292 (re-search-forward
10293 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10294 (setq type 'dedicated pos (match-beginning 0))))
10295 ;; Found an invisible target.
10296 (goto-char pos))
10297 ((save-excursion
10298 (goto-char (point-min))
10299 (and
10300 (re-search-forward
10301 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10302 (setq type 'dedicated pos (match-beginning 0))))
10303 ;; Found an element with a matching #+name affiliated keyword.
10304 (goto-char pos))
10305 ((and (string-match "^(\\(.*\\))$" s0)
10306 (save-excursion
10307 (goto-char (point-min))
10308 (and
10309 (re-search-forward
10310 (concat "[^[]" (regexp-quote
10311 (format org-coderef-label-format
10312 (match-string 1 s0))))
10313 nil t)
10314 (setq type 'dedicated
10315 pos (1+ (match-beginning 0))))))
10316 ;; There is a coderef target for this
10317 (goto-char pos))
10318 ((string-match "^/\\(.*\\)/$" s)
10319 ;; A regular expression
10320 (cond
10321 ((derived-mode-p 'org-mode)
10322 (org-occur (match-string 1 s)))
10323 ;;((eq major-mode 'dired-mode)
10324 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10325 (t (org-do-occur (match-string 1 s)))))
10326 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10327 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10328 (goto-char (point-min))
10329 (cond
10330 ((let (case-fold-search)
10331 (re-search-forward (format org-complex-heading-regexp-format
10332 (regexp-quote s))
10333 nil t))
10334 ;; OK, found a match
10335 (setq type 'dedicated)
10336 (goto-char (match-beginning 0)))
10337 ((and (not org-link-search-inhibit-query)
10338 (eq org-link-search-must-match-exact-headline 'query-to-create)
10339 (y-or-n-p "No match - create this as a new heading? "))
10340 (goto-char (point-max))
10341 (or (bolp) (newline))
10342 (insert "* " s "\n")
10343 (beginning-of-line 0))
10345 (goto-char pos)
10346 (error "No match"))))
10348 ;; A normal search string
10349 (when (equal (string-to-char s) ?*)
10350 ;; Anchor on headlines, post may include tags.
10351 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10352 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10353 s (substring s 1)))
10354 (remove-text-properties
10355 0 (length s)
10356 '(face nil mouse-face nil keymap nil fontified nil) s)
10357 ;; Make a series of regular expressions to find a match
10358 (setq words (org-split-string s "[ \n\r\t]+")
10360 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10361 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10362 "\\)" markers)
10363 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10364 re2a (concat "[ \t\r\n]" re2a_)
10365 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10366 re4 (concat "[^a-zA-Z_]" re4_)
10368 re1 (concat pre re2 post)
10369 re3 (concat pre (if pre re4_ re4) post)
10370 re5 (concat pre ".*" re4)
10371 re2 (concat pre re2)
10372 re2a (concat pre (if pre re2a_ re2a))
10373 re4 (concat pre (if pre re4_ re4))
10374 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10375 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10376 re5 "\\)"
10378 (cond
10379 ((eq type 'org-occur) (org-occur reall))
10380 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10381 (t (goto-char (point-min))
10382 (setq type 'fuzzy)
10383 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10384 (org-search-not-self 1 re1 nil t)
10385 (org-search-not-self 1 re2 nil t)
10386 (org-search-not-self 1 re2a nil t)
10387 (org-search-not-self 1 re3 nil t)
10388 (org-search-not-self 1 re4 nil t)
10389 (org-search-not-self 1 re5 nil t)
10391 (goto-char (match-beginning 1))
10392 (goto-char pos)
10393 (error "No match"))))))
10394 (and (derived-mode-p 'org-mode)
10395 (not stealth)
10396 (org-show-context 'link-search))
10397 type))
10399 (defun org-search-not-self (group &rest args)
10400 "Execute `re-search-forward', but only accept matches that do not
10401 enclose the position of `org-open-link-marker'."
10402 (let ((m org-open-link-marker))
10403 (catch 'exit
10404 (while (apply 're-search-forward args)
10405 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10406 (goto-char (match-end group))
10407 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10408 (> (match-beginning 0) (marker-position m))
10409 (< (match-end 0) (marker-position m)))
10410 (save-match-data
10411 (or (not (org-in-regexp
10412 org-bracket-link-analytic-regexp 1))
10413 (not (match-end 4)) ; no description
10414 (and (<= (match-beginning 4) (point))
10415 (>= (match-end 4) (point))))))
10416 (throw 'exit (point))))))))
10418 (defun org-get-buffer-for-internal-link (buffer)
10419 "Return a buffer to be used for displaying the link target of internal links."
10420 (cond
10421 ((not org-display-internal-link-with-indirect-buffer)
10422 buffer)
10423 ((string-match "(Clone)$" (buffer-name buffer))
10424 (message "Buffer is already a clone, not making another one")
10425 ;; we also do not modify visibility in this case
10426 buffer)
10427 (t ; make a new indirect buffer for displaying the link
10428 (let* ((bn (buffer-name buffer))
10429 (ibn (concat bn "(Clone)"))
10430 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10431 (with-current-buffer ib (org-overview))
10432 ib))))
10434 (defun org-do-occur (regexp &optional cleanup)
10435 "Call the Emacs command `occur'.
10436 If CLEANUP is non-nil, remove the printout of the regular expression
10437 in the *Occur* buffer. This is useful if the regex is long and not useful
10438 to read."
10439 (occur regexp)
10440 (when cleanup
10441 (let ((cwin (selected-window)) win beg end)
10442 (when (setq win (get-buffer-window "*Occur*"))
10443 (select-window win))
10444 (goto-char (point-min))
10445 (when (re-search-forward "match[a-z]+" nil t)
10446 (setq beg (match-end 0))
10447 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10448 (setq end (1- (match-beginning 0)))))
10449 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10450 (goto-char (point-min))
10451 (select-window cwin))))
10453 ;;; The mark ring for links jumps
10455 (defvar org-mark-ring nil
10456 "Mark ring for positions before jumps in Org-mode.")
10457 (defvar org-mark-ring-last-goto nil
10458 "Last position in the mark ring used to go back.")
10459 ;; Fill and close the ring
10460 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10461 (loop for i from 1 to org-mark-ring-length do
10462 (push (make-marker) org-mark-ring))
10463 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10464 org-mark-ring)
10466 (defun org-mark-ring-push (&optional pos buffer)
10467 "Put the current position or POS into the mark ring and rotate it."
10468 (interactive)
10469 (setq pos (or pos (point)))
10470 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10471 (move-marker (car org-mark-ring)
10472 (or pos (point))
10473 (or buffer (current-buffer)))
10474 (message "%s"
10475 (substitute-command-keys
10476 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10478 (defun org-mark-ring-goto (&optional n)
10479 "Jump to the previous position in the mark ring.
10480 With prefix arg N, jump back that many stored positions. When
10481 called several times in succession, walk through the entire ring.
10482 Org-mode commands jumping to a different position in the current file,
10483 or to another Org-mode file, automatically push the old position
10484 onto the ring."
10485 (interactive "p")
10486 (let (p m)
10487 (if (eq last-command this-command)
10488 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10489 (setq p org-mark-ring))
10490 (setq org-mark-ring-last-goto p)
10491 (setq m (car p))
10492 (org-pop-to-buffer-same-window (marker-buffer m))
10493 (goto-char m)
10494 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10496 (defun org-remove-angle-brackets (s)
10497 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10498 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10500 (defun org-add-angle-brackets (s)
10501 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10502 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10504 (defun org-remove-double-quotes (s)
10505 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10506 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10509 ;;; Following specific links
10511 (defun org-follow-timestamp-link ()
10512 "Open an agenda view for the time-stamp date/range at point."
10513 (cond
10514 ((org-at-date-range-p t)
10515 (let ((org-agenda-start-on-weekday)
10516 (t1 (match-string 1))
10517 (t2 (match-string 2)) tt1 tt2)
10518 (setq tt1 (time-to-days (org-time-string-to-time t1))
10519 tt2 (time-to-days (org-time-string-to-time t2)))
10520 (let ((org-agenda-buffer-tmp-name
10521 (format "*Org Agenda(a:%s)"
10522 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10523 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10524 ((org-at-timestamp-p t)
10525 (let ((org-agenda-buffer-tmp-name
10526 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10527 (org-agenda-list nil (time-to-days (org-time-string-to-time
10528 (substring (match-string 1) 0 10)))
10529 1)))
10530 (t (error "This should not happen"))))
10533 ;;; Following file links
10534 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10535 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10536 (declare-function mailcap-mime-info
10537 "mailcap" (string &optional request no-decode))
10538 (defvar org-wait nil)
10539 (defun org-open-file (path &optional in-emacs line search)
10540 "Open the file at PATH.
10541 First, this expands any special file name abbreviations. Then the
10542 configuration variable `org-file-apps' is checked if it contains an
10543 entry for this file type, and if yes, the corresponding command is launched.
10545 If no application is found, Emacs simply visits the file.
10547 With optional prefix argument IN-EMACS, Emacs will visit the file.
10548 With a double \\[universal-argument] \\[universal-argument] \
10549 prefix arg, Org tries to avoid opening in Emacs
10550 and to use an external application to visit the file.
10552 Optional LINE specifies a line to go to, optional SEARCH a string
10553 to search for. If LINE or SEARCH is given, the file will be
10554 opened in Emacs, unless an entry from org-file-apps that makes
10555 use of groups in a regexp matches.
10557 If you want to change the way frames are used when following a
10558 link, please customize `org-link-frame-setup'.
10560 If the file does not exist, an error is thrown."
10561 (let* ((file (if (equal path "")
10562 buffer-file-name
10563 (substitute-in-file-name (expand-file-name path))))
10564 (file-apps (append org-file-apps (org-default-apps)))
10565 (apps (org-remove-if
10566 'org-file-apps-entry-match-against-dlink-p file-apps))
10567 (apps-dlink (org-remove-if-not
10568 'org-file-apps-entry-match-against-dlink-p file-apps))
10569 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10570 (dirp (if remp nil (file-directory-p file)))
10571 (file (if (and dirp org-open-directory-means-index-dot-org)
10572 (concat (file-name-as-directory file) "index.org")
10573 file))
10574 (a-m-a-p (assq 'auto-mode apps))
10575 (dfile (downcase file))
10576 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10577 (link (cond ((and (eq line nil)
10578 (eq search nil))
10579 file)
10580 (line
10581 (concat file "::" (number-to-string line)))
10582 (search
10583 (concat file "::" search))))
10584 (dlink (downcase link))
10585 (old-buffer (current-buffer))
10586 (old-pos (point))
10587 (old-mode major-mode)
10588 ext cmd link-match-data)
10589 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10590 (setq ext (match-string 1 dfile))
10591 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10592 (setq ext (match-string 1 dfile))))
10593 (cond
10594 ((member in-emacs '((16) system))
10595 (setq cmd (cdr (assoc 'system apps))))
10596 (in-emacs (setq cmd 'emacs))
10598 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10599 (and dirp (cdr (assoc 'directory apps)))
10600 ; first, try matching against apps-dlink
10601 ; if we get a match here, store the match data for later
10602 (let ((match (assoc-default dlink apps-dlink
10603 'string-match)))
10604 (if match
10605 (progn (setq link-match-data (match-data))
10606 match)
10607 (progn (setq in-emacs (or in-emacs line search))
10608 nil))) ; if we have no match in apps-dlink,
10609 ; always open the file in emacs if line or search
10610 ; is given (for backwards compatibility)
10611 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10612 'string-match)
10613 (cdr (assoc ext apps))
10614 (cdr (assoc t apps))))))
10615 (when (eq cmd 'system)
10616 (setq cmd (cdr (assoc 'system apps))))
10617 (when (eq cmd 'default)
10618 (setq cmd (cdr (assoc t apps))))
10619 (when (eq cmd 'mailcap)
10620 (require 'mailcap)
10621 (mailcap-parse-mailcaps)
10622 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10623 (command (mailcap-mime-info mime-type)))
10624 (if (stringp command)
10625 (setq cmd command)
10626 (setq cmd 'emacs))))
10627 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10628 (not (file-exists-p file))
10629 (not org-open-non-existing-files))
10630 (error "No such file: %s" file))
10631 (cond
10632 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10633 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10634 (while (string-match "['\"]%s['\"]" cmd)
10635 (setq cmd (replace-match "%s" t t cmd)))
10636 (while (string-match "%s" cmd)
10637 (setq cmd (replace-match
10638 (save-match-data
10639 (shell-quote-argument
10640 (convert-standard-filename file)))
10641 t t cmd)))
10643 ;; Replace "%1", "%2" etc. in command with group matches from regex
10644 (save-match-data
10645 (let ((match-index 1)
10646 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10647 (set-match-data link-match-data)
10648 (while (<= match-index number-of-groups)
10649 (let ((regex (concat "%" (number-to-string match-index)))
10650 (replace-with (match-string match-index dlink)))
10651 (while (string-match regex cmd)
10652 (setq cmd (replace-match replace-with t t cmd))))
10653 (setq match-index (+ match-index 1)))))
10655 (save-window-excursion
10656 (message "Running %s...done" cmd)
10657 (start-process-shell-command cmd nil cmd)
10658 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10659 ((or (stringp cmd)
10660 (eq cmd 'emacs))
10661 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10662 (widen)
10663 (if line (org-goto-line line)
10664 (if search (org-link-search search))))
10665 ((consp cmd)
10666 (let ((file (convert-standard-filename file)))
10667 (save-match-data
10668 (set-match-data link-match-data)
10669 (eval cmd))))
10670 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10671 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10672 (or (not (equal old-buffer (current-buffer)))
10673 (not (equal old-pos (point))))
10674 (org-mark-ring-push old-pos old-buffer))))
10676 (defun org-file-apps-entry-match-against-dlink-p (entry)
10677 "This function returns non-nil if `entry' uses a regular
10678 expression which should be matched against the whole link by
10679 org-open-file.
10681 It assumes that is the case when the entry uses a regular
10682 expression which has at least one grouping construct and the
10683 action is either a lisp form or a command string containing
10684 '%1', i.e. using at least one subexpression match as a
10685 parameter."
10686 (let ((selector (car entry))
10687 (action (cdr entry)))
10688 (if (stringp selector)
10689 (and (> (regexp-opt-depth selector) 0)
10690 (or (and (stringp action)
10691 (string-match "%[0-9]" action))
10692 (consp action)))
10693 nil)))
10695 (defun org-default-apps ()
10696 "Return the default applications for this operating system."
10697 (cond
10698 ((eq system-type 'darwin)
10699 org-file-apps-defaults-macosx)
10700 ((eq system-type 'windows-nt)
10701 org-file-apps-defaults-windowsnt)
10702 (t org-file-apps-defaults-gnu)))
10704 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10705 "Convert extensions to regular expressions in the cars of LIST.
10706 Also, weed out any non-string entries, because the return value is used
10707 only for regexp matching.
10708 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10709 point to the symbol `emacs', indicating that the file should
10710 be opened in Emacs."
10711 (append
10712 (delq nil
10713 (mapcar (lambda (x)
10714 (if (not (stringp (car x)))
10716 (if (string-match "\\W" (car x))
10718 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10719 list))
10720 (if add-auto-mode
10721 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10723 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10724 (defun org-file-remote-p (file)
10725 "Test whether FILE specifies a location on a remote system.
10726 Return non-nil if the location is indeed remote.
10728 For example, the filename \"/user@host:/foo\" specifies a location
10729 on the system \"/user@host:\"."
10730 (cond ((fboundp 'file-remote-p)
10731 (file-remote-p file))
10732 ((fboundp 'tramp-handle-file-remote-p)
10733 (tramp-handle-file-remote-p file))
10734 ((and (boundp 'ange-ftp-name-format)
10735 (string-match (car ange-ftp-name-format) file))
10736 t)))
10739 ;;;; Refiling
10741 (defun org-get-org-file ()
10742 "Read a filename, with default directory `org-directory'."
10743 (let ((default (or org-default-notes-file remember-data-file)))
10744 (read-file-name (format "File name [%s]: " default)
10745 (file-name-as-directory org-directory)
10746 default)))
10748 (defun org-notes-order-reversed-p ()
10749 "Check if the current file should receive notes in reversed order."
10750 (cond
10751 ((not org-reverse-note-order) nil)
10752 ((eq t org-reverse-note-order) t)
10753 ((not (listp org-reverse-note-order)) nil)
10754 (t (catch 'exit
10755 (let ((all org-reverse-note-order)
10756 entry)
10757 (while (setq entry (pop all))
10758 (if (string-match (car entry) buffer-file-name)
10759 (throw 'exit (cdr entry))))
10760 nil)))))
10762 (defvar org-refile-target-table nil
10763 "The list of refile targets, created by `org-refile'.")
10765 (defvar org-agenda-new-buffers nil
10766 "Buffers created to visit agenda files.")
10768 (defvar org-refile-cache nil
10769 "Cache for refile targets.")
10771 (defvar org-refile-markers nil
10772 "All the markers used for caching refile locations.")
10774 (defun org-refile-marker (pos)
10775 "Get a new refile marker, but only if caching is in use."
10776 (if (not org-refile-use-cache)
10778 (let ((m (make-marker)))
10779 (move-marker m pos)
10780 (push m org-refile-markers)
10781 m)))
10783 (defun org-refile-cache-clear ()
10784 "Clear the refile cache and disable all the markers."
10785 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10786 (setq org-refile-markers nil)
10787 (setq org-refile-cache nil)
10788 (message "Refile cache has been cleared"))
10790 (defun org-refile-cache-check-set (set)
10791 "Check if all the markers in the cache still have live buffers."
10792 (let (marker)
10793 (catch 'exit
10794 (while (and set (setq marker (nth 3 (pop set))))
10795 ;; if org-refile-use-outline-path is 'file, marker may be nil
10796 (when (and marker (null (marker-buffer marker)))
10797 (message "not found") (sit-for 3)
10798 (throw 'exit nil)))
10799 t)))
10801 (defun org-refile-cache-put (set &rest identifiers)
10802 "Push the refile targets SET into the cache, under IDENTIFIERS."
10803 (let* ((key (sha1 (prin1-to-string identifiers)))
10804 (entry (assoc key org-refile-cache)))
10805 (if entry
10806 (setcdr entry set)
10807 (push (cons key set) org-refile-cache))))
10809 (defun org-refile-cache-get (&rest identifiers)
10810 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10811 (cond
10812 ((not org-refile-cache) nil)
10813 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10815 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10816 org-refile-cache))))
10817 (and set (org-refile-cache-check-set set) set)))))
10819 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10820 "Produce a table with refile targets."
10821 (let ((case-fold-search nil)
10822 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10823 (entries (or org-refile-targets '((nil . (:level . 1)))))
10824 targets tgs txt re files f desc descre fast-path-p level pos0)
10825 (message "Getting targets...")
10826 (with-current-buffer (or default-buffer (current-buffer))
10827 (while (setq entry (pop entries))
10828 (setq files (car entry) desc (cdr entry))
10829 (setq fast-path-p nil)
10830 (cond
10831 ((null files) (setq files (list (current-buffer))))
10832 ((eq files 'org-agenda-files)
10833 (setq files (org-agenda-files 'unrestricted)))
10834 ((and (symbolp files) (fboundp files))
10835 (setq files (funcall files)))
10836 ((and (symbolp files) (boundp files))
10837 (setq files (symbol-value files))))
10838 (if (stringp files) (setq files (list files)))
10839 (cond
10840 ((eq (car desc) :tag)
10841 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10842 ((eq (car desc) :todo)
10843 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10844 ((eq (car desc) :regexp)
10845 (setq descre (cdr desc)))
10846 ((eq (car desc) :level)
10847 (setq descre (concat "^\\*\\{" (number-to-string
10848 (if org-odd-levels-only
10849 (1- (* 2 (cdr desc)))
10850 (cdr desc)))
10851 "\\}[ \t]")))
10852 ((eq (car desc) :maxlevel)
10853 (setq fast-path-p t)
10854 (setq descre (concat "^\\*\\{1," (number-to-string
10855 (if org-odd-levels-only
10856 (1- (* 2 (cdr desc)))
10857 (cdr desc)))
10858 "\\}[ \t]")))
10859 (t (error "Bad refiling target description %s" desc)))
10860 (while (setq f (pop files))
10861 (with-current-buffer
10862 (if (bufferp f) f (org-get-agenda-file-buffer f))
10864 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10865 (progn
10866 (if (bufferp f) (setq f (buffer-file-name
10867 (buffer-base-buffer f))))
10868 (setq f (and f (expand-file-name f)))
10869 (if (eq org-refile-use-outline-path 'file)
10870 (push (list (file-name-nondirectory f) f nil nil) tgs))
10871 (save-excursion
10872 (save-restriction
10873 (widen)
10874 (goto-char (point-min))
10875 (while (re-search-forward descre nil t)
10876 (goto-char (setq pos0 (point-at-bol)))
10877 (catch 'next
10878 (when org-refile-target-verify-function
10879 (save-match-data
10880 (or (funcall org-refile-target-verify-function)
10881 (throw 'next t))))
10882 (when (and (looking-at org-complex-heading-regexp)
10883 (not (member (match-string 4) excluded-entries))
10884 (match-string 4))
10885 (setq level (org-reduced-level
10886 (- (match-end 1) (match-beginning 1)))
10887 txt (org-link-display-format (match-string 4))
10888 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10889 re (format org-complex-heading-regexp-format
10890 (regexp-quote (match-string 4))))
10891 (when org-refile-use-outline-path
10892 (setq txt (mapconcat
10893 'org-protect-slash
10894 (append
10895 (if (eq org-refile-use-outline-path
10896 'file)
10897 (list (file-name-nondirectory
10898 (buffer-file-name
10899 (buffer-base-buffer))))
10900 (if (eq org-refile-use-outline-path
10901 'full-file-path)
10902 (list (buffer-file-name
10903 (buffer-base-buffer)))))
10904 (org-get-outline-path fast-path-p
10905 level txt)
10906 (list txt))
10907 "/")))
10908 (push (list txt f re (org-refile-marker (point)))
10909 tgs)))
10910 (when (= (point) pos0)
10911 ;; verification function has not moved point
10912 (goto-char (point-at-eol))))))))
10913 (when org-refile-use-cache
10914 (org-refile-cache-put tgs (buffer-file-name) descre))
10915 (setq targets (append tgs targets))
10916 ))))
10917 (message "Getting targets...done")
10918 (nreverse targets)))
10920 (defun org-protect-slash (s)
10921 (while (string-match "/" s)
10922 (setq s (replace-match "\\" t t s)))
10925 (defvar org-olpa (make-vector 20 nil))
10927 (defun org-get-outline-path (&optional fastp level heading)
10928 "Return the outline path to the current entry, as a list.
10930 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10931 routine which makes outline path derivations for an entire file,
10932 avoiding backtracing. Refile target collection makes use of that."
10933 (if fastp
10934 (progn
10935 (if (> level 19)
10936 (error "Outline path failure, more than 19 levels"))
10937 (loop for i from level upto 19 do
10938 (aset org-olpa i nil))
10939 (prog1
10940 (delq nil (append org-olpa nil))
10941 (aset org-olpa level heading)))
10942 (let (rtn case-fold-search)
10943 (save-excursion
10944 (save-restriction
10945 (widen)
10946 (while (org-up-heading-safe)
10947 (when (looking-at org-complex-heading-regexp)
10948 (push (org-match-string-no-properties 4) rtn)))
10949 rtn)))))
10951 (defun org-format-outline-path (path &optional width prefix separator)
10952 "Format the outline path PATH for display.
10953 WIDTH is the maximum number of characters that is available.
10954 PREFIX is a prefix to be included in the returned string,
10955 such as the file name.
10956 SEPARATOR is inserted between the different parts of the path,
10957 the default is \"/\"."
10958 (setq width (or width 79))
10959 (if prefix (setq width (- width (length prefix))))
10960 (if (not path)
10961 (or prefix "")
10962 (let* ((nsteps (length path))
10963 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10964 (maxwidth (if (<= total-width width)
10965 10000 ;; everything fits
10966 ;; we need to shorten the level headings
10967 (/ (- width nsteps) nsteps)))
10968 (org-odd-levels-only nil)
10969 (n 0)
10970 (total (1+ (length prefix))))
10971 (setq maxwidth (max maxwidth 10))
10972 (concat prefix
10973 (if prefix (or separator "/"))
10974 (mapconcat
10975 (lambda (h)
10976 (setq n (1+ n))
10977 (if (and (= n nsteps) (< maxwidth 10000))
10978 (setq maxwidth (- total-width total)))
10979 (if (< (length h) maxwidth)
10980 (progn (setq total (+ total (length h) 1)) h)
10981 (setq h (substring h 0 (- maxwidth 2))
10982 total (+ total maxwidth 1))
10983 (if (string-match "[ \t]+\\'" h)
10984 (setq h (substring h 0 (match-beginning 0))))
10985 (setq h (concat h "..")))
10986 (org-add-props h nil 'face
10987 (nth (% (1- n) org-n-level-faces)
10988 org-level-faces))
10990 path (or separator "/"))))))
10992 (defun org-display-outline-path (&optional file current separator just-return-string)
10993 "Display the current outline path in the echo area.
10995 If FILE is non-nil, prepend the output with the file name.
10996 If CURRENT is non-nil, append the current heading to the output.
10997 SEPARATOR is passed through to `org-format-outline-path'. It separates
10998 the different parts of the path and defaults to \"/\".
10999 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11000 (interactive "P")
11001 (let* (case-fold-search
11002 message-log-max ; Don't populate the *Messages* buffer
11003 (bfn (buffer-file-name (buffer-base-buffer)))
11004 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11005 res)
11006 (if current (setq path (append path
11007 (save-excursion
11008 (org-back-to-heading t)
11009 (if (looking-at org-complex-heading-regexp)
11010 (list (match-string 4)))))))
11011 (setq res
11012 (org-format-outline-path
11013 path
11014 (1- (frame-width))
11015 (and file bfn (concat (file-name-nondirectory bfn) separator))
11016 separator))
11017 (if just-return-string
11018 (org-no-properties res)
11019 (message "%s" res))))
11021 (defvar org-refile-history nil
11022 "History for refiling operations.")
11024 (defvar org-after-refile-insert-hook nil
11025 "Hook run after `org-refile' has inserted its stuff at the new location.
11026 Note that this is still *before* the stuff will be removed from
11027 the *old* location.")
11029 (defvar org-capture-last-stored-marker)
11030 (defvar org-refile-keep nil
11031 "Non-nil means `org-refile' will copy instead of refile.")
11033 (defun org-copy ()
11034 "Like `org-refile', but copy."
11035 (interactive)
11036 (let ((org-refile-keep t))
11037 (funcall 'org-refile nil nil nil "Copy")))
11039 (defun org-refile (&optional goto default-buffer rfloc msg)
11040 "Move the entry or entries at point to another heading.
11041 The list of target headings is compiled using the information in
11042 `org-refile-targets', which see.
11044 At the target location, the entry is filed as a subitem of the target
11045 heading. Depending on `org-reverse-note-order', the new subitem will
11046 either be the first or the last subitem.
11048 If there is an active region, all entries in that region will be moved.
11049 However, the region must fulfill the requirement that the first heading
11050 is the first one sets the top-level of the moved text - at most siblings
11051 below it are allowed.
11053 With prefix arg GOTO, the command will only visit the target location
11054 and not actually move anything.
11056 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11057 go to the location where the last refiling operation has put the subtree.
11058 With a prefix argument of `2', refile to the running clock.
11060 RFLOC can be a refile location obtained in a different way.
11062 MSG is a string to replace \"Refile\" in the default prompt with
11063 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11065 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11067 If you are using target caching (see `org-refile-use-cache'),
11068 you have to clear the target cache in order to find new targets.
11069 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11070 prefix argument (`C-u C-u C-u C-c C-w')."
11072 (interactive "P")
11073 (if (member goto '(0 (64)))
11074 (org-refile-cache-clear)
11075 (let* ((actionmsg (or msg "Refile"))
11076 (cbuf (current-buffer))
11077 (regionp (org-region-active-p))
11078 (region-start (and regionp (region-beginning)))
11079 (region-end (and regionp (region-end)))
11080 (region-length (and regionp (- region-end region-start)))
11081 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11082 pos it nbuf file re level reversed)
11083 (setq last-command nil)
11084 (when regionp
11085 (goto-char region-start)
11086 (or (bolp) (goto-char (point-at-bol)))
11087 (setq region-start (point))
11088 (unless (or (org-kill-is-subtree-p
11089 (buffer-substring region-start region-end))
11090 (prog1 org-refile-active-region-within-subtree
11091 (org-toggle-heading)))
11092 (error "The region is not a (sequence of) subtree(s)")))
11093 (if (equal goto '(16))
11094 (org-refile-goto-last-stored)
11095 (when (or
11096 (and (equal goto 2)
11097 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11098 (prog1
11099 (setq it (list (or org-clock-heading "running clock")
11100 (buffer-file-name
11101 (marker-buffer org-clock-hd-marker))
11103 (marker-position org-clock-hd-marker)))
11104 (setq goto nil)))
11105 (setq it (or rfloc
11106 (let (heading-text)
11107 (save-excursion
11108 (unless goto
11109 (org-back-to-heading t)
11110 (setq heading-text
11111 (nth 4 (org-heading-components))))
11113 (org-refile-get-location
11114 (cond (goto "Goto")
11115 (regionp (concat actionmsg " region to"))
11116 (t (concat actionmsg " subtree \""
11117 heading-text "\" to")))
11118 default-buffer
11119 (and (not (equal '(4) goto))
11120 org-refile-allow-creating-parent-nodes)
11121 goto))))))
11122 (setq file (nth 1 it)
11123 re (nth 2 it)
11124 pos (nth 3 it))
11125 (if (and (not goto)
11127 (equal (buffer-file-name) file)
11128 (if regionp
11129 (and (>= pos region-start)
11130 (<= pos region-end))
11131 (and (>= pos (point))
11132 (< pos (save-excursion
11133 (org-end-of-subtree t t))))))
11134 (error "Cannot refile to position inside the tree or region"))
11136 (setq nbuf (or (find-buffer-visiting file)
11137 (find-file-noselect file)))
11138 (if goto
11139 (progn
11140 (org-pop-to-buffer-same-window nbuf)
11141 (goto-char pos)
11142 (org-show-context 'org-goto))
11143 (if regionp
11144 (progn
11145 (org-kill-new (buffer-substring region-start region-end))
11146 (org-save-markers-in-region region-start region-end))
11147 (org-copy-subtree 1 nil t))
11148 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11149 (find-file-noselect file)))
11150 (setq reversed (org-notes-order-reversed-p))
11151 (save-excursion
11152 (save-restriction
11153 (widen)
11154 (if pos
11155 (progn
11156 (goto-char pos)
11157 (looking-at org-outline-regexp)
11158 (setq level (org-get-valid-level (funcall outline-level) 1))
11159 (goto-char
11160 (if reversed
11161 (or (outline-next-heading) (point-max))
11162 (or (save-excursion (org-get-next-sibling))
11163 (org-end-of-subtree t t)
11164 (point-max)))))
11165 (setq level 1)
11166 (if (not reversed)
11167 (goto-char (point-max))
11168 (goto-char (point-min))
11169 (or (outline-next-heading) (goto-char (point-max)))))
11170 (if (not (bolp)) (newline))
11171 (org-paste-subtree level)
11172 (when org-log-refile
11173 (org-add-log-setup 'refile nil nil 'findpos
11174 org-log-refile)
11175 (unless (eq org-log-refile 'note)
11176 (save-excursion (org-add-log-note))))
11177 (and org-auto-align-tags
11178 (let ((org-loop-over-headlines-in-active-region nil))
11179 (org-set-tags nil t)))
11180 (with-demoted-errors
11181 (bookmark-set "org-refile-last-stored"))
11182 ;; If we are refiling for capture, make sure that the
11183 ;; last-capture pointers point here
11184 (when (org-bound-and-true-p org-refile-for-capture)
11185 (with-demoted-errors
11186 (bookmark-set "org-capture-last-stored-marker"))
11187 (move-marker org-capture-last-stored-marker (point)))
11188 (if (fboundp 'deactivate-mark) (deactivate-mark))
11189 (run-hooks 'org-after-refile-insert-hook))))
11190 (unless org-refile-keep
11191 (if regionp
11192 (delete-region (point) (+ (point) region-length))
11193 (org-cut-subtree)))
11194 (when (featurep 'org-inlinetask)
11195 (org-inlinetask-remove-END-maybe))
11196 (setq org-markers-to-move nil)
11197 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11199 (defun org-refile-goto-last-stored ()
11200 "Go to the location where the last refile was stored."
11201 (interactive)
11202 (bookmark-jump "org-refile-last-stored")
11203 (message "This is the location of the last refile"))
11205 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11206 no-exclude)
11207 "Prompt the user for a refile location, using PROMPT.
11208 PROMPT should not be suffixed with a colon and a space, because
11209 this function appends the default value from
11210 `org-refile-history' automatically, if that is not empty.
11211 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11212 this is used for the GOTO interface."
11213 (let ((org-refile-targets org-refile-targets)
11214 (org-refile-use-outline-path org-refile-use-outline-path)
11215 excluded-entries)
11216 (when (and (derived-mode-p 'org-mode)
11217 (not org-refile-use-cache)
11218 (not no-exclude))
11219 (org-map-tree
11220 (lambda()
11221 (setq excluded-entries
11222 (append excluded-entries (list (org-get-heading t t)))))))
11223 (setq org-refile-target-table
11224 (org-refile-get-targets default-buffer excluded-entries)))
11225 (unless org-refile-target-table
11226 (error "No refile targets"))
11227 (let* ((cbuf (current-buffer))
11228 (partial-completion-mode nil)
11229 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11230 (cfunc (if (and org-refile-use-outline-path
11231 org-outline-path-complete-in-steps)
11232 'org-olpath-completing-read
11233 'org-icompleting-read))
11234 (extra (if org-refile-use-outline-path "/" ""))
11235 (cbnex (concat (buffer-name) extra))
11236 (filename (and cfn (expand-file-name cfn)))
11237 (tbl (mapcar
11238 (lambda (x)
11239 (if (and (not (member org-refile-use-outline-path
11240 '(file full-file-path)))
11241 (not (equal filename (nth 1 x))))
11242 (cons (concat (car x) extra " ("
11243 (file-name-nondirectory (nth 1 x)) ")")
11244 (cdr x))
11245 (cons (concat (car x) extra) (cdr x))))
11246 org-refile-target-table))
11247 (completion-ignore-case t)
11248 cdef
11249 (prompt (concat prompt
11250 (or (and (car org-refile-history)
11251 (concat " (default " (car org-refile-history) ")"))
11252 (and (assoc cbnex tbl) (setq cdef cbnex)
11253 (concat " (default " cbnex ")"))) ": "))
11254 pa answ parent-target child parent old-hist)
11255 (setq old-hist org-refile-history)
11256 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11257 nil 'org-refile-history (or cdef (car org-refile-history))))
11258 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11259 (org-refile-check-position pa)
11260 (if pa
11261 (progn
11262 (when (or (not org-refile-history)
11263 (not (eq old-hist org-refile-history))
11264 (not (equal (car pa) (car org-refile-history))))
11265 (setq org-refile-history
11266 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11267 org-refile-history
11268 (cdr org-refile-history))))
11269 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11270 (pop org-refile-history)))
11272 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11273 (progn
11274 (setq parent (match-string 1 answ)
11275 child (match-string 2 answ))
11276 (setq parent-target (or (assoc parent tbl)
11277 (assoc (concat parent "/") tbl)))
11278 (when (and parent-target
11279 (or (eq new-nodes t)
11280 (and (eq new-nodes 'confirm)
11281 (y-or-n-p (format "Create new node \"%s\"? "
11282 child)))))
11283 (org-refile-new-child parent-target child)))
11284 (error "Invalid target location")))))
11286 (declare-function org-string-nw-p "org-macs" (s))
11287 (defun org-refile-check-position (refile-pointer)
11288 "Check if the refile pointer matches the headline to which it points."
11289 (let* ((file (nth 1 refile-pointer))
11290 (re (nth 2 refile-pointer))
11291 (pos (nth 3 refile-pointer))
11292 buffer)
11293 (if (and (not (markerp pos)) (not file))
11294 (error "Please save the buffer to a file before refiling")
11295 (when (org-string-nw-p re)
11296 (setq buffer (if (markerp pos)
11297 (marker-buffer pos)
11298 (or (find-buffer-visiting file)
11299 (find-file-noselect file))))
11300 (with-current-buffer buffer
11301 (save-excursion
11302 (save-restriction
11303 (widen)
11304 (goto-char pos)
11305 (beginning-of-line 1)
11306 (unless (org-looking-at-p re)
11307 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11309 (defun org-refile-new-child (parent-target child)
11310 "Use refile target PARENT-TARGET to add new CHILD below it."
11311 (unless parent-target
11312 (error "Cannot find parent for new node"))
11313 (let ((file (nth 1 parent-target))
11314 (pos (nth 3 parent-target))
11315 level)
11316 (with-current-buffer (or (find-buffer-visiting file)
11317 (find-file-noselect file))
11318 (save-excursion
11319 (save-restriction
11320 (widen)
11321 (if pos
11322 (goto-char pos)
11323 (goto-char (point-max))
11324 (if (not (bolp)) (newline)))
11325 (when (looking-at org-outline-regexp)
11326 (setq level (funcall outline-level))
11327 (org-end-of-subtree t t))
11328 (org-back-over-empty-lines)
11329 (insert "\n" (make-string
11330 (if pos (org-get-valid-level level 1) 1) ?*)
11331 " " child "\n")
11332 (beginning-of-line 0)
11333 (list (concat (car parent-target) "/" child) file "" (point)))))))
11335 (defun org-olpath-completing-read (prompt collection &rest args)
11336 "Read an outline path like a file name."
11337 (let ((thetable collection)
11338 (org-completion-use-ido nil) ; does not work with ido.
11339 (org-completion-use-iswitchb nil)) ; or iswitchb
11340 (apply
11341 'org-icompleting-read prompt
11342 (lambda (string predicate &optional flag)
11343 (let (rtn r f (l (length string)))
11344 (cond
11345 ((eq flag nil)
11346 ;; try completion
11347 (try-completion string thetable))
11348 ((eq flag t)
11349 ;; all-completions
11350 (setq rtn (all-completions string thetable predicate))
11351 (mapcar
11352 (lambda (x)
11353 (setq r (substring x l))
11354 (if (string-match " ([^)]*)$" x)
11355 (setq f (match-string 0 x))
11356 (setq f ""))
11357 (if (string-match "/" r)
11358 (concat string (substring r 0 (match-end 0)) f)
11360 rtn))
11361 ((eq flag 'lambda)
11362 ;; exact match?
11363 (assoc string thetable)))))
11364 args)))
11366 ;;;; Dynamic blocks
11368 (defun org-find-dblock (name)
11369 "Find the first dynamic block with name NAME in the buffer.
11370 If not found, stay at current position and return nil."
11371 (let ((case-fold-search t) pos)
11372 (save-excursion
11373 (goto-char (point-min))
11374 (setq pos (and (re-search-forward
11375 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11376 (match-beginning 0))))
11377 (if pos (goto-char pos))
11378 pos))
11380 (defconst org-dblock-start-re
11381 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11382 "Matches the start line of a dynamic block, with parameters.")
11384 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11385 "Matches the end of a dynamic block.")
11387 (defun org-create-dblock (plist)
11388 "Create a dynamic block section, with parameters taken from PLIST.
11389 PLIST must contain a :name entry which is used as name of the block."
11390 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11391 (end-of-line 1)
11392 (newline))
11393 (let ((col (current-column))
11394 (name (plist-get plist :name)))
11395 (insert "#+BEGIN: " name)
11396 (while plist
11397 (if (eq (car plist) :name)
11398 (setq plist (cddr plist))
11399 (insert " " (prin1-to-string (pop plist)))))
11400 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11401 (beginning-of-line -2)))
11403 (defun org-prepare-dblock ()
11404 "Prepare dynamic block for refresh.
11405 This empties the block, puts the cursor at the insert position and returns
11406 the property list including an extra property :name with the block name."
11407 (unless (looking-at org-dblock-start-re)
11408 (error "Not at a dynamic block"))
11409 (let* ((begdel (1+ (match-end 0)))
11410 (name (org-no-properties (match-string 1)))
11411 (params (append (list :name name)
11412 (read (concat "(" (match-string 3) ")")))))
11413 (save-excursion
11414 (beginning-of-line 1)
11415 (skip-chars-forward " \t")
11416 (setq params (plist-put params :indentation-column (current-column))))
11417 (unless (re-search-forward org-dblock-end-re nil t)
11418 (error "Dynamic block not terminated"))
11419 (setq params
11420 (append params
11421 (list :content (buffer-substring
11422 begdel (match-beginning 0)))))
11423 (delete-region begdel (match-beginning 0))
11424 (goto-char begdel)
11425 (open-line 1)
11426 params))
11428 (defun org-map-dblocks (&optional command)
11429 "Apply COMMAND to all dynamic blocks in the current buffer.
11430 If COMMAND is not given, use `org-update-dblock'."
11431 (let ((cmd (or command 'org-update-dblock)))
11432 (save-excursion
11433 (goto-char (point-min))
11434 (while (re-search-forward org-dblock-start-re nil t)
11435 (goto-char (match-beginning 0))
11436 (save-excursion
11437 (condition-case nil
11438 (funcall cmd)
11439 (error (message "Error during update of dynamic block"))))
11440 (unless (re-search-forward org-dblock-end-re nil t)
11441 (error "Dynamic block not terminated"))))))
11443 (defun org-dblock-update (&optional arg)
11444 "User command for updating dynamic blocks.
11445 Update the dynamic block at point. With prefix ARG, update all dynamic
11446 blocks in the buffer."
11447 (interactive "P")
11448 (if arg
11449 (org-update-all-dblocks)
11450 (or (looking-at org-dblock-start-re)
11451 (org-beginning-of-dblock))
11452 (org-update-dblock)))
11454 (defun org-update-dblock ()
11455 "Update the dynamic block at point.
11456 This means to empty the block, parse for parameters and then call
11457 the correct writing function."
11458 (interactive)
11459 (save-window-excursion
11460 (let* ((pos (point))
11461 (line (org-current-line))
11462 (params (org-prepare-dblock))
11463 (name (plist-get params :name))
11464 (indent (plist-get params :indentation-column))
11465 (cmd (intern (concat "org-dblock-write:" name))))
11466 (message "Updating dynamic block `%s' at line %d..." name line)
11467 (funcall cmd params)
11468 (message "Updating dynamic block `%s' at line %d...done" name line)
11469 (goto-char pos)
11470 (when (and indent (> indent 0))
11471 (setq indent (make-string indent ?\ ))
11472 (save-excursion
11473 (org-beginning-of-dblock)
11474 (forward-line 1)
11475 (while (not (looking-at org-dblock-end-re))
11476 (insert indent)
11477 (beginning-of-line 2))
11478 (when (looking-at org-dblock-end-re)
11479 (and (looking-at "[ \t]+")
11480 (replace-match ""))
11481 (insert indent)))))))
11483 (defun org-beginning-of-dblock ()
11484 "Find the beginning of the dynamic block at point.
11485 Error if there is no such block at point."
11486 (let ((pos (point))
11487 beg)
11488 (end-of-line 1)
11489 (if (and (re-search-backward org-dblock-start-re nil t)
11490 (setq beg (match-beginning 0))
11491 (re-search-forward org-dblock-end-re nil t)
11492 (> (match-end 0) pos))
11493 (goto-char beg)
11494 (goto-char pos)
11495 (error "Not in a dynamic block"))))
11497 (defun org-update-all-dblocks ()
11498 "Update all dynamic blocks in the buffer.
11499 This function can be used in a hook."
11500 (interactive)
11501 (when (derived-mode-p 'org-mode)
11502 (org-map-dblocks 'org-update-dblock)))
11505 ;;;; Completion
11507 (defun org-get-export-keywords ()
11508 "Return a list of all currently understood export keywords.
11509 Export keywords include options, block names, attributes and
11510 keywords relative to each registered export back-end."
11511 (delq nil
11512 (let (keywords)
11513 (mapc
11514 (lambda (back-end)
11515 (let ((props (cdr back-end)))
11516 ;; Back-end name (for keywords, like #+LATEX:)
11517 (push (upcase (symbol-name (car back-end))) keywords)
11518 ;; Back-end options.
11519 (mapc (lambda (option) (push (cadr option) keywords))
11520 (plist-get (cdr back-end) :options-alist))))
11521 (org-bound-and-true-p org-export-registered-backends))
11522 keywords)))
11524 (defconst org-options-keywords
11525 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE"
11526 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11527 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY"
11528 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11529 "TITLE:" "TODO:" "TYP_TODO:"))
11531 (defcustom org-structure-template-alist
11532 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11533 "<src lang=\"?\">\n\n</src>")
11534 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11535 "<example>\n?\n</example>")
11536 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11537 "<quote>\n?\n</quote>")
11538 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11539 "<verse>\n?\n</verse>")
11540 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11541 "<verbatim>\n?\n</verbatim>")
11542 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11543 "<center>\n?\n</center>")
11544 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11545 "<literal style=\"latex\">\n?\n</literal>")
11546 ("L" "#+LaTeX: "
11547 "<literal style=\"latex\">?</literal>")
11548 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11549 "<literal style=\"html\">\n?\n</literal>")
11550 ("H" "#+HTML: "
11551 "<literal style=\"html\">?</literal>")
11552 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11553 ("A" "#+ASCII: ")
11554 ("i" "#+INDEX: ?"
11555 "#+INDEX: ?")
11556 ("I" "#+INCLUDE: %file ?"
11557 "<include file=%file markup=\"?\">"))
11558 "Structure completion elements.
11559 This is a list of abbreviation keys and values. The value gets inserted
11560 if you type `<' followed by the key and then press the completion key,
11561 usually `M-TAB'. %file will be replaced by a file name after prompting
11562 for the file using completion. The cursor will be placed at the position
11563 of the `?` in the template.
11564 There are two templates for each key, the first uses the original Org syntax,
11565 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11566 the default when the /org-mtags.el/ module has been loaded. See also the
11567 variable `org-mtags-prefer-muse-templates'."
11568 :group 'org-completion
11569 :type '(repeat
11570 (string :tag "Key")
11571 (string :tag "Template")
11572 (string :tag "Muse Template")))
11574 (defun org-try-structure-completion ()
11575 "Try to complete a structure template before point.
11576 This looks for strings like \"<e\" on an otherwise empty line and
11577 expands them."
11578 (let ((l (buffer-substring (point-at-bol) (point)))
11580 (when (and (looking-at "[ \t]*$")
11581 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11582 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11583 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11584 (match-beginning 1)) a)
11585 t)))
11587 (defun org-complete-expand-structure-template (start cell)
11588 "Expand a structure template."
11589 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11590 (rpl (nth (if musep 2 1) cell))
11591 (ind ""))
11592 (delete-region start (point))
11593 (when (string-match "\\`#\\+" rpl)
11594 (cond
11595 ((bolp))
11596 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11597 (setq ind (buffer-substring (point-at-bol) (point))))
11598 (t (newline))))
11599 (setq start (point))
11600 (if (string-match "%file" rpl)
11601 (setq rpl (replace-match
11602 (concat
11603 "\""
11604 (save-match-data
11605 (abbreviate-file-name (read-file-name "Include file: ")))
11606 "\"")
11607 t t rpl)))
11608 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11609 (concat "\n" ind)))
11610 (insert rpl)
11611 (if (re-search-backward "\\?" start t) (delete-char 1))))
11613 ;;;; TODO, DEADLINE, Comments
11615 (defun org-toggle-comment ()
11616 "Change the COMMENT state of an entry."
11617 (interactive)
11618 (save-excursion
11619 (org-back-to-heading)
11620 (let (case-fold-search)
11621 (cond
11622 ((looking-at (format org-heading-keyword-regexp-format
11623 org-comment-string))
11624 (goto-char (match-end 1))
11625 (looking-at (concat " +" org-comment-string))
11626 (replace-match "" t t)
11627 (when (eolp) (insert " ")))
11628 ((looking-at org-outline-regexp)
11629 (goto-char (match-end 0))
11630 (insert org-comment-string " "))))))
11632 (defvar org-last-todo-state-is-todo nil
11633 "This is non-nil when the last TODO state change led to a TODO state.
11634 If the last change removed the TODO tag or switched to DONE, then
11635 this is nil.")
11637 (defvar org-setting-tags nil) ; dynamically skipped
11639 (defvar org-todo-setup-filter-hook nil
11640 "Hook for functions that pre-filter todo specs.
11641 Each function takes a todo spec and returns either nil or the spec
11642 transformed into canonical form." )
11644 (defvar org-todo-get-default-hook nil
11645 "Hook for functions that get a default item for todo.
11646 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11647 nil or a string to be used for the todo mark." )
11649 (defvar org-agenda-headline-snapshot-before-repeat)
11651 (defun org-current-effective-time ()
11652 "Return current time adjusted for `org-extend-today-until' variable."
11653 (let* ((ct (org-current-time))
11654 (dct (decode-time ct))
11655 (ct1
11656 (cond
11657 (org-use-last-clock-out-time-as-effective-time
11658 (or (org-clock-get-last-clock-out-time) ct))
11659 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11660 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11661 (t ct))))
11662 ct1))
11664 (defun org-todo-yesterday (&optional arg)
11665 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11666 (interactive "P")
11667 (if (eq major-mode 'org-agenda-mode)
11668 (apply 'org-agenda-todo-yesterday arg)
11669 (let* ((hour (third (decode-time
11670 (org-current-time))))
11671 (org-extend-today-until (1+ hour)))
11672 (org-todo arg))))
11674 (defvar org-block-entry-blocking ""
11675 "First entry preventing the TODO state change.")
11677 (defun org-todo (&optional arg)
11678 "Change the TODO state of an item.
11679 The state of an item is given by a keyword at the start of the heading,
11680 like
11681 *** TODO Write paper
11682 *** DONE Call mom
11684 The different keywords are specified in the variable `org-todo-keywords'.
11685 By default the available states are \"TODO\" and \"DONE\".
11686 So for this example: when the item starts with TODO, it is changed to DONE.
11687 When it starts with DONE, the DONE is removed. And when neither TODO nor
11688 DONE are present, add TODO at the beginning of the heading.
11690 With \\[universal-argument] prefix arg, use completion to determine the new \
11691 state.
11692 With numeric prefix arg, switch to that state.
11693 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11694 keywords (nextset).
11695 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11696 With a numeric prefix arg of 0, inhibit note taking for the change.
11698 For calling through lisp, arg is also interpreted in the following way:
11699 'none -> empty state
11700 \"\"(empty string) -> switch to empty state
11701 'done -> switch to DONE
11702 'nextset -> switch to the next set of keywords
11703 'previousset -> switch to the previous set of keywords
11704 \"WAITING\" -> switch to the specified keyword, but only if it
11705 really is a member of `org-todo-keywords'."
11706 (interactive "P")
11707 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11708 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11709 'region-start-level 'region))
11710 org-loop-over-headlines-in-active-region)
11711 (org-map-entries
11712 `(org-todo ,arg)
11713 org-loop-over-headlines-in-active-region
11714 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11715 (if (equal arg '(16)) (setq arg 'nextset))
11716 (let ((org-blocker-hook org-blocker-hook)
11717 commentp
11718 case-fold-search)
11719 (when (equal arg '(64))
11720 (setq arg nil org-blocker-hook nil))
11721 (when (and org-blocker-hook
11722 (or org-inhibit-blocking
11723 (org-entry-get nil "NOBLOCKING")))
11724 (setq org-blocker-hook nil))
11725 (save-excursion
11726 (catch 'exit
11727 (org-back-to-heading t)
11728 (when (looking-at (concat "^\\*+ " org-comment-string))
11729 (org-toggle-comment)
11730 (setq commentp t))
11731 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11732 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11733 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11734 (let* ((match-data (match-data))
11735 (startpos (point-at-bol))
11736 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11737 (org-log-done org-log-done)
11738 (org-log-repeat org-log-repeat)
11739 (org-todo-log-states org-todo-log-states)
11740 (org-inhibit-logging
11741 (if (equal arg 0)
11742 (progn (setq arg nil) 'note) org-inhibit-logging))
11743 (this (match-string 1))
11744 (hl-pos (match-beginning 0))
11745 (head (org-get-todo-sequence-head this))
11746 (ass (assoc head org-todo-kwd-alist))
11747 (interpret (nth 1 ass))
11748 (done-word (nth 3 ass))
11749 (final-done-word (nth 4 ass))
11750 (org-last-state (or this ""))
11751 (completion-ignore-case t)
11752 (member (member this org-todo-keywords-1))
11753 (tail (cdr member))
11754 (org-state (cond
11755 ((and org-todo-key-trigger
11756 (or (and (equal arg '(4))
11757 (eq org-use-fast-todo-selection 'prefix))
11758 (and (not arg) org-use-fast-todo-selection
11759 (not (eq org-use-fast-todo-selection
11760 'prefix)))))
11761 ;; Use fast selection
11762 (org-fast-todo-selection))
11763 ((and (equal arg '(4))
11764 (or (not org-use-fast-todo-selection)
11765 (not org-todo-key-trigger)))
11766 ;; Read a state with completion
11767 (org-icompleting-read
11768 "State: " (mapcar (lambda(x) (list x))
11769 org-todo-keywords-1)
11770 nil t))
11771 ((eq arg 'right)
11772 (if this
11773 (if tail (car tail) nil)
11774 (car org-todo-keywords-1)))
11775 ((eq arg 'left)
11776 (if (equal member org-todo-keywords-1)
11778 (if this
11779 (nth (- (length org-todo-keywords-1)
11780 (length tail) 2)
11781 org-todo-keywords-1)
11782 (org-last org-todo-keywords-1))))
11783 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11784 (setq arg nil))) ; hack to fall back to cycling
11785 (arg
11786 ;; user or caller requests a specific state
11787 (cond
11788 ((equal arg "") nil)
11789 ((eq arg 'none) nil)
11790 ((eq arg 'done) (or done-word (car org-done-keywords)))
11791 ((eq arg 'nextset)
11792 (or (car (cdr (member head org-todo-heads)))
11793 (car org-todo-heads)))
11794 ((eq arg 'previousset)
11795 (let ((org-todo-heads (reverse org-todo-heads)))
11796 (or (car (cdr (member head org-todo-heads)))
11797 (car org-todo-heads))))
11798 ((car (member arg org-todo-keywords-1)))
11799 ((stringp arg)
11800 (error "State `%s' not valid in this file" arg))
11801 ((nth (1- (prefix-numeric-value arg))
11802 org-todo-keywords-1))))
11803 ((null member) (or head (car org-todo-keywords-1)))
11804 ((equal this final-done-word) nil) ;; -> make empty
11805 ((null tail) nil) ;; -> first entry
11806 ((memq interpret '(type priority))
11807 (if (eq this-command last-command)
11808 (car tail)
11809 (if (> (length tail) 0)
11810 (or done-word (car org-done-keywords))
11811 nil)))
11813 (car tail))))
11814 (org-state (or
11815 (run-hook-with-args-until-success
11816 'org-todo-get-default-hook org-state org-last-state)
11817 org-state))
11818 (next (if org-state (concat " " org-state " ") " "))
11819 (change-plist (list :type 'todo-state-change :from this :to org-state
11820 :position startpos))
11821 dolog now-done-p)
11822 (when org-blocker-hook
11823 (setq org-last-todo-state-is-todo
11824 (not (member this org-done-keywords)))
11825 (unless (save-excursion
11826 (save-match-data
11827 (org-with-wide-buffer
11828 (run-hook-with-args-until-failure
11829 'org-blocker-hook change-plist))))
11830 (if (org-called-interactively-p 'interactive)
11831 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11832 this org-state org-block-entry-blocking)
11833 ;; fail silently
11834 (message "TODO state change from %s to %s blocked (by \"%s\")"
11835 this org-state org-block-entry-blocking)
11836 (throw 'exit nil))))
11837 (store-match-data match-data)
11838 (replace-match next t t)
11839 (unless (pos-visible-in-window-p hl-pos)
11840 (message "TODO state changed to %s" (org-trim next)))
11841 (unless head
11842 (setq head (org-get-todo-sequence-head org-state)
11843 ass (assoc head org-todo-kwd-alist)
11844 interpret (nth 1 ass)
11845 done-word (nth 3 ass)
11846 final-done-word (nth 4 ass)))
11847 (when (memq arg '(nextset previousset))
11848 (message "Keyword-Set %d/%d: %s"
11849 (- (length org-todo-sets) -1
11850 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11851 (length org-todo-sets)
11852 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11853 (setq org-last-todo-state-is-todo
11854 (not (member org-state org-done-keywords)))
11855 (setq now-done-p (and (member org-state org-done-keywords)
11856 (not (member this org-done-keywords))))
11857 (and logging (org-local-logging logging))
11858 (when (and (or org-todo-log-states org-log-done)
11859 (not (eq org-inhibit-logging t))
11860 (not (memq arg '(nextset previousset))))
11861 ;; we need to look at recording a time and note
11862 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11863 (nth 2 (assoc this org-todo-log-states))))
11864 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11865 (setq dolog 'time))
11866 (when (and org-state
11867 (member org-state org-not-done-keywords)
11868 (not (member this org-not-done-keywords)))
11869 ;; This is now a todo state and was not one before
11870 ;; If there was a CLOSED time stamp, get rid of it.
11871 (org-add-planning-info nil nil 'closed))
11872 (when (and now-done-p org-log-done)
11873 ;; It is now done, and it was not done before
11874 (org-add-planning-info 'closed (org-current-effective-time))
11875 (if (and (not dolog) (eq 'note org-log-done))
11876 (org-add-log-setup 'done org-state this 'findpos 'note)))
11877 (when (and org-state dolog)
11878 ;; This is a non-nil state, and we need to log it
11879 (org-add-log-setup 'state org-state this 'findpos dolog)))
11880 ;; Fixup tag positioning
11881 (org-todo-trigger-tag-changes org-state)
11882 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11883 (when org-provide-todo-statistics
11884 (org-update-parent-todo-statistics))
11885 (run-hooks 'org-after-todo-state-change-hook)
11886 (if (and arg (not (member org-state org-done-keywords)))
11887 (setq head (org-get-todo-sequence-head org-state)))
11888 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11889 ;; Do we need to trigger a repeat?
11890 (when now-done-p
11891 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11892 ;; This is for the agenda, take a snapshot of the headline.
11893 (save-match-data
11894 (setq org-agenda-headline-snapshot-before-repeat
11895 (org-get-heading))))
11896 (org-auto-repeat-maybe org-state))
11897 ;; Fixup cursor location if close to the keyword
11898 (if (and (outline-on-heading-p)
11899 (not (bolp))
11900 (save-excursion (beginning-of-line 1)
11901 (looking-at org-todo-line-regexp))
11902 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11903 (progn
11904 (goto-char (or (match-end 2) (match-end 1)))
11905 (and (looking-at " ") (just-one-space))))
11906 (when org-trigger-hook
11907 (save-excursion
11908 (run-hook-with-args 'org-trigger-hook change-plist)))
11909 (when commentp (org-toggle-comment))))))))
11911 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11912 "Block turning an entry into a TODO, using the hierarchy.
11913 This checks whether the current task should be blocked from state
11914 changes. Such blocking occurs when:
11916 1. The task has children which are not all in a completed state.
11918 2. A task has a parent with the property :ORDERED:, and there
11919 are siblings prior to the current task with incomplete
11920 status.
11922 3. The parent of the task is blocked because it has siblings that should
11923 be done first, or is child of a block grandparent TODO entry."
11925 (if (not org-enforce-todo-dependencies)
11926 t ; if locally turned off don't block
11927 (catch 'dont-block
11928 ;; If this is not a todo state change, or if this entry is already DONE,
11929 ;; do not block
11930 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11931 (member (plist-get change-plist :from)
11932 (cons 'done org-done-keywords))
11933 (member (plist-get change-plist :to)
11934 (cons 'todo org-not-done-keywords))
11935 (not (plist-get change-plist :to)))
11936 (throw 'dont-block t))
11937 ;; If this task has children, and any are undone, it's blocked
11938 (save-excursion
11939 (org-back-to-heading t)
11940 (let ((this-level (funcall outline-level)))
11941 (outline-next-heading)
11942 (let ((child-level (funcall outline-level)))
11943 (while (and (not (eobp))
11944 (> child-level this-level))
11945 ;; this todo has children, check whether they are all
11946 ;; completed
11947 (if (and (not (org-entry-is-done-p))
11948 (org-entry-is-todo-p))
11949 (progn (setq org-block-entry-blocking (org-get-heading))
11950 (throw 'dont-block nil)))
11951 (outline-next-heading)
11952 (setq child-level (funcall outline-level))))))
11953 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11954 ;; any previous siblings are undone, it's blocked
11955 (save-excursion
11956 (org-back-to-heading t)
11957 (let* ((pos (point))
11958 (parent-pos (and (org-up-heading-safe) (point))))
11959 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11960 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11961 (forward-line 1)
11962 (re-search-forward org-not-done-heading-regexp pos t))
11963 (setq org-block-entry-blocking (match-string 0))
11964 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11965 ;; Search further up the hierarchy, to see if an ancestor is blocked
11966 (while t
11967 (goto-char parent-pos)
11968 (if (not (looking-at org-not-done-heading-regexp))
11969 (throw 'dont-block t)) ; do not block, parent is not a TODO
11970 (setq pos (point))
11971 (setq parent-pos (and (org-up-heading-safe) (point)))
11972 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11973 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11974 (forward-line 1)
11975 (re-search-forward org-not-done-heading-regexp pos t)
11976 (setq org-block-entry-blocking (org-get-heading)))
11977 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11979 (defcustom org-track-ordered-property-with-tag nil
11980 "Should the ORDERED property also be shown as a tag?
11981 The ORDERED property decides if an entry should require subtasks to be
11982 completed in sequence. Since a property is not very visible, setting
11983 this option means that toggling the ORDERED property with the command
11984 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11985 not relevant for the behavior, but it makes things more visible.
11987 Note that toggling the tag with tags commands will not change the property
11988 and therefore not influence behavior!
11990 This can be t, meaning the tag ORDERED should be used, It can also be a
11991 string to select a different tag for this task."
11992 :group 'org-todo
11993 :type '(choice
11994 (const :tag "No tracking" nil)
11995 (const :tag "Track with ORDERED tag" t)
11996 (string :tag "Use other tag")))
11998 (defun org-toggle-ordered-property ()
11999 "Toggle the ORDERED property of the current entry.
12000 For better visibility, you can track the value of this property with a tag.
12001 See variable `org-track-ordered-property-with-tag'."
12002 (interactive)
12003 (let* ((t1 org-track-ordered-property-with-tag)
12004 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12005 (save-excursion
12006 (org-back-to-heading)
12007 (if (org-entry-get nil "ORDERED")
12008 (progn
12009 (org-delete-property "ORDERED")
12010 (and tag (org-toggle-tag tag 'off))
12011 (message "Subtasks can be completed in arbitrary order"))
12012 (org-entry-put nil "ORDERED" "t")
12013 (and tag (org-toggle-tag tag 'on))
12014 (message "Subtasks must be completed in sequence")))))
12016 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12017 (defun org-block-todo-from-checkboxes (change-plist)
12018 "Block turning an entry into a TODO, using checkboxes.
12019 This checks whether the current task should be blocked from state
12020 changes because there are unchecked boxes in this entry."
12021 (if (not org-enforce-todo-checkbox-dependencies)
12022 t ; if locally turned off don't block
12023 (catch 'dont-block
12024 ;; If this is not a todo state change, or if this entry is already DONE,
12025 ;; do not block
12026 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12027 (member (plist-get change-plist :from)
12028 (cons 'done org-done-keywords))
12029 (member (plist-get change-plist :to)
12030 (cons 'todo org-not-done-keywords))
12031 (not (plist-get change-plist :to)))
12032 (throw 'dont-block t))
12033 ;; If this task has checkboxes that are not checked, it's blocked
12034 (save-excursion
12035 (org-back-to-heading t)
12036 (let ((beg (point)) end)
12037 (outline-next-heading)
12038 (setq end (point))
12039 (goto-char beg)
12040 (if (org-list-search-forward
12041 (concat (org-item-beginning-re)
12042 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12043 "\\[[- ]\\]")
12044 end t)
12045 (progn
12046 (if (boundp 'org-blocked-by-checkboxes)
12047 (setq org-blocked-by-checkboxes t))
12048 (throw 'dont-block nil)))))
12049 t))) ; do not block
12051 (defun org-entry-blocked-p ()
12052 "Is the current entry blocked?"
12053 (org-with-buffer-modified-unmodified
12054 (if (org-entry-get nil "NOBLOCKING")
12055 nil ;; Never block this entry
12056 (not
12057 (run-hook-with-args-until-failure
12058 'org-blocker-hook
12059 (list :type 'todo-state-change
12060 :position (point)
12061 :from 'todo
12062 :to 'done))))))
12064 (defun org-update-statistics-cookies (all)
12065 "Update the statistics cookie, either from TODO or from checkboxes.
12066 This should be called with the cursor in a line with a statistics cookie."
12067 (interactive "P")
12068 (if all
12069 (progn
12070 (org-update-checkbox-count 'all)
12071 (org-map-entries 'org-update-parent-todo-statistics))
12072 (if (not (org-at-heading-p))
12073 (org-update-checkbox-count)
12074 (let ((pos (point-marker))
12075 end l1 l2)
12076 (ignore-errors (org-back-to-heading t))
12077 (if (not (org-at-heading-p))
12078 (org-update-checkbox-count)
12079 (setq l1 (org-outline-level))
12080 (setq end (save-excursion
12081 (outline-next-heading)
12082 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12083 (point)))
12084 (if (and (save-excursion
12085 (re-search-forward
12086 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12087 (not (save-excursion (re-search-forward
12088 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12089 (org-update-checkbox-count)
12090 (if (and l2 (> l2 l1))
12091 (progn
12092 (goto-char end)
12093 (org-update-parent-todo-statistics))
12094 (goto-char pos)
12095 (beginning-of-line 1)
12096 (while (re-search-forward
12097 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12098 (point-at-eol) t)
12099 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12100 (goto-char pos)
12101 (move-marker pos nil)))))
12103 (defvar org-entry-property-inherited-from) ;; defined below
12104 (defun org-update-parent-todo-statistics ()
12105 "Update any statistics cookie in the parent of the current headline.
12106 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12107 the entire subtree and this will travel up the hierarchy and update
12108 statistics everywhere."
12109 (let* ((prop (save-excursion (org-up-heading-safe)
12110 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12111 (recursive (or (not org-hierarchical-todo-statistics)
12112 (and prop (string-match "\\<recursive\\>" prop))))
12113 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12115 (first t)
12116 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12117 level ltoggle l1 new ndel
12118 (cnt-all 0) (cnt-done 0) is-percent kwd
12119 checkbox-beg ov ovs ove cookie-present)
12120 (catch 'exit
12121 (save-excursion
12122 (beginning-of-line 1)
12123 (setq ltoggle (funcall outline-level))
12124 ;; Three situations are to consider:
12126 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12127 ;; to the top-level ancestor on the headline;
12129 ;; 2. If parent has "recursive" property, repeat up to the
12130 ;; headline setting that property, taking inheritance into
12131 ;; account;
12133 ;; 3. Else, move up to direct parent and proceed only once.
12134 (while (and (setq level (org-up-heading-safe))
12135 (or recursive first)
12136 (>= (point) lim))
12137 (setq first nil cookie-present nil)
12138 (unless (and level
12139 (not (string-match
12140 "\\<checkbox\\>"
12141 (downcase (or (org-entry-get nil "COOKIE_DATA")
12142 "")))))
12143 (throw 'exit nil))
12144 (while (re-search-forward box-re (point-at-eol) t)
12145 (setq cnt-all 0 cnt-done 0 cookie-present t)
12146 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12147 (save-match-data
12148 (unless (outline-next-heading) (throw 'exit nil))
12149 (while (and (looking-at org-complex-heading-regexp)
12150 (> (setq l1 (length (match-string 1))) level))
12151 (setq kwd (and (or recursive (= l1 ltoggle))
12152 (match-string 2)))
12153 (if (or (eq org-provide-todo-statistics 'all-headlines)
12154 (and (listp org-provide-todo-statistics)
12155 (or (member kwd org-provide-todo-statistics)
12156 (member kwd org-done-keywords))))
12157 (setq cnt-all (1+ cnt-all))
12158 (if (eq org-provide-todo-statistics t)
12159 (and kwd (setq cnt-all (1+ cnt-all)))))
12160 (and (member kwd org-done-keywords)
12161 (setq cnt-done (1+ cnt-done)))
12162 (outline-next-heading)))
12163 (setq new
12164 (if is-percent
12165 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12166 (format "[%d/%d]" cnt-done cnt-all))
12167 ndel (- (match-end 0) checkbox-beg))
12168 ;; handle overlays when updating cookie from column view
12169 (when (setq ov (car (overlays-at checkbox-beg)))
12170 (setq ovs (overlay-start ov) ove (overlay-end ov))
12171 (delete-overlay ov))
12172 (goto-char checkbox-beg)
12173 (insert new)
12174 (delete-region (point) (+ (point) ndel))
12175 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12176 (when ov (move-overlay ov ovs ove)))
12177 (when cookie-present
12178 (run-hook-with-args 'org-after-todo-statistics-hook
12179 cnt-done (- cnt-all cnt-done))))))
12180 (run-hooks 'org-todo-statistics-hook)))
12182 (defvar org-after-todo-statistics-hook nil
12183 "Hook that is called after a TODO statistics cookie has been updated.
12184 Each function is called with two arguments: the number of not-done entries
12185 and the number of done entries.
12187 For example, the following function, when added to this hook, will switch
12188 an entry to DONE when all children are done, and back to TODO when new
12189 entries are set to a TODO status. Note that this hook is only called
12190 when there is a statistics cookie in the headline!
12192 (defun org-summary-todo (n-done n-not-done)
12193 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12194 (let (org-log-done org-log-states) ; turn off logging
12195 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12198 (defvar org-todo-statistics-hook nil
12199 "Hook that is run whenever Org thinks TODO statistics should be updated.
12200 This hook runs even if there is no statistics cookie present, in which case
12201 `org-after-todo-statistics-hook' would not run.")
12203 (defun org-todo-trigger-tag-changes (state)
12204 "Apply the changes defined in `org-todo-state-tags-triggers'."
12205 (let ((l org-todo-state-tags-triggers)
12206 changes)
12207 (when (or (not state) (equal state ""))
12208 (setq changes (append changes (cdr (assoc "" l)))))
12209 (when (and (stringp state) (> (length state) 0))
12210 (setq changes (append changes (cdr (assoc state l)))))
12211 (when (member state org-not-done-keywords)
12212 (setq changes (append changes (cdr (assoc 'todo l)))))
12213 (when (member state org-done-keywords)
12214 (setq changes (append changes (cdr (assoc 'done l)))))
12215 (dolist (c changes)
12216 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12218 (defun org-local-logging (value)
12219 "Get logging settings from a property VALUE."
12220 (let* (words w a)
12221 ;; directly set the variables, they are already local.
12222 (setq org-log-done nil
12223 org-log-repeat nil
12224 org-todo-log-states nil)
12225 (setq words (org-split-string value))
12226 (while (setq w (pop words))
12227 (cond
12228 ((setq a (assoc w org-startup-options))
12229 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12230 (set (nth 1 a) (nth 2 a))))
12231 ((setq a (org-extract-log-state-settings w))
12232 (and (member (car a) org-todo-keywords-1)
12233 (push a org-todo-log-states)))))))
12235 (defun org-get-todo-sequence-head (kwd)
12236 "Return the head of the TODO sequence to which KWD belongs.
12237 If KWD is not set, check if there is a text property remembering the
12238 right sequence."
12239 (let (p)
12240 (cond
12241 ((not kwd)
12242 (or (get-text-property (point-at-bol) 'org-todo-head)
12243 (progn
12244 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12245 nil (point-at-eol)))
12246 (get-text-property p 'org-todo-head))))
12247 ((not (member kwd org-todo-keywords-1))
12248 (car org-todo-keywords-1))
12249 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12251 (defun org-fast-todo-selection ()
12252 "Fast TODO keyword selection with single keys.
12253 Returns the new TODO keyword, or nil if no state change should occur."
12254 (let* ((fulltable org-todo-key-alist)
12255 (done-keywords org-done-keywords) ;; needed for the faces.
12256 (maxlen (apply 'max (mapcar
12257 (lambda (x)
12258 (if (stringp (car x)) (string-width (car x)) 0))
12259 fulltable)))
12260 (expert nil)
12261 (fwidth (+ maxlen 3 1 3))
12262 (ncol (/ (- (window-width) 4) fwidth))
12263 tg cnt e c tbl
12264 groups ingroup)
12265 (save-excursion
12266 (save-window-excursion
12267 (if expert
12268 (set-buffer (get-buffer-create " *Org todo*"))
12269 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12270 (erase-buffer)
12271 (org-set-local 'org-done-keywords done-keywords)
12272 (setq tbl fulltable cnt 0)
12273 (while (setq e (pop tbl))
12274 (cond
12275 ((equal e '(:startgroup))
12276 (push '() groups) (setq ingroup t)
12277 (when (not (= cnt 0))
12278 (setq cnt 0)
12279 (insert "\n"))
12280 (insert "{ "))
12281 ((equal e '(:endgroup))
12282 (setq ingroup nil cnt 0)
12283 (insert "}\n"))
12284 ((equal e '(:newline))
12285 (when (not (= cnt 0))
12286 (setq cnt 0)
12287 (insert "\n")
12288 (setq e (car tbl))
12289 (while (equal (car tbl) '(:newline))
12290 (insert "\n")
12291 (setq tbl (cdr tbl)))))
12293 (setq tg (car e) c (cdr e))
12294 (if ingroup (push tg (car groups)))
12295 (setq tg (org-add-props tg nil 'face
12296 (org-get-todo-face tg)))
12297 (if (and (= cnt 0) (not ingroup)) (insert " "))
12298 (insert "[" c "] " tg (make-string
12299 (- fwidth 4 (length tg)) ?\ ))
12300 (when (= (setq cnt (1+ cnt)) ncol)
12301 (insert "\n")
12302 (if ingroup (insert " "))
12303 (setq cnt 0)))))
12304 (insert "\n")
12305 (goto-char (point-min))
12306 (if (not expert) (org-fit-window-to-buffer))
12307 (message "[a-z..]:Set [SPC]:clear")
12308 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12309 (cond
12310 ((or (= c ?\C-g)
12311 (and (= c ?q) (not (rassoc c fulltable))))
12312 (setq quit-flag t))
12313 ((= c ?\ ) nil)
12314 ((setq e (rassoc c fulltable) tg (car e))
12316 (t (setq quit-flag t)))))))
12318 (defun org-entry-is-todo-p ()
12319 (member (org-get-todo-state) org-not-done-keywords))
12321 (defun org-entry-is-done-p ()
12322 (member (org-get-todo-state) org-done-keywords))
12324 (defun org-get-todo-state ()
12325 (save-excursion
12326 (org-back-to-heading t)
12327 (and (looking-at org-todo-line-regexp)
12328 (match-end 2)
12329 (match-string 2))))
12331 (defun org-at-date-range-p (&optional inactive-ok)
12332 "Is the cursor inside a date range?"
12333 (interactive)
12334 (save-excursion
12335 (catch 'exit
12336 (let ((pos (point)))
12337 (skip-chars-backward "^[<\r\n")
12338 (skip-chars-backward "<[")
12339 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12340 (>= (match-end 0) pos)
12341 (throw 'exit t))
12342 (skip-chars-backward "^<[\r\n")
12343 (skip-chars-backward "<[")
12344 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12345 (>= (match-end 0) pos)
12346 (throw 'exit t)))
12347 nil)))
12349 (defun org-get-repeat (&optional tagline)
12350 "Check if there is a deadline/schedule with repeater in this entry."
12351 (save-match-data
12352 (save-excursion
12353 (org-back-to-heading t)
12354 (and (re-search-forward (if tagline
12355 (concat tagline "\\s-*" org-repeat-re)
12356 org-repeat-re)
12357 (org-entry-end-position) t)
12358 (match-string-no-properties 1)))))
12360 (defvar org-last-changed-timestamp)
12361 (defvar org-last-inserted-timestamp)
12362 (defvar org-log-post-message)
12363 (defvar org-log-note-purpose)
12364 (defvar org-log-note-how)
12365 (defvar org-log-note-extra)
12366 (defun org-auto-repeat-maybe (done-word)
12367 "Check if the current headline contains a repeated deadline/schedule.
12368 If yes, set TODO state back to what it was and change the base date
12369 of repeating deadline/scheduled time stamps to new date.
12370 This function is run automatically after each state change to a DONE state."
12371 ;; last-state is dynamically scoped into this function
12372 (let* ((repeat (org-get-repeat))
12373 (aa (assoc org-last-state org-todo-kwd-alist))
12374 (interpret (nth 1 aa))
12375 (head (nth 2 aa))
12376 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12377 (msg "Entry repeats: ")
12378 (org-log-done nil)
12379 (org-todo-log-states nil)
12380 re type n what ts time to-state)
12381 (when repeat
12382 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12383 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12384 org-todo-repeat-to-state))
12385 (unless (and to-state (member to-state org-todo-keywords-1))
12386 (setq to-state (if (eq interpret 'type) org-last-state head)))
12387 (org-todo to-state)
12388 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12389 (org-entry-put nil "LAST_REPEAT" (format-time-string
12390 (org-time-stamp-format t t))))
12391 (when org-log-repeat
12392 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12393 (memq 'org-add-log-note post-command-hook))
12394 ;; OK, we are already setup for some record
12395 (if (eq org-log-repeat 'note)
12396 ;; make sure we take a note, not only a time stamp
12397 (setq org-log-note-how 'note))
12398 ;; Set up for taking a record
12399 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12400 org-last-state
12401 'findpos org-log-repeat)))
12402 (org-back-to-heading t)
12403 (org-add-planning-info nil nil 'closed)
12404 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12405 org-deadline-time-regexp "\\)\\|\\("
12406 org-ts-regexp "\\)"))
12407 (while (re-search-forward
12408 re (save-excursion (outline-next-heading) (point)) t)
12409 (setq type (if (match-end 1) org-scheduled-string
12410 (if (match-end 3) org-deadline-string "Plain:"))
12411 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12412 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12413 (setq n (string-to-number (match-string 2 ts))
12414 what (match-string 3 ts))
12415 (if (equal what "w") (setq n (* n 7) what "d"))
12416 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12417 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12418 ;; Preparation, see if we need to modify the start date for the change
12419 (when (match-end 1)
12420 (setq time (save-match-data (org-time-string-to-time ts)))
12421 (cond
12422 ((equal (match-string 1 ts) ".")
12423 ;; Shift starting date to today
12424 (org-timestamp-change
12425 (- (org-today) (time-to-days time))
12426 'day))
12427 ((equal (match-string 1 ts) "+")
12428 (let ((nshiftmax 10) (nshift 0))
12429 (while (or (= nshift 0)
12430 (<= (time-to-days time)
12431 (time-to-days (current-time))))
12432 (when (= (incf nshift) nshiftmax)
12433 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12434 (error "Abort")))
12435 (org-timestamp-change n (cdr (assoc what whata)))
12436 (org-at-timestamp-p t)
12437 (setq ts (match-string 1))
12438 (setq time (save-match-data (org-time-string-to-time ts)))))
12439 (org-timestamp-change (- n) (cdr (assoc what whata)))
12440 ;; rematch, so that we have everything in place for the real shift
12441 (org-at-timestamp-p t)
12442 (setq ts (match-string 1))
12443 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12444 (org-timestamp-change n (cdr (assoc what whata)))
12445 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12446 (setq org-log-post-message msg)
12447 (message "%s" msg))))
12449 (defun org-show-todo-tree (arg)
12450 "Make a compact tree which shows all headlines marked with TODO.
12451 The tree will show the lines where the regexp matches, and all higher
12452 headlines above the match.
12453 With a \\[universal-argument] prefix, prompt for a regexp to match.
12454 With a numeric prefix N, construct a sparse tree for the Nth element
12455 of `org-todo-keywords-1'."
12456 (interactive "P")
12457 (let ((case-fold-search nil)
12458 (kwd-re
12459 (cond ((null arg) org-not-done-regexp)
12460 ((equal arg '(4))
12461 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12462 (mapcar 'list org-todo-keywords-1))))
12463 (concat "\\("
12464 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12465 "\\)\\>")))
12466 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12467 (regexp-quote (nth (1- (prefix-numeric-value arg))
12468 org-todo-keywords-1)))
12469 (t (error "Invalid prefix argument: %s" arg)))))
12470 (message "%d TODO entries found"
12471 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12473 (defun org-deadline (&optional arg time)
12474 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12475 With one universal prefix argument, remove any deadline from the item.
12476 With two universal prefix arguments, prompt for a warning delay.
12477 With argument TIME, set the deadline at the corresponding date. TIME
12478 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12479 (interactive "P")
12480 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12481 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12482 'region-start-level 'region))
12483 org-loop-over-headlines-in-active-region)
12484 (org-map-entries
12485 `(org-deadline ',arg ,time)
12486 org-loop-over-headlines-in-active-region
12487 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12488 (let* ((old-date (org-entry-get nil "DEADLINE"))
12489 (repeater (and old-date
12490 (string-match
12491 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12492 old-date)
12493 (match-string 1 old-date))))
12494 (cond
12495 ((equal arg '(4))
12496 (when (and old-date org-log-redeadline)
12497 (org-add-log-setup 'deldeadline nil old-date 'findpos
12498 org-log-redeadline))
12499 (org-remove-timestamp-with-keyword org-deadline-string)
12500 (message "Item no longer has a deadline."))
12501 ((equal arg '(16))
12502 (save-excursion
12503 (if (re-search-forward
12504 org-deadline-time-regexp
12505 (save-excursion (outline-next-heading) (point)) t)
12506 (let* ((rpl0 (match-string 1))
12507 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12508 (replace-match
12509 (concat org-deadline-string
12510 " <" rpl
12511 (format " -%dd" (abs
12512 (- (time-to-days
12513 (save-match-data
12514 (org-read-date nil t nil "Warn starting from")))
12515 (time-to-days nil))))
12516 ">") t t))
12517 (user-error "No deadline information to update"))))
12519 (org-add-planning-info 'deadline time 'closed)
12520 (when (and old-date org-log-redeadline
12521 (not (equal old-date
12522 (substring org-last-inserted-timestamp 1 -1))))
12523 (org-add-log-setup 'redeadline nil old-date 'findpos
12524 org-log-redeadline))
12525 (when repeater
12526 (save-excursion
12527 (org-back-to-heading t)
12528 (when (re-search-forward (concat org-deadline-string " "
12529 org-last-inserted-timestamp)
12530 (save-excursion
12531 (outline-next-heading) (point)) t)
12532 (goto-char (1- (match-end 0)))
12533 (insert " " repeater)
12534 (setq org-last-inserted-timestamp
12535 (concat (substring org-last-inserted-timestamp 0 -1)
12536 " " repeater
12537 (substring org-last-inserted-timestamp -1))))))
12538 (message "Deadline on %s" org-last-inserted-timestamp))))))
12540 (defun org-schedule (&optional arg time)
12541 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12542 With one universal prefix argument, remove any scheduling date from the item.
12543 With two universal prefix arguments, prompt for a delay cookie.
12544 With argument TIME, scheduled at the corresponding date. TIME can
12545 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12546 (interactive "P")
12547 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12548 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12549 'region-start-level 'region))
12550 org-loop-over-headlines-in-active-region)
12551 (org-map-entries
12552 `(org-schedule ',arg ,time)
12553 org-loop-over-headlines-in-active-region
12554 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12555 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12556 (repeater (and old-date
12557 (string-match
12558 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12559 old-date)
12560 (match-string 1 old-date))))
12561 (cond
12562 ((equal arg '(4))
12563 (progn
12564 (when (and old-date org-log-reschedule)
12565 (org-add-log-setup 'delschedule nil old-date 'findpos
12566 org-log-reschedule))
12567 (org-remove-timestamp-with-keyword org-scheduled-string)
12568 (message "Item is no longer scheduled.")))
12569 ((equal arg '(16))
12570 (save-excursion
12571 (if (re-search-forward
12572 org-scheduled-time-regexp
12573 (save-excursion (outline-next-heading) (point)) t)
12574 (let* ((rpl0 (match-string 1))
12575 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12576 (replace-match
12577 (concat org-scheduled-string
12578 " <" rpl
12579 (format " -%dd" (abs
12580 (- (time-to-days
12581 (save-match-data
12582 (org-read-date nil t nil "Delay until")))
12583 (time-to-days nil))))
12584 ">") t t))
12585 (user-error "No scheduled information to update"))))
12587 (org-add-planning-info 'scheduled time 'closed)
12588 (when (and old-date org-log-reschedule
12589 (not (equal old-date
12590 (substring org-last-inserted-timestamp 1 -1))))
12591 (org-add-log-setup 'reschedule nil old-date 'findpos
12592 org-log-reschedule))
12593 (when repeater
12594 (save-excursion
12595 (org-back-to-heading t)
12596 (when (re-search-forward (concat org-scheduled-string " "
12597 org-last-inserted-timestamp)
12598 (save-excursion
12599 (outline-next-heading) (point)) t)
12600 (goto-char (1- (match-end 0)))
12601 (insert " " repeater)
12602 (setq org-last-inserted-timestamp
12603 (concat (substring org-last-inserted-timestamp 0 -1)
12604 " " repeater
12605 (substring org-last-inserted-timestamp -1))))))
12606 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12608 (defun org-get-scheduled-time (pom &optional inherit)
12609 "Get the scheduled time as a time tuple, of a format suitable
12610 for calling org-schedule with, or if there is no scheduling,
12611 returns nil."
12612 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12613 (when time
12614 (apply 'encode-time (org-parse-time-string time)))))
12616 (defun org-get-deadline-time (pom &optional inherit)
12617 "Get the deadline as a time tuple, of a format suitable for
12618 calling org-deadline with, or if there is no scheduling, returns
12619 nil."
12620 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12621 (when time
12622 (apply 'encode-time (org-parse-time-string time)))))
12624 (defun org-remove-timestamp-with-keyword (keyword)
12625 "Remove all time stamps with KEYWORD in the current entry."
12626 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12627 beg)
12628 (save-excursion
12629 (org-back-to-heading t)
12630 (setq beg (point))
12631 (outline-next-heading)
12632 (while (re-search-backward re beg t)
12633 (replace-match "")
12634 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12635 (equal (char-before) ?\ ))
12636 (backward-delete-char 1)
12637 (if (string-match "^[ \t]*$" (buffer-substring
12638 (point-at-bol) (point-at-eol)))
12639 (delete-region (point-at-bol)
12640 (min (point-max) (1+ (point-at-eol))))))))))
12642 (defun org-add-planning-info (what &optional time &rest remove)
12643 "Insert new timestamp with keyword in the line directly after the headline.
12644 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12645 If non is given, the user is prompted for a date.
12646 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12647 be removed."
12648 (interactive)
12649 (let (org-time-was-given org-end-time-was-given ts
12650 end default-time default-input)
12652 (catch 'exit
12653 (when (and (memq what '(scheduled deadline))
12654 (or (not time)
12655 (and (stringp time)
12656 (string-match "^[-+]+[0-9]" time))))
12657 ;; Try to get a default date/time from existing timestamp
12658 (save-excursion
12659 (org-back-to-heading t)
12660 (setq end (save-excursion (outline-next-heading) (point)))
12661 (when (re-search-forward (if (eq what 'scheduled)
12662 org-scheduled-time-regexp
12663 org-deadline-time-regexp)
12664 end t)
12665 (setq ts (match-string 1)
12666 default-time
12667 (apply 'encode-time (org-parse-time-string ts))
12668 default-input (and ts (org-get-compact-tod ts))))))
12669 (when what
12670 (setq time
12671 (if (stringp time)
12672 ;; This is a string (relative or absolute), set proper date
12673 (apply 'encode-time
12674 (org-read-date-analyze
12675 time default-time (decode-time default-time)))
12676 ;; If necessary, get the time from the user
12677 (or time (org-read-date nil 'to-time nil nil
12678 default-time default-input)))))
12680 (when (and org-insert-labeled-timestamps-at-point
12681 (member what '(scheduled deadline)))
12682 (insert
12683 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12684 (org-insert-time-stamp time org-time-was-given
12685 nil nil nil (list org-end-time-was-given))
12686 (setq what nil))
12687 (save-excursion
12688 (save-restriction
12689 (let (col list elt ts buffer-invisibility-spec)
12690 (org-back-to-heading t)
12691 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12692 (goto-char (match-end 1))
12693 (setq col (current-column))
12694 (goto-char (match-end 0))
12695 (if (eobp) (insert "\n") (forward-char 1))
12696 (when (and (not what)
12697 (not (looking-at
12698 (concat "[ \t]*"
12699 org-keyword-time-not-clock-regexp))))
12700 ;; Nothing to add, nothing to remove...... :-)
12701 (throw 'exit nil))
12702 (if (and (not (looking-at org-outline-regexp))
12703 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12704 "[^\r\n]*"))
12705 (not (equal (match-string 1) org-clock-string)))
12706 (narrow-to-region (match-beginning 0) (match-end 0))
12707 (insert-before-markers "\n")
12708 (backward-char 1)
12709 (narrow-to-region (point) (point))
12710 (and org-adapt-indentation (org-indent-to-column col)))
12711 ;; Check if we have to remove something.
12712 (setq list (cons what remove))
12713 (while list
12714 (setq elt (pop list))
12715 (when (or (and (eq elt 'scheduled)
12716 (re-search-forward org-scheduled-time-regexp nil t))
12717 (and (eq elt 'deadline)
12718 (re-search-forward org-deadline-time-regexp nil t))
12719 (and (eq elt 'closed)
12720 (re-search-forward org-closed-time-regexp nil t)))
12721 (replace-match "")
12722 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12723 (and (looking-at "[ \t]+") (replace-match ""))
12724 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12725 (when what
12726 (insert
12727 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12728 (cond ((eq what 'scheduled) org-scheduled-string)
12729 ((eq what 'deadline) org-deadline-string)
12730 ((eq what 'closed) org-closed-string))
12731 " ")
12732 (setq ts (org-insert-time-stamp
12733 time
12734 (or org-time-was-given
12735 (and (eq what 'closed) org-log-done-with-time))
12736 (eq what 'closed)
12737 nil nil (list org-end-time-was-given)))
12738 (insert
12739 (if (not (or (bolp) (eq (char-before) ?\ )
12740 (memq (char-after) '(32 10))
12741 (eobp))) " " ""))
12742 (end-of-line 1))
12743 (goto-char (point-min))
12744 (widen)
12745 (if (and (looking-at "[ \t]*\n")
12746 (equal (char-before) ?\n))
12747 (delete-region (1- (point)) (point-at-eol)))
12748 ts))))))
12750 (defvar org-log-note-marker (make-marker))
12751 (defvar org-log-note-purpose nil)
12752 (defvar org-log-note-state nil)
12753 (defvar org-log-note-previous-state nil)
12754 (defvar org-log-note-how nil)
12755 (defvar org-log-note-extra nil)
12756 (defvar org-log-note-window-configuration nil)
12757 (defvar org-log-note-return-to (make-marker))
12758 (defvar org-log-note-effective-time nil
12759 "Remembered current time so that dynamically scoped
12760 `org-extend-today-until' affects tha timestamps in state change
12761 log")
12763 (defvar org-log-post-message nil
12764 "Message to be displayed after a log note has been stored.
12765 The auto-repeater uses this.")
12767 (defun org-add-note ()
12768 "Add a note to the current entry.
12769 This is done in the same way as adding a state change note."
12770 (interactive)
12771 (org-add-log-setup 'note nil nil 'findpos nil))
12773 (defvar org-property-end-re)
12774 (defun org-add-log-setup (&optional purpose state prev-state
12775 findpos how extra)
12776 "Set up the post command hook to take a note.
12777 If this is about to TODO state change, the new state is expected in STATE.
12778 When FINDPOS is non-nil, find the correct position for the note in
12779 the current entry. If not, assume that it can be inserted at point.
12780 HOW is an indicator what kind of note should be created.
12781 EXTRA is additional text that will be inserted into the notes buffer."
12782 (let* ((org-log-into-drawer (org-log-into-drawer))
12783 (drawer (cond ((stringp org-log-into-drawer)
12784 org-log-into-drawer)
12785 (org-log-into-drawer "LOGBOOK"))))
12786 (save-restriction
12787 (save-excursion
12788 (when findpos
12789 (org-back-to-heading t)
12790 (narrow-to-region (point) (save-excursion
12791 (outline-next-heading) (point)))
12792 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12793 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12794 "[^\r\n]*\\)?"))
12795 (goto-char (match-end 0))
12796 (cond
12797 (drawer
12798 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12799 nil t)
12800 (progn
12801 (goto-char (match-end 0))
12802 (or org-log-states-order-reversed
12803 (and (re-search-forward org-property-end-re nil t)
12804 (goto-char (1- (match-beginning 0))))))
12805 (insert "\n:" drawer ":\n:END:")
12806 (beginning-of-line 0)
12807 (org-indent-line)
12808 (beginning-of-line 2)
12809 (org-indent-line)
12810 (end-of-line 0)))
12811 ((and org-log-state-notes-insert-after-drawers
12812 (save-excursion
12813 (forward-line) (looking-at org-drawer-regexp)))
12814 (forward-line)
12815 (while (looking-at org-drawer-regexp)
12816 (goto-char (match-end 0))
12817 (re-search-forward org-property-end-re (point-max) t)
12818 (forward-line))
12819 (forward-line -1)))
12820 (unless org-log-states-order-reversed
12821 (and (= (char-after) ?\n) (forward-char 1))
12822 (org-skip-over-state-notes)
12823 (skip-chars-backward " \t\n\r")))
12824 (move-marker org-log-note-marker (point))
12825 (setq org-log-note-purpose purpose
12826 org-log-note-state state
12827 org-log-note-previous-state prev-state
12828 org-log-note-how how
12829 org-log-note-extra extra
12830 org-log-note-effective-time (org-current-effective-time))
12831 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12833 (defun org-skip-over-state-notes ()
12834 "Skip past the list of State notes in an entry."
12835 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12836 (when (ignore-errors (goto-char (org-in-item-p)))
12837 (let* ((struct (org-list-struct))
12838 (prevs (org-list-prevs-alist struct)))
12839 (while (looking-at "[ \t]*- State")
12840 (goto-char (or (org-list-get-next-item (point) struct prevs)
12841 (org-list-get-item-end (point) struct)))))))
12843 (defun org-add-log-note (&optional purpose)
12844 "Pop up a window for taking a note, and add this note later at point."
12845 (remove-hook 'post-command-hook 'org-add-log-note)
12846 (setq org-log-note-window-configuration (current-window-configuration))
12847 (delete-other-windows)
12848 (move-marker org-log-note-return-to (point))
12849 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12850 (goto-char org-log-note-marker)
12851 (org-switch-to-buffer-other-window "*Org Note*")
12852 (erase-buffer)
12853 (if (memq org-log-note-how '(time state))
12854 (let (current-prefix-arg) (org-store-log-note))
12855 (let ((org-inhibit-startup t)) (org-mode))
12856 (insert (format "# Insert note for %s.
12857 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12858 (cond
12859 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12860 ((eq org-log-note-purpose 'done) "closed todo item")
12861 ((eq org-log-note-purpose 'state)
12862 (format "state change from \"%s\" to \"%s\""
12863 (or org-log-note-previous-state "")
12864 (or org-log-note-state "")))
12865 ((eq org-log-note-purpose 'reschedule)
12866 "rescheduling")
12867 ((eq org-log-note-purpose 'delschedule)
12868 "no longer scheduled")
12869 ((eq org-log-note-purpose 'redeadline)
12870 "changing deadline")
12871 ((eq org-log-note-purpose 'deldeadline)
12872 "removing deadline")
12873 ((eq org-log-note-purpose 'refile)
12874 "refiling")
12875 ((eq org-log-note-purpose 'note)
12876 "this entry")
12877 (t (error "This should not happen")))))
12878 (if org-log-note-extra (insert org-log-note-extra))
12879 (org-set-local 'org-finish-function 'org-store-log-note)
12880 (run-hooks 'org-log-buffer-setup-hook)))
12882 (defvar org-note-abort nil) ; dynamically scoped
12883 (defun org-store-log-note ()
12884 "Finish taking a log note, and insert it to where it belongs."
12885 (let ((txt (buffer-string)))
12886 (kill-buffer (current-buffer))
12887 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12888 lines ind bul)
12889 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12890 (setq txt (replace-match "" t t txt)))
12891 (if (string-match "\\s-+\\'" txt)
12892 (setq txt (replace-match "" t t txt)))
12893 (setq lines (org-split-string txt "\n"))
12894 (when (and note (string-match "\\S-" note))
12895 (setq note
12896 (org-replace-escapes
12897 note
12898 (list (cons "%u" (user-login-name))
12899 (cons "%U" user-full-name)
12900 (cons "%t" (format-time-string
12901 (org-time-stamp-format 'long 'inactive)
12902 org-log-note-effective-time))
12903 (cons "%T" (format-time-string
12904 (org-time-stamp-format 'long nil)
12905 org-log-note-effective-time))
12906 (cons "%d" (format-time-string
12907 (org-time-stamp-format nil 'inactive)
12908 org-log-note-effective-time))
12909 (cons "%D" (format-time-string
12910 (org-time-stamp-format nil nil)
12911 org-log-note-effective-time))
12912 (cons "%s" (if org-log-note-state
12913 (concat "\"" org-log-note-state "\"")
12914 ""))
12915 (cons "%S" (if org-log-note-previous-state
12916 (concat "\"" org-log-note-previous-state "\"")
12917 "\"\"")))))
12918 (if lines (setq note (concat note " \\\\")))
12919 (push note lines))
12920 (when (or current-prefix-arg org-note-abort)
12921 (when org-log-into-drawer
12922 (org-remove-empty-drawer-at
12923 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12924 org-log-note-marker))
12925 (setq lines nil))
12926 (when lines
12927 (with-current-buffer (marker-buffer org-log-note-marker)
12928 (save-excursion
12929 (goto-char org-log-note-marker)
12930 (move-marker org-log-note-marker nil)
12931 (end-of-line 1)
12932 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12933 (setq ind (save-excursion
12934 (if (ignore-errors (goto-char (org-in-item-p)))
12935 (let ((struct (org-list-struct)))
12936 (org-list-get-ind
12937 (org-list-get-top-point struct) struct))
12938 (skip-chars-backward " \r\t\n")
12939 (cond
12940 ((and (org-at-heading-p)
12941 org-adapt-indentation)
12942 (1+ (org-current-level)))
12943 ((org-at-heading-p) 0)
12944 (t (org-get-indentation))))))
12945 (setq bul (org-list-bullet-string "-"))
12946 (org-indent-line-to ind)
12947 (insert bul (pop lines))
12948 (let ((ind-body (+ (length bul) ind)))
12949 (while lines
12950 (insert "\n")
12951 (org-indent-line-to ind-body)
12952 (insert (pop lines))))
12953 (message "Note stored")
12954 (org-back-to-heading t)
12955 (org-cycle-hide-drawers 'children))))))
12956 (set-window-configuration org-log-note-window-configuration)
12957 (with-current-buffer (marker-buffer org-log-note-return-to)
12958 (goto-char org-log-note-return-to))
12959 (move-marker org-log-note-return-to nil)
12960 (and org-log-post-message (message "%s" org-log-post-message)))
12962 (defun org-remove-empty-drawer-at (drawer pos)
12963 "Remove an empty drawer DRAWER at position POS.
12964 POS may also be a marker."
12965 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12966 (save-excursion
12967 (save-restriction
12968 (widen)
12969 (goto-char pos)
12970 (if (org-in-regexp
12971 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12972 (replace-match ""))))))
12974 (defvar org-ts-type nil)
12975 (defun org-sparse-tree (&optional arg type)
12976 "Create a sparse tree, prompt for the details.
12977 This command can create sparse trees. You first need to select the type
12978 of match used to create the tree:
12980 t Show all TODO entries.
12981 T Show entries with a specific TODO keyword.
12982 m Show entries selected by a tags/property match.
12983 p Enter a property name and its value (both with completion on existing
12984 names/values) and show entries with that property.
12985 r Show entries matching a regular expression (`/' can be used as well).
12986 b Show deadlines and scheduled items before a date.
12987 a Show deadlines and scheduled items after a date.
12988 d Show deadlines due within `org-deadline-warning-days'.
12989 D Show deadlines and scheduled items between a date range."
12990 (interactive "P")
12991 (let (ans kwd value ts-type)
12992 (setq type (or type org-sparse-tree-default-date-type))
12993 (setq org-ts-type type)
12994 (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"
12995 (cond ((eq type 'all) "all timestamps")
12996 ((eq type 'scheduled) "only scheduled")
12997 ((eq type 'deadline) "only deadline")
12998 ((eq type 'active) "only active timestamps")
12999 ((eq type 'inactive) "only inactive timestamps")
13000 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13001 (t "scheduled/deadline")))
13002 (setq ans (read-char-exclusive))
13003 (cond
13004 ((equal ans ?c)
13005 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13006 ((equal ans ?d)
13007 (call-interactively 'org-check-deadlines))
13008 ((equal ans ?b)
13009 (call-interactively 'org-check-before-date))
13010 ((equal ans ?a)
13011 (call-interactively 'org-check-after-date))
13012 ((equal ans ?D)
13013 (call-interactively 'org-check-dates-range))
13014 ((equal ans ?t)
13015 (call-interactively 'org-show-todo-tree))
13016 ((equal ans ?T)
13017 (org-show-todo-tree '(4)))
13018 ((member ans '(?T ?m))
13019 (call-interactively 'org-match-sparse-tree))
13020 ((member ans '(?p ?P))
13021 (setq kwd (org-icompleting-read "Property: "
13022 (mapcar 'list (org-buffer-property-keys))))
13023 (setq value (org-icompleting-read "Value: "
13024 (mapcar 'list (org-property-values kwd))))
13025 (unless (string-match "\\`{.*}\\'" value)
13026 (setq value (concat "\"" value "\"")))
13027 (org-match-sparse-tree arg (concat kwd "=" value)))
13028 ((member ans '(?r ?R ?/))
13029 (call-interactively 'org-occur))
13030 (t (error "No such sparse tree command \"%c\"" ans)))))
13032 (defvar org-occur-highlights nil
13033 "List of overlays used for occur matches.")
13034 (make-variable-buffer-local 'org-occur-highlights)
13035 (defvar org-occur-parameters nil
13036 "Parameters of the active org-occur calls.
13037 This is a list, each call to org-occur pushes as cons cell,
13038 containing the regular expression and the callback, onto the list.
13039 The list can contain several entries if `org-occur' has been called
13040 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13041 will only contain one set of parameters. When the highlights are
13042 removed (for example with `C-c C-c', or with the next edit (depending
13043 on `org-remove-highlights-with-change'), this variable is emptied
13044 as well.")
13045 (make-variable-buffer-local 'org-occur-parameters)
13047 (defun org-occur (regexp &optional keep-previous callback)
13048 "Make a compact tree which shows all matches of REGEXP.
13049 The tree will show the lines where the regexp matches, and all higher
13050 headlines above the match. It will also show the heading after the match,
13051 to make sure editing the matching entry is easy.
13052 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13053 call to `org-occur' will be kept, to allow stacking of calls to this
13054 command.
13055 If CALLBACK is non-nil, it is a function which is called to confirm
13056 that the match should indeed be shown."
13057 (interactive "sRegexp: \nP")
13058 (when (equal regexp "")
13059 (error "Regexp cannot be empty"))
13060 (unless keep-previous
13061 (org-remove-occur-highlights nil nil t))
13062 (push (cons regexp callback) org-occur-parameters)
13063 (let ((cnt 0))
13064 (save-excursion
13065 (goto-char (point-min))
13066 (if (or (not keep-previous) ; do not want to keep
13067 (not org-occur-highlights)) ; no previous matches
13068 ;; hide everything
13069 (org-overview))
13070 (while (re-search-forward regexp nil t)
13071 (when (or (not callback)
13072 (save-match-data (funcall callback)))
13073 (setq cnt (1+ cnt))
13074 (when org-highlight-sparse-tree-matches
13075 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13076 (org-show-context 'occur-tree))))
13077 (when org-remove-highlights-with-change
13078 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13079 nil 'local))
13080 (unless org-sparse-tree-open-archived-trees
13081 (org-hide-archived-subtrees (point-min) (point-max)))
13082 (run-hooks 'org-occur-hook)
13083 (if (org-called-interactively-p 'interactive)
13084 (message "%d match(es) for regexp %s" cnt regexp))
13085 cnt))
13087 (defun org-occur-next-match (&optional n reset)
13088 "Function for `next-error-function' to find sparse tree matches.
13089 N is the number of matches to move, when negative move backwards.
13090 RESET is entirely ignored - this function always goes back to the
13091 starting point when no match is found."
13092 (let* ((limit (if (< n 0) (point-min) (point-max)))
13093 (search-func (if (< n 0)
13094 'previous-single-char-property-change
13095 'next-single-char-property-change))
13096 (n (abs n))
13097 (pos (point))
13099 (catch 'exit
13100 (while (setq p1 (funcall search-func (point) 'org-type))
13101 (when (equal p1 limit)
13102 (goto-char pos)
13103 (error "No more matches"))
13104 (when (equal (get-char-property p1 'org-type) 'org-occur)
13105 (setq n (1- n))
13106 (when (= n 0)
13107 (goto-char p1)
13108 (throw 'exit (point))))
13109 (goto-char p1))
13110 (goto-char p1)
13111 (error "No more matches"))))
13113 (defun org-show-context (&optional key)
13114 "Make sure point and context are visible.
13115 How much context is shown depends upon the variables
13116 `org-show-hierarchy-above', `org-show-following-heading',
13117 `org-show-entry-below' and `org-show-siblings'."
13118 (let ((heading-p (org-at-heading-p t))
13119 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13120 (following-p (org-get-alist-option org-show-following-heading key))
13121 (entry-p (org-get-alist-option org-show-entry-below key))
13122 (siblings-p (org-get-alist-option org-show-siblings key)))
13123 (catch 'exit
13124 ;; Show heading or entry text
13125 (if (and heading-p (not entry-p))
13126 (org-flag-heading nil) ; only show the heading
13127 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13128 (org-show-hidden-entry))) ; show entire entry
13129 (when following-p
13130 ;; Show next sibling, or heading below text
13131 (save-excursion
13132 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13133 (org-flag-heading nil))))
13134 (when siblings-p (org-show-siblings))
13135 (when hierarchy-p
13136 ;; show all higher headings, possibly with siblings
13137 (save-excursion
13138 (while (and (condition-case nil
13139 (progn (org-up-heading-all 1) t)
13140 (error nil))
13141 (not (bobp)))
13142 (org-flag-heading nil)
13143 (when siblings-p (org-show-siblings))))))))
13145 (defvar org-reveal-start-hook nil
13146 "Hook run before revealing a location.")
13148 (defun org-reveal (&optional siblings)
13149 "Show current entry, hierarchy above it, and the following headline.
13150 This can be used to show a consistent set of context around locations
13151 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13152 not t for the search context.
13154 With optional argument SIBLINGS, on each level of the hierarchy all
13155 siblings are shown. This repairs the tree structure to what it would
13156 look like when opened with hierarchical calls to `org-cycle'.
13157 With double optional argument \\[universal-argument] \\[universal-argument], \
13158 go to the parent and show the
13159 entire tree."
13160 (interactive "P")
13161 (run-hooks 'org-reveal-start-hook)
13162 (let ((org-show-hierarchy-above t)
13163 (org-show-following-heading t)
13164 (org-show-siblings (if siblings t org-show-siblings)))
13165 (org-show-context nil))
13166 (when (equal siblings '(16))
13167 (save-excursion
13168 (when (org-up-heading-safe)
13169 (org-show-subtree)
13170 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13172 (defun org-highlight-new-match (beg end)
13173 "Highlight from BEG to END and mark the highlight is an occur headline."
13174 (let ((ov (make-overlay beg end)))
13175 (overlay-put ov 'face 'secondary-selection)
13176 (overlay-put ov 'org-type 'org-occur)
13177 (push ov org-occur-highlights)))
13179 (defun org-remove-occur-highlights (&optional beg end noremove)
13180 "Remove the occur highlights from the buffer.
13181 BEG and END are ignored. If NOREMOVE is nil, remove this function
13182 from the `before-change-functions' in the current buffer."
13183 (interactive)
13184 (unless org-inhibit-highlight-removal
13185 (mapc 'delete-overlay org-occur-highlights)
13186 (setq org-occur-highlights nil)
13187 (setq org-occur-parameters nil)
13188 (unless noremove
13189 (remove-hook 'before-change-functions
13190 'org-remove-occur-highlights 'local))))
13192 ;;;; Priorities
13194 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13195 "Regular expression matching the priority indicator.")
13197 (defvar org-remove-priority-next-time nil)
13199 (defun org-priority-up ()
13200 "Increase the priority of the current item."
13201 (interactive)
13202 (org-priority 'up))
13204 (defun org-priority-down ()
13205 "Decrease the priority of the current item."
13206 (interactive)
13207 (org-priority 'down))
13209 (defun org-priority (&optional action show)
13210 "Change the priority of an item.
13211 ACTION can be `set', `up', `down', or a character."
13212 (interactive "P")
13213 (if (equal action '(4))
13214 (org-show-priority)
13215 (unless org-enable-priority-commands
13216 (error "Priority commands are disabled"))
13217 (setq action (or action 'set))
13218 (let (current new news have remove)
13219 (save-excursion
13220 (org-back-to-heading t)
13221 (if (looking-at org-priority-regexp)
13222 (setq current (string-to-char (match-string 2))
13223 have t))
13224 (cond
13225 ((eq action 'remove)
13226 (setq remove t new ?\ ))
13227 ((or (eq action 'set)
13228 (if (featurep 'xemacs) (characterp action) (integerp action)))
13229 (if (not (eq action 'set))
13230 (setq new action)
13231 (message "Priority %c-%c, SPC to remove: "
13232 org-highest-priority org-lowest-priority)
13233 (save-match-data
13234 (setq new (read-char-exclusive))))
13235 (if (and (= (upcase org-highest-priority) org-highest-priority)
13236 (= (upcase org-lowest-priority) org-lowest-priority))
13237 (setq new (upcase new)))
13238 (cond ((equal new ?\ ) (setq remove t))
13239 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13240 (error "Priority must be between `%c' and `%c'"
13241 org-highest-priority org-lowest-priority))))
13242 ((eq action 'up)
13243 (setq new (if have
13244 (1- current) ; normal cycling
13245 ;; last priority was empty
13246 (if (eq last-command this-command)
13247 org-lowest-priority ; wrap around empty to lowest
13248 ;; default
13249 (if org-priority-start-cycle-with-default
13250 org-default-priority
13251 (1- org-default-priority))))))
13252 ((eq action 'down)
13253 (setq new (if have
13254 (1+ current) ; normal cycling
13255 ;; last priority was empty
13256 (if (eq last-command this-command)
13257 org-highest-priority ; wrap around empty to highest
13258 ;; default
13259 (if org-priority-start-cycle-with-default
13260 org-default-priority
13261 (1+ org-default-priority))))))
13262 (t (error "Invalid action")))
13263 (if (or (< (upcase new) org-highest-priority)
13264 (> (upcase new) org-lowest-priority))
13265 (if (and (memq action '(up down))
13266 (not have) (not (eq last-command this-command)))
13267 ;; `new' is from default priority
13268 (error
13269 "The default can not be set, see `org-default-priority' why")
13270 ;; normal cycling: `new' is beyond highest/lowest priority
13271 ;; and is wrapped around to the empty priority
13272 (setq remove t)))
13273 (setq news (format "%c" new))
13274 (if have
13275 (if remove
13276 (replace-match "" t t nil 1)
13277 (replace-match news t t nil 2))
13278 (if remove
13279 (error "No priority cookie found in line")
13280 (let ((case-fold-search nil))
13281 (looking-at org-todo-line-regexp))
13282 (if (match-end 2)
13283 (progn
13284 (goto-char (match-end 2))
13285 (insert " [#" news "]"))
13286 (goto-char (match-beginning 3))
13287 (insert "[#" news "] "))))
13288 (org-preserve-lc (org-set-tags nil 'align)))
13289 (if remove
13290 (message "Priority removed")
13291 (message "Priority of current item set to %s" news)))))
13293 (defun org-show-priority ()
13294 "Show the priority of the current item.
13295 This priority is composed of the main priority given with the [#A] cookies,
13296 and by additional input from the age of a schedules or deadline entry."
13297 (interactive)
13298 (let ((pri (if (eq major-mode 'org-agenda-mode)
13299 (org-get-at-bol 'priority)
13300 (save-excursion
13301 (save-match-data
13302 (beginning-of-line)
13303 (and (looking-at org-heading-regexp)
13304 (org-get-priority (match-string 0))))))))
13305 (message "Priority is %d" (if pri pri -1000))))
13307 (defun org-get-priority (s)
13308 "Find priority cookie and return priority."
13309 (save-match-data
13310 (if (functionp org-get-priority-function)
13311 (funcall org-get-priority-function)
13312 (if (not (string-match org-priority-regexp s))
13313 (* 1000 (- org-lowest-priority org-default-priority))
13314 (* 1000 (- org-lowest-priority
13315 (string-to-char (match-string 2 s))))))))
13317 ;;;; Tags
13319 (defvar org-agenda-archives-mode)
13320 (defvar org-map-continue-from nil
13321 "Position from where mapping should continue.
13322 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13324 (defvar org-scanner-tags nil
13325 "The current tag list while the tags scanner is running.")
13326 (defvar org-trust-scanner-tags nil
13327 "Should `org-get-tags-at' use the tags for the scanner.
13328 This is for internal dynamical scoping only.
13329 When this is non-nil, the function `org-get-tags-at' will return the value
13330 of `org-scanner-tags' instead of building the list by itself. This
13331 can lead to large speed-ups when the tags scanner is used in a file with
13332 many entries, and when the list of tags is retrieved, for example to
13333 obtain a list of properties. Building the tags list for each entry in such
13334 a file becomes an N^2 operation - but with this variable set, it scales
13335 as N.")
13337 (defun org-scan-tags (action matcher todo-only &optional start-level)
13338 "Scan headline tags with inheritance and produce output ACTION.
13340 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13341 or `agenda' to produce an entry list for an agenda view. It can also be
13342 a Lisp form or a function that should be called at each matched headline, in
13343 this case the return value is a list of all return values from these calls.
13345 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13346 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13347 only lines with a not-done TODO keyword are included in the output.
13348 This should be the same variable that was scoped into
13349 and set by `org-make-tags-matcher' when it constructed MATCHER.
13351 START-LEVEL can be a string with asterisks, reducing the scope to
13352 headlines matching this string."
13353 (require 'org-agenda)
13354 (let* ((re (concat "^"
13355 (if start-level
13356 ;; Get the correct level to match
13357 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13358 org-outline-regexp)
13359 " *\\(\\<\\("
13360 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13361 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13362 (props (list 'face 'default
13363 'done-face 'org-agenda-done
13364 'undone-face 'default
13365 'mouse-face 'highlight
13366 'org-not-done-regexp org-not-done-regexp
13367 'org-todo-regexp org-todo-regexp
13368 'org-complex-heading-regexp org-complex-heading-regexp
13369 'help-echo
13370 (format "mouse-2 or RET jump to org file %s"
13371 (abbreviate-file-name
13372 (or (buffer-file-name (buffer-base-buffer))
13373 (buffer-name (buffer-base-buffer)))))))
13374 (case-fold-search nil)
13375 (org-map-continue-from nil)
13376 lspos tags tags-list
13377 (tags-alist (list (cons 0 org-file-tags)))
13378 (llast 0) rtn rtn1 level category i txt
13379 todo marker entry priority)
13380 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13381 (setq action (list 'lambda nil action)))
13382 (save-excursion
13383 (goto-char (point-min))
13384 (when (eq action 'sparse-tree)
13385 (org-overview)
13386 (org-remove-occur-highlights))
13387 (while (re-search-forward re nil t)
13388 (setq org-map-continue-from nil)
13389 (catch :skip
13390 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13391 tags (if (match-end 4) (org-match-string-no-properties 4)))
13392 (goto-char (setq lspos (match-beginning 0)))
13393 (setq level (org-reduced-level (org-outline-level))
13394 category (org-get-category))
13395 (setq i llast llast level)
13396 ;; remove tag lists from same and sublevels
13397 (while (>= i level)
13398 (when (setq entry (assoc i tags-alist))
13399 (setq tags-alist (delete entry tags-alist)))
13400 (setq i (1- i)))
13401 ;; add the next tags
13402 (when tags
13403 (setq tags (org-split-string tags ":")
13404 tags-alist
13405 (cons (cons level tags) tags-alist)))
13406 ;; compile tags for current headline
13407 (setq tags-list
13408 (if org-use-tag-inheritance
13409 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13410 tags)
13411 org-scanner-tags tags-list)
13412 (when org-use-tag-inheritance
13413 (setcdr (car tags-alist)
13414 (mapcar (lambda (x)
13415 (setq x (copy-sequence x))
13416 (org-add-prop-inherited x))
13417 (cdar tags-alist))))
13418 (when (and tags org-use-tag-inheritance
13419 (or (not (eq t org-use-tag-inheritance))
13420 org-tags-exclude-from-inheritance))
13421 ;; selective inheritance, remove uninherited ones
13422 (setcdr (car tags-alist)
13423 (org-remove-uninherited-tags (cdar tags-alist))))
13424 (when (and
13426 ;; eval matcher only when the todo condition is OK
13427 (and (or (not todo-only) (member todo org-not-done-keywords))
13428 (let ((case-fold-search t) (org-trust-scanner-tags t))
13429 (eval matcher)))
13431 ;; Call the skipper, but return t if it does not skip,
13432 ;; so that the `and' form continues evaluating
13433 (progn
13434 (unless (eq action 'sparse-tree) (org-agenda-skip))
13437 ;; Check if timestamps are deselecting this entry
13438 (or (not todo-only)
13439 (and (member todo org-not-done-keywords)
13440 (or (not org-agenda-tags-todo-honor-ignore-options)
13441 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13443 ;; select this headline
13444 (cond
13445 ((eq action 'sparse-tree)
13446 (and org-highlight-sparse-tree-matches
13447 (org-get-heading) (match-end 0)
13448 (org-highlight-new-match
13449 (match-beginning 1) (match-end 1)))
13450 (org-show-context 'tags-tree))
13451 ((eq action 'agenda)
13452 (setq txt (org-agenda-format-item
13454 (concat
13455 (if (eq org-tags-match-list-sublevels 'indented)
13456 (make-string (1- level) ?.) "")
13457 (org-get-heading))
13458 level category
13459 tags-list)
13460 priority (org-get-priority txt))
13461 (goto-char lspos)
13462 (setq marker (org-agenda-new-marker))
13463 (org-add-props txt props
13464 'org-marker marker 'org-hd-marker marker 'org-category category
13465 'todo-state todo
13466 'priority priority 'type "tagsmatch")
13467 (push txt rtn))
13468 ((functionp action)
13469 (setq org-map-continue-from nil)
13470 (save-excursion
13471 (setq rtn1 (funcall action))
13472 (push rtn1 rtn)))
13473 (t (error "Invalid action")))
13475 ;; if we are to skip sublevels, jump to end of subtree
13476 (unless org-tags-match-list-sublevels
13477 (org-end-of-subtree t)
13478 (backward-char 1))))
13479 ;; Get the correct position from where to continue
13480 (if org-map-continue-from
13481 (goto-char org-map-continue-from)
13482 (and (= (point) lspos) (end-of-line 1)))))
13483 (when (and (eq action 'sparse-tree)
13484 (not org-sparse-tree-open-archived-trees))
13485 (org-hide-archived-subtrees (point-min) (point-max)))
13486 (nreverse rtn)))
13488 (defun org-remove-uninherited-tags (tags)
13489 "Remove all tags that are not inherited from the list TAGS."
13490 (cond
13491 ((eq org-use-tag-inheritance t)
13492 (if org-tags-exclude-from-inheritance
13493 (org-delete-all org-tags-exclude-from-inheritance tags)
13494 tags))
13495 ((not org-use-tag-inheritance) nil)
13496 ((stringp org-use-tag-inheritance)
13497 (delq nil (mapcar
13498 (lambda (x)
13499 (if (and (string-match org-use-tag-inheritance x)
13500 (not (member x org-tags-exclude-from-inheritance)))
13501 x nil))
13502 tags)))
13503 ((listp org-use-tag-inheritance)
13504 (delq nil (mapcar
13505 (lambda (x)
13506 (if (member x org-use-tag-inheritance) x nil))
13507 tags)))))
13509 (defun org-match-sparse-tree (&optional todo-only match)
13510 "Create a sparse tree according to tags string MATCH.
13511 MATCH can contain positive and negative selection of tags, like
13512 \"+WORK+URGENT-WITHBOSS\".
13513 If optional argument TODO-ONLY is non-nil, only select lines that are
13514 also TODO lines."
13515 (interactive "P")
13516 (org-agenda-prepare-buffers (list (current-buffer)))
13517 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13519 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13521 (defvar org-cached-props nil)
13522 (defun org-cached-entry-get (pom property)
13523 (if (or (eq t org-use-property-inheritance)
13524 (and (stringp org-use-property-inheritance)
13525 (string-match org-use-property-inheritance property))
13526 (and (listp org-use-property-inheritance)
13527 (member property org-use-property-inheritance)))
13528 ;; Caching is not possible, check it directly
13529 (org-entry-get pom property 'inherit)
13530 ;; Get all properties, so that we can do complicated checks easily
13531 (cdr (assoc property (or org-cached-props
13532 (setq org-cached-props
13533 (org-entry-properties pom)))))))
13535 (defun org-global-tags-completion-table (&optional files)
13536 "Return the list of all tags in all agenda buffer/files.
13537 Optional FILES argument is a list of files which can be used
13538 instead of the agenda files."
13539 (save-excursion
13540 (org-uniquify
13541 (delq nil
13542 (apply 'append
13543 (mapcar
13544 (lambda (file)
13545 (set-buffer (find-file-noselect file))
13546 (append (org-get-buffer-tags)
13547 (mapcar (lambda (x) (if (stringp (car-safe x))
13548 (list (car-safe x)) nil))
13549 org-tag-alist)))
13550 (if (and files (car files))
13551 files
13552 (org-agenda-files))))))))
13554 (defun org-make-tags-matcher (match)
13555 "Create the TAGS/TODO matcher form for the selection string MATCH.
13557 The variable `todo-only' is scoped dynamically into this function.
13558 It will be set to t if the matcher restricts matching to TODO entries,
13559 otherwise will not be touched.
13561 Returns a cons of the selection string MATCH and the constructed
13562 lisp form implementing the matcher. The matcher is to be evaluated
13563 at an Org entry, with point on the headline, and returns t if the
13564 entry matches the selection string MATCH. The returned lisp form
13565 references two variables with information about the entry, which
13566 must be bound around the form's evaluation: todo, the TODO keyword
13567 at the entry (or nil of none); and tags-list, the list of all tags
13568 at the entry including inherited ones. Additionally, the category
13569 of the entry (if any) must be specified as the text property
13570 'org-category on the headline.
13572 See also `org-scan-tags'.
13574 (declare (special todo-only))
13575 (unless (boundp 'todo-only)
13576 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13577 (unless match
13578 ;; Get a new match request, with completion
13579 (let ((org-last-tags-completion-table
13580 (org-global-tags-completion-table)))
13581 (setq match (org-completing-read-no-i
13582 "Match: " 'org-tags-completion-function nil nil nil
13583 'org-tags-history))))
13585 ;; Parse the string and create a lisp form
13586 (let ((match0 match)
13587 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13588 minus tag mm
13589 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13590 orterms term orlist re-p str-p level-p level-op time-p
13591 prop-p pn pv po gv rest)
13592 (if (string-match "/+" match)
13593 ;; match contains also a todo-matching request
13594 (progn
13595 (setq tagsmatch (substring match 0 (match-beginning 0))
13596 todomatch (substring match (match-end 0)))
13597 (if (string-match "^!" todomatch)
13598 (setq todo-only t todomatch (substring todomatch 1)))
13599 (if (string-match "^\\s-*$" todomatch)
13600 (setq todomatch nil)))
13601 ;; only matching tags
13602 (setq tagsmatch match todomatch nil))
13604 ;; Make the tags matcher
13605 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13606 (setq tagsmatcher t)
13607 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13608 (while (setq term (pop orterms))
13609 (while (and (equal (substring term -1) "\\") orterms)
13610 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13611 (while (string-match re term)
13612 (setq rest (substring term (match-end 0))
13613 minus (and (match-end 1)
13614 (equal (match-string 1 term) "-"))
13615 tag (save-match-data (replace-regexp-in-string
13616 "\\\\-" "-"
13617 (match-string 2 term)))
13618 re-p (equal (string-to-char tag) ?{)
13619 level-p (match-end 4)
13620 prop-p (match-end 5)
13621 mm (cond
13622 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13623 (level-p
13624 (setq level-op (org-op-to-function (match-string 3 term)))
13625 `(,level-op level ,(string-to-number
13626 (match-string 4 term))))
13627 (prop-p
13628 (setq pn (match-string 5 term)
13629 po (match-string 6 term)
13630 pv (match-string 7 term)
13631 re-p (equal (string-to-char pv) ?{)
13632 str-p (equal (string-to-char pv) ?\")
13633 time-p (save-match-data
13634 (string-match "^\"[[<].*[]>]\"$" pv))
13635 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13636 (if time-p (setq pv (org-matcher-time pv)))
13637 (setq po (org-op-to-function po (if time-p 'time str-p)))
13638 (cond
13639 ((equal pn "CATEGORY")
13640 (setq gv '(get-text-property (point) 'org-category)))
13641 ((equal pn "TODO")
13642 (setq gv 'todo))
13644 (setq gv `(org-cached-entry-get nil ,pn))))
13645 (if re-p
13646 (if (eq po 'org<>)
13647 `(not (string-match ,pv (or ,gv "")))
13648 `(string-match ,pv (or ,gv "")))
13649 (if str-p
13650 `(,po (or ,gv "") ,pv)
13651 `(,po (string-to-number (or ,gv ""))
13652 ,(string-to-number pv) ))))
13653 (t `(member ,tag tags-list)))
13654 mm (if minus (list 'not mm) mm)
13655 term rest)
13656 (push mm tagsmatcher))
13657 (push (if (> (length tagsmatcher) 1)
13658 (cons 'and tagsmatcher)
13659 (car tagsmatcher))
13660 orlist)
13661 (setq tagsmatcher nil))
13662 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13663 (setq tagsmatcher
13664 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13665 ;; Make the todo matcher
13666 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13667 (setq todomatcher t)
13668 (setq orterms (org-split-string todomatch "|") orlist nil)
13669 (while (setq term (pop orterms))
13670 (while (string-match re term)
13671 (setq minus (and (match-end 1)
13672 (equal (match-string 1 term) "-"))
13673 kwd (match-string 2 term)
13674 re-p (equal (string-to-char kwd) ?{)
13675 term (substring term (match-end 0))
13676 mm (if re-p
13677 `(string-match ,(substring kwd 1 -1) todo)
13678 (list 'equal 'todo kwd))
13679 mm (if minus (list 'not mm) mm))
13680 (push mm todomatcher))
13681 (push (if (> (length todomatcher) 1)
13682 (cons 'and todomatcher)
13683 (car todomatcher))
13684 orlist)
13685 (setq todomatcher nil))
13686 (setq todomatcher (if (> (length orlist) 1)
13687 (cons 'or orlist) (car orlist))))
13689 ;; Return the string and lisp forms of the matcher
13690 (setq matcher (if todomatcher
13691 (list 'and tagsmatcher todomatcher)
13692 tagsmatcher))
13693 (when todo-only
13694 (setq matcher (list 'and '(member todo org-not-done-keywords)
13695 matcher)))
13696 (cons match0 matcher)))
13698 (defun org-op-to-function (op &optional stringp)
13699 "Turn an operator into the appropriate function."
13700 (setq op
13701 (cond
13702 ((equal op "<" ) '(< string< org-time<))
13703 ((equal op ">" ) '(> org-string> org-time>))
13704 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13705 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13706 ((member op '("=" "==")) '(= string= org-time=))
13707 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13708 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13710 (defun org<> (a b) (not (= a b)))
13711 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13712 (defun org-string>= (a b) (not (string< a b)))
13713 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13714 (defun org-string<> (a b) (not (string= a b)))
13715 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13716 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13717 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13718 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13719 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13720 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13721 (defun org-2ft (s)
13722 "Convert S to a floating point time.
13723 If S is already a number, just return it. If it is a string, parse
13724 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13725 (cond
13726 ((numberp s) s)
13727 ((stringp s)
13728 (condition-case nil
13729 (float-time (apply 'encode-time (org-parse-time-string s)))
13730 (error 0.)))
13731 (t 0.)))
13733 (defun org-time-today ()
13734 "Time in seconds today at 0:00.
13735 Returns the float number of seconds since the beginning of the
13736 epoch to the beginning of today (00:00)."
13737 (float-time (apply 'encode-time
13738 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13740 (defun org-matcher-time (s)
13741 "Interpret a time comparison value."
13742 (save-match-data
13743 (cond
13744 ((string= s "<now>") (float-time))
13745 ((string= s "<today>") (org-time-today))
13746 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13747 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13748 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13749 (+ (org-time-today)
13750 (* (string-to-number (match-string 1 s))
13751 (cdr (assoc (match-string 2 s)
13752 '(("d" . 86400.0) ("w" . 604800.0)
13753 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13754 (t (org-2ft s)))))
13756 (defun org-match-any-p (re list)
13757 "Does re match any element of list?"
13758 (setq list (mapcar (lambda (x) (string-match re x)) list))
13759 (delq nil list))
13761 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13762 (defvar org-tags-overlay (make-overlay 1 1))
13763 (org-detach-overlay org-tags-overlay)
13765 (defun org-get-local-tags-at (&optional pos)
13766 "Get a list of tags defined in the current headline."
13767 (org-get-tags-at pos 'local))
13769 (defun org-get-local-tags ()
13770 "Get a list of tags defined in the current headline."
13771 (org-get-tags-at nil 'local))
13773 (defun org-get-tags-at (&optional pos local)
13774 "Get a list of all headline tags applicable at POS.
13775 POS defaults to point. If tags are inherited, the list contains
13776 the targets in the same sequence as the headlines appear, i.e.
13777 the tags of the current headline come last.
13778 When LOCAL is non-nil, only return tags from the current headline,
13779 ignore inherited ones."
13780 (interactive)
13781 (if (and org-trust-scanner-tags
13782 (or (not pos) (equal pos (point)))
13783 (not local))
13784 org-scanner-tags
13785 (let (tags ltags lastpos parent)
13786 (save-excursion
13787 (save-restriction
13788 (widen)
13789 (goto-char (or pos (point)))
13790 (save-match-data
13791 (catch 'done
13792 (condition-case nil
13793 (progn
13794 (org-back-to-heading t)
13795 (while (not (equal lastpos (point)))
13796 (setq lastpos (point))
13797 (when (looking-at
13798 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13799 (setq ltags (org-split-string
13800 (org-match-string-no-properties 1) ":"))
13801 (when parent
13802 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13803 (setq tags (append
13804 (if parent
13805 (org-remove-uninherited-tags ltags)
13806 ltags)
13807 tags)))
13808 (or org-use-tag-inheritance (throw 'done t))
13809 (if local (throw 'done t))
13810 (or (org-up-heading-safe) (error nil))
13811 (setq parent t)))
13812 (error nil)))))
13813 (if local
13814 tags
13815 (reverse (delete-dups
13816 (reverse (append
13817 (org-remove-uninherited-tags
13818 org-file-tags) tags)))))))))
13820 (defun org-add-prop-inherited (s)
13821 (add-text-properties 0 (length s) '(inherited t) s)
13824 (defun org-toggle-tag (tag &optional onoff)
13825 "Toggle the tag TAG for the current line.
13826 If ONOFF is `on' or `off', don't toggle but set to this state."
13827 (let (res current)
13828 (save-excursion
13829 (org-back-to-heading t)
13830 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13831 (point-at-eol) t)
13832 (progn
13833 (setq current (match-string 1))
13834 (replace-match ""))
13835 (setq current ""))
13836 (setq current (nreverse (org-split-string current ":")))
13837 (cond
13838 ((eq onoff 'on)
13839 (setq res t)
13840 (or (member tag current) (push tag current)))
13841 ((eq onoff 'off)
13842 (or (not (member tag current)) (setq current (delete tag current))))
13843 (t (if (member tag current)
13844 (setq current (delete tag current))
13845 (setq res t)
13846 (push tag current))))
13847 (end-of-line 1)
13848 (if current
13849 (progn
13850 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13851 (org-set-tags nil t))
13852 (delete-horizontal-space))
13853 (run-hooks 'org-after-tags-change-hook))
13854 res))
13856 (defun org-align-tags-here (to-col)
13857 ;; Assumes that this is a headline
13858 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13859 (beginning-of-line 1)
13860 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13861 (< pos (match-beginning 2)))
13862 (progn
13863 (setq tags-l (- (match-end 2) (match-beginning 2)))
13864 (goto-char (match-beginning 1))
13865 (insert " ")
13866 (delete-region (point) (1+ (match-beginning 2)))
13867 (setq ncol (max (current-column)
13868 (1+ col)
13869 (if (> to-col 0)
13870 to-col
13871 (- (abs to-col) tags-l))))
13872 (setq p (point))
13873 (insert (make-string (- ncol (current-column)) ?\ ))
13874 (setq ncol (current-column))
13875 (when indent-tabs-mode (tabify p (point-at-eol)))
13876 (org-move-to-column (min ncol col) t))
13877 (goto-char pos))))
13879 (defun org-set-tags-command (&optional arg just-align)
13880 "Call the set-tags command for the current entry."
13881 (interactive "P")
13882 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13883 (org-set-tags arg just-align)
13884 (save-excursion
13885 (org-back-to-heading t)
13886 (org-set-tags arg just-align))))
13888 (defun org-set-tags-to (data)
13889 "Set the tags of the current entry to DATA, replacing the current tags.
13890 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13891 If DATA is nil or the empty string, any tags will be removed."
13892 (interactive "sTags: ")
13893 (setq data
13894 (cond
13895 ((eq data nil) "")
13896 ((equal data "") "")
13897 ((stringp data)
13898 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13899 ":"))
13900 ((listp data)
13901 (concat ":" (mapconcat 'identity data ":") ":"))))
13902 (when data
13903 (save-excursion
13904 (org-back-to-heading t)
13905 (when (looking-at org-complex-heading-regexp)
13906 (if (match-end 5)
13907 (progn
13908 (goto-char (match-beginning 5))
13909 (insert data)
13910 (delete-region (point) (point-at-eol))
13911 (org-set-tags nil 'align))
13912 (goto-char (point-at-eol))
13913 (insert " " data)
13914 (org-set-tags nil 'align)))
13915 (beginning-of-line 1)
13916 (if (looking-at ".*?\\([ \t]+\\)$")
13917 (delete-region (match-beginning 1) (match-end 1))))))
13919 (defun org-align-all-tags ()
13920 "Align the tags i all headings."
13921 (interactive)
13922 (save-excursion
13923 (or (ignore-errors (org-back-to-heading t))
13924 (outline-next-heading))
13925 (if (org-at-heading-p)
13926 (org-set-tags t)
13927 (message "No headings"))))
13929 (defvar org-indent-indentation-per-level)
13930 (defun org-set-tags (&optional arg just-align)
13931 "Set the tags for the current headline.
13932 With prefix ARG, realign all tags in headings in the current buffer."
13933 (interactive "P")
13934 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13935 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13936 'region-start-level 'region))
13937 org-loop-over-headlines-in-active-region)
13938 (org-map-entries
13939 ;; We don't use ARG and JUST-ALIGN here these args are not
13940 ;; useful when looping over headlines
13941 `(org-set-tags)
13942 org-loop-over-headlines-in-active-region
13943 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13944 (let* ((re org-outline-regexp-bol)
13945 (current (unless arg (org-get-tags-string)))
13946 (col (current-column))
13947 (org-setting-tags t)
13948 table current-tags inherited-tags ; computed below when needed
13949 tags p0 c0 c1 rpl di tc level)
13950 (if arg
13951 (save-excursion
13952 (goto-char (point-min))
13953 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13954 (while (re-search-forward re nil t)
13955 (org-set-tags nil t)
13956 (end-of-line 1)))
13957 (message "All tags realigned to column %d" org-tags-column))
13958 (if just-align
13959 (setq tags current)
13960 ;; Get a new set of tags from the user
13961 (save-excursion
13962 (setq table (append org-tag-persistent-alist
13963 (or org-tag-alist (org-get-buffer-tags))
13964 (and
13965 org-complete-tags-always-offer-all-agenda-tags
13966 (org-global-tags-completion-table
13967 (org-agenda-files))))
13968 org-last-tags-completion-table table
13969 current-tags (org-split-string current ":")
13970 inherited-tags (nreverse
13971 (nthcdr (length current-tags)
13972 (nreverse (org-get-tags-at))))
13973 tags
13974 (if (or (eq t org-use-fast-tag-selection)
13975 (and org-use-fast-tag-selection
13976 (delq nil (mapcar 'cdr table))))
13977 (org-fast-tag-selection
13978 current-tags inherited-tags table
13979 (if org-fast-tag-selection-include-todo
13980 org-todo-key-alist))
13981 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13982 (org-trim
13983 (org-icompleting-read "Tags: "
13984 'org-tags-completion-function
13985 nil nil current 'org-tags-history))))))
13986 (while (string-match "[-+&]+" tags)
13987 ;; No boolean logic, just a list
13988 (setq tags (replace-match ":" t t tags))))
13990 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13992 (if org-tags-sort-function
13993 (setq tags (mapconcat 'identity
13994 (sort (org-split-string
13995 tags (org-re "[^[:alnum:]_@#%]+"))
13996 org-tags-sort-function) ":")))
13998 (if (string-match "\\`[\t ]*\\'" tags)
13999 (setq tags "")
14000 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14001 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14003 ;; Insert new tags at the correct column
14004 (beginning-of-line 1)
14005 (setq level (or (and (looking-at org-outline-regexp)
14006 (- (match-end 0) (point) 1))
14008 (cond
14009 ((and (equal current "") (equal tags "")))
14010 ((re-search-forward
14011 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14012 (point-at-eol) t)
14013 (if (equal tags "")
14014 (setq rpl "")
14015 (goto-char (match-beginning 0))
14016 (setq c0 (current-column)
14017 ;; compute offset for the case of org-indent-mode active
14018 di (if org-indent-mode
14019 (* (1- org-indent-indentation-per-level) (1- level))
14021 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14022 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14023 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14024 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14025 (replace-match rpl t t)
14026 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14027 tags)
14028 (t (error "Tags alignment failed")))
14029 (org-move-to-column col)
14030 (unless just-align
14031 (run-hooks 'org-after-tags-change-hook))))))
14033 (defun org-change-tag-in-region (beg end tag off)
14034 "Add or remove TAG for each entry in the region.
14035 This works in the agenda, and also in an org-mode buffer."
14036 (interactive
14037 (list (region-beginning) (region-end)
14038 (let ((org-last-tags-completion-table
14039 (if (derived-mode-p 'org-mode)
14040 (org-get-buffer-tags)
14041 (org-global-tags-completion-table))))
14042 (org-icompleting-read
14043 "Tag: " 'org-tags-completion-function nil nil nil
14044 'org-tags-history))
14045 (progn
14046 (message "[s]et or [r]emove? ")
14047 (equal (read-char-exclusive) ?r))))
14048 (if (fboundp 'deactivate-mark) (deactivate-mark))
14049 (let ((agendap (equal major-mode 'org-agenda-mode))
14050 l1 l2 m buf pos newhead (cnt 0))
14051 (goto-char end)
14052 (setq l2 (1- (org-current-line)))
14053 (goto-char beg)
14054 (setq l1 (org-current-line))
14055 (loop for l from l1 to l2 do
14056 (org-goto-line l)
14057 (setq m (get-text-property (point) 'org-hd-marker))
14058 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14059 (and agendap m))
14060 (setq buf (if agendap (marker-buffer m) (current-buffer))
14061 pos (if agendap m (point)))
14062 (with-current-buffer buf
14063 (save-excursion
14064 (save-restriction
14065 (goto-char pos)
14066 (setq cnt (1+ cnt))
14067 (org-toggle-tag tag (if off 'off 'on))
14068 (setq newhead (org-get-heading)))))
14069 (and agendap (org-agenda-change-all-lines newhead m))))
14070 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14072 (defun org-tags-completion-function (string predicate &optional flag)
14073 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14074 (confirm (lambda (x) (stringp (car x)))))
14075 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14076 (setq s1 (match-string 1 string)
14077 s2 (match-string 2 string))
14078 (setq s1 "" s2 string))
14079 (cond
14080 ((eq flag nil)
14081 ;; try completion
14082 (setq rtn (try-completion s2 ctable confirm))
14083 (if (stringp rtn)
14084 (setq rtn
14085 (concat s1 s2 (substring rtn (length s2))
14086 (if (and org-add-colon-after-tag-completion
14087 (assoc rtn ctable))
14088 ":" ""))))
14089 rtn)
14090 ((eq flag t)
14091 ;; all-completions
14092 (all-completions s2 ctable confirm)
14094 ((eq flag 'lambda)
14095 ;; exact match?
14096 (assoc s2 ctable)))
14099 (defun org-fast-tag-insert (kwd tags face &optional end)
14100 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14101 (insert (format "%-12s" (concat kwd ":"))
14102 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14103 (or end "")))
14105 (defun org-fast-tag-show-exit (flag)
14106 (save-excursion
14107 (org-goto-line 3)
14108 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14109 (replace-match ""))
14110 (when flag
14111 (end-of-line 1)
14112 (org-move-to-column (- (window-width) 19) t)
14113 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14115 (defun org-set-current-tags-overlay (current prefix)
14116 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14117 (if (featurep 'xemacs)
14118 (org-overlay-display org-tags-overlay (concat prefix s)
14119 'secondary-selection)
14120 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14121 (org-overlay-display org-tags-overlay (concat prefix s)))))
14123 (defvar org-last-tag-selection-key nil)
14124 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14125 "Fast tag selection with single keys.
14126 CURRENT is the current list of tags in the headline, INHERITED is the
14127 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14128 possibly with grouping information. TODO-TABLE is a similar table with
14129 TODO keywords, should these have keys assigned to them.
14130 If the keys are nil, a-z are automatically assigned.
14131 Returns the new tags string, or nil to not change the current settings."
14132 (let* ((fulltable (append table todo-table))
14133 (maxlen (apply 'max (mapcar
14134 (lambda (x)
14135 (if (stringp (car x)) (string-width (car x)) 0))
14136 fulltable)))
14137 (buf (current-buffer))
14138 (expert (eq org-fast-tag-selection-single-key 'expert))
14139 (buffer-tags nil)
14140 (fwidth (+ maxlen 3 1 3))
14141 (ncol (/ (- (window-width) 4) fwidth))
14142 (i-face 'org-done)
14143 (c-face 'org-todo)
14144 tg cnt e c char c1 c2 ntable tbl rtn
14145 ov-start ov-end ov-prefix
14146 (exit-after-next org-fast-tag-selection-single-key)
14147 (done-keywords org-done-keywords)
14148 groups ingroup)
14149 (save-excursion
14150 (beginning-of-line 1)
14151 (if (looking-at
14152 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14153 (setq ov-start (match-beginning 1)
14154 ov-end (match-end 1)
14155 ov-prefix "")
14156 (setq ov-start (1- (point-at-eol))
14157 ov-end (1+ ov-start))
14158 (skip-chars-forward "^\n\r")
14159 (setq ov-prefix
14160 (concat
14161 (buffer-substring (1- (point)) (point))
14162 (if (> (current-column) org-tags-column)
14164 (make-string (- org-tags-column (current-column)) ?\ ))))))
14165 (move-overlay org-tags-overlay ov-start ov-end)
14166 (save-window-excursion
14167 (if expert
14168 (set-buffer (get-buffer-create " *Org tags*"))
14169 (delete-other-windows)
14170 (split-window-vertically)
14171 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14172 (erase-buffer)
14173 (org-set-local 'org-done-keywords done-keywords)
14174 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14175 (org-fast-tag-insert "Current" current c-face "\n\n")
14176 (org-fast-tag-show-exit exit-after-next)
14177 (org-set-current-tags-overlay current ov-prefix)
14178 (setq tbl fulltable char ?a cnt 0)
14179 (while (setq e (pop tbl))
14180 (cond
14181 ((equal (car e) :startgroup)
14182 (push '() groups) (setq ingroup t)
14183 (when (not (= cnt 0))
14184 (setq cnt 0)
14185 (insert "\n"))
14186 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14187 ((equal (car e) :endgroup)
14188 (setq ingroup nil cnt 0)
14189 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14190 ((equal e '(:newline))
14191 (when (not (= cnt 0))
14192 (setq cnt 0)
14193 (insert "\n")
14194 (setq e (car tbl))
14195 (while (equal (car tbl) '(:newline))
14196 (insert "\n")
14197 (setq tbl (cdr tbl)))))
14199 (setq tg (copy-sequence (car e)) c2 nil)
14200 (if (cdr e)
14201 (setq c (cdr e))
14202 ;; automatically assign a character.
14203 (setq c1 (string-to-char
14204 (downcase (substring
14205 tg (if (= (string-to-char tg) ?@) 1 0)))))
14206 (if (or (rassoc c1 ntable) (rassoc c1 table))
14207 (while (or (rassoc char ntable) (rassoc char table))
14208 (setq char (1+ char)))
14209 (setq c2 c1))
14210 (setq c (or c2 char)))
14211 (if ingroup (push tg (car groups)))
14212 (setq tg (org-add-props tg nil 'face
14213 (cond
14214 ((not (assoc tg table))
14215 (org-get-todo-face tg))
14216 ((member tg current) c-face)
14217 ((member tg inherited) i-face))))
14218 (if (and (= cnt 0) (not ingroup)) (insert " "))
14219 (insert "[" c "] " tg (make-string
14220 (- fwidth 4 (length tg)) ?\ ))
14221 (push (cons tg c) ntable)
14222 (when (= (setq cnt (1+ cnt)) ncol)
14223 (insert "\n")
14224 (if ingroup (insert " "))
14225 (setq cnt 0)))))
14226 (setq ntable (nreverse ntable))
14227 (insert "\n")
14228 (goto-char (point-min))
14229 (if (not expert) (org-fit-window-to-buffer))
14230 (setq rtn
14231 (catch 'exit
14232 (while t
14233 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14234 (if (not groups) "no " "")
14235 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14236 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14237 (setq org-last-tag-selection-key c)
14238 (cond
14239 ((= c ?\r) (throw 'exit t))
14240 ((= c ?!)
14241 (setq groups (not groups))
14242 (goto-char (point-min))
14243 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14244 ((= c ?\C-c)
14245 (if (not expert)
14246 (org-fast-tag-show-exit
14247 (setq exit-after-next (not exit-after-next)))
14248 (setq expert nil)
14249 (delete-other-windows)
14250 (set-window-buffer (split-window-vertically) " *Org tags*")
14251 (org-switch-to-buffer-other-window " *Org tags*")
14252 (org-fit-window-to-buffer)))
14253 ((or (= c ?\C-g)
14254 (and (= c ?q) (not (rassoc c ntable))))
14255 (org-detach-overlay org-tags-overlay)
14256 (setq quit-flag t))
14257 ((= c ?\ )
14258 (setq current nil)
14259 (if exit-after-next (setq exit-after-next 'now)))
14260 ((= c ?\t)
14261 (condition-case nil
14262 (setq tg (org-icompleting-read
14263 "Tag: "
14264 (or buffer-tags
14265 (with-current-buffer buf
14266 (org-get-buffer-tags)))))
14267 (quit (setq tg "")))
14268 (when (string-match "\\S-" tg)
14269 (add-to-list 'buffer-tags (list tg))
14270 (if (member tg current)
14271 (setq current (delete tg current))
14272 (push tg current)))
14273 (if exit-after-next (setq exit-after-next 'now)))
14274 ((setq e (rassoc c todo-table) tg (car e))
14275 (with-current-buffer buf
14276 (save-excursion (org-todo tg)))
14277 (if exit-after-next (setq exit-after-next 'now)))
14278 ((setq e (rassoc c ntable) tg (car e))
14279 (if (member tg current)
14280 (setq current (delete tg current))
14281 (loop for g in groups do
14282 (if (member tg g)
14283 (mapc (lambda (x)
14284 (setq current (delete x current)))
14285 g)))
14286 (push tg current))
14287 (if exit-after-next (setq exit-after-next 'now))))
14289 ;; Create a sorted list
14290 (setq current
14291 (sort current
14292 (lambda (a b)
14293 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14294 (if (eq exit-after-next 'now) (throw 'exit t))
14295 (goto-char (point-min))
14296 (beginning-of-line 2)
14297 (delete-region (point) (point-at-eol))
14298 (org-fast-tag-insert "Current" current c-face)
14299 (org-set-current-tags-overlay current ov-prefix)
14300 (while (re-search-forward
14301 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14302 (setq tg (match-string 1))
14303 (add-text-properties
14304 (match-beginning 1) (match-end 1)
14305 (list 'face
14306 (cond
14307 ((member tg current) c-face)
14308 ((member tg inherited) i-face)
14309 (t (get-text-property (match-beginning 1) 'face))))))
14310 (goto-char (point-min)))))
14311 (org-detach-overlay org-tags-overlay)
14312 (if rtn
14313 (mapconcat 'identity current ":")
14314 nil))))
14316 (defun org-get-tags-string ()
14317 "Get the TAGS string in the current headline."
14318 (unless (org-at-heading-p t)
14319 (error "Not on a heading"))
14320 (save-excursion
14321 (beginning-of-line 1)
14322 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14323 (org-match-string-no-properties 1)
14324 "")))
14326 (defun org-get-tags ()
14327 "Get the list of tags specified in the current headline."
14328 (org-split-string (org-get-tags-string) ":"))
14330 (defun org-get-buffer-tags ()
14331 "Get a table of all tags used in the buffer, for completion."
14332 (let (tags)
14333 (save-excursion
14334 (goto-char (point-min))
14335 (while (re-search-forward
14336 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14337 (when (equal (char-after (point-at-bol 0)) ?*)
14338 (mapc (lambda (x) (add-to-list 'tags x))
14339 (org-split-string (org-match-string-no-properties 1) ":")))))
14340 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14341 (mapcar 'list tags)))
14343 ;;;; The mapping API
14345 (defun org-map-entries (func &optional match scope &rest skip)
14346 "Call FUNC at each headline selected by MATCH in SCOPE.
14348 FUNC is a function or a lisp form. The function will be called without
14349 arguments, with the cursor positioned at the beginning of the headline.
14350 The return values of all calls to the function will be collected and
14351 returned as a list.
14353 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14354 does not need to preserve point. After evaluation, the cursor will be
14355 moved to the end of the line (presumably of the headline of the
14356 processed entry) and search continues from there. Under some
14357 circumstances, this may not produce the wanted results. For example,
14358 if you have removed (e.g. archived) the current (sub)tree it could
14359 mean that the next entry will be skipped entirely. In such cases, you
14360 can specify the position from where search should continue by making
14361 FUNC set the variable `org-map-continue-from' to the desired buffer
14362 position.
14364 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14365 Only headlines that are matched by this query will be considered during
14366 the iteration. When MATCH is nil or t, all headlines will be
14367 visited by the iteration.
14369 SCOPE determines the scope of this command. It can be any of:
14371 nil The current buffer, respecting the restriction if any
14372 tree The subtree started with the entry at point
14373 region The entries within the active region, if any
14374 region-start-level
14375 The entries within the active region, but only those at
14376 the same level than the first one.
14377 file The current buffer, without restriction
14378 file-with-archives
14379 The current buffer, and any archives associated with it
14380 agenda All agenda files
14381 agenda-with-archives
14382 All agenda files with any archive files associated with them
14383 \(file1 file2 ...)
14384 If this is a list, all files in the list will be scanned
14386 The remaining args are treated as settings for the skipping facilities of
14387 the scanner. The following items can be given here:
14389 archive skip trees with the archive tag.
14390 comment skip trees with the COMMENT keyword
14391 function or Emacs Lisp form:
14392 will be used as value for `org-agenda-skip-function', so whenever
14393 the function returns t, FUNC will not be called for that
14394 entry and search will continue from the point where the
14395 function leaves it.
14397 If your function needs to retrieve the tags including inherited tags
14398 at the *current* entry, you can use the value of the variable
14399 `org-scanner-tags' which will be much faster than getting the value
14400 with `org-get-tags-at'. If your function gets properties with
14401 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14402 to t around the call to `org-entry-properties' to get the same speedup.
14403 Note that if your function moves around to retrieve tags and properties at
14404 a *different* entry, you cannot use these techniques."
14405 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14406 (not (org-region-active-p)))
14407 (let* ((org-agenda-archives-mode nil) ; just to make sure
14408 (org-agenda-skip-archived-trees (memq 'archive skip))
14409 (org-agenda-skip-comment-trees (memq 'comment skip))
14410 (org-agenda-skip-function
14411 (car (org-delete-all '(comment archive) skip)))
14412 (org-tags-match-list-sublevels t)
14413 (start-level (eq scope 'region-start-level))
14414 matcher file res
14415 org-todo-keywords-for-agenda
14416 org-done-keywords-for-agenda
14417 org-todo-keyword-alist-for-agenda
14418 org-drawers-for-agenda
14419 org-tag-alist-for-agenda
14420 todo-only)
14422 (cond
14423 ((eq match t) (setq matcher t))
14424 ((eq match nil) (setq matcher t))
14425 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14427 (save-excursion
14428 (save-restriction
14429 (cond ((eq scope 'tree)
14430 (org-back-to-heading t)
14431 (org-narrow-to-subtree)
14432 (setq scope nil))
14433 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14434 (org-region-active-p))
14435 ;; If needed, set start-level to a string like "2"
14436 (when start-level
14437 (save-excursion
14438 (goto-char (region-beginning))
14439 (unless (org-at-heading-p) (outline-next-heading))
14440 (setq start-level (org-current-level))))
14441 (narrow-to-region (region-beginning)
14442 (save-excursion
14443 (goto-char (region-end))
14444 (unless (and (bolp) (org-at-heading-p))
14445 (outline-next-heading))
14446 (point)))
14447 (setq scope nil)))
14449 (if (not scope)
14450 (progn
14451 (org-agenda-prepare-buffers
14452 (list (buffer-file-name (current-buffer))))
14453 (setq res (org-scan-tags func matcher todo-only start-level)))
14454 ;; Get the right scope
14455 (cond
14456 ((and scope (listp scope) (symbolp (car scope)))
14457 (setq scope (eval scope)))
14458 ((eq scope 'agenda)
14459 (setq scope (org-agenda-files t)))
14460 ((eq scope 'agenda-with-archives)
14461 (setq scope (org-agenda-files t))
14462 (setq scope (org-add-archive-files scope)))
14463 ((eq scope 'file)
14464 (setq scope (list (buffer-file-name))))
14465 ((eq scope 'file-with-archives)
14466 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14467 (org-agenda-prepare-buffers scope)
14468 (while (setq file (pop scope))
14469 (with-current-buffer (org-find-base-buffer-visiting file)
14470 (save-excursion
14471 (save-restriction
14472 (widen)
14473 (goto-char (point-min))
14474 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14475 res)))
14477 ;;;; Properties
14479 ;;; Setting and retrieving properties
14481 (defconst org-special-properties
14482 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14483 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14484 "The special properties valid in Org-mode.
14486 These are properties that are not defined in the property drawer,
14487 but in some other way.")
14489 (defconst org-default-properties
14490 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14491 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14492 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14493 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14494 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14495 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14496 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14497 "Some properties that are used by Org-mode for various purposes.
14498 Being in this list makes sure that they are offered for completion.")
14500 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14501 "Regular expression matching the first line of a property drawer.")
14503 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14504 "Regular expression matching the last line of a property drawer.")
14506 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14507 "Regular expression matching the first line of a property drawer.")
14509 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14510 "Regular expression matching the first line of a property drawer.")
14512 (defconst org-property-drawer-re
14513 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14514 org-property-end-re "\\)\n?")
14515 "Matches an entire property drawer.")
14517 (defconst org-clock-drawer-re
14518 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14519 org-property-end-re "\\)\n?")
14520 "Matches an entire clock drawer.")
14522 (defsubst org-re-property (property)
14523 "Return a regexp matching a PROPERTY line.
14524 Match group 1 will be set to the value."
14525 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14527 (defsubst org-re-property-keyword (property)
14528 "Return a regexp matching a PROPERTY line, possibly with no
14529 value for the property."
14530 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14532 (defun org-property-action ()
14533 "Do an action on properties."
14534 (interactive)
14535 (let (c)
14536 (org-at-property-p)
14537 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14538 (setq c (read-char-exclusive))
14539 (cond
14540 ((equal c ?s)
14541 (call-interactively 'org-set-property))
14542 ((equal c ?d)
14543 (call-interactively 'org-delete-property))
14544 ((equal c ?D)
14545 (call-interactively 'org-delete-property-globally))
14546 ((equal c ?c)
14547 (call-interactively 'org-compute-property-at-point))
14548 (t (error "No such property action %c" c)))))
14550 (defun org-inc-effort ()
14551 "Increment the value of the effort property in the current entry."
14552 (interactive)
14553 (org-set-effort nil t))
14555 (defun org-set-effort (&optional value increment)
14556 "Set the effort property of the current entry.
14557 With numerical prefix arg, use the nth allowed value, 0 stands for the
14558 10th allowed value.
14560 When INCREMENT is non-nil, set the property to the next allowed value."
14561 (interactive "P")
14562 (if (equal value 0) (setq value 10))
14563 (let* ((completion-ignore-case t)
14564 (prop org-effort-property)
14565 (cur (org-entry-get nil prop))
14566 (allowed (org-property-get-allowed-values nil prop 'table))
14567 (existing (mapcar 'list (org-property-values prop)))
14569 (val (cond
14570 ((stringp value) value)
14571 ((and allowed (integerp value))
14572 (or (car (nth (1- value) allowed))
14573 (car (org-last allowed))))
14574 ((and allowed increment)
14575 (or (caadr (member (list cur) allowed))
14576 (error "Allowed effort values are not set")))
14577 (allowed
14578 (message "Select 1-9,0, [RET%s]: %s"
14579 (if cur (concat "=" cur) "")
14580 (mapconcat 'car allowed " "))
14581 (setq rpl (read-char-exclusive))
14582 (if (equal rpl ?\r)
14584 (setq rpl (- rpl ?0))
14585 (if (equal rpl 0) (setq rpl 10))
14586 (if (and (> rpl 0) (<= rpl (length allowed)))
14587 (car (nth (1- rpl) allowed))
14588 (org-completing-read "Effort: " allowed nil))))
14590 (let (org-completion-use-ido org-completion-use-iswitchb)
14591 (org-completing-read
14592 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14593 (concat "[" cur "]") "")
14594 ": ")
14595 existing nil nil "" nil cur))))))
14596 (unless (equal (org-entry-get nil prop) val)
14597 (org-entry-put nil prop val))
14598 (save-excursion
14599 (org-back-to-heading t)
14600 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14601 (message "%s is now %s" prop val)))
14603 (defun org-at-property-p ()
14604 "Is cursor inside a property drawer?"
14605 (save-excursion
14606 (beginning-of-line 1)
14607 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14608 (save-match-data ;; Used by calling procedures
14609 (let ((p (point))
14610 (range (unless (org-before-first-heading-p)
14611 (org-get-property-block))))
14612 (and range (<= (car range) p) (< p (cdr range))))))))
14614 (defun org-get-property-block (&optional beg end force)
14615 "Return the (beg . end) range of the body of the property drawer.
14616 BEG and END are the beginning and end of the current subtree, or of
14617 the part before the first headline. If they are not given, they will
14618 be found. If the drawer does not exist and FORCE is non-nil, create
14619 the drawer."
14620 (catch 'exit
14621 (save-excursion
14622 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14623 (progn (org-back-to-heading t) (point))))
14624 (end (or end (and (not (outline-next-heading)) (point-max))
14625 (point))))
14626 (goto-char beg)
14627 (if (re-search-forward org-property-start-re end t)
14628 (setq beg (1+ (match-end 0)))
14629 (if force
14630 (save-excursion
14631 (org-insert-property-drawer)
14632 (setq end (progn (outline-next-heading) (point))))
14633 (throw 'exit nil))
14634 (goto-char beg)
14635 (if (re-search-forward org-property-start-re end t)
14636 (setq beg (1+ (match-end 0)))))
14637 (if (re-search-forward org-property-end-re end t)
14638 (setq end (match-beginning 0))
14639 (or force (throw 'exit nil))
14640 (goto-char beg)
14641 (setq end beg)
14642 (org-indent-line)
14643 (insert ":END:\n"))
14644 (cons beg end)))))
14646 (defun org-entry-properties (&optional pom which specific)
14647 "Get all properties of the entry at point-or-marker POM.
14648 This includes the TODO keyword, the tags, time strings for deadline,
14649 scheduled, and clocking, and any additional properties defined in the
14650 entry. The return value is an alist, keys may occur multiple times
14651 if the property key was used several times.
14652 POM may also be nil, in which case the current entry is used.
14653 If WHICH is nil or `all', get all properties. If WHICH is
14654 `special' or `standard', only get that subclass. If WHICH
14655 is a string only get exactly this property. SPECIFIC can be a string, the
14656 specific property we are interested in. Specifying it can speed
14657 things up because then unnecessary parsing is avoided."
14658 (setq which (or which 'all))
14659 (org-with-point-at pom
14660 (let ((clockstr (substring org-clock-string 0 -1))
14661 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14662 (case-fold-search nil)
14663 beg end range props sum-props key key1 value string clocksum clocksumt)
14664 (save-excursion
14665 (when (condition-case nil
14666 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14667 (error nil))
14668 (setq beg (point))
14669 (setq sum-props (get-text-property (point) 'org-summaries))
14670 (setq clocksum (get-text-property (point) :org-clock-minutes)
14671 clocksumt (get-text-property (point) :org-clock-minutes-today))
14672 (outline-next-heading)
14673 (setq end (point))
14674 (when (memq which '(all special))
14675 ;; Get the special properties, like TODO and tags
14676 (goto-char beg)
14677 (when (and (or (not specific) (string= specific "TODO"))
14678 (looking-at org-todo-line-regexp) (match-end 2))
14679 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14680 (when (and (or (not specific) (string= specific "PRIORITY"))
14681 (looking-at org-priority-regexp))
14682 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14683 (when (or (not specific) (string= specific "FILE"))
14684 (push (cons "FILE" buffer-file-name) props))
14685 (when (and (or (not specific) (string= specific "TAGS"))
14686 (setq value (org-get-tags-string))
14687 (string-match "\\S-" value))
14688 (push (cons "TAGS" value) props))
14689 (when (and (or (not specific) (string= specific "ALLTAGS"))
14690 (setq value (org-get-tags-at)))
14691 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14692 ":"))
14693 props))
14694 (when (or (not specific) (string= specific "BLOCKED"))
14695 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14696 (when (or (not specific)
14697 (member specific
14698 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14699 "TIMESTAMP" "TIMESTAMP_IA")))
14700 (catch 'match
14701 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14702 (setq key (if (match-end 1)
14703 (substring (org-match-string-no-properties 1)
14704 0 -1))
14705 string (if (equal key clockstr)
14706 (org-trim
14707 (buffer-substring-no-properties
14708 (match-beginning 3) (goto-char
14709 (point-at-eol))))
14710 (substring (org-match-string-no-properties 3)
14711 1 -1)))
14712 ;; Get the correct property name from the key. This is
14713 ;; necessary if the user has configured time keywords.
14714 (setq key1 (concat key ":"))
14715 (cond
14716 ((not key)
14717 (setq key
14718 (if (= (char-after (match-beginning 3)) ?\[)
14719 "TIMESTAMP_IA" "TIMESTAMP")))
14720 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14721 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14722 ((equal key1 org-closed-string) (setq key "CLOSED"))
14723 ((equal key1 org-clock-string) (setq key "CLOCK")))
14724 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14725 (progn
14726 (push (cons key string) props)
14727 ;; no need to search further if match is found
14728 (throw 'match t))
14729 (when (or (equal key "CLOCK") (not (assoc key props)))
14730 (push (cons key string) props)))))))
14732 (when (memq which '(all standard))
14733 ;; Get the standard properties, like :PROP: ...
14734 (setq range (org-get-property-block beg end))
14735 (when range
14736 (goto-char (car range))
14737 (while (re-search-forward
14738 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14739 (cdr range) t)
14740 (setq key (org-match-string-no-properties 1)
14741 value (org-trim (or (org-match-string-no-properties 2) "")))
14742 (unless (member key excluded)
14743 (push (cons key (or value "")) props)))))
14744 (if clocksum
14745 (push (cons "CLOCKSUM"
14746 (org-columns-number-to-string (/ (float clocksum) 60.)
14747 'add_times))
14748 props))
14749 (if clocksumt
14750 (push (cons "CLOCKSUM_T"
14751 (org-columns-number-to-string (/ (float clocksumt) 60.)
14752 'add_times))
14753 props))
14754 (unless (assoc "CATEGORY" props)
14755 (push (cons "CATEGORY" (org-get-category)) props))
14756 (append sum-props (nreverse props)))))))
14758 (defun org-entry-get (pom property &optional inherit literal-nil)
14759 "Get value of PROPERTY for entry or content at point-or-marker POM.
14760 If INHERIT is non-nil and the entry does not have the property,
14761 then also check higher levels of the hierarchy.
14762 If INHERIT is the symbol `selective', use inheritance only if the setting
14763 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14764 If the property is present but empty, the return value is the empty string.
14765 If the property is not present at all, nil is returned.
14767 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14768 do not interpret it as the list atom nil. This is used for inheritance
14769 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14770 (org-with-point-at pom
14771 (if (and inherit (if (eq inherit 'selective)
14772 (org-property-inherit-p property)
14774 (org-entry-get-with-inheritance property literal-nil)
14775 (if (member property org-special-properties)
14776 ;; We need a special property. Use `org-entry-properties' to
14777 ;; retrieve it, but specify the wanted property
14778 (cdr (assoc property (org-entry-properties nil 'special property)))
14779 (let ((range (org-get-property-block)))
14780 (when (and range (not (eq (car range) (cdr range))))
14781 (let* ((props (list (or (assoc property org-file-properties)
14782 (assoc property org-global-properties)
14783 (assoc property org-global-properties-fixed))))
14784 (ap (lambda (key)
14785 (when (re-search-forward
14786 (org-re-property key) (cdr range) t)
14787 (setq props
14788 (org-update-property-plist
14790 (if (match-end 1)
14791 (org-match-string-no-properties 1) "")
14792 props)))))
14793 val)
14794 (goto-char (car range))
14795 (funcall ap property)
14796 (goto-char (car range))
14797 (while (funcall ap (concat property "+")))
14798 (setq val (cdr (assoc property props)))
14799 (when val (if literal-nil val (org-not-nil val))))))))))
14801 (defun org-property-or-variable-value (var &optional inherit)
14802 "Check if there is a property fixing the value of VAR.
14803 If yes, return this value. If not, return the current value of the variable."
14804 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14805 (if (and prop (stringp prop) (string-match "\\S-" prop))
14806 (read prop)
14807 (symbol-value var))))
14809 (defun org-entry-delete (pom property)
14810 "Delete the property PROPERTY from entry at point-or-marker POM."
14811 (org-with-point-at pom
14812 (if (member property org-special-properties)
14813 nil ; cannot delete these properties.
14814 (let ((range (org-get-property-block)))
14815 (if (and range
14816 (goto-char (car range))
14817 (re-search-forward
14818 (org-re-property property)
14819 (cdr range) t))
14820 (progn
14821 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14823 nil)))))
14825 ;; Multi-values properties are properties that contain multiple values
14826 ;; These values are assumed to be single words, separated by whitespace.
14827 (defun org-entry-add-to-multivalued-property (pom property value)
14828 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14829 (let* ((old (org-entry-get pom property))
14830 (values (and old (org-split-string old "[ \t]"))))
14831 (setq value (org-entry-protect-space value))
14832 (unless (member value values)
14833 (setq values (cons value values))
14834 (org-entry-put pom property
14835 (mapconcat 'identity values " ")))))
14837 (defun org-entry-remove-from-multivalued-property (pom property value)
14838 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14839 (let* ((old (org-entry-get pom property))
14840 (values (and old (org-split-string old "[ \t]"))))
14841 (setq value (org-entry-protect-space value))
14842 (when (member value values)
14843 (setq values (delete value values))
14844 (org-entry-put pom property
14845 (mapconcat 'identity values " ")))))
14847 (defun org-entry-member-in-multivalued-property (pom property value)
14848 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14849 (let* ((old (org-entry-get pom property))
14850 (values (and old (org-split-string old "[ \t]"))))
14851 (setq value (org-entry-protect-space value))
14852 (member value values)))
14854 (defun org-entry-get-multivalued-property (pom property)
14855 "Return a list of values in a multivalued property."
14856 (let* ((value (org-entry-get pom property))
14857 (values (and value (org-split-string value "[ \t]"))))
14858 (mapcar 'org-entry-restore-space values)))
14860 (defun org-entry-put-multivalued-property (pom property &rest values)
14861 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14862 VALUES should be a list of strings. Spaces will be protected."
14863 (org-entry-put pom property
14864 (mapconcat 'org-entry-protect-space values " "))
14865 (let* ((value (org-entry-get pom property))
14866 (values (and value (org-split-string value "[ \t]"))))
14867 (mapcar 'org-entry-restore-space values)))
14869 (defun org-entry-protect-space (s)
14870 "Protect spaces and newline in string S."
14871 (while (string-match " " s)
14872 (setq s (replace-match "%20" t t s)))
14873 (while (string-match "\n" s)
14874 (setq s (replace-match "%0A" t t s)))
14877 (defun org-entry-restore-space (s)
14878 "Restore spaces and newline in string S."
14879 (while (string-match "%20" s)
14880 (setq s (replace-match " " t t s)))
14881 (while (string-match "%0A" s)
14882 (setq s (replace-match "\n" t t s)))
14885 (defvar org-entry-property-inherited-from (make-marker)
14886 "Marker pointing to the entry from where a property was inherited.
14887 Each call to `org-entry-get-with-inheritance' will set this marker to the
14888 location of the entry where the inheritance search matched. If there was
14889 no match, the marker will point nowhere.
14890 Note that also `org-entry-get' calls this function, if the INHERIT flag
14891 is set.")
14893 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14894 "Get PROPERTY of entry or content at point, search higher levels if needed.
14895 The search will stop at the first ancestor which has the property defined.
14896 If the value found is \"nil\", return nil to show that the property
14897 should be considered as undefined (this is the meaning of nil here).
14898 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14899 (move-marker org-entry-property-inherited-from nil)
14900 (let (tmp)
14901 (save-excursion
14902 (save-restriction
14903 (widen)
14904 (catch 'ex
14905 (while t
14906 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14907 (or (ignore-errors (org-back-to-heading t))
14908 (goto-char (point-min)))
14909 (move-marker org-entry-property-inherited-from (point))
14910 (throw 'ex tmp))
14911 (or (ignore-errors (org-up-heading-safe))
14912 (throw 'ex nil))))))
14913 (setq tmp (or tmp
14914 (cdr (assoc property org-file-properties))
14915 (cdr (assoc property org-global-properties))
14916 (cdr (assoc property org-global-properties-fixed))))
14917 (if literal-nil tmp (org-not-nil tmp))))
14919 (defvar org-property-changed-functions nil
14920 "Hook called when the value of a property has changed.
14921 Each hook function should accept two arguments, the name of the property
14922 and the new value.")
14924 (defun org-entry-put (pom property value)
14925 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14926 (org-with-point-at pom
14927 (org-back-to-heading t)
14928 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14929 range)
14930 (cond
14931 ((equal property "TODO")
14932 (when (and (stringp value) (string-match "\\S-" value)
14933 (not (member value org-todo-keywords-1)))
14934 (error "\"%s\" is not a valid TODO state" value))
14935 (if (or (not value)
14936 (not (string-match "\\S-" value)))
14937 (setq value 'none))
14938 (org-todo value)
14939 (org-set-tags nil 'align))
14940 ((equal property "PRIORITY")
14941 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14942 (string-to-char value) ?\ ))
14943 (org-set-tags nil 'align))
14944 ((equal property "CLOCKSUM")
14945 (if (not (re-search-forward
14946 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14947 (error "Cannot find a clock log")
14948 (goto-char (- (match-end 1) 2))
14949 (cond
14950 ((eq value 'earlier) (org-timestamp-down))
14951 ((eq value 'later) (org-timestamp-up)))
14952 (org-clock-sum-current-item)))
14953 ((equal property "SCHEDULED")
14954 (if (re-search-forward org-scheduled-time-regexp end t)
14955 (cond
14956 ((eq value 'earlier) (org-timestamp-change -1 'day))
14957 ((eq value 'later) (org-timestamp-change 1 'day))
14958 (t (call-interactively 'org-schedule)))
14959 (call-interactively 'org-schedule)))
14960 ((equal property "DEADLINE")
14961 (if (re-search-forward org-deadline-time-regexp end t)
14962 (cond
14963 ((eq value 'earlier) (org-timestamp-change -1 'day))
14964 ((eq value 'later) (org-timestamp-change 1 'day))
14965 (t (call-interactively 'org-deadline)))
14966 (call-interactively 'org-deadline)))
14967 ((member property org-special-properties)
14968 (error "The %s property can not yet be set with `org-entry-put'"
14969 property))
14970 (t ; a non-special property
14971 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14972 (setq range (org-get-property-block beg end 'force))
14973 (goto-char (car range))
14974 (if (re-search-forward
14975 (org-re-property-keyword property) (cdr range) t)
14976 (progn
14977 (delete-region (match-beginning 0) (match-end 0))
14978 (goto-char (match-beginning 0)))
14979 (goto-char (cdr range))
14980 (insert "\n")
14981 (backward-char 1)
14982 (org-indent-line))
14983 (insert ":" property ":")
14984 (and value (insert " " value))
14985 (org-indent-line)))))
14986 (run-hook-with-args 'org-property-changed-functions property value)))
14988 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14989 "Get all property keys in the current buffer.
14990 With INCLUDE-SPECIALS, also list the special properties that reflect things
14991 like tags and TODO state.
14992 With INCLUDE-DEFAULTS, also include properties that has special meaning
14993 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14994 and others.
14995 With INCLUDE-COLUMNS, also include property names given in COLUMN
14996 formats in the current buffer."
14997 (let (rtn range cfmt s p)
14998 (save-excursion
14999 (save-restriction
15000 (widen)
15001 (goto-char (point-min))
15002 (while (re-search-forward org-property-start-re nil t)
15003 (setq range (org-get-property-block))
15004 (goto-char (car range))
15005 (while (re-search-forward
15006 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15007 (cdr range) t)
15008 (add-to-list 'rtn (org-match-string-no-properties 1)))
15009 (outline-next-heading))))
15011 (when include-specials
15012 (setq rtn (append org-special-properties rtn)))
15014 (when include-defaults
15015 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15016 (add-to-list 'rtn org-effort-property))
15018 (when include-columns
15019 (save-excursion
15020 (save-restriction
15021 (widen)
15022 (goto-char (point-min))
15023 (while (re-search-forward
15024 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15025 nil t)
15026 (setq cfmt (match-string 2) s 0)
15027 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15028 cfmt s)
15029 (setq s (match-end 0)
15030 p (match-string 1 cfmt))
15031 (unless (or (equal p "ITEM")
15032 (member p org-special-properties))
15033 (add-to-list 'rtn (match-string 1 cfmt))))))))
15035 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15037 (defun org-property-values (key)
15038 "Return a list of all values of property KEY in the current buffer."
15039 (save-excursion
15040 (save-restriction
15041 (widen)
15042 (goto-char (point-min))
15043 (let ((re (org-re-property key))
15044 values)
15045 (while (re-search-forward re nil t)
15046 (add-to-list 'values (org-trim (match-string 1))))
15047 (delete "" values)))))
15049 (defun org-insert-property-drawer ()
15050 "Insert a property drawer into the current entry."
15051 (org-back-to-heading t)
15052 (looking-at org-outline-regexp)
15053 (let ((indent (if org-adapt-indentation
15054 (- (match-end 0) (match-beginning 0))
15056 (beg (point))
15057 (re (concat "^[ \t]*" org-keyword-time-regexp))
15058 end hiddenp)
15059 (outline-next-heading)
15060 (setq end (point))
15061 (goto-char beg)
15062 (while (re-search-forward re end t))
15063 (setq hiddenp (outline-invisible-p))
15064 (end-of-line 1)
15065 (and (equal (char-after) ?\n) (forward-char 1))
15066 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15067 (if (member (match-string 1) '("CLOCK:" ":END:"))
15068 ;; just skip this line
15069 (beginning-of-line 2)
15070 ;; Drawer start, find the end
15071 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15072 (beginning-of-line 1)))
15073 (org-skip-over-state-notes)
15074 (skip-chars-backward " \t\n\r")
15075 (if (eq (char-before) ?*) (forward-char 1))
15076 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15077 (beginning-of-line 0)
15078 (org-indent-to-column indent)
15079 (beginning-of-line 2)
15080 (org-indent-to-column indent)
15081 (beginning-of-line 0)
15082 (if hiddenp
15083 (save-excursion
15084 (org-back-to-heading t)
15085 (hide-entry))
15086 (org-flag-drawer t))))
15088 (defun org-insert-drawer (&optional arg drawer)
15089 "Insert a drawer at point.
15091 Optional argument DRAWER, when non-nil, is a string representing
15092 drawer's name. Otherwise, the user is prompted for a name.
15094 If a region is active, insert the drawer around that region
15095 instead.
15097 Point is left between drawer's boundaries."
15098 (interactive "P")
15099 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15100 "LOGBOOK"))
15101 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15102 ;; internally by Org. They are meant to be inserted
15103 ;; automatically.
15104 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15105 ;; Remove system drawers from list. Note: For some reason,
15106 ;; `org-completing-read' ignores the predicate while
15107 ;; `completing-read' handles it fine.
15108 (drawer (if arg "PROPERTIES"
15109 (or drawer
15110 (completing-read
15111 "Drawer: " org-drawers
15112 (lambda (d) (not (member d system-drawers))))))))
15113 (cond
15114 ;; With C-u, fall back on `org-insert-property-drawer'
15115 (arg (org-insert-property-drawer))
15116 ;; With an active region, insert a drawer at point.
15117 ((not (org-region-active-p))
15118 (progn
15119 (unless (bolp) (insert "\n"))
15120 (insert (format ":%s:\n\n:END:\n" drawer))
15121 (forward-line -2)))
15122 ;; Otherwise, insert the drawer at point
15124 (let ((rbeg (region-beginning))
15125 (rend (copy-marker (region-end))))
15126 (unwind-protect
15127 (progn
15128 (goto-char rbeg)
15129 (beginning-of-line)
15130 (when (save-excursion
15131 (re-search-forward org-outline-regexp-bol rend t))
15132 (error "Drawers cannot contain headlines"))
15133 ;; Position point at the beginning of the first
15134 ;; non-blank line in region. Insert drawer's opening
15135 ;; there, then indent it.
15136 (org-skip-whitespace)
15137 (beginning-of-line)
15138 (insert ":" drawer ":\n")
15139 (forward-line -1)
15140 (indent-for-tab-command)
15141 ;; Move point to the beginning of the first blank line
15142 ;; after the last non-blank line in region. Insert
15143 ;; drawer's closing, then indent it.
15144 (goto-char rend)
15145 (skip-chars-backward " \r\t\n")
15146 (insert "\n:END:")
15147 (deactivate-mark t)
15148 (indent-for-tab-command)
15149 (unless (eolp) (insert "\n")))
15150 ;; Clear marker, whatever the outcome of insertion is.
15151 (set-marker rend nil)))))))
15153 (defvar org-property-set-functions-alist nil
15154 "Property set function alist.
15155 Each entry should have the following format:
15157 (PROPERTY . READ-FUNCTION)
15159 The read function will be called with the same argument as
15160 `org-completing-read'.")
15162 (defun org-set-property-function (property)
15163 "Get the function that should be used to set PROPERTY.
15164 This is computed according to `org-property-set-functions-alist'."
15165 (or (cdr (assoc property org-property-set-functions-alist))
15166 'org-completing-read))
15168 (defun org-read-property-value (property)
15169 "Read PROPERTY value from user."
15170 (let* ((completion-ignore-case t)
15171 (allowed (org-property-get-allowed-values nil property 'table))
15172 (cur (org-entry-get nil property))
15173 (prompt (concat property " value"
15174 (if (and cur (string-match "\\S-" cur))
15175 (concat " [" cur "]") "") ": "))
15176 (set-function (org-set-property-function property))
15177 (val (if allowed
15178 (funcall set-function prompt allowed nil
15179 (not (get-text-property 0 'org-unrestricted
15180 (caar allowed))))
15181 (let (org-completion-use-ido org-completion-use-iswitchb)
15182 (funcall set-function prompt
15183 (mapcar 'list (org-property-values property))
15184 nil nil "" nil cur)))))
15185 (if (equal val "")
15187 val)))
15189 (defvar org-last-set-property nil)
15190 (defvar org-last-set-property-value nil)
15191 (defun org-read-property-name ()
15192 "Read a property name."
15193 (let* ((completion-ignore-case t)
15194 (keys (org-buffer-property-keys nil t t))
15195 (default-prop (or (save-excursion
15196 (save-match-data
15197 (beginning-of-line)
15198 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15199 (null (string= (match-string 1) "END"))
15200 (match-string 1))))
15201 org-last-set-property))
15202 (property (org-icompleting-read
15203 (concat "Property"
15204 (if default-prop (concat " [" default-prop "]") "")
15205 ": ")
15206 (mapcar 'list keys)
15207 nil nil nil nil
15208 default-prop)))
15209 (if (member property keys)
15210 property
15211 (or (cdr (assoc (downcase property)
15212 (mapcar (lambda (x) (cons (downcase x) x))
15213 keys)))
15214 property))))
15216 (defun org-set-property-and-value (use-last)
15217 "Allow to set [PROPERTY]: [value] direction from prompt.
15218 When use-default, don't even ask, just use the last
15219 \"[PROPERTY]: [value]\" string from the history."
15220 (interactive "P")
15221 (let* ((completion-ignore-case t)
15222 (pv (or (and use-last org-last-set-property-value)
15223 (org-completing-read
15224 "Enter a \"[Property]: [value]\" pair: "
15225 nil nil nil nil nil
15226 org-last-set-property-value)))
15227 prop val)
15228 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15229 (setq prop (match-string 1 pv)
15230 val (match-string 2 pv))
15231 (org-set-property prop val))))
15233 (defun org-set-property (property value)
15234 "In the current entry, set PROPERTY to VALUE.
15235 When called interactively, this will prompt for a property name, offering
15236 completion on existing and default properties. And then it will prompt
15237 for a value, offering completion either on allowed values (via an inherited
15238 xxx_ALL property) or on existing values in other instances of this property
15239 in the current file."
15240 (interactive (list nil nil))
15241 (let* ((property (or property (org-read-property-name)))
15242 (value (or value (org-read-property-value property)))
15243 (fn (cdr (assoc property org-properties-postprocess-alist))))
15244 (setq org-last-set-property property)
15245 (setq org-last-set-property-value (concat property ": " value))
15246 ;; Possibly postprocess the inserted value:
15247 (when fn (setq value (funcall fn value)))
15248 (unless (equal (org-entry-get nil property) value)
15249 (org-entry-put nil property value))))
15251 (defun org-delete-property (property)
15252 "In the current entry, delete PROPERTY."
15253 (interactive
15254 (let* ((completion-ignore-case t)
15255 (prop (org-icompleting-read "Property: "
15256 (org-entry-properties nil 'standard))))
15257 (list prop)))
15258 (message "Property %s %s" property
15259 (if (org-entry-delete nil property)
15260 "deleted"
15261 "was not present in the entry")))
15263 (defun org-delete-property-globally (property)
15264 "Remove PROPERTY globally, from all entries."
15265 (interactive
15266 (let* ((completion-ignore-case t)
15267 (prop (org-icompleting-read
15268 "Globally remove property: "
15269 (mapcar 'list (org-buffer-property-keys)))))
15270 (list prop)))
15271 (save-excursion
15272 (save-restriction
15273 (widen)
15274 (goto-char (point-min))
15275 (let ((cnt 0))
15276 (while (re-search-forward
15277 (org-re-property property)
15278 nil t)
15279 (setq cnt (1+ cnt))
15280 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15281 (message "Property \"%s\" removed from %d entries" property cnt)))))
15283 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15285 (defun org-compute-property-at-point ()
15286 "Compute the property at point.
15287 This looks for an enclosing column format, extracts the operator and
15288 then applies it to the property in the column format's scope."
15289 (interactive)
15290 (unless (org-at-property-p)
15291 (error "Not at a property"))
15292 (let ((prop (org-match-string-no-properties 2)))
15293 (org-columns-get-format-and-top-level)
15294 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15295 (error "No operator defined for property %s" prop))
15296 (org-columns-compute prop)))
15298 (defvar org-property-allowed-value-functions nil
15299 "Hook for functions supplying allowed values for a specific property.
15300 The functions must take a single argument, the name of the property, and
15301 return a flat list of allowed values. If \":ETC\" is one of
15302 the values, this means that these values are intended as defaults for
15303 completion, but that other values should be allowed too.
15304 The functions must return nil if they are not responsible for this
15305 property.")
15307 (defun org-property-get-allowed-values (pom property &optional table)
15308 "Get allowed values for the property PROPERTY.
15309 When TABLE is non-nil, return an alist that can directly be used for
15310 completion."
15311 (let (vals)
15312 (cond
15313 ((equal property "TODO")
15314 (setq vals (org-with-point-at pom
15315 (append org-todo-keywords-1 '("")))))
15316 ((equal property "PRIORITY")
15317 (let ((n org-lowest-priority))
15318 (while (>= n org-highest-priority)
15319 (push (char-to-string n) vals)
15320 (setq n (1- n)))))
15321 ((member property org-special-properties))
15322 ((setq vals (run-hook-with-args-until-success
15323 'org-property-allowed-value-functions property)))
15325 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15326 (when (and vals (string-match "\\S-" vals))
15327 (setq vals (car (read-from-string (concat "(" vals ")"))))
15328 (setq vals (mapcar (lambda (x)
15329 (cond ((stringp x) x)
15330 ((numberp x) (number-to-string x))
15331 ((symbolp x) (symbol-name x))
15332 (t "???")))
15333 vals)))))
15334 (when (member ":ETC" vals)
15335 (setq vals (remove ":ETC" vals))
15336 (org-add-props (car vals) '(org-unrestricted t)))
15337 (if table (mapcar 'list vals) vals)))
15339 (defun org-property-previous-allowed-value (&optional previous)
15340 "Switch to the next allowed value for this property."
15341 (interactive)
15342 (org-property-next-allowed-value t))
15344 (defun org-property-next-allowed-value (&optional previous)
15345 "Switch to the next allowed value for this property."
15346 (interactive)
15347 (unless (org-at-property-p)
15348 (error "Not at a property"))
15349 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15350 (key (match-string 2))
15351 (value (match-string 3))
15352 (allowed (or (org-property-get-allowed-values (point) key)
15353 (and (member value '("[ ]" "[-]" "[X]"))
15354 '("[ ]" "[X]"))))
15355 nval)
15356 (unless allowed
15357 (error "Allowed values for this property have not been defined"))
15358 (if previous (setq allowed (reverse allowed)))
15359 (if (member value allowed)
15360 (setq nval (car (cdr (member value allowed)))))
15361 (setq nval (or nval (car allowed)))
15362 (if (equal nval value)
15363 (error "Only one allowed value for this property"))
15364 (org-at-property-p)
15365 (replace-match (concat " :" key ": " nval) t t)
15366 (org-indent-line)
15367 (beginning-of-line 1)
15368 (skip-chars-forward " \t")
15369 (when (equal prop org-effort-property)
15370 (save-excursion
15371 (org-back-to-heading t)
15372 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15373 (run-hook-with-args 'org-property-changed-functions key nval)))
15375 (defun org-find-olp (path &optional this-buffer)
15376 "Return a marker pointing to the entry at outline path OLP.
15377 If anything goes wrong, throw an error.
15378 You can wrap this call to catch the error like this:
15380 (condition-case msg
15381 (org-mobile-locate-entry (match-string 4))
15382 (error (nth 1 msg)))
15384 The return value will then be either a string with the error message,
15385 or a marker if everything is OK.
15387 If THIS-BUFFER is set, the outline path does not contain a file,
15388 only headings."
15389 (let* ((file (if this-buffer buffer-file-name (pop path)))
15390 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15391 (level 1)
15392 (lmin 1)
15393 (lmax 1)
15394 limit re end found pos heading cnt flevel)
15395 (unless buffer (error "File not found :%s" file))
15396 (with-current-buffer buffer
15397 (save-excursion
15398 (save-restriction
15399 (widen)
15400 (setq limit (point-max))
15401 (goto-char (point-min))
15402 (while (setq heading (pop path))
15403 (setq re (format org-complex-heading-regexp-format
15404 (regexp-quote heading)))
15405 (setq cnt 0 pos (point))
15406 (while (re-search-forward re end t)
15407 (setq level (- (match-end 1) (match-beginning 1)))
15408 (if (and (>= level lmin) (<= level lmax))
15409 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15410 (when (= cnt 0) (error "Heading not found on level %d: %s"
15411 lmax heading))
15412 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15413 lmax heading))
15414 (goto-char found)
15415 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15416 (setq end (save-excursion (org-end-of-subtree t t))))
15417 (when (org-at-heading-p)
15418 (point-marker)))))))
15420 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15421 "Find node HEADING in BUFFER.
15422 Return a marker to the heading if it was found, or nil if not.
15423 If POS-ONLY is set, return just the position instead of a marker.
15425 The heading text must match exact, but it may have a TODO keyword,
15426 a priority cookie and tags in the standard locations."
15427 (with-current-buffer (or buffer (current-buffer))
15428 (save-excursion
15429 (save-restriction
15430 (widen)
15431 (goto-char (point-min))
15432 (let (case-fold-search)
15433 (if (re-search-forward
15434 (format org-complex-heading-regexp-format
15435 (regexp-quote heading)) nil t)
15436 (if pos-only
15437 (match-beginning 0)
15438 (move-marker (make-marker) (match-beginning 0)))))))))
15440 (defun org-find-exact-heading-in-directory (heading &optional dir)
15441 "Find Org node headline HEADING in all .org files in directory DIR.
15442 When the target headline is found, return a marker to this location."
15443 (let ((files (directory-files (or dir default-directory)
15444 nil "\\`[^.#].*\\.org\\'"))
15445 file visiting m buffer)
15446 (catch 'found
15447 (while (setq file (pop files))
15448 (message "trying %s" file)
15449 (setq visiting (org-find-base-buffer-visiting file))
15450 (setq buffer (or visiting (find-file-noselect file)))
15451 (setq m (org-find-exact-headline-in-buffer
15452 heading buffer))
15453 (when (and (not m) (not visiting)) (kill-buffer buffer))
15454 (and m (throw 'found m))))))
15456 (defun org-find-entry-with-id (ident)
15457 "Locate the entry that contains the ID property with exact value IDENT.
15458 IDENT can be a string, a symbol or a number, this function will search for
15459 the string representation of it.
15460 Return the position where this entry starts, or nil if there is no such entry."
15461 (interactive "sID: ")
15462 (let ((id (cond
15463 ((stringp ident) ident)
15464 ((symbol-name ident) (symbol-name ident))
15465 ((numberp ident) (number-to-string ident))
15466 (t (error "IDENT %s must be a string, symbol or number" ident))))
15467 (case-fold-search nil))
15468 (save-excursion
15469 (save-restriction
15470 (widen)
15471 (goto-char (point-min))
15472 (when (re-search-forward
15473 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15474 nil t)
15475 (org-back-to-heading t)
15476 (point))))))
15478 ;;;; Timestamps
15480 (defvar org-last-changed-timestamp nil)
15481 (defvar org-last-inserted-timestamp nil
15482 "The last time stamp inserted with `org-insert-time-stamp'.")
15483 (defvar org-time-was-given) ; dynamically scoped parameter
15484 (defvar org-end-time-was-given) ; dynamically scoped parameter
15485 (defvar org-ts-what) ; dynamically scoped parameter
15487 (defun org-time-stamp (arg &optional inactive)
15488 "Prompt for a date/time and insert a time stamp.
15489 If the user specifies a time like HH:MM or if this command is
15490 called with at least one prefix argument, the time stamp contains
15491 the date and the time. Otherwise, only the date is be included.
15493 All parts of a date not specified by the user is filled in from
15494 the current date/time. So if you just press return without
15495 typing anything, the time stamp will represent the current
15496 date/time.
15498 If there is already a timestamp at the cursor, it will be
15499 modified.
15501 With two universal prefix arguments, insert an active timestamp
15502 with the current time without prompting the user."
15503 (interactive "P")
15504 (let* ((ts nil)
15505 (default-time
15506 ;; Default time is either today, or, when entering a range,
15507 ;; the range start.
15508 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15509 (save-excursion
15510 (re-search-backward
15511 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15512 (- (point) 20) t)))
15513 (apply 'encode-time (org-parse-time-string (match-string 1)))
15514 (current-time)))
15515 (default-input (and ts (org-get-compact-tod ts)))
15516 (repeater (save-excursion
15517 (save-match-data
15518 (beginning-of-line)
15519 (when (re-search-forward
15520 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15521 (save-excursion (progn (end-of-line) (point))) t)
15522 (match-string 0)))))
15523 org-time-was-given org-end-time-was-given time)
15524 (cond
15525 ((and (org-at-timestamp-p t)
15526 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15527 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15528 (insert "--")
15529 (setq time (let ((this-command this-command))
15530 (org-read-date arg 'totime nil nil
15531 default-time default-input inactive)))
15532 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15533 ((org-at-timestamp-p t)
15534 (setq time (let ((this-command this-command))
15535 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15536 (when (org-at-timestamp-p t) ; just to get the match data
15537 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15538 (replace-match "")
15539 (setq org-last-changed-timestamp
15540 (org-insert-time-stamp
15541 time (or org-time-was-given arg)
15542 inactive nil nil (list org-end-time-was-given)))
15543 (when repeater (goto-char (1- (point))) (insert " " repeater)
15544 (setq org-last-changed-timestamp
15545 (concat (substring org-last-inserted-timestamp 0 -1)
15546 " " repeater ">"))))
15547 (message "Timestamp updated"))
15548 ((equal arg '(16))
15549 (org-insert-time-stamp (current-time) t))
15551 (setq time (let ((this-command this-command))
15552 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15553 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15554 nil nil (list org-end-time-was-given))))))
15556 ;; FIXME: can we use this for something else, like computing time differences?
15557 (defun org-get-compact-tod (s)
15558 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15559 (let* ((t1 (match-string 1 s))
15560 (h1 (string-to-number (match-string 2 s)))
15561 (m1 (string-to-number (match-string 3 s)))
15562 (t2 (and (match-end 4) (match-string 5 s)))
15563 (h2 (and t2 (string-to-number (match-string 6 s))))
15564 (m2 (and t2 (string-to-number (match-string 7 s))))
15565 dh dm)
15566 (if (not t2)
15568 (setq dh (- h2 h1) dm (- m2 m1))
15569 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15570 (concat t1 "+" (number-to-string dh)
15571 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15573 (defun org-time-stamp-inactive (&optional arg)
15574 "Insert an inactive time stamp.
15575 An inactive time stamp is enclosed in square brackets instead of angle
15576 brackets. It is inactive in the sense that it does not trigger agenda entries,
15577 does not link to the calendar and cannot be changed with the S-cursor keys.
15578 So these are more for recording a certain time/date."
15579 (interactive "P")
15580 (org-time-stamp arg 'inactive))
15582 (defvar org-date-ovl (make-overlay 1 1))
15583 (overlay-put org-date-ovl 'face 'org-date-selected)
15584 (org-detach-overlay org-date-ovl)
15586 (defvar org-ans1) ; dynamically scoped parameter
15587 (defvar org-ans2) ; dynamically scoped parameter
15589 (defvar org-plain-time-of-day-regexp) ; defined below
15591 (defvar org-overriding-default-time nil) ; dynamically scoped
15592 (defvar org-read-date-overlay nil)
15593 (defvar org-dcst nil) ; dynamically scoped
15594 (defvar org-read-date-history nil)
15595 (defvar org-read-date-final-answer nil)
15596 (defvar org-read-date-analyze-futurep nil)
15597 (defvar org-read-date-analyze-forced-year nil)
15598 (defvar org-read-date-inactive)
15600 (defvar org-read-date-minibuffer-local-map
15601 (let ((map (make-sparse-keymap)))
15602 (set-keymap-parent map minibuffer-local-map)
15603 (org-defkey map [(meta shift left)]
15604 (lambda () (interactive)
15605 (org-eval-in-calendar '(calendar-backward-month 1))))
15606 (org-defkey map [(meta shift right)]
15607 (lambda () (interactive)
15608 (org-eval-in-calendar '(calendar-forward-month 1))))
15609 (org-defkey map [(meta shift up)]
15610 (lambda () (interactive)
15611 (org-eval-in-calendar '(calendar-backward-year 1))))
15612 (org-defkey map [(meta shift down)]
15613 (lambda () (interactive)
15614 (org-eval-in-calendar '(calendar-forward-year 1))))
15615 (org-defkey map [?\e (shift left)]
15616 (lambda () (interactive)
15617 (org-eval-in-calendar '(calendar-backward-month 1))))
15618 (org-defkey map [?\e (shift right)]
15619 (lambda () (interactive)
15620 (org-eval-in-calendar '(calendar-forward-month 1))))
15621 (org-defkey map [?\e (shift up)]
15622 (lambda () (interactive)
15623 (org-eval-in-calendar '(calendar-backward-year 1))))
15624 (org-defkey map [?\e (shift down)]
15625 (lambda () (interactive)
15626 (org-eval-in-calendar '(calendar-forward-year 1))))
15627 (org-defkey map [(shift up)]
15628 (lambda () (interactive)
15629 (org-eval-in-calendar '(calendar-backward-week 1))))
15630 (org-defkey map [(shift down)]
15631 (lambda () (interactive)
15632 (org-eval-in-calendar '(calendar-forward-week 1))))
15633 (org-defkey map [(shift left)]
15634 (lambda () (interactive)
15635 (org-eval-in-calendar '(calendar-backward-day 1))))
15636 (org-defkey map [(shift right)]
15637 (lambda () (interactive)
15638 (org-eval-in-calendar '(calendar-forward-day 1))))
15639 (org-defkey map "?"
15640 (lambda () (interactive)
15641 (org-eval-in-calendar '(diary-view-entries))
15642 (message "")))
15643 (org-defkey map ">"
15644 (lambda () (interactive)
15645 (org-eval-in-calendar '(scroll-calendar-left 1))))
15646 (org-defkey map "<"
15647 (lambda () (interactive)
15648 (org-eval-in-calendar '(scroll-calendar-right 1))))
15649 (org-defkey map "\C-v"
15650 (lambda () (interactive)
15651 (org-eval-in-calendar
15652 '(calendar-scroll-left-three-months 1))))
15653 (org-defkey map "\M-v"
15654 (lambda () (interactive)
15655 (org-eval-in-calendar
15656 '(calendar-scroll-right-three-months 1))))
15657 map)
15658 "Keymap for minibuffer commands when using `org-read-date'.")
15660 (defun org-read-date (&optional org-with-time to-time from-string prompt
15661 default-time default-input inactive)
15662 "Read a date, possibly a time, and make things smooth for the user.
15663 The prompt will suggest to enter an ISO date, but you can also enter anything
15664 which will at least partially be understood by `parse-time-string'.
15665 Unrecognized parts of the date will default to the current day, month, year,
15666 hour and minute. If this command is called to replace a timestamp at point,
15667 or to enter the second timestamp of a range, the default time is taken
15668 from the existing stamp. Furthermore, the command prefers the future,
15669 so if you are giving a date where the year is not given, and the day-month
15670 combination is already past in the current year, it will assume you
15671 mean next year. For details, see the manual. A few examples:
15673 3-2-5 --> 2003-02-05
15674 feb 15 --> currentyear-02-15
15675 2/15 --> currentyear-02-15
15676 sep 12 9 --> 2009-09-12
15677 12:45 --> today 12:45
15678 22 sept 0:34 --> currentyear-09-22 0:34
15679 12 --> currentyear-currentmonth-12
15680 Fri --> nearest Friday (today or later)
15681 etc.
15683 Furthermore you can specify a relative date by giving, as the *first* thing
15684 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15685 change in days weeks, months, years.
15686 With a single plus or minus, the date is relative to today. With a double
15687 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15688 +4d --> four days from today
15689 +4 --> same as above
15690 +2w --> two weeks from today
15691 ++5 --> five days from default date
15693 The function understands only English month and weekday abbreviations.
15695 While prompting, a calendar is popped up - you can also select the
15696 date with the mouse (button 1). The calendar shows a period of three
15697 months. To scroll it to other months, use the keys `>' and `<'.
15698 If you don't like the calendar, turn it off with
15699 \(setq org-read-date-popup-calendar nil)
15701 With optional argument TO-TIME, the date will immediately be converted
15702 to an internal time.
15703 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15704 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15705 still enter a time, and this function will inform the calling routine
15706 about this change. The calling routine may then choose to change the
15707 format used to insert the time stamp into the buffer to include the time.
15708 With optional argument FROM-STRING, read from this string instead from
15709 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15710 the time/date that is used for everything that is not specified by the
15711 user."
15712 (require 'parse-time)
15713 (let* ((org-time-stamp-rounding-minutes
15714 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15715 (org-dcst org-display-custom-times)
15716 (ct (org-current-time))
15717 (org-def (or org-overriding-default-time default-time ct))
15718 (org-defdecode (decode-time org-def))
15719 (dummy (progn
15720 (when (< (nth 2 org-defdecode) org-extend-today-until)
15721 (setcar (nthcdr 2 org-defdecode) -1)
15722 (setcar (nthcdr 1 org-defdecode) 59)
15723 (setq org-def (apply 'encode-time org-defdecode)
15724 org-defdecode (decode-time org-def)))))
15725 (mouse-autoselect-window nil) ; Don't let the mouse jump
15726 (calendar-frame-setup nil)
15727 (calendar-setup nil)
15728 (calendar-move-hook nil)
15729 (calendar-view-diary-initially-flag nil)
15730 (calendar-view-holidays-initially-flag nil)
15731 (timestr (format-time-string
15732 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15733 (prompt (concat (if prompt (concat prompt " ") "")
15734 (format "Date+time [%s]: " timestr)))
15735 ans (org-ans0 "") org-ans1 org-ans2 final)
15737 (cond
15738 (from-string (setq ans from-string))
15739 (org-read-date-popup-calendar
15740 (save-excursion
15741 (save-window-excursion
15742 (calendar)
15743 (org-eval-in-calendar '(setq cursor-type nil) t)
15744 (unwind-protect
15745 (progn
15746 (calendar-forward-day (- (time-to-days org-def)
15747 (calendar-absolute-from-gregorian
15748 (calendar-current-date))))
15749 (org-eval-in-calendar nil t)
15750 (let* ((old-map (current-local-map))
15751 (map (copy-keymap calendar-mode-map))
15752 (minibuffer-local-map
15753 (copy-keymap org-read-date-minibuffer-local-map)))
15754 (org-defkey map (kbd "RET") 'org-calendar-select)
15755 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15756 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15757 (unwind-protect
15758 (progn
15759 (use-local-map map)
15760 (setq org-read-date-inactive inactive)
15761 (add-hook 'post-command-hook 'org-read-date-display)
15762 (setq org-ans0 (read-string prompt default-input
15763 'org-read-date-history nil))
15764 ;; org-ans0: from prompt
15765 ;; org-ans1: from mouse click
15766 ;; org-ans2: from calendar motion
15767 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15768 (remove-hook 'post-command-hook 'org-read-date-display)
15769 (use-local-map old-map)
15770 (when org-read-date-overlay
15771 (delete-overlay org-read-date-overlay)
15772 (setq org-read-date-overlay nil)))))
15773 (bury-buffer "*Calendar*")))))
15775 (t ; Naked prompt only
15776 (unwind-protect
15777 (setq ans (read-string prompt default-input
15778 'org-read-date-history timestr))
15779 (when org-read-date-overlay
15780 (delete-overlay org-read-date-overlay)
15781 (setq org-read-date-overlay nil)))))
15783 (setq final (org-read-date-analyze ans org-def org-defdecode))
15785 (when org-read-date-analyze-forced-year
15786 (message "Year was forced into %s"
15787 (if org-read-date-force-compatible-dates
15788 "compatible range (1970-2037)"
15789 "range representable on this machine"))
15790 (ding))
15792 ;; One round trip to get rid of 34th of August and stuff like that....
15793 (setq final (decode-time (apply 'encode-time final)))
15795 (setq org-read-date-final-answer ans)
15797 (if to-time
15798 (apply 'encode-time final)
15799 (if (and (boundp 'org-time-was-given) org-time-was-given)
15800 (format "%04d-%02d-%02d %02d:%02d"
15801 (nth 5 final) (nth 4 final) (nth 3 final)
15802 (nth 2 final) (nth 1 final))
15803 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15805 (defvar org-def)
15806 (defvar org-defdecode)
15807 (defvar org-with-time)
15808 (defun org-read-date-display ()
15809 "Display the current date prompt interpretation in the minibuffer."
15810 (when org-read-date-display-live
15811 (when org-read-date-overlay
15812 (delete-overlay org-read-date-overlay))
15813 (when (minibufferp (current-buffer))
15814 (save-excursion
15815 (end-of-line 1)
15816 (while (not (equal (buffer-substring
15817 (max (point-min) (- (point) 4)) (point))
15818 " "))
15819 (insert " ")))
15820 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15821 " " (or org-ans1 org-ans2)))
15822 (org-end-time-was-given nil)
15823 (f (org-read-date-analyze ans org-def org-defdecode))
15824 (fmts (if org-dcst
15825 org-time-stamp-custom-formats
15826 org-time-stamp-formats))
15827 (fmt (if (or org-with-time
15828 (and (boundp 'org-time-was-given) org-time-was-given))
15829 (cdr fmts)
15830 (car fmts)))
15831 (txt (format-time-string fmt (apply 'encode-time f)))
15832 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15833 (txt (concat "=> " txt)))
15834 (when (and org-end-time-was-given
15835 (string-match org-plain-time-of-day-regexp txt))
15836 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15837 org-end-time-was-given
15838 (substring txt (match-end 0)))))
15839 (when org-read-date-analyze-futurep
15840 (setq txt (concat txt " (=>F)")))
15841 (setq org-read-date-overlay
15842 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15843 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15845 (defun org-read-date-analyze (ans org-def org-defdecode)
15846 "Analyze the combined answer of the date prompt."
15847 ;; FIXME: cleanup and comment
15848 (let ((nowdecode (decode-time (current-time)))
15849 delta deltan deltaw deltadef year month day
15850 hour minute second wday pm h2 m2 tl wday1
15851 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15852 (setq org-read-date-analyze-futurep nil
15853 org-read-date-analyze-forced-year nil)
15854 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15855 (setq ans "+0"))
15857 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15858 (setq ans (replace-match "" t t ans)
15859 deltan (car delta)
15860 deltaw (nth 1 delta)
15861 deltadef (nth 2 delta)))
15863 ;; Check if there is an iso week date in there. If yes, store the
15864 ;; info and postpone interpreting it until the rest of the parsing
15865 ;; is done.
15866 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15867 (setq iso-year (if (match-end 1)
15868 (org-small-year-to-year
15869 (string-to-number (match-string 1 ans))))
15870 iso-weekday (if (match-end 3)
15871 (string-to-number (match-string 3 ans)))
15872 iso-week (string-to-number (match-string 2 ans)))
15873 (setq ans (replace-match "" t t ans)))
15875 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15876 (when (string-match
15877 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15878 (setq year (if (match-end 2)
15879 (string-to-number (match-string 2 ans))
15880 (progn (setq kill-year t)
15881 (string-to-number (format-time-string "%Y"))))
15882 month (string-to-number (match-string 3 ans))
15883 day (string-to-number (match-string 4 ans)))
15884 (if (< year 100) (setq year (+ 2000 year)))
15885 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15886 t nil ans)))
15888 ;; Help matching dotted european dates
15889 (when (string-match
15890 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15891 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15892 (setq kill-year t)
15893 (string-to-number (format-time-string "%Y")))
15894 day (string-to-number (match-string 1 ans))
15895 month (string-to-number (match-string 2 ans))
15896 ans (replace-match (format "%04d-%02d-%02d" year month day)
15897 t nil ans)))
15899 ;; Help matching american dates, like 5/30 or 5/30/7
15900 (when (string-match
15901 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15902 (setq year (if (match-end 4)
15903 (string-to-number (match-string 4 ans))
15904 (progn (setq kill-year t)
15905 (string-to-number (format-time-string "%Y"))))
15906 month (string-to-number (match-string 1 ans))
15907 day (string-to-number (match-string 2 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)))
15911 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15912 ;; If there is a time with am/pm, and *no* time without it, we convert
15913 ;; so that matching will be successful.
15914 (loop for i from 1 to 2 do ; twice, for end time as well
15915 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15916 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15917 (setq hour (string-to-number (match-string 1 ans))
15918 minute (if (match-end 3)
15919 (string-to-number (match-string 3 ans))
15921 pm (equal ?p
15922 (string-to-char (downcase (match-string 4 ans)))))
15923 (if (and (= hour 12) (not pm))
15924 (setq hour 0)
15925 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15926 (setq ans (replace-match (format "%02d:%02d" hour minute)
15927 t t ans))))
15929 ;; Check if a time range is given as a duration
15930 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15931 (setq hour (string-to-number (match-string 1 ans))
15932 h2 (+ hour (string-to-number (match-string 3 ans)))
15933 minute (string-to-number (match-string 2 ans))
15934 m2 (+ minute (if (match-end 5) (string-to-number
15935 (match-string 5 ans))0)))
15936 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15937 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15938 t t ans)))
15940 ;; Check if there is a time range
15941 (when (boundp 'org-end-time-was-given)
15942 (setq org-time-was-given nil)
15943 (when (and (string-match org-plain-time-of-day-regexp ans)
15944 (match-end 8))
15945 (setq org-end-time-was-given (match-string 8 ans))
15946 (setq ans (concat (substring ans 0 (match-beginning 7))
15947 (substring ans (match-end 7))))))
15949 (setq tl (parse-time-string ans)
15950 day (or (nth 3 tl) (nth 3 org-defdecode))
15951 month (or (nth 4 tl)
15952 (if (and org-read-date-prefer-future
15953 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15954 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15955 (nth 4 org-defdecode)))
15956 year (or (and (not kill-year) (nth 5 tl))
15957 (if (and org-read-date-prefer-future
15958 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15959 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15960 (nth 5 org-defdecode)))
15961 hour (or (nth 2 tl) (nth 2 org-defdecode))
15962 minute (or (nth 1 tl) (nth 1 org-defdecode))
15963 second (or (nth 0 tl) 0)
15964 wday (nth 6 tl))
15966 (when (and (eq org-read-date-prefer-future 'time)
15967 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15968 (equal day (nth 3 nowdecode))
15969 (equal month (nth 4 nowdecode))
15970 (equal year (nth 5 nowdecode))
15971 (nth 2 tl)
15972 (or (< (nth 2 tl) (nth 2 nowdecode))
15973 (and (= (nth 2 tl) (nth 2 nowdecode))
15974 (nth 1 tl)
15975 (< (nth 1 tl) (nth 1 nowdecode)))))
15976 (setq day (1+ day)
15977 futurep t))
15979 ;; Special date definitions below
15980 (cond
15981 (iso-week
15982 ;; There was an iso week
15983 (require 'cal-iso)
15984 (setq futurep nil)
15985 (setq year (or iso-year year)
15986 day (or iso-weekday wday 1)
15987 wday nil ; to make sure that the trigger below does not match
15988 iso-date (calendar-gregorian-from-absolute
15989 (calendar-absolute-from-iso
15990 (list iso-week day year))))
15991 ; FIXME: Should we also push ISO weeks into the future?
15992 ; (when (and org-read-date-prefer-future
15993 ; (not iso-year)
15994 ; (< (calendar-absolute-from-gregorian iso-date)
15995 ; (time-to-days (current-time))))
15996 ; (setq year (1+ year)
15997 ; iso-date (calendar-gregorian-from-absolute
15998 ; (calendar-absolute-from-iso
15999 ; (list iso-week day year)))))
16000 (setq month (car iso-date)
16001 year (nth 2 iso-date)
16002 day (nth 1 iso-date)))
16003 (deltan
16004 (setq futurep nil)
16005 (unless deltadef
16006 (let ((now (decode-time (current-time))))
16007 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16008 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16009 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16010 ((equal deltaw "m") (setq month (+ month deltan)))
16011 ((equal deltaw "y") (setq year (+ year deltan)))))
16012 ((and wday (not (nth 3 tl)))
16013 ;; Weekday was given, but no day, so pick that day in the week
16014 ;; on or after the derived date.
16015 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16016 (unless (equal wday wday1)
16017 (setq day (+ day (% (- wday wday1 -7) 7))))))
16018 (if (and (boundp 'org-time-was-given)
16019 (nth 2 tl))
16020 (setq org-time-was-given t))
16021 (if (< year 100) (setq year (+ 2000 year)))
16022 ;; Check of the date is representable
16023 (if org-read-date-force-compatible-dates
16024 (progn
16025 (if (< year 1970)
16026 (setq year 1970 org-read-date-analyze-forced-year t))
16027 (if (> year 2037)
16028 (setq year 2037 org-read-date-analyze-forced-year t)))
16029 (condition-case nil
16030 (ignore (encode-time second minute hour day month year))
16031 (error
16032 (setq year (nth 5 org-defdecode))
16033 (setq org-read-date-analyze-forced-year t))))
16034 (setq org-read-date-analyze-futurep futurep)
16035 (list second minute hour day month year)))
16037 (defvar parse-time-weekdays)
16038 (defun org-read-date-get-relative (s today default)
16039 "Check string S for special relative date string.
16040 TODAY and DEFAULT are internal times, for today and for a default.
16041 Return shift list (N what def-flag)
16042 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16043 N is the number of WHATs to shift.
16044 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16045 the DEFAULT date rather than TODAY."
16046 (require 'parse-time)
16047 (when (and
16048 (string-match
16049 (concat
16050 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16051 "\\([0-9]+\\)?"
16052 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16053 "\\([ \t]\\|$\\)") s)
16054 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16055 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16056 (string-to-char (substring (match-string 1 s) -1))
16057 ?+))
16058 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16059 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16060 (what (if (match-end 3) (match-string 3 s) "d"))
16061 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16062 (date (if rel default today))
16063 (wday (nth 6 (decode-time date)))
16064 delta)
16065 (if wday1
16066 (progn
16067 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16068 (if (= dir ?-) (setq delta (- delta 7)))
16069 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16070 (list delta "d" rel))
16071 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16073 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16074 "Turn a user-specified date into the internal representation.
16075 The internal representation needed by the calendar is (month day year).
16076 This is a wrapper to handle the brain-dead convention in calendar that
16077 user function argument order change dependent on argument order."
16078 (if (boundp 'calendar-date-style)
16079 (cond
16080 ((eq calendar-date-style 'american)
16081 (list arg1 arg2 arg3))
16082 ((eq calendar-date-style 'european)
16083 (list arg2 arg1 arg3))
16084 ((eq calendar-date-style 'iso)
16085 (list arg2 arg3 arg1)))
16086 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16087 (if (org-bound-and-true-p european-calendar-style)
16088 (list arg2 arg1 arg3)
16089 (list arg1 arg2 arg3)))))
16091 (defun org-eval-in-calendar (form &optional keepdate)
16092 "Eval FORM in the calendar window and return to current window.
16093 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16094 otherwise stick to the current value of `org-ans2'."
16095 (let ((sf (selected-frame))
16096 (sw (selected-window)))
16097 (select-window (get-buffer-window "*Calendar*" t))
16098 (eval form)
16099 (when (and (not keepdate) (calendar-cursor-to-date))
16100 (let* ((date (calendar-cursor-to-date))
16101 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16102 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16103 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16104 (select-window sw)
16105 (org-select-frame-set-input-focus sf)))
16107 (defun org-calendar-select ()
16108 "Return to `org-read-date' with the date currently selected.
16109 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16110 (interactive)
16111 (when (calendar-cursor-to-date)
16112 (let* ((date (calendar-cursor-to-date))
16113 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16114 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16115 (if (active-minibuffer-window) (exit-minibuffer))))
16117 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16118 "Insert a date stamp for the date given by the internal TIME.
16119 WITH-HM means use the stamp format that includes the time of the day.
16120 INACTIVE means use square brackets instead of angular ones, so that the
16121 stamp will not contribute to the agenda.
16122 PRE and POST are optional strings to be inserted before and after the
16123 stamp.
16124 The command returns the inserted time stamp."
16125 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16126 stamp)
16127 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16128 (insert-before-markers (or pre ""))
16129 (when (listp extra)
16130 (setq extra (car extra))
16131 (if (and (stringp extra)
16132 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16133 (setq extra (format "-%02d:%02d"
16134 (string-to-number (match-string 1 extra))
16135 (string-to-number (match-string 2 extra))))
16136 (setq extra nil)))
16137 (when extra
16138 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16139 (insert-before-markers (setq stamp (format-time-string fmt time)))
16140 (insert-before-markers (or post ""))
16141 (setq org-last-inserted-timestamp stamp)))
16143 (defun org-toggle-time-stamp-overlays ()
16144 "Toggle the use of custom time stamp formats."
16145 (interactive)
16146 (setq org-display-custom-times (not org-display-custom-times))
16147 (unless org-display-custom-times
16148 (let ((p (point-min)) (bmp (buffer-modified-p)))
16149 (while (setq p (next-single-property-change p 'display))
16150 (if (and (get-text-property p 'display)
16151 (eq (get-text-property p 'face) 'org-date))
16152 (remove-text-properties
16153 p (setq p (next-single-property-change p 'display))
16154 '(display t))))
16155 (set-buffer-modified-p bmp)))
16156 (if (featurep 'xemacs)
16157 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16158 (org-restart-font-lock)
16159 (setq org-table-may-need-update t)
16160 (if org-display-custom-times
16161 (message "Time stamps are overlaid with custom format")
16162 (message "Time stamp overlays removed")))
16164 (defun org-display-custom-time (beg end)
16165 "Overlay modified time stamp format over timestamp between BEG and END."
16166 (let* ((ts (buffer-substring beg end))
16167 t1 w1 with-hm tf time str w2 (off 0))
16168 (save-match-data
16169 (setq t1 (org-parse-time-string ts t))
16170 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16171 (setq off (- (match-end 0) (match-beginning 0)))))
16172 (setq end (- end off))
16173 (setq w1 (- end beg)
16174 with-hm (and (nth 1 t1) (nth 2 t1))
16175 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16176 time (org-fix-decoded-time t1)
16177 str (org-add-props
16178 (format-time-string
16179 (substring tf 1 -1) (apply 'encode-time time))
16180 nil 'mouse-face 'highlight)
16181 w2 (length str))
16182 (if (not (= w2 w1))
16183 (add-text-properties (1+ beg) (+ 2 beg)
16184 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16185 (if (featurep 'xemacs)
16186 (progn
16187 (put-text-property beg end 'invisible t)
16188 (put-text-property beg end 'end-glyph (make-glyph str)))
16189 (put-text-property beg end 'display str))))
16191 (defun org-translate-time (string)
16192 "Translate all timestamps in STRING to custom format.
16193 But do this only if the variable `org-display-custom-times' is set."
16194 (when org-display-custom-times
16195 (save-match-data
16196 (let* ((start 0)
16197 (re org-ts-regexp-both)
16198 t1 with-hm inactive tf time str beg end)
16199 (while (setq start (string-match re string start))
16200 (setq beg (match-beginning 0)
16201 end (match-end 0)
16202 t1 (save-match-data
16203 (org-parse-time-string (substring string beg end) t))
16204 with-hm (and (nth 1 t1) (nth 2 t1))
16205 inactive (equal (substring string beg (1+ beg)) "[")
16206 tf (funcall (if with-hm 'cdr 'car)
16207 org-time-stamp-custom-formats)
16208 time (org-fix-decoded-time t1)
16209 str (format-time-string
16210 (concat
16211 (if inactive "[" "<") (substring tf 1 -1)
16212 (if inactive "]" ">"))
16213 (apply 'encode-time time))
16214 string (replace-match str t t string)
16215 start (+ start (length str)))))))
16216 string)
16218 (defun org-fix-decoded-time (time)
16219 "Set 0 instead of nil for the first 6 elements of time.
16220 Don't touch the rest."
16221 (let ((n 0))
16222 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16224 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16226 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16227 "Difference between TIMESTAMP-STRING and now in days.
16228 If SECONDS is non-nil, return the difference in seconds."
16229 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16230 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16231 (funcall fdiff (current-time)))))
16233 (defun org-deadline-close (timestamp-string &optional ndays)
16234 "Is the time in TIMESTAMP-STRING close to the current date?"
16235 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16236 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16237 (not (org-entry-is-done-p))))
16239 (defun org-get-wdays (ts &optional delay zero-delay)
16240 "Get the deadline lead time appropriate for timestring TS.
16241 When DELAY is non-nil, get the delay time for scheduled items
16242 instead of the deadline lead time. When ZERO-DELAY is non-nil
16243 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16244 don't try to find the delay cookie in the scheduled timestamp."
16245 (let ((tv (if delay org-scheduled-delay-days
16246 org-deadline-warning-days)))
16247 (cond
16248 ((or (and delay (< tv 0))
16249 (and delay zero-delay (<= tv 0))
16250 (and (not delay) (<= tv 0)))
16251 ;; Enforce this value no matter what
16252 (- tv))
16253 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16254 ;; lead time is specified.
16255 (floor (* (string-to-number (match-string 1 ts))
16256 (cdr (assoc (match-string 2 ts)
16257 '(("d" . 1) ("w" . 7)
16258 ("m" . 30.4) ("y" . 365.25)
16259 ("h" . 0.041667)))))))
16260 ;; go for the default.
16261 (t tv))))
16263 (defun org-calendar-select-mouse (ev)
16264 "Return to `org-read-date' with the date currently selected.
16265 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16266 (interactive "e")
16267 (mouse-set-point ev)
16268 (when (calendar-cursor-to-date)
16269 (let* ((date (calendar-cursor-to-date))
16270 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16271 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16272 (if (active-minibuffer-window) (exit-minibuffer))))
16274 (defun org-check-deadlines (ndays)
16275 "Check if there are any deadlines due or past due.
16276 A deadline is considered due if it happens within `org-deadline-warning-days'
16277 days from today's date. If the deadline appears in an entry marked DONE,
16278 it is not shown. The prefix arg NDAYS can be used to test that many
16279 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16280 (interactive "P")
16281 (let* ((org-warn-days
16282 (cond
16283 ((equal ndays '(4)) 100000)
16284 (ndays (prefix-numeric-value ndays))
16285 (t (abs org-deadline-warning-days))))
16286 (case-fold-search nil)
16287 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16288 (callback
16289 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16291 (message "%d deadlines past-due or due within %d days"
16292 (org-occur regexp nil callback)
16293 org-warn-days)))
16295 (defsubst org-re-timestamp (type)
16296 "Return a regexp for timestamp TYPE.
16297 Allowed values for TYPE are:
16299 all: all timestamps
16300 active: only active timestamps (<...>)
16301 inactive: only inactive timestamps ([...])
16302 scheduled: only scheduled timestamps
16303 deadline: only deadline timestamps
16305 When TYPE is nil, fall back on returning a regexp that matches
16306 both scheduled and deadline timestamps."
16307 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16308 ((eq type 'active) org-ts-regexp)
16309 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16310 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16311 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16312 ((eq type 'scheduled-or-deadline)
16313 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16315 (defun org-check-before-date (date)
16316 "Check if there are deadlines or scheduled entries before DATE."
16317 (interactive (list (org-read-date)))
16318 (let ((case-fold-search nil)
16319 (regexp (org-re-timestamp org-ts-type))
16320 (callback
16321 (lambda () (time-less-p
16322 (org-time-string-to-time (match-string 1))
16323 (org-time-string-to-time date)))))
16324 (message "%d entries before %s"
16325 (org-occur regexp nil callback) date)))
16327 (defun org-check-after-date (date)
16328 "Check if there are deadlines or scheduled entries after DATE."
16329 (interactive (list (org-read-date)))
16330 (let ((case-fold-search nil)
16331 (regexp (org-re-timestamp org-ts-type))
16332 (callback
16333 (lambda () (not
16334 (time-less-p
16335 (org-time-string-to-time (match-string 1))
16336 (org-time-string-to-time date))))))
16337 (message "%d entries after %s"
16338 (org-occur regexp nil callback) date)))
16340 (defun org-check-dates-range (start-date end-date)
16341 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16342 (interactive (list (org-read-date nil nil nil "Range starts")
16343 (org-read-date nil nil nil "Range end")))
16344 (let ((case-fold-search nil)
16345 (regexp (org-re-timestamp org-ts-type))
16346 (callback
16347 (lambda ()
16348 (let ((match (match-string 1)))
16349 (and
16350 (not (time-less-p
16351 (org-time-string-to-time match)
16352 (org-time-string-to-time start-date)))
16353 (time-less-p
16354 (org-time-string-to-time match)
16355 (org-time-string-to-time end-date)))))))
16356 (message "%d entries between %s and %s"
16357 (org-occur regexp nil callback) start-date end-date)))
16359 (defun org-evaluate-time-range (&optional to-buffer)
16360 "Evaluate a time range by computing the difference between start and end.
16361 Normally the result is just printed in the echo area, but with prefix arg
16362 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16363 If the time range is actually in a table, the result is inserted into the
16364 next column.
16365 For time difference computation, a year is assumed to be exactly 365
16366 days in order to avoid rounding problems."
16367 (interactive "P")
16369 (org-clock-update-time-maybe)
16370 (save-excursion
16371 (unless (org-at-date-range-p t)
16372 (goto-char (point-at-bol))
16373 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16374 (if (not (org-at-date-range-p t))
16375 (error "Not at a time-stamp range, and none found in current line")))
16376 (let* ((ts1 (match-string 1))
16377 (ts2 (match-string 2))
16378 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16379 (match-end (match-end 0))
16380 (time1 (org-time-string-to-time ts1))
16381 (time2 (org-time-string-to-time ts2))
16382 (t1 (org-float-time time1))
16383 (t2 (org-float-time time2))
16384 (diff (abs (- t2 t1)))
16385 (negative (< (- t2 t1) 0))
16386 ;; (ys (floor (* 365 24 60 60)))
16387 (ds (* 24 60 60))
16388 (hs (* 60 60))
16389 (fy "%dy %dd %02d:%02d")
16390 (fy1 "%dy %dd")
16391 (fd "%dd %02d:%02d")
16392 (fd1 "%dd")
16393 (fh "%02d:%02d")
16394 y d h m align)
16395 (if havetime
16396 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16398 d (floor (/ diff ds)) diff (mod diff ds)
16399 h (floor (/ diff hs)) diff (mod diff hs)
16400 m (floor (/ diff 60)))
16401 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16403 d (floor (+ (/ diff ds) 0.5))
16404 h 0 m 0))
16405 (if (not to-buffer)
16406 (message "%s" (org-make-tdiff-string y d h m))
16407 (if (org-at-table-p)
16408 (progn
16409 (goto-char match-end)
16410 (setq align t)
16411 (and (looking-at " *|") (goto-char (match-end 0))))
16412 (goto-char match-end))
16413 (if (looking-at
16414 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16415 (replace-match ""))
16416 (if negative (insert " -"))
16417 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16418 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16419 (insert " " (format fh h m))))
16420 (if align (org-table-align))
16421 (message "Time difference inserted")))))
16423 (defun org-make-tdiff-string (y d h m)
16424 (let ((fmt "")
16425 (l nil))
16426 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16427 l (push y l)))
16428 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16429 l (push d l)))
16430 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16431 l (push h l)))
16432 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16433 l (push m l)))
16434 (apply 'format fmt (nreverse l))))
16436 (defun org-time-string-to-time (s &optional buffer pos)
16437 "Convert a timestamp string into internal time."
16438 (condition-case errdata
16439 (apply 'encode-time (org-parse-time-string s))
16440 (error (error "Bad timestamp `%s'%s\nError was: %s"
16441 s (if (not (and buffer pos))
16443 (format " at %d in buffer `%s'" pos buffer))
16444 (cdr errdata)))))
16446 (defun org-time-string-to-seconds (s)
16447 "Convert a timestamp string to a number of seconds."
16448 (org-float-time (org-time-string-to-time s)))
16450 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16451 "Convert a time stamp to an absolute day number.
16452 If there is a specifier for a cyclic time stamp, get the closest date to
16453 DAYNR.
16454 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16455 The variable date is bound by the calendar when this is called."
16456 (cond
16457 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16458 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16459 daynr
16460 (+ daynr 1000)))
16461 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16462 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16463 (time-to-days (current-time))) (match-string 0 s)
16464 prefer show-all))
16465 (t (time-to-days
16466 (condition-case errdata
16467 (apply 'encode-time (org-parse-time-string s))
16468 (error (error "Bad timestamp `%s'%s\nError was: %s"
16469 s (if (not (and buffer pos))
16471 (format " at %d in buffer `%s'" pos buffer))
16472 (cdr errdata))))))))
16474 (defun org-days-to-iso-week (days)
16475 "Return the iso week number."
16476 (require 'cal-iso)
16477 (car (calendar-iso-from-absolute days)))
16479 (defun org-small-year-to-year (year)
16480 "Convert 2-digit years into 4-digit years.
16481 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16482 The year 2000 cannot be abbreviated. Any year larger than 99
16483 is returned unchanged."
16484 (if (< year 38)
16485 (setq year (+ 2000 year))
16486 (if (< year 100)
16487 (setq year (+ 1900 year))))
16488 year)
16490 (defun org-time-from-absolute (d)
16491 "Return the time corresponding to date D.
16492 D may be an absolute day number, or a calendar-type list (month day year)."
16493 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16494 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16496 (defun org-calendar-holiday ()
16497 "List of holidays, for Diary display in Org-mode."
16498 (require 'holidays)
16499 (let ((hl (funcall
16500 (if (fboundp 'calendar-check-holidays)
16501 'calendar-check-holidays 'check-calendar-holidays) date)))
16502 (if hl (mapconcat 'identity hl "; "))))
16504 (defun org-diary-sexp-entry (sexp entry date)
16505 "Process a SEXP diary ENTRY for DATE."
16506 (require 'diary-lib)
16507 (let ((result (if calendar-debug-sexp
16508 (let ((stack-trace-on-error t))
16509 (eval (car (read-from-string sexp))))
16510 (condition-case nil
16511 (eval (car (read-from-string sexp)))
16512 (error
16513 (beep)
16514 (message "Bad sexp at line %d in %s: %s"
16515 (org-current-line)
16516 (buffer-file-name) sexp)
16517 (sleep-for 2))))))
16518 (cond ((stringp result) (split-string result "; "))
16519 ((and (consp result)
16520 (not (consp (cdr result)))
16521 (stringp (cdr result))) (cdr result))
16522 ((and (consp result)
16523 (stringp (car result))) result)
16524 (result entry))))
16526 (defun org-diary-to-ical-string (frombuf)
16527 "Get iCalendar entries from diary entries in buffer FROMBUF.
16528 This uses the icalendar.el library."
16529 (let* ((tmpdir (if (featurep 'xemacs)
16530 (temp-directory)
16531 temporary-file-directory))
16532 (tmpfile (make-temp-name
16533 (expand-file-name "orgics" tmpdir)))
16534 buf rtn b e)
16535 (with-current-buffer frombuf
16536 (icalendar-export-region (point-min) (point-max) tmpfile)
16537 (setq buf (find-buffer-visiting tmpfile))
16538 (set-buffer buf)
16539 (goto-char (point-min))
16540 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16541 (setq b (match-beginning 0)))
16542 (goto-char (point-max))
16543 (if (re-search-backward "^END:VEVENT" nil t)
16544 (setq e (match-end 0)))
16545 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16546 (kill-buffer buf)
16547 (delete-file tmpfile)
16548 rtn))
16550 (defun org-closest-date (start current change prefer show-all)
16551 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16552 When PREFER is `past', return a date that is either CURRENT or past.
16553 When PREFER is `future', return a date that is either CURRENT or future.
16554 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16555 ;; Make the proper lists from the dates
16556 (catch 'exit
16557 (let ((a1 '(("h" . hour)
16558 ("d" . day)
16559 ("w" . week)
16560 ("m" . month)
16561 ("y" . year)))
16562 (shour (nth 2 (org-parse-time-string start)))
16563 dn dw sday cday n1 n2 n0
16564 d m y y1 y2 date1 date2 nmonths nm ny m2)
16566 (setq start (org-date-to-gregorian start)
16567 current (org-date-to-gregorian
16568 (if show-all
16569 current
16570 (time-to-days (current-time))))
16571 sday (calendar-absolute-from-gregorian start)
16572 cday (calendar-absolute-from-gregorian current))
16574 (if (<= cday sday) (throw 'exit sday))
16576 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16577 (setq dn (string-to-number (match-string 1 change))
16578 dw (cdr (assoc (match-string 2 change) a1)))
16579 (error "Invalid change specifier: %s" change))
16580 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16581 (cond
16582 ((eq dw 'hour)
16583 (let ((missing-hours
16584 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16585 dn)))
16586 (setq n1 (if (zerop missing-hours) cday
16587 (- cday (1+ (floor (/ missing-hours 24)))))
16588 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16589 ((eq dw 'day)
16590 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16591 n2 (+ n1 dn)))
16592 ((eq dw 'year)
16593 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16594 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16595 (setq date1 (list m d y1)
16596 n1 (calendar-absolute-from-gregorian date1)
16597 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16598 n2 (calendar-absolute-from-gregorian date2)))
16599 ((eq dw 'month)
16600 ;; approx number of month between the two dates
16601 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16602 ;; How often does dn fit in there?
16603 (setq d (nth 1 start) m (car start) y (nth 2 start)
16604 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16605 m (+ m nm)
16606 ny (floor (/ m 12))
16607 y (+ y ny)
16608 m (- m (* ny 12)))
16609 (while (> m 12) (setq m (- m 12) y (1+ y)))
16610 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16611 (setq m2 (+ m dn) y2 y)
16612 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16613 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16614 (while (<= n2 cday)
16615 (setq n1 n2 m m2 y y2)
16616 (setq m2 (+ m dn) y2 y)
16617 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16618 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16619 ;; Make sure n1 is the earlier date
16620 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16621 (if show-all
16622 (cond
16623 ((eq prefer 'past) (if (= cday n2) n2 n1))
16624 ((eq prefer 'future) (if (= cday n1) n1 n2))
16625 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16626 (cond
16627 ((eq prefer 'past) (if (= cday n2) n2 n1))
16628 ((eq prefer 'future) (if (= cday n1) n1 n2))
16629 (t (if (= cday n1) n1 n2)))))))
16631 (defun org-date-to-gregorian (date)
16632 "Turn any specification of DATE into a Gregorian date for the calendar."
16633 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16634 ((and (listp date) (= (length date) 3)) date)
16635 ((stringp date)
16636 (setq date (org-parse-time-string date))
16637 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16638 ((listp date)
16639 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16641 (defun org-parse-time-string (s &optional nodefault)
16642 "Parse the standard Org-mode time string.
16643 This should be a lot faster than the normal `parse-time-string'.
16644 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16645 hour and minute fields will be nil if not given."
16646 (cond ((string-match org-ts-regexp0 s)
16647 (list 0
16648 (if (or (match-beginning 8) (not nodefault))
16649 (string-to-number (or (match-string 8 s) "0")))
16650 (if (or (match-beginning 7) (not nodefault))
16651 (string-to-number (or (match-string 7 s) "0")))
16652 (string-to-number (match-string 4 s))
16653 (string-to-number (match-string 3 s))
16654 (string-to-number (match-string 2 s))
16655 nil nil nil))
16656 ((string-match "^<[^>]+>$" s)
16657 (decode-time (seconds-to-time (org-matcher-time s))))
16658 (t (error "Not a standard Org-mode time string: %s" s))))
16660 (defun org-timestamp-up (&optional arg)
16661 "Increase the date item at the cursor by one.
16662 If the cursor is on the year, change the year. If it is on the month,
16663 the day or the time, change that.
16664 With prefix ARG, change by that many units."
16665 (interactive "p")
16666 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16668 (defun org-timestamp-down (&optional arg)
16669 "Decrease the date item at the cursor by one.
16670 If the cursor is on the year, change the year. If it is on the month,
16671 the day or the time, change that.
16672 With prefix ARG, change by that many units."
16673 (interactive "p")
16674 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16676 (defun org-timestamp-up-day (&optional arg)
16677 "Increase the date in the time stamp by one day.
16678 With prefix ARG, change that many days."
16679 (interactive "p")
16680 (if (and (not (org-at-timestamp-p t))
16681 (org-at-heading-p))
16682 (org-todo 'up)
16683 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16685 (defun org-timestamp-down-day (&optional arg)
16686 "Decrease the date in the time stamp by one day.
16687 With prefix ARG, change that many days."
16688 (interactive "p")
16689 (if (and (not (org-at-timestamp-p t))
16690 (org-at-heading-p))
16691 (org-todo 'down)
16692 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16694 (defun org-at-timestamp-p (&optional inactive-ok)
16695 "Determine if the cursor is in or at a timestamp."
16696 (interactive)
16697 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16698 (pos (point))
16699 (ans (or (looking-at tsr)
16700 (save-excursion
16701 (skip-chars-backward "^[<\n\r\t")
16702 (if (> (point) (point-min)) (backward-char 1))
16703 (and (looking-at tsr)
16704 (> (- (match-end 0) pos) -1))))))
16705 (and ans
16706 (boundp 'org-ts-what)
16707 (setq org-ts-what
16708 (cond
16709 ((= pos (match-beginning 0)) 'bracket)
16710 ;; Point is considered to be "on the bracket" whether
16711 ;; it's really on it or right after it.
16712 ((= pos (1- (match-end 0))) 'bracket)
16713 ((= pos (match-end 0)) 'after)
16714 ((org-pos-in-match-range pos 2) 'year)
16715 ((org-pos-in-match-range pos 3) 'month)
16716 ((org-pos-in-match-range pos 7) 'hour)
16717 ((org-pos-in-match-range pos 8) 'minute)
16718 ((or (org-pos-in-match-range pos 4)
16719 (org-pos-in-match-range pos 5)) 'day)
16720 ((and (> pos (or (match-end 8) (match-end 5)))
16721 (< pos (match-end 0)))
16722 (- pos (or (match-end 8) (match-end 5))))
16723 (t 'day))))
16724 ans))
16726 (defun org-toggle-timestamp-type ()
16727 "Toggle the type (<active> or [inactive]) of a time stamp."
16728 (interactive)
16729 (when (org-at-timestamp-p t)
16730 (let ((beg (match-beginning 0)) (end (match-end 0))
16731 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16732 (save-excursion
16733 (goto-char beg)
16734 (while (re-search-forward "[][<>]" end t)
16735 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16736 t t)))
16737 (message "Timestamp is now %sactive"
16738 (if (equal (char-after beg) ?<) "" "in")))))
16740 (defvar org-clock-history) ; defined in org-clock.el
16741 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16742 (defun org-timestamp-change (n &optional what updown)
16743 "Change the date in the time stamp at point.
16744 The date will be changed by N times WHAT. WHAT can be `day', `month',
16745 `year', `minute', `second'. If WHAT is not given, the cursor position
16746 in the timestamp determines what will be changed."
16747 (let ((origin (point)) origin-cat
16748 with-hm inactive
16749 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16750 org-ts-what
16751 extra rem
16752 ts time time0 fixnext clrgx)
16753 (if (not (org-at-timestamp-p t))
16754 (error "Not at a timestamp"))
16755 (if (and (not what) (eq org-ts-what 'bracket))
16756 (org-toggle-timestamp-type)
16757 ;; Point isn't on brackets. Remember the part of the time-stamp
16758 ;; the point was in. Indeed, size of time-stamps may change,
16759 ;; but point must be kept in the same category nonetheless.
16760 (setq origin-cat org-ts-what)
16761 (if (and (not what) (not (eq org-ts-what 'day))
16762 org-display-custom-times
16763 (get-text-property (point) 'display)
16764 (not (get-text-property (1- (point)) 'display)))
16765 (setq org-ts-what 'day))
16766 (setq org-ts-what (or what org-ts-what)
16767 inactive (= (char-after (match-beginning 0)) ?\[)
16768 ts (match-string 0))
16769 (replace-match "")
16770 (if (string-match
16771 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16773 (setq extra (match-string 1 ts)))
16774 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16775 (setq with-hm t))
16776 (setq time0 (org-parse-time-string ts))
16777 (when (and updown
16778 (eq org-ts-what 'minute)
16779 (not current-prefix-arg))
16780 ;; This looks like s-up and s-down. Change by one rounding step.
16781 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16782 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16783 (setcar (cdr time0) (+ (nth 1 time0)
16784 (if (> n 0) (- rem) (- dm rem))))))
16785 (setq time
16786 (encode-time (or (car time0) 0)
16787 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16788 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16789 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16790 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16791 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16792 (nthcdr 6 time0)))
16793 (when (and (member org-ts-what '(hour minute))
16794 extra
16795 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16796 (setq extra (org-modify-ts-extra
16797 extra
16798 (if (eq org-ts-what 'hour) 2 5)
16799 n dm)))
16800 (when (integerp org-ts-what)
16801 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16802 (if (eq what 'calendar)
16803 (let ((cal-date (org-get-date-from-calendar)))
16804 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16805 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16806 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16807 (setcar time0 (or (car time0) 0))
16808 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16809 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16810 (setq time (apply 'encode-time time0))))
16811 ;; Insert the new time-stamp, and ensure point stays in the same
16812 ;; category as before (i.e. not after the last position in that
16813 ;; category).
16814 (let ((pos (point)))
16815 ;; Stay before inserted string. `save-excursion' is of no use.
16816 (setq org-last-changed-timestamp
16817 (org-insert-time-stamp time with-hm inactive nil nil extra))
16818 (goto-char pos))
16819 (save-match-data
16820 (looking-at org-ts-regexp3)
16821 (goto-char (cond
16822 ;; `day' category ends before `hour' if any, or at
16823 ;; the end of the day name.
16824 ((eq origin-cat 'day)
16825 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16826 ((eq origin-cat 'hour) (min (match-end 7) origin))
16827 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16828 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16829 ;; `year' and `month' have both fixed size: point
16830 ;; couldn't have moved into another part.
16831 (t origin))))
16832 ;; Update clock if on a CLOCK line.
16833 (org-clock-update-time-maybe)
16834 ;; Maybe adjust the closest clock in `org-clock-history'
16835 (when org-clock-adjust-closest
16836 (if (not (and (org-at-clock-log-p)
16837 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16838 org-clock-history))))))
16839 (message "No clock to adjust")
16840 (cond ((save-excursion ; fix previous clock?
16841 (re-search-backward org-ts-regexp0 nil t)
16842 (org-looking-back (concat org-clock-string " \\[")))
16843 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16844 ((save-excursion ; fix next clock?
16845 (re-search-backward org-ts-regexp0 nil t)
16846 (looking-at (concat org-ts-regexp0 "\\] =>")))
16847 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16848 (save-window-excursion
16849 ;; Find closest clock to point, adjust the previous/next one in history
16850 (let* ((p (save-excursion (org-back-to-heading t)))
16851 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16852 (clfixnth
16853 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16854 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16855 (if (not clfixpos)
16856 (message "No clock to adjust")
16857 (save-excursion
16858 (org-goto-marker-or-bmk clfixpos)
16859 (org-show-subtree)
16860 (when (re-search-forward clrgx nil t)
16861 (goto-char (match-beginning 1))
16862 (let (org-clock-adjust-closest)
16863 (org-timestamp-change n org-ts-what updown))
16864 (message "Clock adjusted in %s for heading: %s"
16865 (file-name-nondirectory (buffer-file-name))
16866 (org-get-heading t t)))))))))
16867 ;; Try to recenter the calendar window, if any.
16868 (if (and org-calendar-follow-timestamp-change
16869 (get-buffer-window "*Calendar*" t)
16870 (memq org-ts-what '(day month year)))
16871 (org-recenter-calendar (time-to-days time))))))
16873 (defun org-modify-ts-extra (s pos n dm)
16874 "Change the different parts of the lead-time and repeat fields in timestamp."
16875 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16876 ng h m new rem)
16877 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16878 (cond
16879 ((or (org-pos-in-match-range pos 2)
16880 (org-pos-in-match-range pos 3))
16881 (setq m (string-to-number (match-string 3 s))
16882 h (string-to-number (match-string 2 s)))
16883 (if (org-pos-in-match-range pos 2)
16884 (setq h (+ h n))
16885 (setq n (* dm (org-no-warnings (signum n))))
16886 (when (not (= 0 (setq rem (% m dm))))
16887 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16888 (setq m (+ m n)))
16889 (if (< m 0) (setq m (+ m 60) h (1- h)))
16890 (if (> m 59) (setq m (- m 60) h (1+ h)))
16891 (setq h (min 24 (max 0 h)))
16892 (setq ng 1 new (format "-%02d:%02d" h m)))
16893 ((org-pos-in-match-range pos 6)
16894 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16895 ((org-pos-in-match-range pos 5)
16896 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16898 ((org-pos-in-match-range pos 9)
16899 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16900 ((org-pos-in-match-range pos 8)
16901 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16903 (when ng
16904 (setq s (concat
16905 (substring s 0 (match-beginning ng))
16907 (substring s (match-end ng))))))
16910 (defun org-recenter-calendar (date)
16911 "If the calendar is visible, recenter it to DATE."
16912 (let ((cwin (get-buffer-window "*Calendar*" t)))
16913 (when cwin
16914 (let ((calendar-move-hook nil))
16915 (with-selected-window cwin
16916 (calendar-goto-date (if (listp date) date
16917 (calendar-gregorian-from-absolute date))))))))
16919 (defun org-goto-calendar (&optional arg)
16920 "Go to the Emacs calendar at the current date.
16921 If there is a time stamp in the current line, go to that date.
16922 A prefix ARG can be used to force the current date."
16923 (interactive "P")
16924 (let ((tsr org-ts-regexp) diff
16925 (calendar-move-hook nil)
16926 (calendar-view-holidays-initially-flag nil)
16927 (calendar-view-diary-initially-flag nil))
16928 (if (or (org-at-timestamp-p)
16929 (save-excursion
16930 (beginning-of-line 1)
16931 (looking-at (concat ".*" tsr))))
16932 (let ((d1 (time-to-days (current-time)))
16933 (d2 (time-to-days
16934 (org-time-string-to-time (match-string 1)))))
16935 (setq diff (- d2 d1))))
16936 (calendar)
16937 (calendar-goto-today)
16938 (if (and diff (not arg)) (calendar-forward-day diff))))
16940 (defun org-get-date-from-calendar ()
16941 "Return a list (month day year) of date at point in calendar."
16942 (with-current-buffer "*Calendar*"
16943 (save-match-data
16944 (calendar-cursor-to-date))))
16946 (defun org-date-from-calendar ()
16947 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16948 If there is already a time stamp at the cursor position, update it."
16949 (interactive)
16950 (if (org-at-timestamp-p t)
16951 (org-timestamp-change 0 'calendar)
16952 (let ((cal-date (org-get-date-from-calendar)))
16953 (org-insert-time-stamp
16954 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16956 (defcustom org-effort-durations
16957 `(("h" . 60)
16958 ("d" . ,(* 60 8))
16959 ("w" . ,(* 60 8 5))
16960 ("m" . ,(* 60 8 5 4))
16961 ("y" . ,(* 60 8 5 40)))
16962 "Conversion factor to minutes for an effort modifier.
16964 Each entry has the form (MODIFIER . MINUTES).
16966 In an effort string, a number followed by MODIFIER is multiplied
16967 by the specified number of MINUTES to obtain an effort in
16968 minutes.
16970 For example, if the value of this variable is ((\"hours\" . 60)), then an
16971 effort string \"2hours\" is equivalent to 120 minutes."
16972 :group 'org-agenda
16973 :version "24.1"
16974 :type '(alist :key-type (string :tag "Modifier")
16975 :value-type (number :tag "Minutes")))
16977 (defun org-minutes-to-clocksum-string (m)
16978 "Format number of minutes as a clocksum string.
16979 The format is determined by `org-time-clocksum-format',
16980 `org-time-clocksum-use-fractional' and
16981 `org-time-clocksum-fractional-format' and
16982 `org-time-clocksum-use-effort-durations'."
16983 (let ((clocksum "") h d w mo y fmt n)
16984 (setq h (if org-time-clocksum-use-effort-durations
16985 (cdr (assoc "h" org-effort-durations)) 60)
16986 d (if org-time-clocksum-use-effort-durations
16987 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
16988 w (if org-time-clocksum-use-effort-durations
16989 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
16990 mo (if org-time-clocksum-use-effort-durations
16991 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
16992 y (if org-time-clocksum-use-effort-durations
16993 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
16994 ;; fractional format
16995 (if org-time-clocksum-use-fractional
16996 (cond
16997 ;; single format string
16998 ((stringp org-time-clocksum-fractional-format)
16999 (format org-time-clocksum-fractional-format (/ m (float h))))
17000 ;; choice of fractional formats for different time units
17001 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17002 (> (/ (truncate m) (* y d h)) 0))
17003 (format fmt (/ m (* y d (float h)))))
17004 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17005 (> (/ (truncate m) (* mo d h)) 0))
17006 (format fmt (/ m (* mo d (float h)))))
17007 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17008 (> (/ (truncate m) (* w d h)) 0))
17009 (format fmt (/ m (* w d (float h)))))
17010 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17011 (> (/ (truncate m) (* d h)) 0))
17012 (format fmt (/ m (* d (float h)))))
17013 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17014 (> (/ (truncate m) h) 0))
17015 (format fmt (/ m (float h))))
17016 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17017 (format fmt m))
17018 ;; fall back to smallest time unit with a format
17019 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17020 (format fmt (/ m (float h))))
17021 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17022 (format fmt (/ m (* d (float h)))))
17023 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17024 (format fmt (/ m (* w d (float h)))))
17025 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17026 (format fmt (/ m (* mo d (float h)))))
17027 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17028 (format fmt (/ m (* y d (float h))))))
17029 ;; standard (non-fractional) format, with single format string
17030 (if (stringp org-time-clocksum-format)
17031 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17032 ;; separate formats components
17033 (and (setq fmt (plist-get org-time-clocksum-format :years))
17034 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17035 (plist-get org-time-clocksum-format :require-years))
17036 (setq clocksum (concat clocksum (format fmt n))
17037 m (- m (* n y d h))))
17038 (and (setq fmt (plist-get org-time-clocksum-format :months))
17039 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17040 (plist-get org-time-clocksum-format :require-months))
17041 (setq clocksum (concat clocksum (format fmt n))
17042 m (- m (* n mo d h))))
17043 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17044 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17045 (plist-get org-time-clocksum-format :require-weeks))
17046 (setq clocksum (concat clocksum (format fmt n))
17047 m (- m (* n w d h))))
17048 (and (setq fmt (plist-get org-time-clocksum-format :days))
17049 (or (> (setq n (/ (truncate m) (* d h))) 0)
17050 (plist-get org-time-clocksum-format :require-days))
17051 (setq clocksum (concat clocksum (format fmt n))
17052 m (- m (* n d h))))
17053 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17054 (or (> (setq n (/ (truncate m) h)) 0)
17055 (plist-get org-time-clocksum-format :require-hours))
17056 (setq clocksum (concat clocksum (format fmt n))
17057 m (- m (* n h))))
17058 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17059 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17060 (setq clocksum (concat clocksum (format fmt m))))
17061 ;; return formatted time duration
17062 clocksum))))
17064 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17065 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17066 "Org mode version 8.0")
17068 (defun org-hours-to-clocksum-string (n)
17069 (org-minutes-to-clocksum-string (* n 60)))
17071 (defun org-hh:mm-string-to-minutes (s)
17072 "Convert a string H:MM to a number of minutes.
17073 If the string is just a number, interpret it as minutes.
17074 In fact, the first hh:mm or number in the string will be taken,
17075 there can be extra stuff in the string.
17076 If no number is found, the return value is 0."
17077 (cond
17078 ((integerp s) s)
17079 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17080 (+ (* (string-to-number (match-string 1 s)) 60)
17081 (string-to-number (match-string 2 s))))
17082 ((string-match "\\([0-9]+\\)" s)
17083 (string-to-number (match-string 1 s)))
17084 (t 0)))
17086 (defcustom org-image-actual-width t
17087 "Should we use the actual width of images when inlining them?
17089 When set to `t', always use the image width.
17091 When set to a number, use imagemagick (when available) to set
17092 the image's width to this value.
17094 When set to a number in a list, try to get the width from the
17095 #+ATTR.* keyword if it matches a width specification like
17096 width=\"[0-9]+\", and fall back on that number if none is found.
17098 When set to nil, try to get the width from an #+ATTR.* keyword
17099 and fall back on the original width if none is found.
17101 This requires Emacs >= 24.1, build with imagemagick support."
17102 :group 'org-appearance
17103 :version "24.3"
17104 :type '(choice
17105 (const :tag "Use the image width" t)
17106 (integer :tag "Use a number of pixels")
17107 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17108 (const :tag "Use #+ATTR* or don't resize" nil)))
17110 (defcustom org-agenda-inhibit-startup t
17111 "Inhibit startup when preparing agenda buffers.
17112 When this variable is `t' (the default), the initialization of
17113 the Org agenda buffers is inhibited: e.g. the visibility state
17114 is not set, the tables are not re-aligned, etc."
17115 :type 'boolean
17116 :version "24.3"
17117 :group 'org-agenda)
17119 (defun org-duration-string-to-minutes (s &optional output-to-string)
17120 "Convert a duration string S to minutes.
17122 A bare number is interpreted as minutes, modifiers can be set by
17123 customizing `org-effort-durations' (which see).
17125 Entries containing a colon are interpreted as H:MM by
17126 `org-hh:mm-string-to-minutes'."
17127 (let ((result 0)
17128 (re (concat "\\([0-9.]+\\) *\\("
17129 (regexp-opt (mapcar 'car org-effort-durations))
17130 "\\)")))
17131 (while (string-match re s)
17132 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17133 (string-to-number (match-string 1 s))))
17134 (setq s (replace-match "" nil t s)))
17135 (setq result (floor result))
17136 (incf result (org-hh:mm-string-to-minutes s))
17137 (if output-to-string (number-to-string result) result)))
17139 ;;;; Files
17141 (defun org-save-all-org-buffers ()
17142 "Save all Org-mode buffers without user confirmation."
17143 (interactive)
17144 (message "Saving all Org-mode buffers...")
17145 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17146 (when (featurep 'org-id) (org-id-locations-save))
17147 (message "Saving all Org-mode buffers... done"))
17149 (defun org-revert-all-org-buffers ()
17150 "Revert all Org-mode buffers.
17151 Prompt for confirmation when there are unsaved changes.
17152 Be sure you know what you are doing before letting this function
17153 overwrite your changes.
17155 This function is useful in a setup where one tracks org files
17156 with a version control system, to revert on one machine after pulling
17157 changes from another. I believe the procedure must be like this:
17159 1. M-x org-save-all-org-buffers
17160 2. Pull changes from the other machine, resolve conflicts
17161 3. M-x org-revert-all-org-buffers"
17162 (interactive)
17163 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17164 (error "Abort"))
17165 (save-excursion
17166 (save-window-excursion
17167 (mapc
17168 (lambda (b)
17169 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17170 (with-current-buffer b buffer-file-name))
17171 (org-pop-to-buffer-same-window b)
17172 (revert-buffer t 'no-confirm)))
17173 (buffer-list))
17174 (when (and (featurep 'org-id) org-id-track-globally)
17175 (org-id-locations-load)))))
17177 ;;;; Agenda files
17179 ;;;###autoload
17180 (defun org-switchb (&optional arg)
17181 "Switch between Org buffers.
17182 With one prefix argument, restrict available buffers to files.
17183 With two prefix arguments, restrict available buffers to agenda files.
17185 Defaults to `iswitchb' for buffer name completion.
17186 Set `org-completion-use-ido' to make it use ido instead."
17187 (interactive "P")
17188 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17189 ((equal arg '(16)) (org-buffer-list 'agenda))
17190 (t (org-buffer-list))))
17191 (org-completion-use-iswitchb org-completion-use-iswitchb)
17192 (org-completion-use-ido org-completion-use-ido))
17193 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17194 (setq org-completion-use-iswitchb t))
17195 (org-pop-to-buffer-same-window
17196 (org-icompleting-read "Org buffer: "
17197 (mapcar 'list (mapcar 'buffer-name blist))
17198 nil t))))
17200 ;;; Define some older names previously used for this functionality
17201 ;;;###autoload
17202 (defalias 'org-ido-switchb 'org-switchb)
17203 ;;;###autoload
17204 (defalias 'org-iswitchb 'org-switchb)
17206 (defun org-buffer-list (&optional predicate exclude-tmp)
17207 "Return a list of Org buffers.
17208 PREDICATE can be `export', `files' or `agenda'.
17210 export restrict the list to Export buffers.
17211 files restrict the list to buffers visiting Org files.
17212 agenda restrict the list to buffers visiting agenda files.
17214 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17215 (let* ((bfn nil)
17216 (agenda-files (and (eq predicate 'agenda)
17217 (mapcar 'file-truename (org-agenda-files t))))
17218 (filter
17219 (cond
17220 ((eq predicate 'files)
17221 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17222 ((eq predicate 'export)
17223 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17224 ((eq predicate 'agenda)
17225 (lambda (b)
17226 (with-current-buffer b
17227 (and (derived-mode-p 'org-mode)
17228 (setq bfn (buffer-file-name b))
17229 (member (file-truename bfn) agenda-files)))))
17230 (t (lambda (b) (with-current-buffer b
17231 (or (derived-mode-p 'org-mode)
17232 (string-match "\*Org .*Export"
17233 (buffer-name b)))))))))
17234 (delq nil
17235 (mapcar
17236 (lambda(b)
17237 (if (and (funcall filter b)
17238 (or (not exclude-tmp)
17239 (not (string-match "tmp" (buffer-name b)))))
17241 nil))
17242 (buffer-list)))))
17244 (defun org-agenda-files (&optional unrestricted archives)
17245 "Get the list of agenda files.
17246 Optional UNRESTRICTED means return the full list even if a restriction
17247 is currently in place.
17248 When ARCHIVES is t, include all archive files that are really being
17249 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17250 `org-agenda-archives-mode' is t."
17251 (let ((files
17252 (cond
17253 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17254 ((stringp org-agenda-files) (org-read-agenda-file-list))
17255 ((listp org-agenda-files) org-agenda-files)
17256 (t (error "Invalid value of `org-agenda-files'")))))
17257 (setq files (apply 'append
17258 (mapcar (lambda (f)
17259 (if (file-directory-p f)
17260 (directory-files
17261 f t org-agenda-file-regexp)
17262 (list f)))
17263 files)))
17264 (when org-agenda-skip-unavailable-files
17265 (setq files (delq nil
17266 (mapcar (function
17267 (lambda (file)
17268 (and (file-readable-p file) file)))
17269 files))))
17270 (when (or (eq archives t)
17271 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17272 (setq files (org-add-archive-files files)))
17273 files))
17275 (defun org-agenda-file-p (&optional file)
17276 "Return non-nil, if FILE is an agenda file.
17277 If FILE is omitted, use the file associated with the current
17278 buffer."
17279 (member (or file (buffer-file-name))
17280 (org-agenda-files t)))
17282 (defun org-edit-agenda-file-list ()
17283 "Edit the list of agenda files.
17284 Depending on setup, this either uses customize to edit the variable
17285 `org-agenda-files', or it visits the file that is holding the list. In the
17286 latter case, the buffer is set up in a way that saving it automatically kills
17287 the buffer and restores the previous window configuration."
17288 (interactive)
17289 (if (stringp org-agenda-files)
17290 (let ((cw (current-window-configuration)))
17291 (find-file org-agenda-files)
17292 (org-set-local 'org-window-configuration cw)
17293 (org-add-hook 'after-save-hook
17294 (lambda ()
17295 (set-window-configuration
17296 (prog1 org-window-configuration
17297 (kill-buffer (current-buffer))))
17298 (org-install-agenda-files-menu)
17299 (message "New agenda file list installed"))
17300 nil 'local)
17301 (message "%s" (substitute-command-keys
17302 "Edit list and finish with \\[save-buffer]")))
17303 (customize-variable 'org-agenda-files)))
17305 (defun org-store-new-agenda-file-list (list)
17306 "Set new value for the agenda file list and save it correctly."
17307 (if (stringp org-agenda-files)
17308 (let ((fe (org-read-agenda-file-list t)) b u)
17309 (while (setq b (find-buffer-visiting org-agenda-files))
17310 (kill-buffer b))
17311 (with-temp-file org-agenda-files
17312 (insert
17313 (mapconcat
17314 (lambda (f) ;; Keep un-expanded entries.
17315 (if (setq u (assoc f fe))
17316 (cdr u)
17318 list "\n")
17319 "\n")))
17320 (let ((org-mode-hook nil) (org-inhibit-startup t)
17321 (org-insert-mode-line-in-empty-file nil))
17322 (setq org-agenda-files list)
17323 (customize-save-variable 'org-agenda-files org-agenda-files))))
17325 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17326 "Read the list of agenda files from a file.
17327 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17328 filenames, used by `org-store-new-agenda-file-list' to write back
17329 un-expanded file names."
17330 (when (file-directory-p org-agenda-files)
17331 (error "`org-agenda-files' cannot be a single directory"))
17332 (when (stringp org-agenda-files)
17333 (with-temp-buffer
17334 (insert-file-contents org-agenda-files)
17335 (mapcar
17336 (lambda (f)
17337 (let ((e (expand-file-name (substitute-in-file-name f)
17338 org-directory)))
17339 (if pair-with-expansion
17340 (cons e f)
17341 e)))
17342 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17344 ;;;###autoload
17345 (defun org-cycle-agenda-files ()
17346 "Cycle through the files in `org-agenda-files'.
17347 If the current buffer visits an agenda file, find the next one in the list.
17348 If the current buffer does not, find the first agenda file."
17349 (interactive)
17350 (let* ((fs (org-agenda-files t))
17351 (files (append fs (list (car fs))))
17352 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17353 file)
17354 (unless files (error "No agenda files"))
17355 (catch 'exit
17356 (while (setq file (pop files))
17357 (if (equal (file-truename file) tcf)
17358 (when (car files)
17359 (find-file (car files))
17360 (throw 'exit t))))
17361 (find-file (car fs)))
17362 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17364 (defun org-agenda-file-to-front (&optional to-end)
17365 "Move/add the current file to the top of the agenda file list.
17366 If the file is not present in the list, it is added to the front. If it is
17367 present, it is moved there. With optional argument TO-END, add/move to the
17368 end of the list."
17369 (interactive "P")
17370 (let ((org-agenda-skip-unavailable-files nil)
17371 (file-alist (mapcar (lambda (x)
17372 (cons (file-truename x) x))
17373 (org-agenda-files t)))
17374 (ctf (file-truename
17375 (or buffer-file-name
17376 (error "Please save the current buffer to a file"))))
17377 x had)
17378 (setq x (assoc ctf file-alist) had x)
17380 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17381 (if to-end
17382 (setq file-alist (append (delq x file-alist) (list x)))
17383 (setq file-alist (cons x (delq x file-alist))))
17384 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17385 (org-install-agenda-files-menu)
17386 (message "File %s to %s of agenda file list"
17387 (if had "moved" "added") (if to-end "end" "front"))))
17389 (defun org-remove-file (&optional file)
17390 "Remove current file from the list of files in variable `org-agenda-files'.
17391 These are the files which are being checked for agenda entries.
17392 Optional argument FILE means use this file instead of the current."
17393 (interactive)
17394 (let* ((org-agenda-skip-unavailable-files nil)
17395 (file (or file buffer-file-name
17396 (error "Current buffer does not visit a file")))
17397 (true-file (file-truename file))
17398 (afile (abbreviate-file-name file))
17399 (files (delq nil (mapcar
17400 (lambda (x)
17401 (if (equal true-file
17402 (file-truename x))
17403 nil x))
17404 (org-agenda-files t)))))
17405 (if (not (= (length files) (length (org-agenda-files t))))
17406 (progn
17407 (org-store-new-agenda-file-list files)
17408 (org-install-agenda-files-menu)
17409 (message "Removed file: %s" afile))
17410 (message "File was not in list: %s (not removed)" afile))))
17412 (defun org-file-menu-entry (file)
17413 (vector file (list 'find-file file) t))
17415 (defun org-check-agenda-file (file)
17416 "Make sure FILE exists. If not, ask user what to do."
17417 (when (not (file-exists-p file))
17418 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17419 (abbreviate-file-name file))
17420 (let ((r (downcase (read-char-exclusive))))
17421 (cond
17422 ((equal r ?r)
17423 (org-remove-file file)
17424 (throw 'nextfile t))
17425 (t (error "Abort"))))))
17427 (defun org-get-agenda-file-buffer (file)
17428 "Get a buffer visiting FILE. If the buffer needs to be created, add
17429 it to the list of buffers which might be released later."
17430 (let ((buf (org-find-base-buffer-visiting file)))
17431 (if buf
17432 buf ; just return it
17433 ;; Make a new buffer and remember it
17434 (setq buf (find-file-noselect file))
17435 (if buf (push buf org-agenda-new-buffers))
17436 buf)))
17438 (defun org-release-buffers (blist)
17439 "Release all buffers in list, asking the user for confirmation when needed.
17440 When a buffer is unmodified, it is just killed. When modified, it is saved
17441 \(if the user agrees) and then killed."
17442 (let (buf file)
17443 (while (setq buf (pop blist))
17444 (setq file (buffer-file-name buf))
17445 (when (and (buffer-modified-p buf)
17446 file
17447 (y-or-n-p (format "Save file %s? " file)))
17448 (with-current-buffer buf (save-buffer)))
17449 (kill-buffer buf))))
17451 (defun org-agenda-prepare-buffers (files)
17452 "Create buffers for all agenda files, protect archived trees and comments."
17453 (interactive)
17454 (let ((pa '(:org-archived t))
17455 (pc '(:org-comment t))
17456 (pall '(:org-archived t :org-comment t))
17457 (inhibit-read-only t)
17458 (org-inhibit-startup org-agenda-inhibit-startup)
17459 (rea (concat ":" org-archive-tag ":"))
17460 bmp file re)
17461 (save-excursion
17462 (save-restriction
17463 (while (setq file (pop files))
17464 (catch 'nextfile
17465 (if (bufferp file)
17466 (set-buffer file)
17467 (org-check-agenda-file file)
17468 (set-buffer (org-get-agenda-file-buffer file)))
17469 (widen)
17470 (setq bmp (buffer-modified-p))
17471 (org-refresh-category-properties)
17472 (org-refresh-properties org-effort-property 'org-effort)
17473 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17474 (setq org-todo-keywords-for-agenda
17475 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17476 (setq org-done-keywords-for-agenda
17477 (append org-done-keywords-for-agenda org-done-keywords))
17478 (setq org-todo-keyword-alist-for-agenda
17479 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17480 (setq org-drawers-for-agenda
17481 (append org-drawers-for-agenda org-drawers))
17482 (setq org-tag-alist-for-agenda
17483 (append org-tag-alist-for-agenda org-tag-alist))
17485 (save-excursion
17486 (remove-text-properties (point-min) (point-max) pall)
17487 (when org-agenda-skip-archived-trees
17488 (goto-char (point-min))
17489 (while (re-search-forward rea nil t)
17490 (if (org-at-heading-p t)
17491 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17492 (goto-char (point-min))
17493 (setq re (format org-heading-keyword-regexp-format
17494 org-comment-string))
17495 (while (re-search-forward re nil t)
17496 (add-text-properties
17497 (match-beginning 0) (org-end-of-subtree t) pc)))
17498 (set-buffer-modified-p bmp)))))
17499 (setq org-todo-keywords-for-agenda
17500 (org-uniquify org-todo-keywords-for-agenda))
17501 (setq org-todo-keyword-alist-for-agenda
17502 (org-uniquify org-todo-keyword-alist-for-agenda)
17503 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17507 ;;;; CDLaTeX minor mode
17509 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17510 "Keymap for the minor `org-cdlatex-mode'.")
17512 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17513 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17514 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17515 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17516 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17518 (defvar org-cdlatex-texmathp-advice-is-done nil
17519 "Flag remembering if we have applied the advice to texmathp already.")
17521 (define-minor-mode org-cdlatex-mode
17522 "Toggle the minor `org-cdlatex-mode'.
17523 This mode supports entering LaTeX environment and math in LaTeX fragments
17524 in Org-mode.
17525 \\{org-cdlatex-mode-map}"
17526 nil " OCDL" nil
17527 (when org-cdlatex-mode
17528 (require 'cdlatex)
17529 (run-hooks 'cdlatex-mode-hook)
17530 (cdlatex-compute-tables))
17531 (unless org-cdlatex-texmathp-advice-is-done
17532 (setq org-cdlatex-texmathp-advice-is-done t)
17533 (defadvice texmathp (around org-math-always-on activate)
17534 "Always return t in org-mode buffers.
17535 This is because we want to insert math symbols without dollars even outside
17536 the LaTeX math segments. If Orgmode thinks that point is actually inside
17537 an embedded LaTeX fragment, let texmathp do its job.
17538 \\[org-cdlatex-mode-map]"
17539 (interactive)
17540 (let (p)
17541 (cond
17542 ((not (derived-mode-p 'org-mode)) ad-do-it)
17543 ((eq this-command 'cdlatex-math-symbol)
17544 (setq ad-return-value t
17545 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17547 (let ((p (org-inside-LaTeX-fragment-p)))
17548 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17549 (setq ad-return-value t
17550 texmathp-why '("Org-mode embedded math" . 0))
17551 (if p ad-do-it)))))))))
17553 (defun turn-on-org-cdlatex ()
17554 "Unconditionally turn on `org-cdlatex-mode'."
17555 (org-cdlatex-mode 1))
17557 (defun org-try-cdlatex-tab ()
17558 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17559 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17560 - inside a LaTeX fragment, or
17561 - after the first word in a line, where an abbreviation expansion could
17562 insert a LaTeX environment."
17563 (when org-cdlatex-mode
17564 (cond
17565 ;; Before any word on the line: No expansion possible.
17566 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17567 ;; Just after first word on the line: Expand it. Make sure it
17568 ;; cannot happen on headlines, though.
17569 ((save-excursion
17570 (skip-chars-backward "a-zA-Z0-9*")
17571 (skip-chars-backward " \t")
17572 (and (bolp) (not (org-at-heading-p))))
17573 (cdlatex-tab) t)
17574 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17576 (defun org-cdlatex-underscore-caret (&optional arg)
17577 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17578 Revert to the normal definition outside of these fragments."
17579 (interactive "P")
17580 (if (org-inside-LaTeX-fragment-p)
17581 (call-interactively 'cdlatex-sub-superscript)
17582 (let (org-cdlatex-mode)
17583 (call-interactively (key-binding (vector last-input-event))))))
17585 (defun org-cdlatex-math-modify (&optional arg)
17586 "Execute `cdlatex-math-modify' in LaTeX fragments.
17587 Revert to the normal definition outside of these fragments."
17588 (interactive "P")
17589 (if (org-inside-LaTeX-fragment-p)
17590 (call-interactively 'cdlatex-math-modify)
17591 (let (org-cdlatex-mode)
17592 (call-interactively (key-binding (vector last-input-event))))))
17596 ;;;; LaTeX fragments
17598 (defvar org-latex-regexps
17599 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17600 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17601 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17602 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17603 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17604 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17605 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17606 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17607 "Regular expressions for matching embedded LaTeX.")
17609 (defun org-inside-LaTeX-fragment-p ()
17610 "Test if point is inside a LaTeX fragment.
17611 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17612 sequence appearing also before point.
17613 Even though the matchers for math are configurable, this function assumes
17614 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17615 delimiters are skipped when they have been removed by customization.
17616 The return value is nil, or a cons cell with the delimiter and the
17617 position of this delimiter.
17619 This function does a reasonably good job, but can locally be fooled by
17620 for example currency specifications. For example it will assume being in
17621 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17622 fragments that are properly closed, but during editing, we have to live
17623 with the uncertainty caused by missing closing delimiters. This function
17624 looks only before point, not after."
17625 (catch 'exit
17626 (let ((pos (point))
17627 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17628 (lim (progn
17629 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17630 (point)))
17631 dd-on str (start 0) m re)
17632 (goto-char pos)
17633 (when dodollar
17634 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17635 re (nth 1 (assoc "$" org-latex-regexps)))
17636 (while (string-match re str start)
17637 (cond
17638 ((= (match-end 0) (length str))
17639 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17640 ((= (match-end 0) (- (length str) 5))
17641 (throw 'exit nil))
17642 (t (setq start (match-end 0))))))
17643 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17644 (goto-char pos)
17645 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17646 (and (match-beginning 2) (throw 'exit nil))
17647 ;; count $$
17648 (while (re-search-backward "\\$\\$" lim t)
17649 (setq dd-on (not dd-on)))
17650 (goto-char pos)
17651 (if dd-on (cons "$$" m))))))
17653 (defun org-inside-latex-macro-p ()
17654 "Is point inside a LaTeX macro or its arguments?"
17655 (save-match-data
17656 (org-in-regexp
17657 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17659 (defvar org-latex-fragment-image-overlays nil
17660 "List of overlays carrying the images of latex fragments.")
17661 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17663 (defun org-remove-latex-fragment-image-overlays ()
17664 "Remove all overlays with LaTeX fragment images in current buffer."
17665 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17666 (setq org-latex-fragment-image-overlays nil))
17668 (defun org-preview-latex-fragment (&optional subtree)
17669 "Preview the LaTeX fragment at point, or all locally or globally.
17670 If the cursor is in a LaTeX fragment, create the image and overlay
17671 it over the source code. If there is no fragment at point, display
17672 all fragments in the current text, from one headline to the next. With
17673 prefix SUBTREE, display all fragments in the current subtree. With a
17674 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17675 the cursor is before the first headline,
17676 display all fragments in the buffer.
17677 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17678 (interactive "P")
17679 (unless buffer-file-name
17680 (error "Can't preview LaTeX fragment in a non-file buffer"))
17681 (org-remove-latex-fragment-image-overlays)
17682 (save-excursion
17683 (save-restriction
17684 (let (beg end at msg)
17685 (cond
17686 ((or (equal subtree '(16))
17687 (not (save-excursion
17688 (re-search-backward org-outline-regexp-bol nil t))))
17689 (setq beg (point-min) end (point-max)
17690 msg "Creating images for buffer...%s"))
17691 ((equal subtree '(4))
17692 (org-back-to-heading)
17693 (setq beg (point) end (org-end-of-subtree t)
17694 msg "Creating images for subtree...%s"))
17696 (if (setq at (org-inside-LaTeX-fragment-p))
17697 (goto-char (max (point-min) (- (cdr at) 2)))
17698 (org-back-to-heading))
17699 (setq beg (point) end (progn (outline-next-heading) (point))
17700 msg (if at "Creating image...%s"
17701 "Creating images for entry...%s"))))
17702 (message msg "")
17703 (narrow-to-region beg end)
17704 (goto-char beg)
17705 (org-format-latex
17706 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17707 (file-name-nondirectory
17708 buffer-file-name)))
17709 default-directory 'overlays msg at 'forbuffer
17710 org-latex-create-formula-image-program)
17711 (message msg "done. Use `C-c C-c' to remove images.")))))
17713 (defun org-format-latex (prefix &optional dir overlays msg at
17714 forbuffer processing-type)
17715 "Replace LaTeX fragments with links to an image, and produce images.
17716 Some of the options can be changed using the variable
17717 `org-format-latex-options'."
17718 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17719 (let* ((prefixnodir (file-name-nondirectory prefix))
17720 (absprefix (expand-file-name prefix dir))
17721 (todir (file-name-directory absprefix))
17722 (opt org-format-latex-options)
17723 (optnew org-format-latex-options)
17724 (matchers (plist-get opt :matchers))
17725 (re-list org-latex-regexps)
17726 (cnt 0) txt hash link beg end re e checkdir
17727 string
17728 m n block-type block linkfile movefile ov)
17729 ;; Check the different regular expressions
17730 (while (setq e (pop re-list))
17731 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17732 block (if block-type "\n\n" ""))
17733 (when (member m matchers)
17734 (goto-char (point-min))
17735 (while (re-search-forward re nil t)
17736 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17737 (or (not overlays)
17738 (not (eq (get-char-property (match-beginning n)
17739 'org-overlay-type)
17740 'org-latex-overlay))))
17741 (cond
17742 ((eq processing-type 'verbatim))
17743 ((eq processing-type 'mathjax)
17744 ;; Prepare for MathJax processing.
17745 (setq string (match-string n))
17746 (when (member m '("$" "$1"))
17747 (save-excursion
17748 (delete-region (match-beginning n) (match-end n))
17749 (goto-char (match-beginning n))
17750 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17751 ((or (eq processing-type 'dvipng)
17752 (eq processing-type 'imagemagick))
17753 ;; Process to an image.
17754 (setq txt (match-string n)
17755 beg (match-beginning n) end (match-end n)
17756 cnt (1+ cnt))
17757 (let ((face (face-at-point))
17758 (fg (plist-get opt :foreground))
17759 (bg (plist-get opt :background))
17760 ;; Ensure full list is printed.
17761 print-length print-level)
17762 (when forbuffer
17763 ;; Get the colors from the face at point.
17764 (goto-char beg)
17765 (when (eq fg 'auto)
17766 (setq fg (face-attribute face :foreground nil 'default)))
17767 (when (eq bg 'auto)
17768 (setq bg (face-attribute face :background nil 'default)))
17769 (setq optnew (copy-sequence opt))
17770 (plist-put optnew :foreground fg)
17771 (plist-put optnew :background bg))
17772 (setq hash (sha1 (prin1-to-string
17773 (list org-format-latex-header
17774 org-latex-default-packages-alist
17775 org-latex-packages-alist
17776 org-format-latex-options
17777 forbuffer txt fg bg)))
17778 linkfile (format "%s_%s.png" prefix hash)
17779 movefile (format "%s_%s.png" absprefix hash)))
17780 (setq link (concat block "[[file:" linkfile "]]" block))
17781 (if msg (message msg cnt))
17782 (goto-char beg)
17783 (unless checkdir ; Ensure the directory exists.
17784 (setq checkdir t)
17785 (or (file-directory-p todir) (make-directory todir t)))
17786 (unless (file-exists-p movefile)
17787 (org-create-formula-image
17788 txt movefile optnew forbuffer processing-type))
17789 (if overlays
17790 (progn
17791 (mapc (lambda (o)
17792 (if (eq (overlay-get o 'org-overlay-type)
17793 'org-latex-overlay)
17794 (delete-overlay o)))
17795 (overlays-in beg end))
17796 (setq ov (make-overlay beg end))
17797 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17798 (if (featurep 'xemacs)
17799 (progn
17800 (overlay-put ov 'invisible t)
17801 (overlay-put
17802 ov 'end-glyph
17803 (make-glyph (vector 'png :file movefile))))
17804 (overlay-put
17805 ov 'display
17806 (list 'image :type 'png :file movefile :ascent 'center)))
17807 (push ov org-latex-fragment-image-overlays)
17808 (goto-char end))
17809 (delete-region beg end)
17810 (insert (org-add-props link
17811 (list 'org-latex-src
17812 (replace-regexp-in-string
17813 "\"" "" txt)
17814 'org-latex-src-embed-type
17815 (if block-type 'paragraph 'character))))))
17816 ((eq processing-type 'mathml)
17817 ;; Process to MathML
17818 (unless (save-match-data (org-format-latex-mathml-available-p))
17819 (error "LaTeX to MathML converter not configured"))
17820 (setq txt (match-string n)
17821 beg (match-beginning n) end (match-end n)
17822 cnt (1+ cnt))
17823 (if msg (message msg cnt))
17824 (goto-char beg)
17825 (delete-region beg end)
17826 (insert (org-format-latex-as-mathml
17827 txt block-type prefix dir)))
17829 (error "Unknown conversion type %s for latex fragments"
17830 processing-type)))))))))
17832 (defun org-create-math-formula (latex-frag &optional mathml-file)
17833 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17834 Use `org-latex-to-mathml-convert-command'. If the conversion is
17835 sucessful, return the portion between \"<math...> </math>\"
17836 elements otherwise return nil. When MATHML-FILE is specified,
17837 write the results in to that file. When invoked as an
17838 interactive command, prompt for LATEX-FRAG, with initial value
17839 set to the current active region and echo the results for user
17840 inspection."
17841 (interactive (list (let ((frag (when (org-region-active-p)
17842 (buffer-substring-no-properties
17843 (region-beginning) (region-end)))))
17844 (read-string "LaTeX Fragment: " frag nil frag))))
17845 (unless latex-frag (error "Invalid latex-frag"))
17846 (let* ((tmp-in-file (file-relative-name
17847 (make-temp-name (expand-file-name "ltxmathml-in"))))
17848 (ignore (write-region latex-frag nil tmp-in-file))
17849 (tmp-out-file (file-relative-name
17850 (make-temp-name (expand-file-name "ltxmathml-out"))))
17851 (cmd (format-spec
17852 org-latex-to-mathml-convert-command
17853 `((?j . ,(shell-quote-argument
17854 (expand-file-name org-latex-to-mathml-jar-file)))
17855 (?I . ,(shell-quote-argument tmp-in-file))
17856 (?o . ,(shell-quote-argument tmp-out-file)))))
17857 mathml shell-command-output)
17858 (when (org-called-interactively-p 'any)
17859 (unless (org-format-latex-mathml-available-p)
17860 (error "LaTeX to MathML converter not configured")))
17861 (message "Running %s" cmd)
17862 (setq shell-command-output (shell-command-to-string cmd))
17863 (setq mathml
17864 (when (file-readable-p tmp-out-file)
17865 (with-current-buffer (find-file-noselect tmp-out-file t)
17866 (goto-char (point-min))
17867 (when (re-search-forward
17868 (concat
17869 (regexp-quote
17870 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17871 "\\(.\\|\n\\)*"
17872 (regexp-quote "</math>")) nil t)
17873 (prog1 (match-string 0) (kill-buffer))))))
17874 (cond
17875 (mathml
17876 (setq mathml
17877 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17878 (when mathml-file
17879 (write-region mathml nil mathml-file))
17880 (when (org-called-interactively-p 'any)
17881 (message mathml)))
17882 ((message "LaTeX to MathML conversion failed")
17883 (message shell-command-output)))
17884 (delete-file tmp-in-file)
17885 (when (file-exists-p tmp-out-file)
17886 (delete-file tmp-out-file))
17887 mathml))
17889 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17890 prefix &optional dir)
17891 "Use `org-create-math-formula' but check local cache first."
17892 (let* ((absprefix (expand-file-name prefix dir))
17893 (print-length nil) (print-level nil)
17894 (formula-id (concat
17895 "formula-"
17896 (sha1
17897 (prin1-to-string
17898 (list latex-frag
17899 org-latex-to-mathml-convert-command)))))
17900 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17901 (formula-cache-dir (file-name-directory formula-cache)))
17903 (unless (file-directory-p formula-cache-dir)
17904 (make-directory formula-cache-dir t))
17906 (unless (file-exists-p formula-cache)
17907 (org-create-math-formula latex-frag formula-cache))
17909 (if (file-exists-p formula-cache)
17910 ;; Successful conversion. Return the link to MathML file.
17911 (org-add-props
17912 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17913 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17914 'org-latex-src-embed-type (if latex-frag-type
17915 'paragraph 'character)))
17916 ;; Failed conversion. Return the LaTeX fragment verbatim
17917 latex-frag)))
17919 (defun org-create-formula-image (string tofile options buffer &optional type)
17920 "Create an image from LaTeX source using dvipng or convert.
17921 This function calls either `org-create-formula-image-with-dvipng'
17922 or `org-create-formula-image-with-imagemagick' depending on the
17923 value of `org-latex-create-formula-image-program' or on the value
17924 of the optional TYPE variable.
17926 Note: ultimately these two function should be combined as they
17927 share a good deal of logic."
17928 (org-check-external-command
17929 "latex" "needed to convert LaTeX fragments to images")
17930 (funcall
17931 (case (or type org-latex-create-formula-image-program)
17932 ('dvipng
17933 (org-check-external-command
17934 "dvipng" "needed to convert LaTeX fragments to images")
17935 #'org-create-formula-image-with-dvipng)
17936 ('imagemagick
17937 (org-check-external-command
17938 "convert" "you need to install imagemagick")
17939 #'org-create-formula-image-with-imagemagick)
17940 (t (error
17941 "invalid value of `org-latex-create-formula-image-program'")))
17942 string tofile options buffer))
17944 ;; This function borrows from Ganesh Swami's latex2png.el
17945 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17946 "This calls dvipng."
17947 (let* ((tmpdir (if (featurep 'xemacs)
17948 (temp-directory)
17949 temporary-file-directory))
17950 (texfilebase (make-temp-name
17951 (expand-file-name "orgtex" tmpdir)))
17952 (texfile (concat texfilebase ".tex"))
17953 (dvifile (concat texfilebase ".dvi"))
17954 (pngfile (concat texfilebase ".png"))
17955 (fnh (if (featurep 'xemacs)
17956 (font-height (face-font 'default))
17957 (face-attribute 'default :height nil)))
17958 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17959 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17960 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17961 "Black"))
17962 (bg (or (plist-get options (if buffer :background :html-background))
17963 "Transparent")))
17964 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17965 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17966 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17967 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17968 (with-temp-file texfile
17969 (require 'ox-latex)
17970 (insert (org-latex-guess-inputenc
17971 (org-splice-latex-header
17972 org-format-latex-header
17973 org-latex-default-packages-alist
17974 org-latex-packages-alist t)))
17975 (insert "\n\\begin{document}\n" string "\n\\end{document}\n"))
17976 (let ((dir default-directory))
17977 (condition-case nil
17978 (progn
17979 (cd tmpdir)
17980 (call-process "latex" nil nil nil texfile))
17981 (error nil))
17982 (cd dir))
17983 (if (not (file-exists-p dvifile))
17984 (progn (message "Failed to create dvi file from %s" texfile) nil)
17985 (condition-case nil
17986 (if (featurep 'xemacs)
17987 (call-process "dvipng" nil nil nil
17988 "-fg" fg "-bg" bg
17989 "-T" "tight"
17990 "-o" pngfile
17991 dvifile)
17992 (call-process "dvipng" nil nil nil
17993 "-fg" fg "-bg" bg
17994 "-D" dpi
17995 ;;"-x" scale "-y" scale
17996 "-T" "tight"
17997 "-o" pngfile
17998 dvifile))
17999 (error nil))
18000 (if (not (file-exists-p pngfile))
18001 (if org-format-latex-signal-error
18002 (error "Failed to create png file from %s" texfile)
18003 (message "Failed to create png file from %s" texfile)
18004 nil)
18005 ;; Use the requested file name and clean up
18006 (copy-file pngfile tofile 'replace)
18007 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18008 (if (file-exists-p (concat texfilebase e))
18009 (delete-file (concat texfilebase e))))
18010 pngfile))))
18012 (defvar org-latex-pdf-process) ; From ox-latex.el
18013 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18014 "This calls convert, which is included into imagemagick."
18015 (let* ((tmpdir (if (featurep 'xemacs)
18016 (temp-directory)
18017 temporary-file-directory))
18018 (texfilebase (make-temp-name
18019 (expand-file-name "orgtex" tmpdir)))
18020 (texfile (concat texfilebase ".tex"))
18021 (pdffile (concat texfilebase ".pdf"))
18022 (pngfile (concat texfilebase ".png"))
18023 (fnh (if (featurep 'xemacs)
18024 (font-height (face-font 'default))
18025 (face-attribute 'default :height nil)))
18026 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18027 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18028 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18029 "black"))
18030 (bg (or (plist-get options (if buffer :background :html-background))
18031 "white")))
18032 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18033 (setq fg (org-latex-color-format fg)))
18034 (if (eq bg 'default) (setq bg (org-latex-color :background))
18035 (setq bg (org-latex-color-format
18036 (if (string= bg "Transparent") "white" bg))))
18037 (with-temp-file texfile
18038 (require 'ox-latex)
18039 (insert (org-latex-guess-inputenc
18040 (org-splice-latex-header
18041 org-format-latex-header
18042 org-latex-default-packages-alist
18043 org-latex-packages-alist t)))
18044 (insert "\n\\begin{document}\n"
18045 "\\definecolor{fg}{rgb}{" fg "}\n"
18046 "\\definecolor{bg}{rgb}{" bg "}\n"
18047 "\n\\pagecolor{bg}\n"
18048 "\n{\\color{fg}\n"
18049 string
18050 "\n}\n"
18051 "\n\\end{document}\n"))
18052 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18053 (condition-case nil
18054 (progn
18055 (cd tmpdir)
18056 (setq cmds org-latex-pdf-process)
18057 (while cmds
18058 (setq latex-frags-cmds (pop cmds))
18059 (if (listp latex-frags-cmds)
18060 (setq cmds nil)
18061 (setq latex-frags-cmds (list (car org-latex-pdf-process)))))
18062 (while latex-frags-cmds
18063 (setq cmd (pop latex-frags-cmds))
18064 (while (string-match "%b" cmd)
18065 (setq cmd (replace-match
18066 (save-match-data
18067 (shell-quote-argument texfile))
18068 t t cmd)))
18069 (while (string-match "%f" cmd)
18070 (setq cmd (replace-match
18071 (save-match-data
18072 (shell-quote-argument
18073 (file-name-nondirectory texfile)))
18074 t t cmd)))
18075 (while (string-match "%o" cmd)
18076 (setq cmd (replace-match
18077 (save-match-data
18078 (shell-quote-argument
18079 (file-name-directory texfile)))
18080 t t cmd)))
18081 (setq cmd (split-string cmd))
18082 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18083 (error nil))
18084 (cd dir))
18085 (if (not (file-exists-p pdffile))
18086 (progn (message "Failed to create pdf file from %s" texfile) nil)
18087 (condition-case nil
18088 (if (featurep 'xemacs)
18089 (call-process "convert" nil nil nil
18090 "-density" "96"
18091 "-trim"
18092 "-antialias"
18093 pdffile
18094 "-quality" "100"
18095 ;; "-sharpen" "0x1.0"
18096 pngfile)
18097 (call-process "convert" nil nil nil
18098 "-density" dpi
18099 "-trim"
18100 "-antialias"
18101 pdffile
18102 "-quality" "100"
18103 ;; "-sharpen" "0x1.0"
18104 pngfile))
18105 (error nil))
18106 (if (not (file-exists-p pngfile))
18107 (if org-format-latex-signal-error
18108 (error "Failed to create png file from %s" texfile)
18109 (message "Failed to create png file from %s" texfile)
18110 nil)
18111 ;; Use the requested file name and clean up
18112 (copy-file pngfile tofile 'replace)
18113 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18114 (if (file-exists-p (concat texfilebase e))
18115 (delete-file (concat texfilebase e))))
18116 pngfile))))
18118 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18119 "Fill a LaTeX header template TPL.
18120 In the template, the following place holders will be recognized:
18122 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18123 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18124 [PACKAGES] \\usepackage statements for PKG
18125 [NO-PACKAGES] do not include PKG
18126 [EXTRA] the string EXTRA
18127 [NO-EXTRA] do not include EXTRA
18129 For backward compatibility, if both the positive and the negative place
18130 holder is missing, the positive one (without the \"NO-\") will be
18131 assumed to be present at the end of the template.
18132 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18133 EXTRA is a string.
18134 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18135 (let (rpl (end ""))
18136 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18137 (setq rpl (if (or (match-end 1) (not def-pkg))
18138 "" (org-latex-packages-to-string def-pkg snippets-p t))
18139 tpl (replace-match rpl t t tpl))
18140 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18142 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18143 (setq rpl (if (or (match-end 1) (not pkg))
18144 "" (org-latex-packages-to-string pkg snippets-p t))
18145 tpl (replace-match rpl t t tpl))
18146 (if pkg (setq end
18147 (concat end "\n"
18148 (org-latex-packages-to-string pkg snippets-p)))))
18150 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18151 (setq rpl (if (or (match-end 1) (not extra))
18152 "" (concat extra "\n"))
18153 tpl (replace-match rpl t t tpl))
18154 (if (and extra (string-match "\\S-" extra))
18155 (setq end (concat end "\n" extra))))
18157 (if (string-match "\\S-" end)
18158 (concat tpl "\n" end)
18159 tpl)))
18161 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18162 "Turn an alist of packages into a string with the \\usepackage macros."
18163 (setq pkg (mapconcat (lambda(p)
18164 (cond
18165 ((stringp p) p)
18166 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18167 (format "%% Package %s omitted" (cadr p)))
18168 ((equal "" (car p))
18169 (format "\\usepackage{%s}" (cadr p)))
18171 (format "\\usepackage[%s]{%s}"
18172 (car p) (cadr p)))))
18174 "\n"))
18175 (if newline (concat pkg "\n") pkg))
18177 (defun org-dvipng-color (attr)
18178 "Return a RGB color specification for dvipng."
18179 (apply 'format "rgb %s %s %s"
18180 (mapcar 'org-normalize-color
18181 (if (featurep 'xemacs)
18182 (color-rgb-components
18183 (face-property 'default
18184 (cond ((eq attr :foreground) 'foreground)
18185 ((eq attr :background) 'background))))
18186 (color-values (face-attribute 'default attr nil))))))
18188 (defun org-dvipng-color-format (color-name)
18189 "Convert COLOR-NAME to a RGB color value for dvipng."
18190 (apply 'format "rgb %s %s %s"
18191 (mapcar 'org-normalize-color
18192 (color-values color-name))))
18194 (defun org-latex-color (attr)
18195 "Return a RGB color for the LaTeX color package."
18196 (apply 'format "%s,%s,%s"
18197 (mapcar 'org-normalize-color
18198 (if (featurep 'xemacs)
18199 (color-rgb-components
18200 (face-property 'default
18201 (cond ((eq attr :foreground) 'foreground)
18202 ((eq attr :background) 'background))))
18203 (color-values (face-attribute 'default attr nil))))))
18205 (defun org-latex-color-format (color-name)
18206 "Convert COLOR-NAME to a RGB color value."
18207 (apply 'format "%s,%s,%s"
18208 (mapcar 'org-normalize-color
18209 (color-values color-name))))
18211 (defun org-normalize-color (value)
18212 "Return string to be used as color value for an RGB component."
18213 (format "%g" (/ value 65535.0)))
18217 ;; Image display
18219 (defvar org-inline-image-overlays nil)
18220 (make-variable-buffer-local 'org-inline-image-overlays)
18222 (defun org-toggle-inline-images (&optional include-linked)
18223 "Toggle the display of inline images.
18224 INCLUDE-LINKED is passed to `org-display-inline-images'."
18225 (interactive "P")
18226 (if org-inline-image-overlays
18227 (progn
18228 (org-remove-inline-images)
18229 (message "Inline image display turned off"))
18230 (org-display-inline-images include-linked)
18231 (if (and (org-called-interactively-p)
18232 org-inline-image-overlays)
18233 (message "%d images displayed inline"
18234 (length org-inline-image-overlays))
18235 (message "No images to display inline"))))
18237 (defun org-redisplay-inline-images ()
18238 "Refresh the display of inline images."
18239 (interactive)
18240 (if (not org-inline-image-overlays)
18241 (org-toggle-inline-images)
18242 (org-toggle-inline-images)
18243 (org-toggle-inline-images)))
18245 (defun org-display-inline-images (&optional include-linked refresh beg end)
18246 "Display inline images.
18247 Normally only links without a description part are inlined, because this
18248 is how it will work for export. When INCLUDE-LINKED is set, also links
18249 with a description part will be inlined. This can be nice for a quick
18250 look at those images, but it does not reflect what exported files will look
18251 like.
18252 When REFRESH is set, refresh existing images between BEG and END.
18253 This will create new image displays only if necessary.
18254 BEG and END default to the buffer boundaries."
18255 (interactive "P")
18256 (unless refresh
18257 (org-remove-inline-images)
18258 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18259 (save-excursion
18260 (save-restriction
18261 (widen)
18262 (setq beg (or beg (point-min)) end (or end (point-max)))
18263 (goto-char beg)
18264 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18265 (substring (org-image-file-name-regexp) 0 -2)
18266 "\\)\\]" (if include-linked "" "\\]")))
18267 old file ov img type attrwidth width)
18268 (while (re-search-forward re end t)
18269 (setq old (get-char-property-and-overlay (match-beginning 1)
18270 'org-image-overlay)
18271 file (expand-file-name
18272 (concat (or (match-string 3) "") (match-string 4))))
18273 (when (image-type-available-p 'imagemagick)
18274 (setq attrwidth (if (or (listp org-image-actual-width)
18275 (null org-image-actual-width))
18276 (save-excursion
18277 (save-match-data
18278 (when (re-search-backward
18279 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18280 (save-excursion
18281 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18282 (string-to-number (match-string 1))))))
18283 width (cond ((eq org-image-actual-width t) nil)
18284 ((null org-image-actual-width) attrwidth)
18285 ((numberp org-image-actual-width)
18286 org-image-actual-width)
18287 ((listp org-image-actual-width)
18288 (or attrwidth (car org-image-actual-width))))
18289 type (if width 'imagemagick)))
18290 (when (file-exists-p file)
18291 (if (and (car-safe old) refresh)
18292 (image-refresh (overlay-get (cdr old) 'display))
18293 (setq img (save-match-data (create-image file type nil :width width)))
18294 (when img
18295 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18296 (overlay-put ov 'display img)
18297 (overlay-put ov 'face 'default)
18298 (overlay-put ov 'org-image-overlay t)
18299 (overlay-put ov 'modification-hooks
18300 (list 'org-display-inline-remove-overlay))
18301 (push ov org-inline-image-overlays)))))))))
18303 (define-obsolete-function-alias
18304 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18306 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18307 "Remove inline-display overlay if a corresponding region is modified."
18308 (let ((inhibit-modification-hooks t))
18309 (when (and ov after)
18310 (delete ov org-inline-image-overlays)
18311 (delete-overlay ov))))
18313 (defun org-remove-inline-images ()
18314 "Remove inline display of images."
18315 (interactive)
18316 (mapc 'delete-overlay org-inline-image-overlays)
18317 (setq org-inline-image-overlays nil))
18319 ;;;; Key bindings
18321 ;; Outline functions from `outline-mode-prefix-map'
18322 ;; that can be remapped in Org:
18323 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18324 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18325 (define-key org-mode-map [remap outline-forward-same-level]
18326 'org-forward-heading-same-level)
18327 (define-key org-mode-map [remap outline-backward-same-level]
18328 'org-backward-heading-same-level)
18329 (define-key org-mode-map [remap show-branches]
18330 'org-kill-note-or-show-branches)
18331 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18332 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18333 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18335 ;; Outline functions from `outline-mode-prefix-map' that can not
18336 ;; be remapped in Org:
18338 ;; - the column "key binding" shows whether the Outline function is still
18339 ;; available in Org mode on the same key that it has been bound to in
18340 ;; Outline mode:
18341 ;; - "overridden": key used for a different functionality in Org mode
18342 ;; - else: key still bound to the same Outline function in Org mode
18344 ;; | Outline function | key binding | Org replacement |
18345 ;; |------------------------------------+-------------+-----------------------|
18346 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18347 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18348 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18349 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18350 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18351 ;; | `show-entry' | overridden | no replacement |
18352 ;; | `show-children' | `C-c C-i' | visibility cycling |
18353 ;; | `show-branches' | `C-c C-k' | still same function |
18354 ;; | `show-subtree' | overridden | visibility cycling |
18355 ;; | `show-all' | overridden | no replacement |
18356 ;; | `hide-subtree' | overridden | visibility cycling |
18357 ;; | `hide-body' | overridden | no replacement |
18358 ;; | `hide-entry' | overridden | visibility cycling |
18359 ;; | `hide-leaves' | overridden | no replacement |
18360 ;; | `hide-sublevels' | overridden | no replacement |
18361 ;; | `hide-other' | overridden | no replacement |
18363 ;; Make `C-c C-x' a prefix key
18364 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18366 ;; TAB key with modifiers
18367 (org-defkey org-mode-map "\C-i" 'org-cycle)
18368 (org-defkey org-mode-map [(tab)] 'org-cycle)
18369 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18370 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18371 ;; The following line is necessary under Suse GNU/Linux
18372 (unless (featurep 'xemacs)
18373 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18374 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18375 (define-key org-mode-map [backtab] 'org-shifttab)
18377 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18378 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18379 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18381 ;; Cursor keys with modifiers
18382 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18383 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18384 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18385 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18387 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18388 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18389 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18390 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18392 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18393 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18394 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18395 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18397 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18398 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18399 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18400 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18402 ;; Babel keys
18403 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18404 (mapc (lambda (pair)
18405 (define-key org-babel-map (car pair) (cdr pair)))
18406 org-babel-key-bindings)
18408 ;;; Extra keys for tty access.
18409 ;; We only set them when really needed because otherwise the
18410 ;; menus don't show the simple keys
18412 (when (or org-use-extra-keys
18413 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18414 (not window-system))
18415 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18416 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18417 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18418 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18419 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18420 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18421 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18422 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18423 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18424 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18425 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18426 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18427 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18428 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18429 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18430 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18431 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18432 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18433 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18434 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18435 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18436 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18437 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18438 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18439 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18440 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18441 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18442 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18444 ;; All the other keys
18446 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18447 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18448 (if (boundp 'narrow-map)
18449 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18450 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18451 (if (boundp 'narrow-map)
18452 (org-defkey narrow-map "b" 'org-narrow-to-block)
18453 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18454 (if (boundp 'narrow-map)
18455 (org-defkey narrow-map "e" 'org-narrow-to-element)
18456 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18457 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18458 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18459 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18460 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18461 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18462 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18463 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18464 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18465 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18466 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18467 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18468 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18469 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18470 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18471 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18472 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18473 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18474 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18475 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18476 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18477 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18478 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18479 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18480 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18481 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18482 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18483 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18484 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18485 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18486 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18487 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18488 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18489 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18490 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18491 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18492 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18493 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18494 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18495 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18496 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18497 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18498 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18499 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18500 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18501 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18502 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18503 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18504 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18505 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18506 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18507 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18508 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18509 (org-defkey org-mode-map "\C-c^" 'org-sort)
18510 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18511 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18512 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18513 (org-defkey org-mode-map "\C-m" 'org-return)
18514 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18515 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18516 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18517 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18518 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18519 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18520 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18521 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18522 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18523 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18524 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18525 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18526 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18527 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18528 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18529 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18530 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18531 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18532 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18533 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18534 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18535 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18536 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18538 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18539 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18540 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18542 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18543 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18544 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18545 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18546 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18547 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18548 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18549 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18550 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18551 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18552 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18553 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18554 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18555 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18556 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18557 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18558 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18559 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18560 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18561 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18562 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18563 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18564 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18566 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18567 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18568 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18569 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18570 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18572 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18574 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18576 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18577 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18579 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18582 (when (featurep 'xemacs)
18583 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18586 (defconst org-speed-commands-default
18588 ("Outline Navigation")
18589 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18590 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18591 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18592 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18593 ("u" . (org-speed-move-safe 'outline-up-heading))
18594 ("j" . org-goto)
18595 ("g" . (org-refile t))
18596 ("Outline Visibility")
18597 ("c" . org-cycle)
18598 ("C" . org-shifttab)
18599 (" " . org-display-outline-path)
18600 ("=" . org-columns)
18601 ("Outline Structure Editing")
18602 ("U" . org-shiftmetaup)
18603 ("D" . org-shiftmetadown)
18604 ("r" . org-metaright)
18605 ("l" . org-metaleft)
18606 ("R" . org-shiftmetaright)
18607 ("L" . org-shiftmetaleft)
18608 ("i" . (progn (forward-char 1) (call-interactively
18609 'org-insert-heading-respect-content)))
18610 ("^" . org-sort)
18611 ("w" . org-refile)
18612 ("a" . org-archive-subtree-default-with-confirmation)
18613 ("." . org-mark-subtree)
18614 ("#" . org-toggle-comment)
18615 ("Clock Commands")
18616 ("I" . org-clock-in)
18617 ("O" . org-clock-out)
18618 ("Meta Data Editing")
18619 ("t" . org-todo)
18620 ("," . (org-priority))
18621 ("0" . (org-priority ?\ ))
18622 ("1" . (org-priority ?A))
18623 ("2" . (org-priority ?B))
18624 ("3" . (org-priority ?C))
18625 (":" . org-set-tags-command)
18626 ("e" . org-set-effort)
18627 ("E" . org-inc-effort)
18628 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18629 (org-entry-put (point) "APPT_WARNTIME" m)))
18630 ("Agenda Views etc")
18631 ("v" . org-agenda)
18632 ("/" . org-sparse-tree)
18633 ("Misc")
18634 ("o" . org-open-at-point)
18635 ("?" . org-speed-command-help)
18636 ("<" . (org-agenda-set-restriction-lock 'subtree))
18637 (">" . (org-agenda-remove-restriction-lock))
18639 "The default speed commands.")
18641 (defun org-print-speed-command (e)
18642 (if (> (length (car e)) 1)
18643 (progn
18644 (princ "\n")
18645 (princ (car e))
18646 (princ "\n")
18647 (princ (make-string (length (car e)) ?-))
18648 (princ "\n"))
18649 (princ (car e))
18650 (princ " ")
18651 (if (symbolp (cdr e))
18652 (princ (symbol-name (cdr e)))
18653 (prin1 (cdr e)))
18654 (princ "\n")))
18656 (defun org-speed-command-help ()
18657 "Show the available speed commands."
18658 (interactive)
18659 (if (not org-use-speed-commands)
18660 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18661 (with-output-to-temp-buffer "*Help*"
18662 (princ "User-defined Speed commands\n===========================\n")
18663 (mapc 'org-print-speed-command org-speed-commands-user)
18664 (princ "\n")
18665 (princ "Built-in Speed commands\n=======================\n")
18666 (mapc 'org-print-speed-command org-speed-commands-default))
18667 (with-current-buffer "*Help*"
18668 (setq truncate-lines t))))
18670 (defun org-speed-move-safe (cmd)
18671 "Execute CMD, but make sure that the cursor always ends up in a headline.
18672 If not, return to the original position and throw an error."
18673 (interactive)
18674 (let ((pos (point)))
18675 (call-interactively cmd)
18676 (unless (and (bolp) (org-at-heading-p))
18677 (goto-char pos)
18678 (error "Boundary reached while executing %s" cmd))))
18680 (defvar org-self-insert-command-undo-counter 0)
18682 (defvar org-table-auto-blank-field) ; defined in org-table.el
18683 (defvar org-speed-command nil)
18685 (define-obsolete-function-alias
18686 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18688 (defun org-speed-command-activate (keys)
18689 "Hook for activating single-letter speed commands.
18690 `org-speed-commands-default' specifies a minimal command set.
18691 Use `org-speed-commands-user' for further customization."
18692 (when (or (and (bolp) (looking-at org-outline-regexp))
18693 (and (functionp org-use-speed-commands)
18694 (funcall org-use-speed-commands)))
18695 (cdr (assoc keys (append org-speed-commands-user
18696 org-speed-commands-default)))))
18698 (define-obsolete-function-alias
18699 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18701 (defun org-babel-speed-command-activate (keys)
18702 "Hook for activating single-letter code block commands."
18703 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18704 (cdr (assoc keys org-babel-key-bindings))))
18706 (defcustom org-speed-command-hook
18707 '(org-speed-command-default-hook org-babel-speed-command-hook)
18708 "Hook for activating speed commands at strategic locations.
18709 Hook functions are called in sequence until a valid handler is
18710 found.
18712 Each hook takes a single argument, a user-pressed command key
18713 which is also a `self-insert-command' from the global map.
18715 Within the hook, examine the cursor position and the command key
18716 and return nil or a valid handler as appropriate. Handler could
18717 be one of an interactive command, a function, or a form.
18719 Set `org-use-speed-commands' to non-nil value to enable this
18720 hook. The default setting is `org-speed-command-activate'."
18721 :group 'org-structure
18722 :version "24.1"
18723 :type 'hook)
18725 (defun org-self-insert-command (N)
18726 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18727 If the cursor is in a table looking at whitespace, the whitespace is
18728 overwritten, and the table is not marked as requiring realignment."
18729 (interactive "p")
18730 (org-check-before-invisible-edit 'insert)
18731 (cond
18732 ((and org-use-speed-commands
18733 (setq org-speed-command
18734 (run-hook-with-args-until-success
18735 'org-speed-command-hook (this-command-keys))))
18736 (cond
18737 ((commandp org-speed-command)
18738 (setq this-command org-speed-command)
18739 (call-interactively org-speed-command))
18740 ((functionp org-speed-command)
18741 (funcall org-speed-command))
18742 ((and org-speed-command (listp org-speed-command))
18743 (eval org-speed-command))
18744 (t (let (org-use-speed-commands)
18745 (call-interactively 'org-self-insert-command)))))
18746 ((and
18747 (org-table-p)
18748 (progn
18749 ;; check if we blank the field, and if that triggers align
18750 (and (featurep 'org-table) org-table-auto-blank-field
18751 (member last-command
18752 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18753 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18754 ;; got extra space, this field does not determine column width
18755 (let (org-table-may-need-update) (org-table-blank-field))
18756 ;; no extra space, this field may determine column width
18757 (org-table-blank-field)))
18759 (eq N 1)
18760 (looking-at "[^|\n]* |"))
18761 (let (org-table-may-need-update)
18762 (goto-char (1- (match-end 0)))
18763 (backward-delete-char 1)
18764 (goto-char (match-beginning 0))
18765 (self-insert-command N)))
18767 (setq org-table-may-need-update t)
18768 (self-insert-command N)
18769 (org-fix-tags-on-the-fly)
18770 (if org-self-insert-cluster-for-undo
18771 (if (not (eq last-command 'org-self-insert-command))
18772 (setq org-self-insert-command-undo-counter 1)
18773 (if (>= org-self-insert-command-undo-counter 20)
18774 (setq org-self-insert-command-undo-counter 1)
18775 (and (> org-self-insert-command-undo-counter 0)
18776 buffer-undo-list (listp buffer-undo-list)
18777 (not (cadr buffer-undo-list)) ; remove nil entry
18778 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18779 (setq org-self-insert-command-undo-counter
18780 (1+ org-self-insert-command-undo-counter))))))))
18782 (defun org-check-before-invisible-edit (kind)
18783 "Check is editing if kind KIND would be dangerous with invisible text around.
18784 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18785 ;; First, try to get out of here as quickly as possible, to reduce overhead
18786 (if (and org-catch-invisible-edits
18787 (or (not (boundp 'visible-mode)) (not visible-mode))
18788 (or (get-char-property (point) 'invisible)
18789 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18790 ;; OK, we need to take a closer look
18791 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18792 (invisible-before-point (if (bobp) nil (get-char-property
18793 (1- (point)) 'invisible)))
18794 (border-and-ok-direction
18796 ;; Check if we are acting predictably before invisible text
18797 (and invisible-at-point (not invisible-before-point)
18798 (memq kind '(insert delete-backward)))
18799 ;; Check if we are acting predictably after invisible text
18800 ;; This works not well, and I have turned it off. It seems
18801 ;; better to always show and stop after invisible text.
18802 ;; (and (not invisible-at-point) invisible-before-point
18803 ;; (memq kind '(insert delete)))
18805 (when (or (memq invisible-at-point '(outline org-hide-block t))
18806 (memq invisible-before-point '(outline org-hide-block t)))
18807 (if (eq org-catch-invisible-edits 'error)
18808 (error "Editing in invisible areas is prohibited - make visible first"))
18809 (if (and org-custom-properties-overlays
18810 (y-or-n-p "Display invisible properties in this buffer? "))
18811 (org-toggle-custom-properties-visibility)
18812 ;; Make the area visible
18813 (save-excursion
18814 (if invisible-before-point
18815 (goto-char (previous-single-char-property-change
18816 (point) 'invisible)))
18817 (org-cycle))
18818 (cond
18819 ((eq org-catch-invisible-edits 'show)
18820 ;; That's it, we do the edit after showing
18821 (message
18822 "Unfolding invisible region around point before editing")
18823 (sit-for 1))
18824 ((and (eq org-catch-invisible-edits 'smart)
18825 border-and-ok-direction)
18826 (message "Unfolding invisible region around point before editing"))
18828 ;; Don't do the edit, make the user repeat it in full visibility
18829 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18831 (defun org-fix-tags-on-the-fly ()
18832 (when (and (equal (char-after (point-at-bol)) ?*)
18833 (org-at-heading-p))
18834 (org-align-tags-here org-tags-column)))
18836 (defun org-delete-backward-char (N)
18837 "Like `delete-backward-char', insert whitespace at field end in tables.
18838 When deleting backwards, in tables this function will insert whitespace in
18839 front of the next \"|\" separator, to keep the table aligned. The table will
18840 still be marked for re-alignment if the field did fill the entire column,
18841 because, in this case the deletion might narrow the column."
18842 (interactive "p")
18843 (save-match-data
18844 (org-check-before-invisible-edit 'delete-backward)
18845 (if (and (org-table-p)
18846 (eq N 1)
18847 (string-match "|" (buffer-substring (point-at-bol) (point)))
18848 (looking-at ".*?|"))
18849 (let ((pos (point))
18850 (noalign (looking-at "[^|\n\r]* |"))
18851 (c org-table-may-need-update))
18852 (backward-delete-char N)
18853 (if (not overwrite-mode)
18854 (progn
18855 (skip-chars-forward "^|")
18856 (insert " ")
18857 (goto-char (1- pos))))
18858 ;; noalign: if there were two spaces at the end, this field
18859 ;; does not determine the width of the column.
18860 (if noalign (setq org-table-may-need-update c)))
18861 (backward-delete-char N)
18862 (org-fix-tags-on-the-fly))))
18864 (defun org-delete-char (N)
18865 "Like `delete-char', but insert whitespace at field end in tables.
18866 When deleting characters, in tables this function will insert whitespace in
18867 front of the next \"|\" separator, to keep the table aligned. The table will
18868 still be marked for re-alignment if the field did fill the entire column,
18869 because, in this case the deletion might narrow the column."
18870 (interactive "p")
18871 (save-match-data
18872 (org-check-before-invisible-edit 'delete)
18873 (if (and (org-table-p)
18874 (not (bolp))
18875 (not (= (char-after) ?|))
18876 (eq N 1))
18877 (if (looking-at ".*?|")
18878 (let ((pos (point))
18879 (noalign (looking-at "[^|\n\r]* |"))
18880 (c org-table-may-need-update))
18881 (replace-match (concat
18882 (substring (match-string 0) 1 -1)
18883 " |"))
18884 (goto-char pos)
18885 ;; noalign: if there were two spaces at the end, this field
18886 ;; does not determine the width of the column.
18887 (if noalign (setq org-table-may-need-update c)))
18888 (delete-char N))
18889 (delete-char N)
18890 (org-fix-tags-on-the-fly))))
18892 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18893 (put 'org-self-insert-command 'delete-selection t)
18894 (put 'orgtbl-self-insert-command 'delete-selection t)
18895 (put 'org-delete-char 'delete-selection 'supersede)
18896 (put 'org-delete-backward-char 'delete-selection 'supersede)
18897 (put 'org-yank 'delete-selection 'yank)
18899 ;; Make `flyspell-mode' delay after some commands
18900 (put 'org-self-insert-command 'flyspell-delayed t)
18901 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18902 (put 'org-delete-char 'flyspell-delayed t)
18903 (put 'org-delete-backward-char 'flyspell-delayed t)
18905 ;; Make pabbrev-mode expand after org-mode commands
18906 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18907 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18909 ;; How to do this: Measure non-white length of current string
18910 ;; If equal to column width, we should realign.
18912 (defun org-remap (map &rest commands)
18913 "In MAP, remap the functions given in COMMANDS.
18914 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18915 (let (new old)
18916 (while commands
18917 (setq old (pop commands) new (pop commands))
18918 (if (fboundp 'command-remapping)
18919 (org-defkey map (vector 'remap old) new)
18920 (substitute-key-definition old new map global-map)))))
18922 (when (eq org-enable-table-editor 'optimized)
18923 ;; If the user wants maximum table support, we need to hijack
18924 ;; some standard editing functions
18925 (org-remap org-mode-map
18926 'self-insert-command 'org-self-insert-command
18927 'delete-char 'org-delete-char
18928 'delete-backward-char 'org-delete-backward-char)
18929 (org-defkey org-mode-map "|" 'org-force-self-insert))
18931 (defvar org-ctrl-c-ctrl-c-hook nil
18932 "Hook for functions attaching themselves to `C-c C-c'.
18934 This can be used to add additional functionality to the C-c C-c
18935 key which executes context-dependent commands. This hook is run
18936 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18937 run after the last test.
18939 Each function will be called with no arguments. The function
18940 must check if the context is appropriate for it to act. If yes,
18941 it should do its thing and then return a non-nil value. If the
18942 context is wrong, just do nothing and return nil.")
18944 (defvar org-ctrl-c-ctrl-c-final-hook nil
18945 "Hook for functions attaching themselves to `C-c C-c'.
18947 This can be used to add additional functionality to the C-c C-c
18948 key which executes context-dependent commands. This hook is run
18949 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18950 before the first test.
18952 Each function will be called with no arguments. The function
18953 must check if the context is appropriate for it to act. If yes,
18954 it should do its thing and then return a non-nil value. If the
18955 context is wrong, just do nothing and return nil.")
18957 (defvar org-tab-first-hook nil
18958 "Hook for functions to attach themselves to TAB.
18959 See `org-ctrl-c-ctrl-c-hook' for more information.
18960 This hook runs as the first action when TAB is pressed, even before
18961 `org-cycle' messes around with the `outline-regexp' to cater for
18962 inline tasks and plain list item folding.
18963 If any function in this hook returns t, any other actions that
18964 would have been caused by TAB (such as table field motion or visibility
18965 cycling) will not occur.")
18967 (defvar org-tab-after-check-for-table-hook nil
18968 "Hook for functions to attach themselves to TAB.
18969 See `org-ctrl-c-ctrl-c-hook' for more information.
18970 This hook runs after it has been established that the cursor is not in a
18971 table, but before checking if the cursor is in a headline or if global cycling
18972 should be done.
18973 If any function in this hook returns t, not other actions like visibility
18974 cycling will be done.")
18976 (defvar org-tab-after-check-for-cycling-hook nil
18977 "Hook for functions to attach themselves to TAB.
18978 See `org-ctrl-c-ctrl-c-hook' for more information.
18979 This hook runs after it has been established that not table field motion and
18980 not visibility should be done because of current context. This is probably
18981 the place where a package like yasnippets can hook in.")
18983 (defvar org-tab-before-tab-emulation-hook nil
18984 "Hook for functions to attach themselves to TAB.
18985 See `org-ctrl-c-ctrl-c-hook' for more information.
18986 This hook runs after every other options for TAB have been exhausted, but
18987 before indentation and \t insertion takes place.")
18989 (defvar org-metaleft-hook nil
18990 "Hook for functions attaching themselves to `M-left'.
18991 See `org-ctrl-c-ctrl-c-hook' for more information.")
18992 (defvar org-metaright-hook nil
18993 "Hook for functions attaching themselves to `M-right'.
18994 See `org-ctrl-c-ctrl-c-hook' for more information.")
18995 (defvar org-metaup-hook nil
18996 "Hook for functions attaching themselves to `M-up'.
18997 See `org-ctrl-c-ctrl-c-hook' for more information.")
18998 (defvar org-metadown-hook nil
18999 "Hook for functions attaching themselves to `M-down'.
19000 See `org-ctrl-c-ctrl-c-hook' for more information.")
19001 (defvar org-shiftmetaleft-hook nil
19002 "Hook for functions attaching themselves to `M-S-left'.
19003 See `org-ctrl-c-ctrl-c-hook' for more information.")
19004 (defvar org-shiftmetaright-hook nil
19005 "Hook for functions attaching themselves to `M-S-right'.
19006 See `org-ctrl-c-ctrl-c-hook' for more information.")
19007 (defvar org-shiftmetaup-hook nil
19008 "Hook for functions attaching themselves to `M-S-up'.
19009 See `org-ctrl-c-ctrl-c-hook' for more information.")
19010 (defvar org-shiftmetadown-hook nil
19011 "Hook for functions attaching themselves to `M-S-down'.
19012 See `org-ctrl-c-ctrl-c-hook' for more information.")
19013 (defvar org-metareturn-hook nil
19014 "Hook for functions attaching themselves to `M-RET'.
19015 See `org-ctrl-c-ctrl-c-hook' for more information.")
19016 (defvar org-shiftup-hook nil
19017 "Hook for functions attaching themselves to `S-up'.
19018 See `org-ctrl-c-ctrl-c-hook' for more information.")
19019 (defvar org-shiftup-final-hook nil
19020 "Hook for functions attaching themselves to `S-up'.
19021 This one runs after all other options except shift-select have been excluded.
19022 See `org-ctrl-c-ctrl-c-hook' for more information.")
19023 (defvar org-shiftdown-hook nil
19024 "Hook for functions attaching themselves to `S-down'.
19025 See `org-ctrl-c-ctrl-c-hook' for more information.")
19026 (defvar org-shiftdown-final-hook nil
19027 "Hook for functions attaching themselves to `S-down'.
19028 This one runs after all other options except shift-select have been excluded.
19029 See `org-ctrl-c-ctrl-c-hook' for more information.")
19030 (defvar org-shiftleft-hook nil
19031 "Hook for functions attaching themselves to `S-left'.
19032 See `org-ctrl-c-ctrl-c-hook' for more information.")
19033 (defvar org-shiftleft-final-hook nil
19034 "Hook for functions attaching themselves to `S-left'.
19035 This one runs after all other options except shift-select have been excluded.
19036 See `org-ctrl-c-ctrl-c-hook' for more information.")
19037 (defvar org-shiftright-hook nil
19038 "Hook for functions attaching themselves to `S-right'.
19039 See `org-ctrl-c-ctrl-c-hook' for more information.")
19040 (defvar org-shiftright-final-hook nil
19041 "Hook for functions attaching themselves to `S-right'.
19042 This one runs after all other options except shift-select have been excluded.
19043 See `org-ctrl-c-ctrl-c-hook' for more information.")
19045 (defun org-modifier-cursor-error ()
19046 "Throw an error, a modified cursor command was applied in wrong context."
19047 (error "This command is active in special context like tables, headlines or items"))
19049 (defun org-shiftselect-error ()
19050 "Throw an error because Shift-Cursor command was applied in wrong context."
19051 (if (and (boundp 'shift-select-mode) shift-select-mode)
19052 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19053 (error "This command works only in special context like headlines or timestamps")))
19055 (defun org-call-for-shift-select (cmd)
19056 (let ((this-command-keys-shift-translated t))
19057 (call-interactively cmd)))
19059 (defun org-shifttab (&optional arg)
19060 "Global visibility cycling or move to previous table field.
19061 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19062 on context.
19063 See the individual commands for more information."
19064 (interactive "P")
19065 (cond
19066 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19067 ((integerp arg)
19068 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19069 (message "Content view to level: %d" arg)
19070 (org-content (prefix-numeric-value arg2))
19071 (setq org-cycle-global-status 'overview)))
19072 (t (call-interactively 'org-global-cycle))))
19074 (defun org-shiftmetaleft ()
19075 "Promote subtree or delete table column.
19076 Calls `org-promote-subtree', `org-outdent-item-tree', or
19077 `org-table-delete-column', depending on context. See the
19078 individual commands for more information."
19079 (interactive)
19080 (cond
19081 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19082 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19083 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19084 ((if (not (org-region-active-p)) (org-at-item-p)
19085 (save-excursion (goto-char (region-beginning))
19086 (org-at-item-p)))
19087 (call-interactively 'org-outdent-item-tree))
19088 (t (org-modifier-cursor-error))))
19090 (defun org-shiftmetaright ()
19091 "Demote subtree or insert table column.
19092 Calls `org-demote-subtree', `org-indent-item-tree', or
19093 `org-table-insert-column', depending on context. See the
19094 individual commands for more information."
19095 (interactive)
19096 (cond
19097 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19098 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19099 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19100 ((if (not (org-region-active-p)) (org-at-item-p)
19101 (save-excursion (goto-char (region-beginning))
19102 (org-at-item-p)))
19103 (call-interactively 'org-indent-item-tree))
19104 (t (org-modifier-cursor-error))))
19106 (defun org-shiftmetaup (&optional arg)
19107 "Move subtree up or kill table row.
19108 Calls `org-move-subtree-up' or `org-table-kill-row' or
19109 `org-move-item-up' or `org-timestamp-up', depending on context.
19110 See the individual commands for more information."
19111 (interactive "P")
19112 (cond
19113 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19114 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19115 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19116 ((org-at-item-p) (call-interactively 'org-move-item-up))
19117 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19118 (call-interactively 'org-timestamp-up)))
19119 (t (org-modifier-cursor-error))))
19121 (defun org-shiftmetadown (&optional arg)
19122 "Move subtree down or insert table row.
19123 Calls `org-move-subtree-down' or `org-table-insert-row' or
19124 `org-move-item-down' or `org-timestamp-up', depending on context.
19125 See the individual commands for more information."
19126 (interactive "P")
19127 (cond
19128 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19129 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19130 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19131 ((org-at-item-p) (call-interactively 'org-move-item-down))
19132 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19133 (call-interactively 'org-timestamp-down)))
19134 (t (org-modifier-cursor-error))))
19136 (defsubst org-hidden-tree-error ()
19137 (error
19138 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19140 (defun org-metaleft (&optional arg)
19141 "Promote heading or move table column to left.
19142 Calls `org-do-promote' or `org-table-move-column', depending on context.
19143 With no specific context, calls the Emacs default `backward-word'.
19144 See the individual commands for more information."
19145 (interactive "P")
19146 (cond
19147 ((run-hook-with-args-until-success 'org-metaleft-hook))
19148 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19149 ((org-with-limited-levels
19150 (or (org-at-heading-p)
19151 (and (org-region-active-p)
19152 (save-excursion
19153 (goto-char (region-beginning))
19154 (org-at-heading-p)))))
19155 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19156 (call-interactively 'org-do-promote))
19157 ;; At an inline task.
19158 ((org-at-heading-p)
19159 (call-interactively 'org-inlinetask-promote))
19160 ((or (org-at-item-p)
19161 (and (org-region-active-p)
19162 (save-excursion
19163 (goto-char (region-beginning))
19164 (org-at-item-p))))
19165 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19166 (call-interactively 'org-outdent-item))
19167 (t (call-interactively 'backward-word))))
19169 (defun org-metaright (&optional arg)
19170 "Demote a subtree, a list item or move table column to right.
19171 In front of a drawer or a block keyword, indent it correctly.
19172 With no specific context, calls the Emacs default `forward-word'.
19173 See the individual commands for more information."
19174 (interactive "P")
19175 (cond
19176 ((run-hook-with-args-until-success 'org-metaright-hook))
19177 ((org-at-table-p) (call-interactively 'org-table-move-column))
19178 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19179 ((org-at-block-p) (call-interactively 'org-indent-block))
19180 ((org-with-limited-levels
19181 (or (org-at-heading-p)
19182 (and (org-region-active-p)
19183 (save-excursion
19184 (goto-char (region-beginning))
19185 (org-at-heading-p)))))
19186 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19187 (call-interactively 'org-do-demote))
19188 ;; At an inline task.
19189 ((org-at-heading-p)
19190 (call-interactively 'org-inlinetask-demote))
19191 ((or (org-at-item-p)
19192 (and (org-region-active-p)
19193 (save-excursion
19194 (goto-char (region-beginning))
19195 (org-at-item-p))))
19196 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19197 (call-interactively 'org-indent-item))
19198 (t (call-interactively 'forward-word))))
19200 (defun org-check-for-hidden (what)
19201 "Check if there are hidden headlines/items in the current visual line.
19202 WHAT can be either `headlines' or `items'. If the current line is
19203 an outline or item heading and it has a folded subtree below it,
19204 this function returns t, nil otherwise."
19205 (let ((re (cond
19206 ((eq what 'headlines) org-outline-regexp-bol)
19207 ((eq what 'items) (org-item-beginning-re))
19208 (t (error "This should not happen"))))
19209 beg end)
19210 (save-excursion
19211 (catch 'exit
19212 (unless (org-region-active-p)
19213 (setq beg (point-at-bol))
19214 (beginning-of-line 2)
19215 (while (and (not (eobp)) ;; this is like `next-line'
19216 (get-char-property (1- (point)) 'invisible))
19217 (beginning-of-line 2))
19218 (setq end (point))
19219 (goto-char beg)
19220 (goto-char (point-at-eol))
19221 (setq end (max end (point)))
19222 (while (re-search-forward re end t)
19223 (if (get-char-property (match-beginning 0) 'invisible)
19224 (throw 'exit t))))
19225 nil))))
19227 (defun org-metaup (&optional arg)
19228 "Move subtree up or move table row up.
19229 Calls `org-move-subtree-up' or `org-table-move-row' or
19230 `org-move-item-up', depending on context. See the individual commands
19231 for more information."
19232 (interactive "P")
19233 (cond
19234 ((run-hook-with-args-until-success 'org-metaup-hook))
19235 ((org-region-active-p)
19236 (let* ((a (min (region-beginning) (region-end)))
19237 (b (1- (max (region-beginning) (region-end))))
19238 (c (save-excursion (goto-char a)
19239 (move-beginning-of-line 0)))
19240 (d (save-excursion (goto-char a)
19241 (move-end-of-line 0) (point))))
19242 (transpose-regions a b c d)
19243 (goto-char c)))
19244 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19245 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19246 ((org-at-item-p) (call-interactively 'org-move-item-up))
19247 (t (org-drag-element-backward))))
19249 (defun org-metadown (&optional arg)
19250 "Move subtree down or move table row down.
19251 Calls `org-move-subtree-down' or `org-table-move-row' or
19252 `org-move-item-down', depending on context. See the individual
19253 commands for more information."
19254 (interactive "P")
19255 (cond
19256 ((run-hook-with-args-until-success 'org-metadown-hook))
19257 ((org-region-active-p)
19258 (let* ((a (min (region-beginning) (region-end)))
19259 (b (max (region-beginning) (region-end)))
19260 (c (save-excursion (goto-char b)
19261 (move-beginning-of-line 1)))
19262 (d (save-excursion (goto-char b)
19263 (move-end-of-line 1) (1+ (point)))))
19264 (transpose-regions a b c d)
19265 (goto-char d)))
19266 ((org-at-table-p) (call-interactively 'org-table-move-row))
19267 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19268 ((org-at-item-p) (call-interactively 'org-move-item-down))
19269 (t (org-drag-element-forward))))
19271 (defun org-shiftup (&optional arg)
19272 "Increase item in timestamp or increase priority of current headline.
19273 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19274 depending on context. See the individual commands for more information."
19275 (interactive "P")
19276 (cond
19277 ((run-hook-with-args-until-success 'org-shiftup-hook))
19278 ((and org-support-shift-select (org-region-active-p))
19279 (org-call-for-shift-select 'previous-line))
19280 ((org-at-timestamp-p t)
19281 (call-interactively (if org-edit-timestamp-down-means-later
19282 'org-timestamp-down 'org-timestamp-up)))
19283 ((and (not (eq org-support-shift-select 'always))
19284 org-enable-priority-commands
19285 (org-at-heading-p))
19286 (call-interactively 'org-priority-up))
19287 ((and (not org-support-shift-select) (org-at-item-p))
19288 (call-interactively 'org-previous-item))
19289 ((org-clocktable-try-shift 'up arg))
19290 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19291 (org-support-shift-select
19292 (org-call-for-shift-select 'previous-line))
19293 (t (org-shiftselect-error))))
19295 (defun org-shiftdown (&optional arg)
19296 "Decrease item in timestamp or decrease priority of current headline.
19297 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19298 depending on context. See the individual commands for more information."
19299 (interactive "P")
19300 (cond
19301 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19302 ((and org-support-shift-select (org-region-active-p))
19303 (org-call-for-shift-select 'next-line))
19304 ((org-at-timestamp-p t)
19305 (call-interactively (if org-edit-timestamp-down-means-later
19306 'org-timestamp-up 'org-timestamp-down)))
19307 ((and (not (eq org-support-shift-select 'always))
19308 org-enable-priority-commands
19309 (org-at-heading-p))
19310 (call-interactively 'org-priority-down))
19311 ((and (not org-support-shift-select) (org-at-item-p))
19312 (call-interactively 'org-next-item))
19313 ((org-clocktable-try-shift 'down arg))
19314 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19315 (org-support-shift-select
19316 (org-call-for-shift-select 'next-line))
19317 (t (org-shiftselect-error))))
19319 (defun org-shiftright (&optional arg)
19320 "Cycle the thing at point or in the current line, depending on context.
19321 Depending on context, this does one of the following:
19323 - switch a timestamp at point one day into the future
19324 - on a headline, switch to the next TODO keyword.
19325 - on an item, switch entire list to the next bullet type
19326 - on a property line, switch to the next allowed value
19327 - on a clocktable definition line, move time block into the future"
19328 (interactive "P")
19329 (cond
19330 ((run-hook-with-args-until-success 'org-shiftright-hook))
19331 ((and org-support-shift-select (org-region-active-p))
19332 (org-call-for-shift-select 'forward-char))
19333 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19334 ((and (not (eq org-support-shift-select 'always))
19335 (org-at-heading-p))
19336 (let ((org-inhibit-logging
19337 (not org-treat-S-cursor-todo-selection-as-state-change))
19338 (org-inhibit-blocking
19339 (not org-treat-S-cursor-todo-selection-as-state-change)))
19340 (org-call-with-arg 'org-todo 'right)))
19341 ((or (and org-support-shift-select
19342 (not (eq org-support-shift-select 'always))
19343 (org-at-item-bullet-p))
19344 (and (not org-support-shift-select) (org-at-item-p)))
19345 (org-call-with-arg 'org-cycle-list-bullet nil))
19346 ((and (not (eq org-support-shift-select 'always))
19347 (org-at-property-p))
19348 (call-interactively 'org-property-next-allowed-value))
19349 ((org-clocktable-try-shift 'right arg))
19350 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19351 (org-support-shift-select
19352 (org-call-for-shift-select 'forward-char))
19353 (t (org-shiftselect-error))))
19355 (defun org-shiftleft (&optional arg)
19356 "Cycle the thing at point or in the current line, depending on context.
19357 Depending on context, this does one of the following:
19359 - switch a timestamp at point one day into the past
19360 - on a headline, switch to the previous TODO keyword.
19361 - on an item, switch entire list to the previous bullet type
19362 - on a property line, switch to the previous allowed value
19363 - on a clocktable definition line, move time block into the past"
19364 (interactive "P")
19365 (cond
19366 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19367 ((and org-support-shift-select (org-region-active-p))
19368 (org-call-for-shift-select 'backward-char))
19369 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19370 ((and (not (eq org-support-shift-select 'always))
19371 (org-at-heading-p))
19372 (let ((org-inhibit-logging
19373 (not org-treat-S-cursor-todo-selection-as-state-change))
19374 (org-inhibit-blocking
19375 (not org-treat-S-cursor-todo-selection-as-state-change)))
19376 (org-call-with-arg 'org-todo 'left)))
19377 ((or (and org-support-shift-select
19378 (not (eq org-support-shift-select 'always))
19379 (org-at-item-bullet-p))
19380 (and (not org-support-shift-select) (org-at-item-p)))
19381 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19382 ((and (not (eq org-support-shift-select 'always))
19383 (org-at-property-p))
19384 (call-interactively 'org-property-previous-allowed-value))
19385 ((org-clocktable-try-shift 'left arg))
19386 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19387 (org-support-shift-select
19388 (org-call-for-shift-select 'backward-char))
19389 (t (org-shiftselect-error))))
19391 (defun org-shiftcontrolright ()
19392 "Switch to next TODO set."
19393 (interactive)
19394 (cond
19395 ((and org-support-shift-select (org-region-active-p))
19396 (org-call-for-shift-select 'forward-word))
19397 ((and (not (eq org-support-shift-select 'always))
19398 (org-at-heading-p))
19399 (org-call-with-arg 'org-todo 'nextset))
19400 (org-support-shift-select
19401 (org-call-for-shift-select 'forward-word))
19402 (t (org-shiftselect-error))))
19404 (defun org-shiftcontrolleft ()
19405 "Switch to previous TODO set."
19406 (interactive)
19407 (cond
19408 ((and org-support-shift-select (org-region-active-p))
19409 (org-call-for-shift-select 'backward-word))
19410 ((and (not (eq org-support-shift-select 'always))
19411 (org-at-heading-p))
19412 (org-call-with-arg 'org-todo 'previousset))
19413 (org-support-shift-select
19414 (org-call-for-shift-select 'backward-word))
19415 (t (org-shiftselect-error))))
19417 (defun org-shiftcontrolup (&optional n)
19418 "Change timestamps synchronously up in CLOCK log lines.
19419 Optional argument N tells to change by that many units."
19420 (interactive "P")
19421 (cond ((and (not org-support-shift-select)
19422 (org-at-clock-log-p)
19423 (org-at-timestamp-p t))
19424 (org-clock-timestamps-up n))
19425 (t (org-shiftselect-error))))
19427 (defun org-shiftcontroldown (&optional n)
19428 "Change timestamps synchronously down in CLOCK log lines.
19429 Optional argument N tells to change by that many units."
19430 (interactive "P")
19431 (cond ((and (not org-support-shift-select)
19432 (org-at-clock-log-p)
19433 (org-at-timestamp-p t))
19434 (org-clock-timestamps-down n))
19435 (t (org-shiftselect-error))))
19437 (defun org-ctrl-c-ret ()
19438 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19439 (interactive)
19440 (cond
19441 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19442 (t (call-interactively 'org-insert-heading))))
19444 (defun org-find-visible ()
19445 (let ((s (point)))
19446 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19447 (get-char-property s 'invisible)))
19449 (defun org-find-invisible ()
19450 (let ((s (point)))
19451 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19452 (not (get-char-property s 'invisible))))
19455 (defun org-copy-visible (beg end)
19456 "Copy the visible parts of the region."
19457 (interactive "r")
19458 (let (snippets s)
19459 (save-excursion
19460 (save-restriction
19461 (narrow-to-region beg end)
19462 (setq s (goto-char (point-min)))
19463 (while (not (= (point) (point-max)))
19464 (goto-char (org-find-invisible))
19465 (push (buffer-substring s (point)) snippets)
19466 (setq s (goto-char (org-find-visible))))))
19467 (kill-new (apply 'concat (nreverse snippets)))))
19469 (defun org-copy-special ()
19470 "Copy region in table or copy current subtree.
19471 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19472 See the individual commands for more information."
19473 (interactive)
19474 (call-interactively
19475 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19477 (defun org-cut-special ()
19478 "Cut region in table or cut current subtree.
19479 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19480 See the individual commands for more information."
19481 (interactive)
19482 (call-interactively
19483 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19485 (defun org-paste-special (arg)
19486 "Paste rectangular region into table, or past subtree relative to level.
19487 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19488 See the individual commands for more information."
19489 (interactive "P")
19490 (if (org-at-table-p)
19491 (org-table-paste-rectangle)
19492 (org-paste-subtree arg)))
19494 (defsubst org-in-fixed-width-region-p ()
19495 "Is point in a fixed-width region?"
19496 (save-match-data
19497 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19499 (defun org-edit-special (&optional arg)
19500 "Call a special editor for the element at point.
19501 When at a table, call the formula editor with `org-table-edit-formulas'.
19502 When in a source code block, call `org-edit-src-code'.
19503 When in a fixed-width region, call `org-edit-fixed-width-region'.
19504 When at an #+INCLUDE keyword, visit the included file.
19505 On a link, call `ffap' to visit the link at point.
19506 Otherwise, return a user error."
19507 (interactive)
19508 (let ((element (org-element-at-point)))
19509 (case (org-element-type element)
19510 (src-block
19511 (if (not arg) (org-edit-src-code)
19512 (let* ((info (org-babel-get-src-block-info))
19513 (lang (nth 0 info))
19514 (params (nth 2 info))
19515 (session (cdr (assq :session params))))
19516 (if (not session) (org-edit-src-code)
19517 ;; At a src-block with a session and function called with
19518 ;; an ARG: switch to the buffer related to the inferior
19519 ;; process.
19520 (funcall (intern (concat "org-babel-prep-session:" lang))
19521 session params)))))
19522 (keyword
19523 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19524 (find-file
19525 (org-remove-double-quotes
19526 (car (org-split-string (org-element-property :value element)))))
19527 (user-error "No special environment to edit here")))
19528 (table
19529 (if (eq (org-element-property :type element) 'table.el)
19530 (org-edit-src-code)
19531 (call-interactively 'org-table-edit-formulas)))
19532 ;; Only Org tables contain `table-row' type elements.
19533 (table-row (call-interactively 'org-table-edit-formulas))
19534 ((example-block export-block) (org-edit-src-code))
19535 (fixed-width (org-edit-fixed-width-region))
19536 (otherwise
19537 ;; No notable element at point. Though, we may be at a link,
19538 ;; which is an object. Thus, scan deeper.
19539 (if (eq (org-element-type (org-element-context element)) 'link)
19540 (call-interactively 'ffap)
19541 (user-error "No special environment to edit here"))))))
19543 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19544 (defun org-ctrl-c-ctrl-c (&optional arg)
19545 "Set tags in headline, or update according to changed information at point.
19547 This command does many different things, depending on context:
19549 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19550 this is what we do.
19552 - If the cursor is on a statistics cookie, update it.
19554 - If the cursor is in a headline, prompt for tags and insert them
19555 into the current line, aligned to `org-tags-column'. When called
19556 with prefix arg, realign all tags in the current buffer.
19558 - If the cursor is in one of the special #+KEYWORD lines, this
19559 triggers scanning the buffer for these lines and updating the
19560 information.
19562 - If the cursor is inside a table, realign the table. This command
19563 works even if the automatic table editor has been turned off.
19565 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19566 the entire table.
19568 - If the cursor is at a footnote reference or definition, jump to
19569 the corresponding definition or references, respectively.
19571 - If the cursor is a the beginning of a dynamic block, update it.
19573 - If the current buffer is a capture buffer, close note and file it.
19575 - If the cursor is on a <<<target>>>, update radio targets and
19576 corresponding links in this buffer.
19578 - If the cursor is on a numbered item in a plain list, renumber the
19579 ordered list.
19581 - If the cursor is on a checkbox, toggle it.
19583 - If the cursor is on a code block, evaluate it. The variable
19584 `org-confirm-babel-evaluate' can be used to control prompting
19585 before code block evaluation, by default every code block
19586 evaluation requires confirmation. Code block evaluation can be
19587 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19588 (interactive "P")
19589 (cond
19590 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19591 org-occur-highlights
19592 org-latex-fragment-image-overlays)
19593 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19594 (org-remove-occur-highlights)
19595 (org-remove-latex-fragment-image-overlays)
19596 (message "Temporary highlights/overlays removed from current buffer"))
19597 ((and (local-variable-p 'org-finish-function (current-buffer))
19598 (fboundp org-finish-function))
19599 (funcall org-finish-function))
19600 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19602 (let* ((context (org-element-context)) (type (org-element-type context)))
19603 ;; Test if point is within blanks at the end of an element.
19604 (if (save-excursion
19605 (or (not context)
19606 (beginning-of-line)
19607 (and (looking-at "[ \t]*$")
19608 (skip-chars-forward " \r\t\n")
19609 (>= (point) (org-element-property :end context)))))
19610 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19611 (user-error "C-c C-c can do nothing useful at this location"))
19612 ;; For convenience: at the first line of a paragraph on the
19613 ;; same line as an item, apply function on that item instead.
19614 (when (eq type 'paragraph)
19615 (let ((parent (org-element-property :parent context)))
19616 (when (and (eq (org-element-type parent) 'item)
19617 (= (point-at-bol) (org-element-property :begin parent)))
19618 (setq context parent type 'item))))
19619 ;; Act according to type of element or object at point.
19620 (case type
19621 (clock (org-clock-update-time-maybe))
19622 (dynamic-block
19623 (save-excursion
19624 (goto-char (org-element-property :post-affiliated context))
19625 (org-update-dblock)))
19626 (footnote-definition
19627 (goto-char (org-element-property :post-affiliated context))
19628 (call-interactively 'org-footnote-action))
19629 (footnote-reference (call-interactively 'org-footnote-action))
19630 ((headline inlinetask)
19631 (save-excursion (goto-char (org-element-property :begin context))
19632 (call-interactively 'org-set-tags)))
19633 (item
19634 ;; At an item: a double C-u set checkbox to "[-]"
19635 ;; unconditionally, whereas a single one will toggle its
19636 ;; presence. Without an universal argument, if the item
19637 ;; has a checkbox, toggle it. Otherwise repair the list.
19638 (let* ((box (org-element-property :checkbox context))
19639 (struct (org-element-property :structure context))
19640 (old-struct (copy-tree struct))
19641 (parents (org-list-parents-alist struct))
19642 (prevs (org-list-prevs-alist struct))
19643 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19644 (org-list-set-checkbox
19645 (org-element-property :begin context) struct
19646 (cond ((equal arg '(16)) "[-]")
19647 ((and (not box) (equal arg '(4))) "[ ]")
19648 ((or (not box) (equal arg '(4))) nil)
19649 ((eq box 'on) "[ ]")
19650 (t "[X]")))
19651 ;; Mimic `org-list-write-struct' but with grabbing
19652 ;; a return value from `org-list-struct-fix-box'.
19653 (org-list-struct-fix-ind struct parents 2)
19654 (org-list-struct-fix-item-end struct)
19655 (org-list-struct-fix-bul struct prevs)
19656 (org-list-struct-fix-ind struct parents)
19657 (let ((block-item
19658 (org-list-struct-fix-box struct parents prevs orderedp)))
19659 (if (and box (equal struct old-struct))
19660 (if (equal arg '(16))
19661 (message "Checkboxes already reset")
19662 (user-error "Cannot toggle this checkbox: %s"
19663 (if (eq box 'on)
19664 "all subitems checked"
19665 "unchecked subitems")))
19666 (org-list-struct-apply-struct struct old-struct)
19667 (org-update-checkbox-count-maybe))
19668 (when block-item
19669 (message "Checkboxes were removed due to empty box at line %d"
19670 (org-current-line block-item))))))
19671 (keyword
19672 (let ((org-inhibit-startup-visibility-stuff t)
19673 (org-startup-align-all-tables nil))
19674 (when (boundp 'org-table-coordinate-overlays)
19675 (mapc 'delete-overlay org-table-coordinate-overlays)
19676 (setq org-table-coordinate-overlays nil))
19677 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19678 (message "Local setup has been refreshed"))
19679 (plain-list
19680 ;; At a plain list, with a double C-u argument, set
19681 ;; checkboxes of each item to "[-]", whereas a single one
19682 ;; will toggle their presence according to the state of the
19683 ;; first item in the list. Without an argument, repair the
19684 ;; list.
19685 (let* ((begin (org-element-property :contents-begin context))
19686 (struct (org-element-property :structure context))
19687 (old-struct (copy-tree struct))
19688 (first-box (save-excursion
19689 (goto-char begin)
19690 (looking-at org-list-full-item-re)
19691 (match-string-no-properties 3)))
19692 (new-box (cond ((equal arg '(16)) "[-]")
19693 ((equal arg '(4)) (unless first-box "[ ]"))
19694 ((equal first-box "[X]") "[ ]")
19695 (t "[X]"))))
19696 (cond
19697 (arg
19698 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19699 (org-list-get-all-items
19700 begin struct (org-list-prevs-alist struct))))
19701 ((and first-box (eq (point) begin))
19702 ;; For convenience, when point is at bol on the first
19703 ;; item of the list and no argument is provided, simply
19704 ;; toggle checkbox of that item, if any.
19705 (org-list-set-checkbox begin struct new-box)))
19706 (org-list-write-struct
19707 struct (org-list-parents-alist struct) old-struct)
19708 (org-update-checkbox-count-maybe)
19709 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19710 ((property-drawer node-property)
19711 (call-interactively 'org-property-action))
19712 ((radio-target target)
19713 (call-interactively 'org-update-radio-target-regexp))
19714 (statistics-cookie
19715 (call-interactively 'org-update-statistics-cookies))
19716 ((table table-cell table-row)
19717 ;; At a table, recalculate every field and align it. Also
19718 ;; send the table if necessary. If the table has
19719 ;; a `table.el' type, just give up. At a table row or
19720 ;; cell, maybe recalculate line but always align table.
19721 (if (eq (org-element-property :type context) 'table.el)
19722 (message "Use C-c ' to edit table.el tables")
19723 (let ((org-enable-table-editor t))
19724 (if (or (eq type 'table)
19725 ;; Check if point is at a TBLFM line.
19726 (and (eq type 'table-row)
19727 (= (point) (org-element-property :end context))))
19728 (save-excursion
19729 (goto-char (org-element-property :contents-begin context))
19730 (org-call-with-arg 'org-table-recalculate (or arg t))
19731 (orgtbl-send-table 'maybe))
19732 (org-table-maybe-eval-formula)
19733 (cond (arg (call-interactively 'org-table-recalculate))
19734 ((org-table-maybe-recalculate-line))
19735 (t (org-table-align)))))))
19736 (timestamp (org-timestamp-change 0 'day))
19737 (otherwise
19738 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19739 (user-error
19740 "C-c C-c can do nothing useful at this location")))))))))
19742 (defun org-mode-restart ()
19743 "Restart Org-mode, to scan again for special lines.
19744 Also updates the keyword regular expressions."
19745 (interactive)
19746 (org-mode)
19747 (message "Org-mode restarted"))
19749 (defun org-kill-note-or-show-branches ()
19750 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19751 (interactive)
19752 (if (not org-finish-function)
19753 (progn
19754 (hide-subtree)
19755 (call-interactively 'show-branches))
19756 (let ((org-note-abort t))
19757 (funcall org-finish-function))))
19759 (defun org-return (&optional indent)
19760 "Goto next table row or insert a newline.
19761 Calls `org-table-next-row' or `newline', depending on context.
19762 See the individual commands for more information."
19763 (interactive)
19764 (let (org-ts-what)
19765 (cond
19766 ((or (bobp) (org-in-src-block-p))
19767 (if indent (newline-and-indent) (newline)))
19768 ((org-at-table-p)
19769 (org-table-justify-field-maybe)
19770 (call-interactively 'org-table-next-row))
19771 ;; when `newline-and-indent' is called within a list, make sure
19772 ;; text moved stays inside the item.
19773 ((and (org-in-item-p) indent)
19774 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19775 (progn
19776 (save-match-data (newline))
19777 (org-indent-line-to (length (match-string 0))))
19778 (let ((ind (org-get-indentation)))
19779 (newline)
19780 (if (org-looking-back org-list-end-re)
19781 (org-indent-line)
19782 (org-indent-line-to ind)))))
19783 ((and org-return-follows-link
19784 (org-at-timestamp-p t)
19785 (not (eq org-ts-what 'after)))
19786 (org-follow-timestamp-link))
19787 ((and org-return-follows-link
19788 (let ((tprop (get-text-property (point) 'face)))
19789 (or (eq tprop 'org-link)
19790 (and (listp tprop) (memq 'org-link tprop)))))
19791 (call-interactively 'org-open-at-point))
19792 ((and (org-at-heading-p)
19793 (looking-at
19794 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19795 (org-show-entry)
19796 (end-of-line 1)
19797 (newline))
19798 (t (if indent (newline-and-indent) (newline))))))
19800 (defun org-return-indent ()
19801 "Goto next table row or insert a newline and indent.
19802 Calls `org-table-next-row' or `newline-and-indent', depending on
19803 context. See the individual commands for more information."
19804 (interactive)
19805 (org-return t))
19807 (defun org-ctrl-c-star ()
19808 "Compute table, or change heading status of lines.
19809 Calls `org-table-recalculate' or `org-toggle-heading',
19810 depending on context."
19811 (interactive)
19812 (cond
19813 ((org-at-table-p)
19814 (call-interactively 'org-table-recalculate))
19816 ;; Convert all lines in region to list items
19817 (call-interactively 'org-toggle-heading))))
19819 (defun org-ctrl-c-minus ()
19820 "Insert separator line in table or modify bullet status of line.
19821 Also turns a plain line or a region of lines into list items.
19822 Calls `org-table-insert-hline', `org-toggle-item', or
19823 `org-cycle-list-bullet', depending on context."
19824 (interactive)
19825 (cond
19826 ((org-at-table-p)
19827 (call-interactively 'org-table-insert-hline))
19828 ((org-region-active-p)
19829 (call-interactively 'org-toggle-item))
19830 ((org-in-item-p)
19831 (call-interactively 'org-cycle-list-bullet))
19833 (call-interactively 'org-toggle-item))))
19835 (defun org-toggle-item (arg)
19836 "Convert headings or normal lines to items, items to normal lines.
19837 If there is no active region, only the current line is considered.
19839 If the first non blank line in the region is an headline, convert
19840 all headlines to items, shifting text accordingly.
19842 If it is an item, convert all items to normal lines.
19844 If it is normal text, change region into an item. With a prefix
19845 argument ARG, change each line in region into an item."
19846 (interactive "P")
19847 (let ((shift-text
19848 (function
19849 ;; Shift text in current section to IND, from point to END.
19850 ;; The function leaves point to END line.
19851 (lambda (ind end)
19852 (let ((min-i 1000) (end (copy-marker end)))
19853 ;; First determine the minimum indentation (MIN-I) of
19854 ;; the text.
19855 (save-excursion
19856 (catch 'exit
19857 (while (< (point) end)
19858 (let ((i (org-get-indentation)))
19859 (cond
19860 ;; Skip blank lines and inline tasks.
19861 ((looking-at "^[ \t]*$"))
19862 ((looking-at org-outline-regexp-bol))
19863 ;; We can't find less than 0 indentation.
19864 ((zerop i) (throw 'exit (setq min-i 0)))
19865 ((< i min-i) (setq min-i i))))
19866 (forward-line))))
19867 ;; Then indent each line so that a line indented to
19868 ;; MIN-I becomes indented to IND. Ignore blank lines
19869 ;; and inline tasks in the process.
19870 (let ((delta (- ind min-i)))
19871 (while (< (point) end)
19872 (unless (or (looking-at "^[ \t]*$")
19873 (looking-at org-outline-regexp-bol))
19874 (org-indent-line-to (+ (org-get-indentation) delta)))
19875 (forward-line)))))))
19876 (skip-blanks
19877 (function
19878 ;; Return beginning of first non-blank line, starting from
19879 ;; line at POS.
19880 (lambda (pos)
19881 (save-excursion
19882 (goto-char pos)
19883 (skip-chars-forward " \r\t\n")
19884 (point-at-bol)))))
19885 beg end)
19886 ;; Determine boundaries of changes.
19887 (if (org-region-active-p)
19888 (setq beg (funcall skip-blanks (region-beginning))
19889 end (copy-marker (region-end)))
19890 (setq beg (funcall skip-blanks (point-at-bol))
19891 end (copy-marker (point-at-eol))))
19892 ;; Depending on the starting line, choose an action on the text
19893 ;; between BEG and END.
19894 (org-with-limited-levels
19895 (save-excursion
19896 (goto-char beg)
19897 (cond
19898 ;; Case 1. Start at an item: de-itemize. Note that it only
19899 ;; happens when a region is active: `org-ctrl-c-minus'
19900 ;; would call `org-cycle-list-bullet' otherwise.
19901 ((org-at-item-p)
19902 (while (< (point) end)
19903 (when (org-at-item-p)
19904 (skip-chars-forward " \t")
19905 (delete-region (point) (match-end 0)))
19906 (forward-line)))
19907 ;; Case 2. Start at an heading: convert to items.
19908 ((org-at-heading-p)
19909 (let* ((bul (org-list-bullet-string "-"))
19910 (bul-len (length bul))
19911 ;; Indentation of the first heading. It should be
19912 ;; relative to the indentation of its parent, if any.
19913 (start-ind (save-excursion
19914 (cond
19915 ((not org-adapt-indentation) 0)
19916 ((not (outline-previous-heading)) 0)
19917 (t (length (match-string 0))))))
19918 ;; Level of first heading. Further headings will be
19919 ;; compared to it to determine hierarchy in the list.
19920 (ref-level (org-reduced-level (org-outline-level))))
19921 (while (< (point) end)
19922 (let* ((level (org-reduced-level (org-outline-level)))
19923 (delta (max 0 (- level ref-level))))
19924 ;; If current headline is less indented than the first
19925 ;; one, set it as reference, in order to preserve
19926 ;; subtrees.
19927 (when (< level ref-level) (setq ref-level level))
19928 (replace-match bul t t)
19929 (org-indent-line-to (+ start-ind (* delta bul-len)))
19930 ;; Ensure all text down to END (or SECTION-END) belongs
19931 ;; to the newly created item.
19932 (let ((section-end (save-excursion
19933 (or (outline-next-heading) (point)))))
19934 (forward-line)
19935 (funcall shift-text
19936 (+ start-ind (* (1+ delta) bul-len))
19937 (min end section-end)))))))
19938 ;; Case 3. Normal line with ARG: turn each non-item line into
19939 ;; an item.
19940 (arg
19941 (while (< (point) end)
19942 (unless (or (org-at-heading-p) (org-at-item-p))
19943 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19944 (replace-match
19945 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19946 (forward-line)))
19947 ;; Case 4. Normal line without ARG: make the first line of
19948 ;; region an item, and shift indentation of others
19949 ;; lines to set them as item's body.
19950 (t (let* ((bul (org-list-bullet-string "-"))
19951 (bul-len (length bul))
19952 (ref-ind (org-get-indentation)))
19953 (skip-chars-forward " \t")
19954 (insert bul)
19955 (forward-line)
19956 (while (< (point) end)
19957 ;; Ensure that lines less indented than first one
19958 ;; still get included in item body.
19959 (funcall shift-text
19960 (+ ref-ind bul-len)
19961 (min end (save-excursion (or (outline-next-heading)
19962 (point)))))
19963 (forward-line)))))))))
19965 (defun org-toggle-heading (&optional nstars)
19966 "Convert headings to normal text, or items or text to headings.
19967 If there is no active region, only the current line is considered.
19969 With a \\[universal-argument] prefix, convert the whole list at
19970 point into heading.
19972 In a region:
19974 - If the first non blank line is an headline, remove the stars
19975 from all headlines in the region.
19977 - If it is a normal line turn each and every normal line (i.e. not an
19978 heading or an item) in the region into a heading.
19980 - If it is a plain list item, turn all plain list items into headings.
19982 When converting a line into a heading, the number of stars is chosen
19983 such that the lines become children of the current entry. However,
19984 when a prefix argument is given, its value determines the number of
19985 stars to add."
19986 (interactive "P")
19987 (let ((skip-blanks
19988 (function
19989 ;; Return beginning of first non-blank line, starting from
19990 ;; line at POS.
19991 (lambda (pos)
19992 (save-excursion
19993 (goto-char pos)
19994 (while (org-at-comment-p) (forward-line))
19995 (skip-chars-forward " \r\t\n")
19996 (point-at-bol)))))
19997 beg end toggled)
19998 ;; Determine boundaries of changes. If a universal prefix has
19999 ;; been given, put the list in a region. If region ends at a bol,
20000 ;; do not consider the last line to be in the region.
20002 (when (and current-prefix-arg (org-at-item-p))
20003 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20004 (org-mark-element))
20006 (if (org-region-active-p)
20007 (setq beg (funcall skip-blanks (region-beginning))
20008 end (copy-marker (save-excursion
20009 (goto-char (region-end))
20010 (if (bolp) (point) (point-at-eol)))))
20011 (setq beg (funcall skip-blanks (point-at-bol))
20012 end (copy-marker (point-at-eol))))
20013 ;; Ensure inline tasks don't count as headings.
20014 (org-with-limited-levels
20015 (save-excursion
20016 (goto-char beg)
20017 (cond
20018 ;; Case 1. Started at an heading: de-star headings.
20019 ((org-at-heading-p)
20020 (while (< (point) end)
20021 (when (org-at-heading-p t)
20022 (looking-at org-outline-regexp) (replace-match "")
20023 (setq toggled t))
20024 (forward-line)))
20025 ;; Case 2. Started at an item: change items into headlines.
20026 ;; One star will be added by `org-list-to-subtree'.
20027 ((org-at-item-p)
20028 (let* ((stars (make-string
20029 (if nstars
20030 ;; subtract the star that will be added again by
20031 ;; `org-list-to-subtree'
20032 (1- (prefix-numeric-value current-prefix-arg))
20033 (or (org-current-level) 0))
20034 ?*))
20035 (add-stars
20036 (cond (nstars "") ; stars from prefix only
20037 ((equal stars "") "") ; before first heading
20038 (org-odd-levels-only "*") ; inside heading, odd
20039 (t "")))) ; inside heading, oddeven
20040 (while (< (point) end)
20041 (when (org-at-item-p)
20042 ;; Pay attention to cases when region ends before list.
20043 (let* ((struct (org-list-struct))
20044 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20045 (save-restriction
20046 (narrow-to-region (point) list-end)
20047 (insert
20048 (org-list-to-subtree
20049 (org-list-parse-list t)
20050 '(:istart (concat stars add-stars (funcall get-stars depth))
20051 :icount (concat stars add-stars (funcall get-stars depth)))))))
20052 (setq toggled t))
20053 (forward-line))))
20054 ;; Case 3. Started at normal text: make every line an heading,
20055 ;; skipping headlines and items.
20056 (t (let* ((stars (make-string
20057 (if nstars
20058 (prefix-numeric-value current-prefix-arg)
20059 (or (org-current-level) 0))
20060 ?*))
20061 (add-stars
20062 (cond (nstars "") ; stars from prefix only
20063 ((equal stars "") "*") ; before first heading
20064 (org-odd-levels-only "**") ; inside heading, odd
20065 (t "*"))) ; inside heading, oddeven
20066 (rpl (concat stars add-stars " ")))
20067 (while (< (point) end)
20068 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20069 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20070 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20071 (forward-line)))))))
20072 (unless toggled (message "Cannot toggle heading from here"))))
20074 (defun org-meta-return (&optional arg)
20075 "Insert a new heading or wrap a region in a table.
20076 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20077 See the individual commands for more information."
20078 (interactive "P")
20079 (cond
20080 ((run-hook-with-args-until-success 'org-metareturn-hook))
20081 ((or (org-at-drawer-p) (org-at-property-p))
20082 (newline-and-indent))
20083 ((org-at-table-p)
20084 (call-interactively 'org-table-wrap-region))
20085 (t (call-interactively 'org-insert-heading))))
20087 ;;; Menu entries
20089 (defsubst org-in-subtree-not-table-p ()
20090 "Are we in a subtree and not in a table?"
20091 (and (not (org-before-first-heading-p))
20092 (not (org-at-table-p))))
20094 ;; Define the Org-mode menus
20095 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20096 '("Tbl"
20097 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20098 ["Next Field" org-cycle (org-at-table-p)]
20099 ["Previous Field" org-shifttab (org-at-table-p)]
20100 ["Next Row" org-return (org-at-table-p)]
20101 "--"
20102 ["Blank Field" org-table-blank-field (org-at-table-p)]
20103 ["Edit Field" org-table-edit-field (org-at-table-p)]
20104 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20105 "--"
20106 ("Column"
20107 ["Move Column Left" org-metaleft (org-at-table-p)]
20108 ["Move Column Right" org-metaright (org-at-table-p)]
20109 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20110 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20111 ("Row"
20112 ["Move Row Up" org-metaup (org-at-table-p)]
20113 ["Move Row Down" org-metadown (org-at-table-p)]
20114 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20115 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20116 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20117 "--"
20118 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20119 ("Rectangle"
20120 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20121 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20122 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20123 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20124 "--"
20125 ("Calculate"
20126 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20127 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20128 ["Edit Formulas" org-edit-special (org-at-table-p)]
20129 "--"
20130 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20131 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20132 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20133 "--"
20134 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20135 "--"
20136 ["Sum Column/Rectangle" org-table-sum
20137 (or (org-at-table-p) (org-region-active-p))]
20138 ["Which Column?" org-table-current-column (org-at-table-p)])
20139 ["Debug Formulas"
20140 org-table-toggle-formula-debugger
20141 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20142 ["Show Col/Row Numbers"
20143 org-table-toggle-coordinate-overlays
20144 :style toggle
20145 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20146 "--"
20147 ["Create" org-table-create (and (not (org-at-table-p))
20148 org-enable-table-editor)]
20149 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20150 ["Import from File" org-table-import (not (org-at-table-p))]
20151 ["Export to File" org-table-export (org-at-table-p)]
20152 "--"
20153 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20155 (easy-menu-define org-org-menu org-mode-map "Org menu"
20156 '("Org"
20157 ("Show/Hide"
20158 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20159 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20160 ["Sparse Tree..." org-sparse-tree t]
20161 ["Reveal Context" org-reveal t]
20162 ["Show All" show-all t]
20163 "--"
20164 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20165 "--"
20166 ["New Heading" org-insert-heading t]
20167 ("Navigate Headings"
20168 ["Up" outline-up-heading t]
20169 ["Next" outline-next-visible-heading t]
20170 ["Previous" outline-previous-visible-heading t]
20171 ["Next Same Level" outline-forward-same-level t]
20172 ["Previous Same Level" outline-backward-same-level t]
20173 "--"
20174 ["Jump" org-goto t])
20175 ("Edit Structure"
20176 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20177 "--"
20178 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20179 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20180 "--"
20181 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20182 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20183 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20184 "--"
20185 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20186 "--"
20187 ["Copy visible text" org-copy-visible t]
20188 "--"
20189 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20190 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20191 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20192 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20193 "--"
20194 ["Sort Region/Children" org-sort t]
20195 "--"
20196 ["Convert to odd levels" org-convert-to-odd-levels t]
20197 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20198 ("Editing"
20199 ["Emphasis..." org-emphasize t]
20200 ["Edit Source Example" org-edit-special t]
20201 "--"
20202 ["Footnote new/jump" org-footnote-action t]
20203 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20204 ("Archive"
20205 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20206 "--"
20207 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20208 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20209 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20211 "--"
20212 ("Hyperlinks"
20213 ["Store Link (Global)" org-store-link t]
20214 ["Find existing link to here" org-occur-link-in-agenda-files t]
20215 ["Insert Link" org-insert-link t]
20216 ["Follow Link" org-open-at-point t]
20217 "--"
20218 ["Next link" org-next-link t]
20219 ["Previous link" org-previous-link t]
20220 "--"
20221 ["Descriptive Links"
20222 org-toggle-link-display
20223 :style radio
20224 :selected org-descriptive-links
20226 ["Literal Links"
20227 org-toggle-link-display
20228 :style radio
20229 :selected (not org-descriptive-links)])
20230 "--"
20231 ("TODO Lists"
20232 ["TODO/DONE/-" org-todo t]
20233 ("Select keyword"
20234 ["Next keyword" org-shiftright (org-at-heading-p)]
20235 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20236 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20237 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20238 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20239 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20240 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20241 "--"
20242 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20243 :selected org-enforce-todo-dependencies :style toggle :active t]
20244 "Settings for tree at point"
20245 ["Do Children sequentially" org-toggle-ordered-property :style radio
20246 :selected (org-entry-get nil "ORDERED")
20247 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20248 ["Do Children parallel" org-toggle-ordered-property :style radio
20249 :selected (not (org-entry-get nil "ORDERED"))
20250 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20251 "--"
20252 ["Set Priority" org-priority t]
20253 ["Priority Up" org-shiftup t]
20254 ["Priority Down" org-shiftdown t]
20255 "--"
20256 ["Get news from all feeds" org-feed-update-all t]
20257 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20258 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20259 ("TAGS and Properties"
20260 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20261 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20262 "--"
20263 ["Set property" org-set-property (not (org-before-first-heading-p))]
20264 ["Column view of properties" org-columns t]
20265 ["Insert Column View DBlock" org-insert-columns-dblock t])
20266 ("Dates and Scheduling"
20267 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20268 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20269 ("Change Date"
20270 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20271 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20272 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20273 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20274 ["Compute Time Range" org-evaluate-time-range t]
20275 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20276 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20277 "--"
20278 ["Custom time format" org-toggle-time-stamp-overlays
20279 :style radio :selected org-display-custom-times]
20280 "--"
20281 ["Goto Calendar" org-goto-calendar t]
20282 ["Date from Calendar" org-date-from-calendar t]
20283 "--"
20284 ["Start/Restart Timer" org-timer-start t]
20285 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20286 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20287 ["Insert Timer String" org-timer t]
20288 ["Insert Timer Item" org-timer-item t])
20289 ("Logging work"
20290 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20291 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20292 ["Clock out" org-clock-out t]
20293 ["Clock cancel" org-clock-cancel t]
20294 "--"
20295 ["Mark as default task" org-clock-mark-default-task t]
20296 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20297 ["Goto running clock" org-clock-goto t]
20298 "--"
20299 ["Display times" org-clock-display t]
20300 ["Create clock table" org-clock-report t]
20301 "--"
20302 ["Record DONE time"
20303 (progn (setq org-log-done (not org-log-done))
20304 (message "Switching to %s will %s record a timestamp"
20305 (car org-done-keywords)
20306 (if org-log-done "automatically" "not")))
20307 :style toggle :selected org-log-done])
20308 "--"
20309 ["Agenda Command..." org-agenda t]
20310 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20311 ("File List for Agenda")
20312 ("Special views current file"
20313 ["TODO Tree" org-show-todo-tree t]
20314 ["Check Deadlines" org-check-deadlines t]
20315 ["Timeline" org-timeline t]
20316 ["Tags/Property tree" org-match-sparse-tree t])
20317 "--"
20318 ["Export/Publish..." org-export-dispatch t]
20319 ("LaTeX"
20320 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20321 :selected org-cdlatex-mode]
20322 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20323 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20324 ["Modify math symbol" org-cdlatex-math-modify
20325 (org-inside-LaTeX-fragment-p)]
20326 ["Insert citation" org-reftex-citation t]
20327 "--"
20328 ["Template for BEAMER" (progn (require 'ox-beamer)
20329 (org-insert-beamer-options-template)) t])
20330 "--"
20331 ("MobileOrg"
20332 ["Push Files and Views" org-mobile-push t]
20333 ["Get Captured and Flagged" org-mobile-pull t]
20334 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20335 "--"
20336 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20337 "--"
20338 ("Documentation"
20339 ["Show Version" org-version t]
20340 ["Info Documentation" org-info t])
20341 ("Customize"
20342 ["Browse Org Group" org-customize t]
20343 "--"
20344 ["Expand This Menu" org-create-customize-menu
20345 (fboundp 'customize-menu-create)])
20346 ["Send bug report" org-submit-bug-report t]
20347 "--"
20348 ("Refresh/Reload"
20349 ["Refresh setup current buffer" org-mode-restart t]
20350 ["Reload Org (after update)" org-reload t]
20351 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20354 (defun org-info (&optional node)
20355 "Read documentation for Org-mode in the info system.
20356 With optional NODE, go directly to that node."
20357 (interactive)
20358 (info (format "(org)%s" (or node ""))))
20360 ;;;###autoload
20361 (defun org-submit-bug-report ()
20362 "Submit a bug report on Org-mode via mail.
20364 Don't hesitate to report any problems or inaccurate documentation.
20366 If you don't have setup sending mail from (X)Emacs, please copy the
20367 output buffer into your mail program, as it gives us important
20368 information about your Org-mode version and configuration."
20369 (interactive)
20370 (require 'reporter)
20371 (org-load-modules-maybe)
20372 (org-require-autoloaded-modules)
20373 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20374 (reporter-submit-bug-report
20375 "emacs-orgmode@gnu.org"
20376 (org-version nil 'full)
20377 (let (list)
20378 (save-window-excursion
20379 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20380 (delete-other-windows)
20381 (erase-buffer)
20382 (insert "You are about to submit a bug report to the Org-mode mailing list.
20384 We would like to add your full Org-mode and Outline configuration to the
20385 bug report. This greatly simplifies the work of the maintainer and
20386 other experts on the mailing list.
20388 HOWEVER, some variables you have customized may contain private
20389 information. The names of customers, colleagues, or friends, might
20390 appear in the form of file names, tags, todo states, or search strings.
20391 If you answer yes to the prompt, you might want to check and remove
20392 such private information before sending the email.")
20393 (add-text-properties (point-min) (point-max) '(face org-warning))
20394 (when (yes-or-no-p "Include your Org-mode configuration ")
20395 (mapatoms
20396 (lambda (v)
20397 (and (boundp v)
20398 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20399 (or (and (symbol-value v)
20400 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20401 (and
20402 (get v 'custom-type) (get v 'standard-value)
20403 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20404 (push v list)))))
20405 (kill-buffer (get-buffer "*Warn about privacy*"))
20406 list))
20407 nil nil
20408 "Remember to cover the basics, that is, what you expected to happen and
20409 what in fact did happen. You don't know how to make a good report? See
20411 http://orgmode.org/manual/Feedback.html#Feedback
20413 Your bug report will be posted to the Org-mode mailing list.
20414 ------------------------------------------------------------------------")
20415 (save-excursion
20416 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20417 (replace-match "\\1Bug: \\3 [\\2]")))))
20420 (defun org-install-agenda-files-menu ()
20421 (let ((bl (buffer-list)))
20422 (save-excursion
20423 (while bl
20424 (set-buffer (pop bl))
20425 (if (derived-mode-p 'org-mode) (setq bl nil)))
20426 (when (derived-mode-p 'org-mode)
20427 (easy-menu-change
20428 '("Org") "File List for Agenda"
20429 (append
20430 (list
20431 ["Edit File List" (org-edit-agenda-file-list) t]
20432 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20433 ["Remove Current File from List" org-remove-file t]
20434 ["Cycle through agenda files" org-cycle-agenda-files t]
20435 ["Occur in all agenda files" org-occur-in-agenda-files t]
20436 "--")
20437 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20439 ;;;; Documentation
20441 (defun org-require-autoloaded-modules ()
20442 (interactive)
20443 (mapc 'require
20444 '(org-agenda org-archive org-attach org-clock org-colview org-id
20445 org-remember org-table org-timer)))
20447 ;;;###autoload
20448 (defun org-reload (&optional uncompiled)
20449 "Reload all org lisp files.
20450 With prefix arg UNCOMPILED, load the uncompiled versions."
20451 (interactive "P")
20452 (require 'loadhist)
20453 (let* ((org-dir (org-find-library-dir "org"))
20454 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20455 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20456 (remove-re (mapconcat 'identity
20457 (mapcar (lambda (f) (concat "^" f "$"))
20458 (list (if (featurep 'xemacs)
20459 "org-colview"
20460 "org-colview-xemacs")
20461 "org" "org-loaddefs" "org-version"))
20462 "\\|"))
20463 (feats (delete-dups
20464 (mapcar 'file-name-sans-extension
20465 (mapcar 'file-name-nondirectory
20466 (delq nil
20467 (mapcar 'feature-file
20468 features))))))
20469 (lfeat (append
20470 (sort
20471 (setq feats
20472 (delq nil (mapcar
20473 (lambda (f)
20474 (if (and (string-match feature-re f)
20475 (not (string-match remove-re f)))
20476 f nil))
20477 feats)))
20478 'string-lessp)
20479 (list "org-version" "org")))
20480 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20481 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20482 load-uncore load-misses)
20483 (setq load-misses
20484 (delq 't
20485 (mapcar (lambda (f)
20486 (or (org-load-noerror-mustsuffix (concat org-dir f))
20487 (and (string= org-dir contrib-dir)
20488 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20489 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20490 (add-to-list 'load-uncore f 'append)
20493 lfeat)))
20494 (if load-uncore
20495 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20496 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20497 (if load-misses
20498 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20499 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20500 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20502 ;;;###autoload
20503 (defun org-customize ()
20504 "Call the customize function with org as argument."
20505 (interactive)
20506 (org-load-modules-maybe)
20507 (org-require-autoloaded-modules)
20508 (customize-browse 'org))
20510 (defun org-create-customize-menu ()
20511 "Create a full customization menu for Org-mode, insert it into the menu."
20512 (interactive)
20513 (org-load-modules-maybe)
20514 (org-require-autoloaded-modules)
20515 (if (fboundp 'customize-menu-create)
20516 (progn
20517 (easy-menu-change
20518 '("Org") "Customize"
20519 `(["Browse Org group" org-customize t]
20520 "--"
20521 ,(customize-menu-create 'org)
20522 ["Set" Custom-set t]
20523 ["Save" Custom-save t]
20524 ["Reset to Current" Custom-reset-current t]
20525 ["Reset to Saved" Custom-reset-saved t]
20526 ["Reset to Standard Settings" Custom-reset-standard t]))
20527 (message "\"Org\"-menu now contains full customization menu"))
20528 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20530 ;;;; Miscellaneous stuff
20532 ;;; Generally useful functions
20534 (defun org-get-at-bol (property)
20535 "Get text property PROPERTY at beginning of line."
20536 (get-text-property (point-at-bol) property))
20538 (defun org-find-text-property-in-string (prop s)
20539 "Return the first non-nil value of property PROP in string S."
20540 (or (get-text-property 0 prop s)
20541 (get-text-property (or (next-single-property-change 0 prop s) 0)
20542 prop s)))
20544 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20545 "Display the given MESSAGE as a warning."
20546 (if (fboundp 'display-warning)
20547 (display-warning 'org message
20548 (if (featurep 'xemacs) 'warning :warning))
20549 (let ((buf (get-buffer-create "*Org warnings*")))
20550 (with-current-buffer buf
20551 (goto-char (point-max))
20552 (insert "Warning (Org): " message)
20553 (unless (bolp)
20554 (newline)))
20555 (display-buffer buf)
20556 (sit-for 0))))
20558 (defun org-eval (form)
20559 "Eval FORM and return result."
20560 (condition-case error
20561 (eval form)
20562 (error (format "%%![Error: %s]" error))))
20564 (defun org-in-clocktable-p ()
20565 "Check if the cursor is in a clocktable."
20566 (let ((pos (point)) start)
20567 (save-excursion
20568 (end-of-line 1)
20569 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20570 (setq start (match-beginning 0))
20571 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20572 (>= (match-end 0) pos)
20573 start))))
20575 (defun org-in-commented-line ()
20576 "Is point in a line starting with `#'?"
20577 (equal (char-after (point-at-bol)) ?#))
20579 (defun org-in-indented-comment-line ()
20580 "Is point in a line starting with `#' after some white space?"
20581 (save-excursion
20582 (save-match-data
20583 (goto-char (point-at-bol))
20584 (looking-at "[ \t]*#"))))
20586 (defun org-in-verbatim-emphasis ()
20587 (save-match-data
20588 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20590 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20591 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20592 (if (and marker (marker-buffer marker)
20593 (buffer-live-p (marker-buffer marker)))
20594 (progn
20595 (org-pop-to-buffer-same-window (marker-buffer marker))
20596 (if (or (> marker (point-max)) (< marker (point-min)))
20597 (widen))
20598 (goto-char marker)
20599 (org-show-context 'org-goto))
20600 (if bookmark
20601 (bookmark-jump bookmark)
20602 (error "Cannot find location"))))
20604 (defun org-quote-csv-field (s)
20605 "Quote field for inclusion in CSV material."
20606 (if (string-match "[\",]" s)
20607 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20610 (defun org-force-self-insert (N)
20611 "Needed to enforce self-insert under remapping."
20612 (interactive "p")
20613 (self-insert-command N))
20615 (defun org-string-width (s)
20616 "Compute width of string, ignoring invisible characters.
20617 This ignores character with invisibility property `org-link', and also
20618 characters with property `org-cwidth', because these will become invisible
20619 upon the next fontification round."
20620 (let (b l)
20621 (when (or (eq t buffer-invisibility-spec)
20622 (assq 'org-link buffer-invisibility-spec))
20623 (while (setq b (text-property-any 0 (length s)
20624 'invisible 'org-link s))
20625 (setq s (concat (substring s 0 b)
20626 (substring s (or (next-single-property-change
20627 b 'invisible s) (length s)))))))
20628 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20629 (setq s (concat (substring s 0 b)
20630 (substring s (or (next-single-property-change
20631 b 'org-cwidth s) (length s))))))
20632 (setq l (string-width s) b -1)
20633 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20634 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20637 (defun org-shorten-string (s maxlength)
20638 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20639 If the string is shorter or has length MAXLENGTH, just return the
20640 original string. If it is longer, the functions finds a space in the
20641 string, breaks this string off at that locations and adds three dots
20642 as ellipsis. Including the ellipsis, the string will not be longer
20643 than MAXLENGTH. If finding a good breaking point in the string does
20644 not work, the string is just chopped off in the middle of a word
20645 if necessary."
20646 (if (<= (length s) maxlength)
20648 (let* ((n (max (- maxlength 4) 1))
20649 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20650 (if (string-match re s)
20651 (concat (match-string 1 s) "...")
20652 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20654 (defun org-get-indentation (&optional line)
20655 "Get the indentation of the current line, interpreting tabs.
20656 When LINE is given, assume it represents a line and compute its indentation."
20657 (if line
20658 (if (string-match "^ *" (org-remove-tabs line))
20659 (match-end 0))
20660 (save-excursion
20661 (beginning-of-line 1)
20662 (skip-chars-forward " \t")
20663 (current-column))))
20665 (defun org-get-string-indentation (s)
20666 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20667 (let ((n -1) (i 0) (w tab-width) c)
20668 (catch 'exit
20669 (while (< (setq n (1+ n)) (length s))
20670 (setq c (aref s n))
20671 (cond ((= c ?\ ) (setq i (1+ i)))
20672 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20673 (t (throw 'exit t)))))
20676 (defun org-remove-tabs (s &optional width)
20677 "Replace tabulators in S with spaces.
20678 Assumes that s is a single line, starting in column 0."
20679 (setq width (or width tab-width))
20680 (while (string-match "\t" s)
20681 (setq s (replace-match
20682 (make-string
20683 (- (* width (/ (+ (match-beginning 0) width) width))
20684 (match-beginning 0)) ?\ )
20685 t t s)))
20688 (defun org-fix-indentation (line ind)
20689 "Fix indentation in LINE.
20690 IND is a cons cell with target and minimum indentation.
20691 If the current indentation in LINE is smaller than the minimum,
20692 leave it alone. If it is larger than ind, set it to the target."
20693 (let* ((l (org-remove-tabs line))
20694 (i (org-get-indentation l))
20695 (i1 (car ind)) (i2 (cdr ind)))
20696 (if (>= i i2) (setq l (substring line i2)))
20697 (if (> i1 0)
20698 (concat (make-string i1 ?\ ) l)
20699 l)))
20701 (defun org-remove-indentation (code &optional n)
20702 "Remove the maximum common indentation from the lines in CODE.
20703 N may optionally be the number of spaces to remove."
20704 (with-temp-buffer
20705 (insert code)
20706 (org-do-remove-indentation n)
20707 (buffer-string)))
20709 (defun org-do-remove-indentation (&optional n)
20710 "Remove the maximum common indentation from the buffer."
20711 (untabify (point-min) (point-max))
20712 (let ((min 10000) re)
20713 (if n
20714 (setq min n)
20715 (goto-char (point-min))
20716 (while (re-search-forward "^ *[^ \n]" nil t)
20717 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20718 (unless (or (= min 0) (= min 10000))
20719 (setq re (format "^ \\{%d\\}" min))
20720 (goto-char (point-min))
20721 (while (re-search-forward re nil t)
20722 (replace-match "")
20723 (end-of-line 1))
20724 min)))
20726 (defun org-fill-template (template alist)
20727 "Find each %key of ALIST in TEMPLATE and replace it."
20728 (let ((case-fold-search nil)
20729 entry key value)
20730 (setq alist (sort (copy-sequence alist)
20731 (lambda (a b) (< (length (car a)) (length (car b))))))
20732 (while (setq entry (pop alist))
20733 (setq template
20734 (replace-regexp-in-string
20735 (concat "%" (regexp-quote (car entry)))
20736 (or (cdr entry) "") template t t)))
20737 template))
20739 (defun org-base-buffer (buffer)
20740 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20741 (if (not buffer)
20742 buffer
20743 (or (buffer-base-buffer buffer)
20744 buffer)))
20746 (defun org-trim (s)
20747 "Remove whitespace at beginning and end of string."
20748 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20749 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20752 (defun org-wrap (string &optional width lines)
20753 "Wrap string to either a number of lines, or a width in characters.
20754 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20755 that costs. If there is a word longer than WIDTH, the text is actually
20756 wrapped to the length of that word.
20757 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20758 many lines, whatever width that takes.
20759 The return value is a list of lines, without newlines at the end."
20760 (let* ((words (org-split-string string "[ \t\n]+"))
20761 (maxword (apply 'max (mapcar 'org-string-width words)))
20762 w ll)
20763 (cond (width
20764 (org-do-wrap words (max maxword width)))
20765 (lines
20766 (setq w maxword)
20767 (setq ll (org-do-wrap words maxword))
20768 (if (<= (length ll) lines)
20770 (setq ll words)
20771 (while (> (length ll) lines)
20772 (setq w (1+ w))
20773 (setq ll (org-do-wrap words w)))
20774 ll))
20775 (t (error "Cannot wrap this")))))
20777 (defun org-do-wrap (words width)
20778 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20779 (let (lines line)
20780 (while words
20781 (setq line (pop words))
20782 (while (and words (< (+ (length line) (length (car words))) width))
20783 (setq line (concat line " " (pop words))))
20784 (setq lines (push line lines)))
20785 (nreverse lines)))
20787 (defun org-split-string (string &optional separators)
20788 "Splits STRING into substrings at SEPARATORS.
20789 No empty strings are returned if there are matches at the beginning
20790 and end of string."
20791 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20792 (start 0)
20793 notfirst
20794 (list nil))
20795 (while (and (string-match rexp string
20796 (if (and notfirst
20797 (= start (match-beginning 0))
20798 (< start (length string)))
20799 (1+ start) start))
20800 (< (match-beginning 0) (length string)))
20801 (setq notfirst t)
20802 (or (eq (match-beginning 0) 0)
20803 (and (eq (match-beginning 0) (match-end 0))
20804 (eq (match-beginning 0) start))
20805 (setq list
20806 (cons (substring string start (match-beginning 0))
20807 list)))
20808 (setq start (match-end 0)))
20809 (or (eq start (length string))
20810 (setq list
20811 (cons (substring string start)
20812 list)))
20813 (nreverse list)))
20815 (defun org-quote-vert (s)
20816 "Replace \"|\" with \"\\vert\"."
20817 (while (string-match "|" s)
20818 (setq s (replace-match "\\vert" t t s)))
20821 (defun org-uuidgen-p (s)
20822 "Is S an ID created by UUIDGEN?"
20823 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20825 (defun org-in-src-block-p (&optional inside)
20826 "Whether point is in a code source block.
20827 When INSIDE is non-nil, don't consider we are within a src block
20828 when point is at #+BEGIN_SRC or #+END_SRC."
20829 (let ((case-fold-search t) ov)
20830 (or (and (setq ov (overlays-at (point)))
20831 (memq 'org-block-background
20832 (overlay-properties (car ov))))
20833 (and (not inside)
20834 (save-match-data
20835 (save-excursion
20836 (beginning-of-line)
20837 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20839 (defun org-context ()
20840 "Return a list of contexts of the current cursor position.
20841 If several contexts apply, all are returned.
20842 Each context entry is a list with a symbol naming the context, and
20843 two positions indicating start and end of the context. Possible
20844 contexts are:
20846 :headline anywhere in a headline
20847 :headline-stars on the leading stars in a headline
20848 :todo-keyword on a TODO keyword (including DONE) in a headline
20849 :tags on the TAGS in a headline
20850 :priority on the priority cookie in a headline
20851 :item on the first line of a plain list item
20852 :item-bullet on the bullet/number of a plain list item
20853 :checkbox on the checkbox in a plain list item
20854 :table in an org-mode table
20855 :table-special on a special filed in a table
20856 :table-table in a table.el table
20857 :clocktable in a clocktable
20858 :src-block in a source block
20859 :link on a hyperlink
20860 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20861 :target on a <<target>>
20862 :radio-target on a <<<radio-target>>>
20863 :latex-fragment on a LaTeX fragment
20864 :latex-preview on a LaTeX fragment with overlaid preview image
20866 This function expects the position to be visible because it uses font-lock
20867 faces as a help to recognize the following contexts: :table-special, :link,
20868 and :keyword."
20869 (let* ((f (get-text-property (point) 'face))
20870 (faces (if (listp f) f (list f)))
20871 (case-fold-search t)
20872 (p (point)) clist o)
20873 ;; First the large context
20874 (cond
20875 ((org-at-heading-p t)
20876 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20877 (when (progn
20878 (beginning-of-line 1)
20879 (looking-at org-todo-line-tags-regexp))
20880 (push (org-point-in-group p 1 :headline-stars) clist)
20881 (push (org-point-in-group p 2 :todo-keyword) clist)
20882 (push (org-point-in-group p 4 :tags) clist))
20883 (goto-char p)
20884 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20885 (if (looking-at "\\[#[A-Z0-9]\\]")
20886 (push (org-point-in-group p 0 :priority) clist)))
20888 ((org-at-item-p)
20889 (push (org-point-in-group p 2 :item-bullet) clist)
20890 (push (list :item (point-at-bol)
20891 (save-excursion (org-end-of-item) (point)))
20892 clist)
20893 (and (org-at-item-checkbox-p)
20894 (push (org-point-in-group p 0 :checkbox) clist)))
20896 ((org-at-table-p)
20897 (push (list :table (org-table-begin) (org-table-end)) clist)
20898 (if (memq 'org-formula faces)
20899 (push (list :table-special
20900 (previous-single-property-change p 'face)
20901 (next-single-property-change p 'face)) clist)))
20902 ((org-at-table-p 'any)
20903 (push (list :table-table) clist)))
20904 (goto-char p)
20906 (let ((case-fold-search t))
20907 ;; New the "medium" contexts: clocktables, source blocks
20908 (cond ((org-in-clocktable-p)
20909 (push (list :clocktable
20910 (and (or (looking-at "#\\+BEGIN: clocktable")
20911 (search-backward "#+BEGIN: clocktable" nil t))
20912 (match-beginning 0))
20913 (and (re-search-forward "#\\+END:?" nil t)
20914 (match-end 0))) clist))
20915 ((org-in-src-block-p)
20916 (push (list :src-block
20917 (and (or (looking-at "#\\+BEGIN_SRC")
20918 (search-backward "#+BEGIN_SRC" nil t))
20919 (match-beginning 0))
20920 (and (search-forward "#+END_SRC" nil t)
20921 (match-beginning 0))) clist))))
20922 (goto-char p)
20924 ;; Now the small context
20925 (cond
20926 ((org-at-timestamp-p)
20927 (push (org-point-in-group p 0 :timestamp) clist))
20928 ((memq 'org-link faces)
20929 (push (list :link
20930 (previous-single-property-change p 'face)
20931 (next-single-property-change p 'face)) clist))
20932 ((memq 'org-special-keyword faces)
20933 (push (list :keyword
20934 (previous-single-property-change p 'face)
20935 (next-single-property-change p 'face)) clist))
20936 ((org-at-target-p)
20937 (push (org-point-in-group p 0 :target) clist)
20938 (goto-char (1- (match-beginning 0)))
20939 (if (looking-at org-radio-target-regexp)
20940 (push (org-point-in-group p 0 :radio-target) clist))
20941 (goto-char p))
20942 ((setq o (car (delq nil
20943 (mapcar
20944 (lambda (x)
20945 (if (memq x org-latex-fragment-image-overlays) x))
20946 (overlays-at (point))))))
20947 (push (list :latex-fragment
20948 (overlay-start o) (overlay-end o)) clist)
20949 (push (list :latex-preview
20950 (overlay-start o) (overlay-end o)) clist))
20951 ((org-inside-LaTeX-fragment-p)
20952 ;; FIXME: positions wrong.
20953 (push (list :latex-fragment (point) (point)) clist)))
20955 (setq clist (nreverse (delq nil clist)))
20956 clist))
20958 ;; FIXME: Compare with at-regexp-p Do we need both?
20959 (defun org-in-regexp (re &optional nlines visually)
20960 "Check if point is inside a match of regexp.
20961 Normally only the current line is checked, but you can include NLINES extra
20962 lines both before and after point into the search.
20963 If VISUALLY is set, require that the cursor is not after the match but
20964 really on, so that the block visually is on the match."
20965 (catch 'exit
20966 (let ((pos (point))
20967 (eol (point-at-eol (+ 1 (or nlines 0))))
20968 (inc (if visually 1 0)))
20969 (save-excursion
20970 (beginning-of-line (- 1 (or nlines 0)))
20971 (while (re-search-forward re eol t)
20972 (if (and (<= (match-beginning 0) pos)
20973 (>= (+ inc (match-end 0)) pos))
20974 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20976 (defun org-at-regexp-p (regexp)
20977 "Is point inside a match of REGEXP in the current line?"
20978 (catch 'exit
20979 (save-excursion
20980 (let ((pos (point)) (end (point-at-eol)))
20981 (beginning-of-line 1)
20982 (while (re-search-forward regexp end t)
20983 (if (and (<= (match-beginning 0) pos)
20984 (>= (match-end 0) pos))
20985 (throw 'exit t)))
20986 nil))))
20988 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20989 "Non-nil when point is between matches of START-RE and END-RE.
20991 Also return a non-nil value when point is on one of the matches.
20993 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20994 buffer positions. Default values are the positions of headlines
20995 surrounding the point.
20997 The functions returns a cons cell whose car (resp. cdr) is the
20998 position before START-RE (resp. after END-RE)."
20999 (save-match-data
21000 (let ((pos (point))
21001 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21002 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21003 beg end)
21004 (save-excursion
21005 ;; Point is on a block when on START-RE or if START-RE can be
21006 ;; found before it...
21007 (and (or (org-at-regexp-p start-re)
21008 (re-search-backward start-re limit-up t))
21009 (setq beg (match-beginning 0))
21010 ;; ... and END-RE after it...
21011 (goto-char (match-end 0))
21012 (re-search-forward end-re limit-down t)
21013 (> (setq end (match-end 0)) pos)
21014 ;; ... without another START-RE in-between.
21015 (goto-char (match-beginning 0))
21016 (not (re-search-backward start-re (1+ beg) t))
21017 ;; Return value.
21018 (cons beg end))))))
21020 (defun org-in-block-p (names)
21021 "Non-nil when point belongs to a block whose name belongs to NAMES.
21023 NAMES is a list of strings containing names of blocks.
21025 Return first block name matched, or nil. Beware that in case of
21026 nested blocks, the returned name may not belong to the closest
21027 block from point."
21028 (save-match-data
21029 (catch 'exit
21030 (let ((case-fold-search t)
21031 (lim-up (save-excursion (outline-previous-heading)))
21032 (lim-down (save-excursion (outline-next-heading))))
21033 (mapc (lambda (name)
21034 (let ((n (regexp-quote name)))
21035 (when (org-between-regexps-p
21036 (concat "^[ \t]*#\\+begin_" n)
21037 (concat "^[ \t]*#\\+end_" n)
21038 lim-up lim-down)
21039 (throw 'exit n))))
21040 names))
21041 nil)))
21043 (defun org-occur-in-agenda-files (regexp &optional nlines)
21044 "Call `multi-occur' with buffers for all agenda files."
21045 (interactive "sOrg-files matching: \np")
21046 (let* ((files (org-agenda-files))
21047 (tnames (mapcar 'file-truename files))
21048 (extra org-agenda-text-search-extra-files)
21050 (when (eq (car extra) 'agenda-archives)
21051 (setq extra (cdr extra))
21052 (setq files (org-add-archive-files files)))
21053 (while (setq f (pop extra))
21054 (unless (member (file-truename f) tnames)
21055 (add-to-list 'files f 'append)
21056 (add-to-list 'tnames (file-truename f) 'append)))
21057 (multi-occur
21058 (mapcar (lambda (x)
21059 (with-current-buffer
21060 (or (get-file-buffer x) (find-file-noselect x))
21061 (widen)
21062 (current-buffer)))
21063 files)
21064 regexp)))
21066 (if (boundp 'occur-mode-find-occurrence-hook)
21067 ;; Emacs 23
21068 (add-hook 'occur-mode-find-occurrence-hook
21069 (lambda ()
21070 (when (derived-mode-p 'org-mode)
21071 (org-reveal))))
21072 ;; Emacs 22
21073 (defadvice occur-mode-goto-occurrence
21074 (after org-occur-reveal activate)
21075 (and (derived-mode-p 'org-mode) (org-reveal)))
21076 (defadvice occur-mode-goto-occurrence-other-window
21077 (after org-occur-reveal activate)
21078 (and (derived-mode-p 'org-mode) (org-reveal)))
21079 (defadvice occur-mode-display-occurrence
21080 (after org-occur-reveal activate)
21081 (when (derived-mode-p 'org-mode)
21082 (let ((pos (occur-mode-find-occurrence)))
21083 (with-current-buffer (marker-buffer pos)
21084 (save-excursion
21085 (goto-char pos)
21086 (org-reveal)))))))
21088 (defun org-occur-link-in-agenda-files ()
21089 "Create a link and search for it in the agendas.
21090 The link is not stored in `org-stored-links', it is just created
21091 for the search purpose."
21092 (interactive)
21093 (let ((link (condition-case nil
21094 (org-store-link nil)
21095 (error "Unable to create a link to here"))))
21096 (org-occur-in-agenda-files (regexp-quote link))))
21098 (defun org-uniquify (list)
21099 "Remove duplicate elements from LIST."
21100 (let (res)
21101 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21102 res))
21104 (defun org-delete-all (elts list)
21105 "Remove all elements in ELTS from LIST."
21106 (while elts
21107 (setq list (delete (pop elts) list)))
21108 list)
21110 (defun org-count (cl-item cl-seq)
21111 "Count the number of occurrences of ITEM in SEQ.
21112 Taken from `count' in cl-seq.el with all keyword arguments removed."
21113 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21114 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21115 (while (< cl-start cl-end)
21116 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21117 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21118 (setq cl-start (1+ cl-start)))
21119 cl-count))
21121 (defun org-remove-if (predicate seq)
21122 "Remove everything from SEQ that fulfills PREDICATE."
21123 (let (res e)
21124 (while seq
21125 (setq e (pop seq))
21126 (if (not (funcall predicate e)) (push e res)))
21127 (nreverse res)))
21129 (defun org-remove-if-not (predicate seq)
21130 "Remove everything from SEQ that does not fulfill PREDICATE."
21131 (let (res e)
21132 (while seq
21133 (setq e (pop seq))
21134 (if (funcall predicate e) (push e res)))
21135 (nreverse res)))
21137 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21138 "Reduce two-argument FUNCTION across SEQ.
21139 Taken from `reduce' in cl-seq.el with all keyword arguments but
21140 \":initial-value\" removed."
21141 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21142 (cadr (memq :initial-value cl-keys)))
21143 (cl-seq (pop cl-seq))
21144 (t (funcall cl-func)))))
21145 (while cl-seq
21146 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21147 cl-accum))
21149 (defun org-back-over-empty-lines ()
21150 "Move backwards over whitespace, to the beginning of the first empty line.
21151 Returns the number of empty lines passed."
21152 (let ((pos (point)))
21153 (if (cdr (assoc 'heading org-blank-before-new-entry))
21154 (skip-chars-backward " \t\n\r")
21155 (unless (eobp)
21156 (forward-line -1)))
21157 (beginning-of-line 2)
21158 (goto-char (min (point) pos))
21159 (count-lines (point) pos)))
21161 (defun org-skip-whitespace ()
21162 (skip-chars-forward " \t\n\r"))
21164 (defun org-point-in-group (point group &optional context)
21165 "Check if POINT is in match-group GROUP.
21166 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21167 match. If the match group does not exist or point is not inside it,
21168 return nil."
21169 (and (match-beginning group)
21170 (>= point (match-beginning group))
21171 (<= point (match-end group))
21172 (if context
21173 (list context (match-beginning group) (match-end group))
21174 t)))
21176 (defun org-switch-to-buffer-other-window (&rest args)
21177 "Switch to buffer in a second window on the current frame.
21178 In particular, do not allow pop-up frames.
21179 Returns the newly created buffer."
21180 (org-no-popups
21181 (apply 'switch-to-buffer-other-window args)))
21183 (defun org-combine-plists (&rest plists)
21184 "Create a single property list from all plists in PLISTS.
21185 The process starts by copying the first list, and then setting properties
21186 from the other lists. Settings in the last list are the most significant
21187 ones and overrule settings in the other lists."
21188 (let ((rtn (copy-sequence (pop plists)))
21189 p v ls)
21190 (while plists
21191 (setq ls (pop plists))
21192 (while ls
21193 (setq p (pop ls) v (pop ls))
21194 (setq rtn (plist-put rtn p v))))
21195 rtn))
21197 (defun org-replace-escapes (string table)
21198 "Replace %-escapes in STRING with values in TABLE.
21199 TABLE is an association list with keys like \"%a\" and string values.
21200 The sequences in STRING may contain normal field width and padding information,
21201 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21202 so values can contain further %-escapes if they are define later in TABLE."
21203 (let ((tbl (copy-alist table))
21204 (case-fold-search nil)
21205 (pchg 0)
21206 e re rpl)
21207 (while (setq e (pop tbl))
21208 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21209 (when (and (cdr e) (string-match re (cdr e)))
21210 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21211 (safe "SREF"))
21212 (add-text-properties 0 3 (list 'sref sref) safe)
21213 (setcdr e (replace-match safe t t (cdr e)))))
21214 (while (string-match re string)
21215 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21216 (cdr e)))
21217 (setq string (replace-match rpl t t string))))
21218 (while (setq pchg (next-property-change pchg string))
21219 (let ((sref (get-text-property pchg 'sref string)))
21220 (when (and sref (string-match "SREF" string pchg))
21221 (setq string (replace-match sref t t string)))))
21222 string))
21224 (defun org-sublist (list start end)
21225 "Return a section of LIST, from START to END.
21226 Counting starts at 1."
21227 (let (rtn (c start))
21228 (setq list (nthcdr (1- start) list))
21229 (while (and list (<= c end))
21230 (push (pop list) rtn)
21231 (setq c (1+ c)))
21232 (nreverse rtn)))
21234 (defun org-find-base-buffer-visiting (file)
21235 "Like `find-buffer-visiting' but always return the base buffer and
21236 not an indirect buffer."
21237 (let ((buf (or (get-file-buffer file)
21238 (find-buffer-visiting file))))
21239 (if buf
21240 (or (buffer-base-buffer buf) buf)
21241 nil)))
21243 (defun org-image-file-name-regexp (&optional extensions)
21244 "Return regexp matching the file names of images.
21245 If EXTENSIONS is given, only match these."
21246 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21247 (image-file-name-regexp)
21248 (let ((image-file-name-extensions
21249 (or extensions
21250 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21251 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21252 (concat "\\."
21253 (regexp-opt (nconc (mapcar 'upcase
21254 image-file-name-extensions)
21255 image-file-name-extensions)
21257 "\\'"))))
21259 (defun org-file-image-p (file &optional extensions)
21260 "Return non-nil if FILE is an image."
21261 (save-match-data
21262 (string-match (org-image-file-name-regexp extensions) file)))
21264 (defun org-get-cursor-date (&optional with-time)
21265 "Return the date at cursor in as a time.
21266 This works in the calendar and in the agenda, anywhere else it just
21267 returns the current time.
21268 If WITH-TIME is non-nil, returns the time of the event at point (in
21269 the agenda) or the current time of the day."
21270 (let (date day defd tp tm hod mod)
21271 (when with-time
21272 (setq tp (get-text-property (point) 'time))
21273 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21274 (setq hod (string-to-number (match-string 1 tp))
21275 mod (string-to-number (match-string 2 tp))))
21276 (or tp (setq hod (nth 2 (decode-time (current-time)))
21277 mod (nth 1 (decode-time (current-time))))))
21278 (cond
21279 ((eq major-mode 'calendar-mode)
21280 (setq date (calendar-cursor-to-date)
21281 defd (encode-time 0 (or mod 0) (or hod 0)
21282 (nth 1 date) (nth 0 date) (nth 2 date))))
21283 ((eq major-mode 'org-agenda-mode)
21284 (setq day (get-text-property (point) 'day))
21285 (if day
21286 (setq date (calendar-gregorian-from-absolute day)
21287 defd (encode-time 0 (or mod 0) (or hod 0)
21288 (nth 1 date) (nth 0 date) (nth 2 date))))))
21289 (or defd (current-time))))
21291 (defun org-mark-subtree (&optional up)
21292 "Mark the current subtree.
21293 This puts point at the start of the current subtree, and mark at
21294 the end. If a numeric prefix UP is given, move up into the
21295 hierarchy of headlines by UP levels before marking the subtree."
21296 (interactive "P")
21297 (org-with-limited-levels
21298 (cond ((org-at-heading-p) (beginning-of-line))
21299 ((org-before-first-heading-p) (error "Not in a subtree"))
21300 (t (outline-previous-visible-heading 1))))
21301 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21302 (if (org-called-interactively-p 'any)
21303 (call-interactively 'org-mark-element)
21304 (org-mark-element)))
21307 ;;; Macros
21309 ;; Macros are expanded with `org-macro-replace-all', which relies
21310 ;; internally on `org-macro-expand'.
21312 ;; Default templates for expansion are stored in the buffer-local
21313 ;; variable `org-macro-templates'. This variable is updated by
21314 ;; `org-macro-initialize-templates'.
21316 ;; Along with macros defined through #+MACRO: keyword, default
21317 ;; templates include the following hard-coded macros:
21318 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21319 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21321 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21322 ;; {{{title}}} will also be provided.
21325 (defvar org-macro-templates nil
21326 "Alist containing all macro templates in current buffer.
21327 Associations are in the shape of (NAME . TEMPLATE) where NAME
21328 stands for macro's name and template for its replacement value,
21329 both as strings. This is an internal variable. Do not set it
21330 directly, use instead:
21332 #+MACRO: name template")
21333 (make-variable-buffer-local 'org-macro-templates)
21335 (defun org-macro-expand (macro templates)
21336 "Return expanded MACRO, as a string.
21337 MACRO is an object, obtained, for example, with
21338 `org-element-context'. TEMPLATES is an alist of templates used
21339 for expansion. See `org-macro-templates' for a buffer-local
21340 default value. Return nil if no template was found."
21341 (let ((template
21342 ;; Macro names are case-insensitive.
21343 (cdr (assoc-string (org-element-property :key macro) templates t))))
21344 (when template
21345 (let ((value (replace-regexp-in-string
21346 "\\$[0-9]+"
21347 (lambda (arg)
21348 (or (nth (1- (string-to-number (substring arg 1)))
21349 (org-element-property :args macro))
21350 ;; No argument provided: remove
21351 ;; place-holder.
21352 ""))
21353 template)))
21354 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21355 (when (string-match "\\`(eval\\>" value)
21356 (setq value (eval (read value))))
21357 ;; Return string.
21358 (format "%s" (or value ""))))))
21360 (defun org-macro-replace-all (templates)
21361 "Replace all macros in current buffer by their expansion.
21362 TEMPLATES is an alist of templates used for expansion. See
21363 `org-macro-templates' for a buffer-local default value."
21364 (save-excursion
21365 (goto-char (point-min))
21366 (let (record)
21367 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21368 (let ((object (org-element-context)))
21369 (when (eq (org-element-type object) 'macro)
21370 (let* ((value (org-macro-expand object templates))
21371 (begin (org-element-property :begin object))
21372 (signature (list begin
21373 object
21374 (org-element-property :args object))))
21375 ;; Avoid circular dependencies by checking if the same
21376 ;; macro with the same arguments is expanded at the same
21377 ;; position twice.
21378 (if (member signature record)
21379 (error "Circular macro expansion: %s"
21380 (org-element-property :key object))
21381 (when value
21382 (push signature record)
21383 (delete-region
21384 begin
21385 ;; Preserve white spaces after the macro.
21386 (progn (goto-char (org-element-property :end object))
21387 (skip-chars-backward " \t")
21388 (point)))
21389 ;; Leave point before replacement in case of recursive
21390 ;; expansions.
21391 (save-excursion (insert value)))))))))))
21393 (defun org-macro-initialize-templates ()
21394 "Collect macro templates defined in current buffer.
21395 Templates are stored in buffer-local variable
21396 `org-macro-templates'. In addition to buffer-defined macros, the
21397 function installs the following ones: \"property\",
21398 \"time\". and, if the buffer is associated to a file,
21399 \"input-file\" and \"modification-time\"."
21400 (let ((case-fold-search t)
21401 (set-template
21402 (lambda (cell)
21403 ;; Add CELL to `org-macro-templates' if there's no
21404 ;; association matching its name already. Otherwise,
21405 ;; replace old association with the new one in that
21406 ;; variable.
21407 (let ((old-template (assoc (car cell) org-macro-templates)))
21408 (if old-template (setcdr old-template (cdr cell))
21409 (push cell org-macro-templates))))))
21410 ;; Install buffer-local macros.
21411 (org-with-wide-buffer
21412 (goto-char (point-min))
21413 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21414 (let ((element (org-element-at-point)))
21415 (when (eq (org-element-type element) 'keyword)
21416 (let ((value (org-element-property :value element)))
21417 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21418 (funcall set-template
21419 (cons (match-string 1 value)
21420 (or (match-string 2 value) "")))))))))
21421 ;; Install hard-coded macros.
21422 (mapc (lambda (cell) (funcall set-template cell))
21423 (list
21424 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21425 (cons "time" "(eval (format-time-string \"$1\"))")))
21426 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21427 (when (and visited-file (file-exists-p visited-file))
21428 (mapc (lambda (cell) (funcall set-template cell))
21429 (list
21430 (cons "input-file" (file-name-nondirectory visited-file))
21431 (cons "modification-time"
21432 (format "(eval (format-time-string \"$1\" '%s))"
21433 (prin1-to-string
21434 (nth 5 (file-attributes visited-file)))))))))))
21437 ;;; Indentation
21439 (defun org-indent-line ()
21440 "Indent line depending on context."
21441 (interactive)
21442 (let* ((pos (point))
21443 (itemp (org-at-item-p))
21444 (case-fold-search t)
21445 (org-drawer-regexp (or org-drawer-regexp "\000"))
21446 (inline-task-p (and (featurep 'org-inlinetask)
21447 (org-inlinetask-in-task-p)))
21448 (inline-re (and inline-task-p
21449 (org-inlinetask-outline-regexp)))
21450 column)
21451 (if (and orgstruct-is-++ (eq pos (point)))
21452 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21453 (indent-according-to-mode))
21454 (beginning-of-line 1)
21455 (cond
21456 ;; Headings
21457 ((looking-at org-outline-regexp) (setq column 0))
21458 ;; Footnote definition
21459 ((looking-at org-footnote-definition-re) (setq column 0))
21460 ;; Literal examples
21461 ((looking-at "[ \t]*:\\( \\|$\\)")
21462 (setq column (org-get-indentation))) ; do nothing
21463 ;; Lists
21464 ((ignore-errors (goto-char (org-in-item-p)))
21465 (setq column (if itemp
21466 (org-get-indentation)
21467 (org-list-item-body-column (point))))
21468 (goto-char pos))
21469 ;; Drawers
21470 ((and (looking-at "[ \t]*:END:")
21471 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21472 (save-excursion
21473 (goto-char (1- (match-beginning 1)))
21474 (setq column (current-column))))
21475 ;; Special blocks
21476 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21477 (save-excursion
21478 (re-search-backward
21479 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21480 (setq column (org-get-indentation (match-string 0))))
21481 ((and (not (looking-at "[ \t]*#\\+begin_"))
21482 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21483 (save-excursion
21484 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21485 (setq column
21486 (cond ((equal (downcase (match-string 1)) "src")
21487 ;; src blocks: let `org-edit-src-exit' handle them
21488 (org-get-indentation))
21489 ((equal (downcase (match-string 1)) "example")
21490 (max (org-get-indentation)
21491 (org-get-indentation (match-string 0))))
21493 (org-get-indentation (match-string 0))))))
21494 ;; This line has nothing special, look at the previous relevant
21495 ;; line to compute indentation
21497 (beginning-of-line 0)
21498 (while (and (not (bobp))
21499 (not (looking-at org-table-line-regexp))
21500 (not (looking-at org-drawer-regexp))
21501 ;; When point started in an inline task, do not move
21502 ;; above task starting line.
21503 (not (and inline-task-p (looking-at inline-re)))
21504 ;; Skip drawers, blocks, empty lines, verbatim,
21505 ;; comments, tables, footnotes definitions, lists,
21506 ;; inline tasks.
21507 (or (and (looking-at "[ \t]*:END:")
21508 (re-search-backward org-drawer-regexp nil t))
21509 (and (looking-at "[ \t]*#\\+end_")
21510 (re-search-backward "[ \t]*#\\+begin_"nil t))
21511 (looking-at "[ \t]*[\n:#|]")
21512 (looking-at org-footnote-definition-re)
21513 (and (ignore-errors (goto-char (org-in-item-p)))
21514 (goto-char
21515 (org-list-get-top-point (org-list-struct))))
21516 (and (not inline-task-p)
21517 (featurep 'org-inlinetask)
21518 (org-inlinetask-in-task-p)
21519 (or (org-inlinetask-goto-beginning) t))))
21520 (beginning-of-line 0))
21521 (cond
21522 ;; There was an heading above.
21523 ((looking-at "\\*+[ \t]+")
21524 (if (not org-adapt-indentation)
21525 (setq column 0)
21526 (goto-char (match-end 0))
21527 (setq column (current-column))))
21528 ;; A drawer had started and is unfinished
21529 ((looking-at org-drawer-regexp)
21530 (goto-char (1- (match-beginning 1)))
21531 (setq column (current-column)))
21532 ;; Else, nothing noticeable found: get indentation and go on.
21533 (t (setq column (org-get-indentation))))))
21534 ;; Now apply indentation and move cursor accordingly
21535 (goto-char pos)
21536 (if (<= (current-column) (current-indentation))
21537 (org-indent-line-to column)
21538 (save-excursion (org-indent-line-to column)))
21539 ;; Special polishing for properties, see `org-property-format'
21540 (setq column (current-column))
21541 (beginning-of-line 1)
21542 (if (looking-at
21543 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21544 (replace-match (concat (match-string 1)
21545 (format org-property-format
21546 (match-string 2) (match-string 3)))
21547 t t))
21548 (org-move-to-column column))))
21550 (defun org-indent-drawer ()
21551 "Indent the drawer at point."
21552 (interactive)
21553 (let ((p (point))
21554 (e (and (save-excursion (re-search-forward ":END:" nil t))
21555 (match-end 0)))
21556 (folded
21557 (save-excursion
21558 (end-of-line)
21559 (when (overlays-at (point))
21560 (member 'invisible (overlay-properties
21561 (car (overlays-at (point)))))))))
21562 (when folded (org-cycle))
21563 (indent-for-tab-command)
21564 (while (and (move-beginning-of-line 2) (< (point) e))
21565 (indent-for-tab-command))
21566 (goto-char p)
21567 (when folded (org-cycle)))
21568 (message "Drawer at point indented"))
21570 (defun org-indent-block ()
21571 "Indent the block at point."
21572 (interactive)
21573 (let ((p (point))
21574 (case-fold-search t)
21575 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21576 (match-end 0)))
21577 (folded
21578 (save-excursion
21579 (end-of-line)
21580 (when (overlays-at (point))
21581 (member 'invisible (overlay-properties
21582 (car (overlays-at (point)))))))))
21583 (when folded (org-cycle))
21584 (indent-for-tab-command)
21585 (while (and (move-beginning-of-line 2) (< (point) e))
21586 (indent-for-tab-command))
21587 (goto-char p)
21588 (when folded (org-cycle)))
21589 (message "Block at point indented"))
21591 (defun org-indent-region (start end)
21592 "Indent region."
21593 (interactive "r")
21594 (save-excursion
21595 (let ((line-end (org-current-line end)))
21596 (goto-char start)
21597 (while (< (org-current-line) line-end)
21598 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21599 (t (call-interactively 'org-indent-line)))
21600 (move-beginning-of-line 2)))))
21603 ;;; Filling
21605 ;; We use our own fill-paragraph and auto-fill functions.
21607 ;; `org-fill-paragraph' relies on adaptive filling and context
21608 ;; checking. Appropriate `fill-prefix' is computed with
21609 ;; `org-adaptive-fill-function'.
21611 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21612 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21613 ;; `org-adaptive-fill-function' value. Internally,
21614 ;; `org-comment-line-break-function' breaks the line.
21616 ;; `org-setup-filling' installs filling and auto-filling related
21617 ;; variables during `org-mode' initialization.
21619 (defun org-setup-filling ()
21620 (interactive)
21621 ;; Prevent auto-fill from inserting unwanted new items.
21622 (when (boundp 'fill-nobreak-predicate)
21623 (org-set-local
21624 'fill-nobreak-predicate
21625 (org-uniquify
21626 (append fill-nobreak-predicate
21627 '(org-fill-paragraph-separate-nobreak-p
21628 org-fill-line-break-nobreak-p)))))
21629 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21630 (org-set-local 'auto-fill-inhibit-regexp nil)
21631 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21632 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21633 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21635 (defvar org-element-paragraph-separate) ; org-element.el
21636 (defun org-fill-paragraph-separate-nobreak-p ()
21637 "Non-nil when a line break at point would insert a new item."
21638 (looking-at (substring org-element-paragraph-separate 1)))
21640 (defun org-fill-line-break-nobreak-p ()
21641 "Non-nil when a line break at point would create an Org line break."
21642 (save-excursion
21643 (skip-chars-backward "[ \t]")
21644 (skip-chars-backward "\\\\")
21645 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21647 (declare-function message-in-body-p "message" ())
21648 (defvar orgtbl-line-start-regexp) ; From org-table.el
21649 (defun org-adaptive-fill-function ()
21650 "Compute a fill prefix for the current line.
21651 Return fill prefix, as a string, or nil if current line isn't
21652 meant to be filled."
21653 (let (prefix)
21654 (catch 'exit
21655 (when (derived-mode-p 'message-mode)
21656 (save-excursion
21657 (beginning-of-line)
21658 (cond ((or (not (message-in-body-p))
21659 (looking-at orgtbl-line-start-regexp))
21660 (throw 'exit nil))
21661 ((looking-at message-cite-prefix-regexp)
21662 (throw 'exit (match-string-no-properties 0)))
21663 ((looking-at org-outline-regexp)
21664 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21665 (org-with-wide-buffer
21666 (let* ((p (line-beginning-position))
21667 (element (save-excursion (beginning-of-line)
21668 (org-element-at-point)))
21669 (type (org-element-type element))
21670 (post-affiliated (org-element-property :post-affiliated element)))
21671 (unless (and post-affiliated (< p post-affiliated))
21672 (case type
21673 (comment (looking-at "[ \t]*# ?") (match-string 0))
21674 (footnote-definition "")
21675 ((item plain-list)
21676 (make-string (org-list-item-body-column
21677 (or post-affiliated
21678 (org-element-property :begin element)))
21679 ? ))
21680 (paragraph
21681 ;; Fill prefix is usually the same as the current line,
21682 ;; except if the paragraph is at the beginning of an item.
21683 (let ((parent (org-element-property :parent element)))
21684 (cond ((eq (org-element-type parent) 'item)
21685 (make-string (org-list-item-body-column
21686 (org-element-property :begin parent))
21687 ? ))
21688 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21689 (match-string 0))
21690 (t ""))))
21691 (comment-block
21692 ;; Only fill contents if P is within block boundaries.
21693 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21694 (forward-line)
21695 (point)))
21696 (cend (save-excursion
21697 (goto-char (org-element-property :end element))
21698 (skip-chars-backward " \r\t\n")
21699 (line-beginning-position))))
21700 (when (and (>= p cbeg) (< p cend))
21701 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21702 (match-string 0)
21703 "")))))))))))
21705 (declare-function message-goto-body "message" ())
21706 (defvar message-cite-prefix-regexp) ; From message.el
21707 (defvar org-element-all-objects) ; From org-element.el
21708 (defun org-fill-paragraph (&optional justify)
21709 "Fill element at point, when applicable.
21711 This function only applies to comment blocks, comments, example
21712 blocks and paragraphs. Also, as a special case, re-align table
21713 when point is at one.
21715 If JUSTIFY is non-nil (interactively, with prefix argument),
21716 justify as well. If `sentence-end-double-space' is non-nil, then
21717 period followed by one space does not end a sentence, so don't
21718 break a line there. The variable `fill-column' controls the
21719 width for filling.
21721 For convenience, when point is at a plain list, an item or
21722 a footnote definition, try to fill the first paragraph within."
21723 (interactive)
21724 (if (and (derived-mode-p 'message-mode)
21725 (or (not (message-in-body-p))
21726 (save-excursion (move-beginning-of-line 1)
21727 (looking-at message-cite-prefix-regexp))))
21728 ;; First ensure filling is correct in message-mode.
21729 (let ((fill-paragraph-function
21730 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21731 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21732 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21733 (paragraph-separate
21734 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21735 (fill-paragraph nil))
21736 (save-excursion
21737 ;; Move to end of line in order to get the first paragraph
21738 ;; within a plain list or a footnote definition.
21739 (end-of-line)
21740 (let ((element (org-element-at-point)))
21741 ;; First check if point is in a blank line at the beginning of
21742 ;; the buffer. In that case, ignore filling.
21743 (if (< (point) (org-element-property :begin element)) t
21744 (case (org-element-type element)
21745 ;; Use major mode filling function is src blocks.
21746 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21747 ;; Align Org tables, leave table.el tables as-is.
21748 (table-row (org-table-align) t)
21749 (table
21750 (when (eq (org-element-property :type element) 'org)
21751 (org-table-align))
21753 (paragraph
21754 ;; Paragraphs may contain `line-break' type objects.
21755 (let ((beg (max (point-min)
21756 (org-element-property :contents-begin element)))
21757 (end (min (point-max)
21758 (org-element-property :contents-end element))))
21759 ;; Do nothing if point is at an affiliated keyword.
21760 (if (< (point) beg) t
21761 (when (derived-mode-p 'message-mode)
21762 ;; In `message-mode', do not fill following
21763 ;; citation in current paragraph nor text before
21764 ;; message body.
21765 (let ((body-start (save-excursion (message-goto-body))))
21766 (when body-start (setq beg (max body-start beg))))
21767 (when (save-excursion
21768 (re-search-forward
21769 (concat "^" message-cite-prefix-regexp) end t))
21770 (setq end (match-beginning 0))))
21771 ;; Fill paragraph, taking line breaks into
21772 ;; consideration. For that, slice the paragraph
21773 ;; using line breaks as separators, and fill the
21774 ;; parts in reverse order to avoid messing with
21775 ;; markers.
21776 (save-excursion
21777 (goto-char end)
21778 (mapc
21779 (lambda (pos)
21780 (fill-region-as-paragraph pos (point) justify)
21781 (goto-char pos))
21782 ;; Find the list of ending positions for line
21783 ;; breaks in the current paragraph. Add paragraph
21784 ;; beginning to include first slice.
21785 (nreverse
21786 (cons
21788 (org-element-map
21789 (org-element--parse-objects
21790 beg end nil org-element-all-objects)
21791 'line-break
21792 (lambda (lb) (org-element-property :end lb)))))))
21793 t)))
21794 ;; Contents of `comment-block' type elements should be
21795 ;; filled as plain text, but only if point is within block
21796 ;; markers.
21797 (comment-block
21798 (let* ((case-fold-search t)
21799 (beg (save-excursion
21800 (goto-char (org-element-property :begin element))
21801 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21802 (forward-line)
21803 (point)))
21804 (end (save-excursion
21805 (goto-char (org-element-property :end element))
21806 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21807 (line-beginning-position))))
21808 (when (and (>= (point) beg) (< (point) end))
21809 (fill-region-as-paragraph
21810 (save-excursion
21811 (end-of-line)
21812 (re-search-backward "^[ \t]*$" beg 'move)
21813 (line-beginning-position))
21814 (save-excursion
21815 (beginning-of-line)
21816 (re-search-forward "^[ \t]*$" end 'move)
21817 (line-beginning-position))
21818 justify)))
21820 ;; Fill comments.
21821 (comment (fill-comment-paragraph justify))
21822 ;; Ignore every other element.
21823 (otherwise t)))))))
21825 (defun org-auto-fill-function ()
21826 "Auto-fill function."
21827 ;; Check if auto-filling is meaningful.
21828 (let ((fc (current-fill-column)))
21829 (when (and fc (> (current-column) fc))
21830 (let* ((fill-prefix (org-adaptive-fill-function))
21831 ;; Enforce empty fill prefix, if required. Otherwise, it
21832 ;; will be computed again.
21833 (adaptive-fill-mode (not (equal fill-prefix ""))))
21834 (when fill-prefix (do-auto-fill))))))
21836 (defun org-comment-line-break-function (&optional soft)
21837 "Break line at point and indent, continuing comment if within one.
21838 The inserted newline is marked hard if variable
21839 `use-hard-newlines' is true, unless optional argument SOFT is
21840 non-nil."
21841 (if soft (insert-and-inherit ?\n) (newline 1))
21842 (save-excursion (forward-char -1) (delete-horizontal-space))
21843 (delete-horizontal-space)
21844 (indent-to-left-margin)
21845 (insert-before-markers-and-inherit fill-prefix))
21848 ;;; Comments
21850 ;; Org comments syntax is quite complex. It requires the entire line
21851 ;; to be just a comment. Also, even with the right syntax at the
21852 ;; beginning of line, some some elements (i.e. verse-block or
21853 ;; example-block) don't accept comments. Usual Emacs comment commands
21854 ;; cannot cope with those requirements. Therefore, Org replaces them.
21856 ;; Org still relies on `comment-dwim', but cannot trust
21857 ;; `comment-only-p'. So, `comment-region-function' and
21858 ;; `uncomment-region-function' both point
21859 ;; to`org-comment-or-uncomment-region'. Eventually,
21860 ;; `org-insert-comment' takes care of insertion of comments at the
21861 ;; beginning of line.
21863 ;; `org-setup-comments-handling' install comments related variables
21864 ;; during `org-mode' initialization.
21866 (defun org-setup-comments-handling ()
21867 (interactive)
21868 (org-set-local 'comment-use-syntax nil)
21869 (org-set-local 'comment-start "# ")
21870 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21871 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21872 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21873 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21875 (defun org-insert-comment ()
21876 "Insert an empty comment above current line.
21877 If the line is empty, insert comment at its beginning."
21878 (beginning-of-line)
21879 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21880 (org-indent-line)
21881 (insert "# "))
21883 (defvar comment-empty-lines) ; From newcomment.el.
21884 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21885 "Comment or uncomment each non-blank line in the region.
21886 Uncomment each non-blank line between BEG and END if it only
21887 contains commented lines. Otherwise, comment them."
21888 (save-restriction
21889 ;; Restrict region
21890 (narrow-to-region (save-excursion (goto-char beg)
21891 (skip-chars-forward " \r\t\n" end)
21892 (line-beginning-position))
21893 (save-excursion (goto-char end)
21894 (skip-chars-backward " \r\t\n" beg)
21895 (line-end-position)))
21896 (let ((uncommentp
21897 ;; UNCOMMENTP is non-nil when every non blank line between
21898 ;; BEG and END is a comment.
21899 (save-excursion
21900 (goto-char (point-min))
21901 (while (and (not (eobp))
21902 (let ((element (org-element-at-point)))
21903 (and (eq (org-element-type element) 'comment)
21904 (goto-char (min (point-max)
21905 (org-element-property
21906 :end element)))))))
21907 (eobp))))
21908 (if uncommentp
21909 ;; Only blank lines and comments in region: uncomment it.
21910 (save-excursion
21911 (goto-char (point-min))
21912 (while (not (eobp))
21913 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21914 (replace-match "" nil nil nil 1))
21915 (forward-line)))
21916 ;; Comment each line in region.
21917 (let ((min-indent (point-max)))
21918 ;; First find the minimum indentation across all lines.
21919 (save-excursion
21920 (goto-char (point-min))
21921 (while (and (not (eobp)) (not (zerop min-indent)))
21922 (unless (looking-at "[ \t]*$")
21923 (setq min-indent (min min-indent (current-indentation))))
21924 (forward-line)))
21925 ;; Then loop over all lines.
21926 (save-excursion
21927 (goto-char (point-min))
21928 (while (not (eobp))
21929 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21930 (org-move-to-column min-indent t)
21931 (insert comment-start))
21932 (forward-line))))))))
21935 ;;; Planning
21937 ;; This section contains tools to operate on timestamp objects, as
21938 ;; returned by, e.g. `org-element-context'.
21940 (defun org-timestamp-has-time-p (timestamp)
21941 "Non-nil when TIMESTAMP has a time specified."
21942 (org-element-property :hour-start timestamp))
21944 (defun org-timestamp-format (timestamp format &optional end utc)
21945 "Format a TIMESTAMP element into a string.
21947 FORMAT is a format specifier to be passed to
21948 `format-time-string'.
21950 When optional argument END is non-nil, use end of date-range or
21951 time-range, if possible.
21953 When optional argument UTC is non-nil, time will be expressed as
21954 Universal Time."
21955 (format-time-string
21956 format
21957 (apply 'encode-time
21958 (cons 0
21959 (mapcar
21960 (lambda (prop) (or (org-element-property prop timestamp) 0))
21961 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21962 '(:minute-start :hour-start :day-start :month-start
21963 :year-start)))))
21964 utc))
21966 (defun org-timestamp-split-range (timestamp &optional end)
21967 "Extract a timestamp object from a date or time range.
21969 TIMESTAMP is a timestamp object. END, when non-nil, means extract
21970 the end of the range. Otherwise, extract its start.
21972 Return a new timestamp object sharing the same parent as
21973 TIMESTAMP."
21974 (let ((type (org-element-property :type timestamp)))
21975 (if (memq type '(active inactive diary)) timestamp
21976 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
21977 ;; Set new type.
21978 (org-element-put-property
21979 split-ts :type (if (eq type 'active-range) 'active 'inactive))
21980 ;; Copy start properties over end properties if END is
21981 ;; non-nil. Otherwise, copy end properties over `start' ones.
21982 (let ((p-alist '((:minute-start . :minute-end)
21983 (:hour-start . :hour-end)
21984 (:day-start . :day-end)
21985 (:month-start . :month-end)
21986 (:year-start . :year-end))))
21987 (dolist (p-cell p-alist)
21988 (org-element-put-property
21989 split-ts
21990 (funcall (if end 'car 'cdr) p-cell)
21991 (org-element-property
21992 (funcall (if end 'cdr 'car) p-cell) split-ts)))
21993 ;; Eventually refresh `:raw-value'.
21994 (org-element-put-property split-ts :raw-value nil)
21995 (org-element-put-property
21996 split-ts :raw-value (org-element-interpret-data split-ts)))))))
21998 (defun org-timestamp-translate (timestamp &optional boundary)
21999 "Apply `org-translate-time' on a TIMESTAMP object.
22000 When optional argument BOUNDARY is non-nil, it is either the
22001 symbol `start' or `end'. In this case, only translate the
22002 starting or ending part of TIMESTAMP if it is a date or time
22003 range. Otherwise, translate both parts."
22004 (if (and (not boundary)
22005 (memq (org-element-property :type timestamp)
22006 '(active-range inactive-range)))
22007 (concat
22008 (org-translate-time
22009 (org-element-property :raw-value
22010 (org-timestamp-split-range timestamp)))
22011 "--"
22012 (org-translate-time
22013 (org-element-property :raw-value
22014 (org-timestamp-split-range timestamp t))))
22015 (org-translate-time
22016 (org-element-property
22017 :raw-value
22018 (if (not boundary) timestamp
22019 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22023 ;;; Other stuff.
22025 (defun org-toggle-fixed-width-section (arg)
22026 "Toggle the fixed-width export.
22027 If there is no active region, the QUOTE keyword at the current headline is
22028 inserted or removed. When present, it causes the text between this headline
22029 and the next to be exported as fixed-width text, and unmodified.
22030 If there is an active region, this command adds or removes a colon as the
22031 first character of this line. If the first character of a line is a colon,
22032 this line is also exported in fixed-width font."
22033 (interactive "P")
22034 (let* ((cc 0)
22035 (regionp (org-region-active-p))
22036 (beg (if regionp (region-beginning) (point)))
22037 (end (if regionp (region-end)))
22038 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22039 (case-fold-search nil)
22040 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22041 off)
22042 (if regionp
22043 (save-excursion
22044 (goto-char beg)
22045 (setq cc (current-column))
22046 (beginning-of-line 1)
22047 (setq off (looking-at re))
22048 (while (> nlines 0)
22049 (setq nlines (1- nlines))
22050 (beginning-of-line 1)
22051 (cond
22052 (arg
22053 (org-move-to-column cc t)
22054 (insert ": \n")
22055 (forward-line -1))
22056 ((and off (looking-at re))
22057 (replace-match "" t t nil 1))
22058 ((not off) (org-move-to-column cc t) (insert ": ")))
22059 (forward-line 1)))
22060 (save-excursion
22061 (org-back-to-heading)
22062 (cond
22063 ((looking-at (format org-heading-keyword-regexp-format
22064 org-quote-string))
22065 (goto-char (match-end 1))
22066 (looking-at (concat " +" org-quote-string))
22067 (replace-match "" t t)
22068 (when (eolp) (insert " ")))
22069 ((looking-at org-outline-regexp)
22070 (goto-char (match-end 0))
22071 (insert org-quote-string " ")))))))
22073 (defun org-reftex-citation ()
22074 "Use reftex-citation to insert a citation into the buffer.
22075 This looks for a line like
22077 #+BIBLIOGRAPHY: foo plain option:-d
22079 and derives from it that foo.bib is the bibliography file relevant
22080 for this document. It then installs the necessary environment for RefTeX
22081 to work in this buffer and calls `reftex-citation' to insert a citation
22082 into the buffer.
22084 Export of such citations to both LaTeX and HTML is handled by the contributed
22085 package org-exp-bibtex by Taru Karttunen."
22086 (interactive)
22087 (let ((reftex-docstruct-symbol 'rds)
22088 (reftex-cite-format "\\cite{%l}")
22089 rds bib)
22090 (save-excursion
22091 (save-restriction
22092 (widen)
22093 (let ((case-fold-search t)
22094 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22095 (if (not (save-excursion
22096 (or (re-search-forward re nil t)
22097 (re-search-backward re nil t))))
22098 (error "No bibliography defined in file")
22099 (setq bib (concat (match-string 1) ".bib")
22100 rds (list (list 'bib bib)))))))
22101 (call-interactively 'reftex-citation)))
22103 ;;;; Functions extending outline functionality
22105 (defun org-beginning-of-line (&optional arg)
22106 "Go to the beginning of the current line. If that is invisible, continue
22107 to a visible line beginning. This makes the function of C-a more intuitive.
22108 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22109 first attempt, and only move to after the tags when the cursor is already
22110 beyond the end of the headline."
22111 (interactive "P")
22112 (let ((pos (point))
22113 (special (if (consp org-special-ctrl-a/e)
22114 (car org-special-ctrl-a/e)
22115 org-special-ctrl-a/e))
22116 refpos)
22117 (if (org-bound-and-true-p visual-line-mode)
22118 (beginning-of-visual-line 1)
22119 (beginning-of-line 1))
22120 (if (and arg (fboundp 'move-beginning-of-line))
22121 (call-interactively 'move-beginning-of-line)
22122 (if (bobp)
22124 (backward-char 1)
22125 (if (org-truely-invisible-p)
22126 (while (and (not (bobp)) (org-truely-invisible-p))
22127 (backward-char 1)
22128 (beginning-of-line 1))
22129 (forward-char 1))))
22130 (when special
22131 (cond
22132 ((and (looking-at org-complex-heading-regexp)
22133 (= (char-after (match-end 1)) ?\ ))
22134 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22135 (point-at-eol)))
22136 (goto-char
22137 (if (eq special t)
22138 (cond ((> pos refpos) refpos)
22139 ((= pos (point)) refpos)
22140 (t (point)))
22141 (cond ((> pos (point)) (point))
22142 ((not (eq last-command this-command)) (point))
22143 (t refpos)))))
22144 ((org-at-item-p)
22145 ;; Being at an item and not looking at an the item means point
22146 ;; was previously moved to beginning of a visual line, which
22147 ;; doesn't contain the item. Therefore, do nothing special,
22148 ;; just stay here.
22149 (when (looking-at org-list-full-item-re)
22150 ;; Set special position at first white space character after
22151 ;; bullet, and check-box, if any.
22152 (let ((after-bullet
22153 (let ((box (match-end 3)))
22154 (if (not box) (match-end 1)
22155 (let ((after (char-after box)))
22156 (if (and after (= after ? )) (1+ box) box))))))
22157 ;; Special case: Move point to special position when
22158 ;; currently after it or at beginning of line.
22159 (if (eq special t)
22160 (when (or (> pos after-bullet) (= (point) pos))
22161 (goto-char after-bullet))
22162 ;; Reversed case: Move point to special position when
22163 ;; point was already at beginning of line and command is
22164 ;; repeated.
22165 (when (and (= (point) pos) (eq last-command this-command))
22166 (goto-char after-bullet))))))))
22167 (org-no-warnings
22168 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22170 (defun org-end-of-line (&optional arg)
22171 "Go to the end of the line.
22172 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22173 tags on the first attempt, and only move to after the tags when
22174 the cursor is already beyond the end of the headline."
22175 (interactive "P")
22176 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22177 org-special-ctrl-a/e))
22178 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22179 'end-of-visual-line)
22180 ((fboundp 'move-end-of-line) 'move-end-of-line)
22181 (t 'end-of-line))))
22182 (if (or (not special) arg) (call-interactively move-fun)
22183 (let* ((element (save-excursion (beginning-of-line)
22184 (org-element-at-point)))
22185 (type (org-element-type element)))
22186 (cond
22187 ((memq type '(headline inlinetask))
22188 (let ((pos (point)))
22189 (beginning-of-line 1)
22190 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22191 (if (eq special t)
22192 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22193 (goto-char (match-beginning 1))
22194 (goto-char (match-end 0)))
22195 (if (or (< pos (match-end 0))
22196 (not (eq this-command last-command)))
22197 (goto-char (match-end 0))
22198 (goto-char (match-beginning 1))))
22199 (call-interactively move-fun))))
22200 ((org-element-property :hiddenp element)
22201 ;; If element is hidden, `move-end-of-line' would put point
22202 ;; after it. Use `end-of-line' to stay on current line.
22203 (call-interactively 'end-of-line))
22204 (t (call-interactively move-fun)))))
22205 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22207 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22208 (define-key org-mode-map "\C-e" 'org-end-of-line)
22210 (defun org-backward-sentence (&optional arg)
22211 "Go to beginning of sentence, or beginning of table field.
22212 This will call `backward-sentence' or `org-table-beginning-of-field',
22213 depending on context."
22214 (interactive "P")
22215 (cond
22216 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22217 (t (call-interactively 'backward-sentence))))
22219 (defun org-forward-sentence (&optional arg)
22220 "Go to end of sentence, or end of table field.
22221 This will call `forward-sentence' or `org-table-end-of-field',
22222 depending on context."
22223 (interactive "P")
22224 (cond
22225 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22226 (t (call-interactively 'forward-sentence))))
22228 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22229 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22231 (defun org-kill-line (&optional arg)
22232 "Kill line, to tags or end of line."
22233 (interactive "P")
22234 (cond
22235 ((or (not org-special-ctrl-k)
22236 (bolp)
22237 (not (org-at-heading-p)))
22238 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22239 org-ctrl-k-protect-subtree)
22240 (if (or (eq org-ctrl-k-protect-subtree 'error)
22241 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22242 (error "C-k aborted - would kill hidden subtree")))
22243 (call-interactively
22244 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22245 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22246 (kill-region (point) (match-beginning 1))
22247 (org-set-tags nil t))
22248 (t (kill-region (point) (point-at-eol)))))
22250 (define-key org-mode-map "\C-k" 'org-kill-line)
22252 (defun org-yank (&optional arg)
22253 "Yank. If the kill is a subtree, treat it specially.
22254 This command will look at the current kill and check if is a single
22255 subtree, or a series of subtrees[1]. If it passes the test, and if the
22256 cursor is at the beginning of a line or after the stars of a currently
22257 empty headline, then the yank is handled specially. How exactly depends
22258 on the value of the following variables, both set by default.
22260 org-yank-folded-subtrees
22261 When set, the subtree(s) will be folded after insertion, but only
22262 if doing so would now swallow text after the yanked text.
22264 org-yank-adjusted-subtrees
22265 When set, the subtree will be promoted or demoted in order to
22266 fit into the local outline tree structure, which means that the level
22267 will be adjusted so that it becomes the smaller one of the two
22268 *visible* surrounding headings.
22270 Any prefix to this command will cause `yank' to be called directly with
22271 no special treatment. In particular, a simple \\[universal-argument] prefix \
22272 will just
22273 plainly yank the text as it is.
22275 \[1] The test checks if the first non-white line is a heading
22276 and if there are no other headings with fewer stars."
22277 (interactive "P")
22278 (org-yank-generic 'yank arg))
22280 (defun org-yank-generic (command arg)
22281 "Perform some yank-like command.
22283 This function implements the behavior described in the `org-yank'
22284 documentation. However, it has been generalized to work for any
22285 interactive command with similar behavior."
22287 ;; pretend to be command COMMAND
22288 (setq this-command command)
22290 (if arg
22291 (call-interactively command)
22293 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22294 (and (org-kill-is-subtree-p)
22295 (or (bolp)
22296 (and (looking-at "[ \t]*$")
22297 (string-match
22298 "\\`\\*+\\'"
22299 (buffer-substring (point-at-bol) (point)))))))
22300 swallowp)
22301 (cond
22302 ((and subtreep org-yank-folded-subtrees)
22303 (let ((beg (point))
22304 end)
22305 (if (and subtreep org-yank-adjusted-subtrees)
22306 (org-paste-subtree nil nil 'for-yank)
22307 (call-interactively command))
22309 (setq end (point))
22310 (goto-char beg)
22311 (when (and (bolp) subtreep
22312 (not (setq swallowp
22313 (org-yank-folding-would-swallow-text beg end))))
22314 (org-with-limited-levels
22315 (or (looking-at org-outline-regexp)
22316 (re-search-forward org-outline-regexp-bol end t))
22317 (while (and (< (point) end) (looking-at org-outline-regexp))
22318 (hide-subtree)
22319 (org-cycle-show-empty-lines 'folded)
22320 (condition-case nil
22321 (outline-forward-same-level 1)
22322 (error (goto-char end))))))
22323 (when swallowp
22324 (message
22325 "Inserted text not folded because that would swallow text"))
22327 (goto-char end)
22328 (skip-chars-forward " \t\n\r")
22329 (beginning-of-line 1)
22330 (push-mark beg 'nomsg)))
22331 ((and subtreep org-yank-adjusted-subtrees)
22332 (let ((beg (point-at-bol)))
22333 (org-paste-subtree nil nil 'for-yank)
22334 (push-mark beg 'nomsg)))
22336 (call-interactively command))))))
22338 (defun org-yank-folding-would-swallow-text (beg end)
22339 "Would hide-subtree at BEG swallow any text after END?"
22340 (let (level)
22341 (org-with-limited-levels
22342 (save-excursion
22343 (goto-char beg)
22344 (when (or (looking-at org-outline-regexp)
22345 (re-search-forward org-outline-regexp-bol end t))
22346 (setq level (org-outline-level)))
22347 (goto-char end)
22348 (skip-chars-forward " \t\r\n\v\f")
22349 (if (or (eobp)
22350 (and (bolp) (looking-at org-outline-regexp)
22351 (<= (org-outline-level) level)))
22352 nil ; Nothing would be swallowed
22353 t))))) ; something would swallow
22355 (define-key org-mode-map "\C-y" 'org-yank)
22357 (defun org-truely-invisible-p ()
22358 "Check if point is at a character currently not visible.
22359 This version does not only check the character property, but also
22360 `visible-mode'."
22361 ;; Early versions of noutline don't have `outline-invisible-p'.
22362 (if (org-bound-and-true-p visible-mode)
22364 (outline-invisible-p)))
22366 (defun org-invisible-p2 ()
22367 "Check if point is at a character currently not visible."
22368 (save-excursion
22369 (if (and (eolp) (not (bobp))) (backward-char 1))
22370 ;; Early versions of noutline don't have `outline-invisible-p'.
22371 (outline-invisible-p)))
22373 (defun org-back-to-heading (&optional invisible-ok)
22374 "Call `outline-back-to-heading', but provide a better error message."
22375 (condition-case nil
22376 (outline-back-to-heading invisible-ok)
22377 (error (error "Before first headline at position %d in buffer %s"
22378 (point) (current-buffer)))))
22380 (defun org-before-first-heading-p ()
22381 "Before first heading?"
22382 (save-excursion
22383 (end-of-line)
22384 (null (re-search-backward org-outline-regexp-bol nil t))))
22386 (defun org-at-heading-p (&optional ignored)
22387 (outline-on-heading-p t))
22388 ;; Compatibility alias with Org versions < 7.8.03
22389 (defalias 'org-on-heading-p 'org-at-heading-p)
22391 (defun org-at-comment-p nil
22392 "Is cursor in a line starting with a # character?"
22393 (save-excursion
22394 (beginning-of-line)
22395 (looking-at "^#")))
22397 (defun org-at-drawer-p nil
22398 "Is cursor at a drawer keyword?"
22399 (save-excursion
22400 (move-beginning-of-line 1)
22401 (looking-at org-drawer-regexp)))
22403 (defun org-at-block-p nil
22404 "Is cursor at a block keyword?"
22405 (save-excursion
22406 (move-beginning-of-line 1)
22407 (looking-at org-block-regexp)))
22409 (defun org-point-at-end-of-empty-headline ()
22410 "If point is at the end of an empty headline, return t, else nil.
22411 If the heading only contains a TODO keyword, it is still still considered
22412 empty."
22413 (and (looking-at "[ \t]*$")
22414 (when org-todo-line-regexp
22415 (save-excursion
22416 (beginning-of-line 1)
22417 (let ((case-fold-search nil))
22418 (looking-at org-todo-line-regexp)
22419 (string= (match-string 3) ""))))))
22421 (defun org-at-heading-or-item-p ()
22422 (or (org-at-heading-p) (org-at-item-p)))
22424 (defun org-at-target-p ()
22425 (or (org-in-regexp org-radio-target-regexp)
22426 (org-in-regexp org-target-regexp)))
22427 ;; Compatibility alias with Org versions < 7.8.03
22428 (defalias 'org-on-target-p 'org-at-target-p)
22430 (defun org-up-heading-all (arg)
22431 "Move to the heading line of which the present line is a subheading.
22432 This function considers both visible and invisible heading lines.
22433 With argument, move up ARG levels."
22434 (if (fboundp 'outline-up-heading-all)
22435 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22436 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22438 (defun org-up-heading-safe ()
22439 "Move to the heading line of which the present line is a subheading.
22440 This version will not throw an error. It will return the level of the
22441 headline found, or nil if no higher level is found.
22443 Also, this function will be a lot faster than `outline-up-heading',
22444 because it relies on stars being the outline starters. This can really
22445 make a significant difference in outlines with very many siblings."
22446 (let (start-level re)
22447 (org-back-to-heading t)
22448 (setq start-level (funcall outline-level))
22449 (if (equal start-level 1)
22451 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22452 (if (re-search-backward re nil t)
22453 (funcall outline-level)))))
22455 (defun org-first-sibling-p ()
22456 "Is this heading the first child of its parents?"
22457 (interactive)
22458 (let ((re org-outline-regexp-bol)
22459 level l)
22460 (unless (org-at-heading-p t)
22461 (error "Not at a heading"))
22462 (setq level (funcall outline-level))
22463 (save-excursion
22464 (if (not (re-search-backward re nil t))
22466 (setq l (funcall outline-level))
22467 (< l level)))))
22469 (defun org-goto-sibling (&optional previous)
22470 "Goto the next sibling, even if it is invisible.
22471 When PREVIOUS is set, go to the previous sibling instead. Returns t
22472 when a sibling was found. When none is found, return nil and don't
22473 move point."
22474 (let ((fun (if previous 're-search-backward 're-search-forward))
22475 (pos (point))
22476 (re org-outline-regexp-bol)
22477 level l)
22478 (when (condition-case nil (org-back-to-heading t) (error nil))
22479 (setq level (funcall outline-level))
22480 (catch 'exit
22481 (or previous (forward-char 1))
22482 (while (funcall fun re nil t)
22483 (setq l (funcall outline-level))
22484 (when (< l level) (goto-char pos) (throw 'exit nil))
22485 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22486 (goto-char pos)
22487 nil))))
22489 (defun org-show-siblings ()
22490 "Show all siblings of the current headline."
22491 (save-excursion
22492 (while (org-goto-sibling) (org-flag-heading nil)))
22493 (save-excursion
22494 (while (org-goto-sibling 'previous)
22495 (org-flag-heading nil))))
22497 (defun org-goto-first-child ()
22498 "Goto the first child, even if it is invisible.
22499 Return t when a child was found. Otherwise don't move point and
22500 return nil."
22501 (let (level (pos (point)) (re org-outline-regexp-bol))
22502 (when (condition-case nil (org-back-to-heading t) (error nil))
22503 (setq level (outline-level))
22504 (forward-char 1)
22505 (if (and (re-search-forward re nil t) (> (outline-level) level))
22506 (progn (goto-char (match-beginning 0)) t)
22507 (goto-char pos) nil))))
22509 (defun org-show-hidden-entry ()
22510 "Show an entry where even the heading is hidden."
22511 (save-excursion
22512 (org-show-entry)))
22514 (defun org-flag-heading (flag &optional entry)
22515 "Flag the current heading. FLAG non-nil means make invisible.
22516 When ENTRY is non-nil, show the entire entry."
22517 (save-excursion
22518 (org-back-to-heading t)
22519 ;; Check if we should show the entire entry
22520 (if entry
22521 (progn
22522 (org-show-entry)
22523 (save-excursion
22524 (and (outline-next-heading)
22525 (org-flag-heading nil))))
22526 (outline-flag-region (max (point-min) (1- (point)))
22527 (save-excursion (outline-end-of-heading) (point))
22528 flag))))
22530 (defun org-get-next-sibling ()
22531 "Move to next heading of the same level, and return point.
22532 If there is no such heading, return nil.
22533 This is like outline-next-sibling, but invisible headings are ok."
22534 (let ((level (funcall outline-level)))
22535 (outline-next-heading)
22536 (while (and (not (eobp)) (> (funcall outline-level) level))
22537 (outline-next-heading))
22538 (if (or (eobp) (< (funcall outline-level) level))
22540 (point))))
22542 (defun org-get-last-sibling ()
22543 "Move to previous heading of the same level, and return point.
22544 If there is no such heading, return nil."
22545 (let ((opoint (point))
22546 (level (funcall outline-level)))
22547 (outline-previous-heading)
22548 (when (and (/= (point) opoint) (outline-on-heading-p t))
22549 (while (and (> (funcall outline-level) level)
22550 (not (bobp)))
22551 (outline-previous-heading))
22552 (if (< (funcall outline-level) level)
22554 (point)))))
22556 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22557 "Goto to the end of a subtree."
22558 ;; This contains an exact copy of the original function, but it uses
22559 ;; `org-back-to-heading', to make it work also in invisible
22560 ;; trees. And is uses an invisible-ok argument.
22561 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22562 ;; Furthermore, when used inside Org, finding the end of a large subtree
22563 ;; with many children and grandchildren etc, this can be much faster
22564 ;; than the outline version.
22565 (org-back-to-heading invisible-ok)
22566 (let ((first t)
22567 (level (funcall outline-level)))
22568 (if (and (derived-mode-p 'org-mode) (< level 1000))
22569 ;; A true heading (not a plain list item), in Org-mode
22570 ;; This means we can easily find the end by looking
22571 ;; only for the right number of stars. Using a regexp to do
22572 ;; this is so much faster than using a Lisp loop.
22573 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22574 (forward-char 1)
22575 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22576 ;; something else, do it the slow way
22577 (while (and (not (eobp))
22578 (or first (> (funcall outline-level) level)))
22579 (setq first nil)
22580 (outline-next-heading)))
22581 (unless to-heading
22582 (if (memq (preceding-char) '(?\n ?\^M))
22583 (progn
22584 ;; Go to end of line before heading
22585 (forward-char -1)
22586 (if (memq (preceding-char) '(?\n ?\^M))
22587 ;; leave blank line before heading
22588 (forward-char -1))))))
22589 (point))
22591 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22592 "Use Org version in org-mode, for dramatic speed-up."
22593 (if (derived-mode-p 'org-mode)
22594 (progn
22595 (org-end-of-subtree nil t)
22596 (unless (eobp) (backward-char 1)))
22597 ad-do-it))
22599 (defun org-end-of-meta-data-and-drawers ()
22600 "Jump to the first text after meta data and drawers in the current entry.
22601 This will move over empty lines, lines with planning time stamps,
22602 clocking lines, and drawers."
22603 (org-back-to-heading t)
22604 (let ((end (save-excursion (outline-next-heading) (point)))
22605 (re (concat "\\(" org-drawer-regexp "\\)"
22606 "\\|" "[ \t]*" org-keyword-time-regexp)))
22607 (forward-line 1)
22608 (while (re-search-forward re end t)
22609 (if (not (match-end 1))
22610 ;; empty or planning line
22611 (forward-line 1)
22612 ;; a drawer, find the end
22613 (re-search-forward "^[ \t]*:END:" end 'move)
22614 (forward-line 1)))
22615 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22616 (point)))
22618 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22619 "Move forward to the arg'th subheading at same level as this one.
22620 Stop at the first and last subheadings of a superior heading.
22621 Normally this only looks at visible headings, but when INVISIBLE-OK is
22622 non-nil it will also look at invisible ones."
22623 (interactive "p")
22624 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22625 (outline-next-heading)
22626 (org-at-heading-p)
22627 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22628 (re (format "^\\*\\{1,%d\\} " level))
22630 (forward-char 1)
22631 (while (> arg 0)
22632 (while (and (re-search-forward re nil 'move)
22633 (setq l (- (match-end 0) (match-beginning 0) 1))
22634 (= l level)
22635 (not invisible-ok)
22636 (progn (backward-char 1) (outline-invisible-p)))
22637 (if (< l level) (setq arg 1)))
22638 (setq arg (1- arg)))
22639 (beginning-of-line 1))))
22641 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22642 "Move backward to the arg'th subheading at same level as this one.
22643 Stop at the first and last subheadings of a superior heading."
22644 (interactive "p")
22645 (if (not (ignore-errors (org-back-to-heading)))
22646 (goto-char (point-min))
22647 (org-at-heading-p)
22648 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22649 (re (format "^\\*\\{1,%d\\} " level))
22651 (while (> arg 0)
22652 (while (and (re-search-backward re nil 'move)
22653 (setq l (- (match-end 0) (match-beginning 0) 1))
22654 (= l level)
22655 (not invisible-ok)
22656 (outline-invisible-p))
22657 (if (< l level) (setq arg 1)))
22658 (setq arg (1- arg))))))
22660 (defun org-forward-element ()
22661 "Move forward by one element.
22662 Move to the next element at the same level, when possible."
22663 (interactive)
22664 (cond ((eobp) (error "Cannot move further down"))
22665 ((org-with-limited-levels (org-at-heading-p))
22666 (let ((origin (point)))
22667 (org-forward-heading-same-level 1)
22668 (unless (org-with-limited-levels (org-at-heading-p))
22669 (goto-char origin)
22670 (error "Cannot move further down"))))
22672 (let* ((elem (org-element-at-point))
22673 (end (org-element-property :end elem))
22674 (parent (org-element-property :parent elem)))
22675 (if (and parent (= (org-element-property :contents-end parent) end))
22676 (goto-char (org-element-property :end parent))
22677 (goto-char end))))))
22679 (defun org-backward-element ()
22680 "Move backward by one element.
22681 Move to the previous element at the same level, when possible."
22682 (interactive)
22683 (cond ((bobp) (error "Cannot move further up"))
22684 ((org-with-limited-levels (org-at-heading-p))
22685 ;; At an headline, move to the previous one, if any, or stay
22686 ;; here.
22687 (let ((origin (point)))
22688 (org-backward-heading-same-level 1)
22689 (unless (org-with-limited-levels (org-at-heading-p))
22690 (goto-char origin)
22691 (error "Cannot move further up"))))
22693 (let* ((trail (org-element-at-point 'keep-trail))
22694 (elem (car trail))
22695 (prev-elem (nth 1 trail))
22696 (beg (org-element-property :begin elem)))
22697 (cond
22698 ;; Move to beginning of current element if point isn't
22699 ;; there already.
22700 ((/= (point) beg) (goto-char beg))
22701 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22702 ((org-before-first-heading-p) (goto-char (point-min)))
22703 (t (org-back-to-heading)))))))
22705 (defun org-up-element ()
22706 "Move to upper element."
22707 (interactive)
22708 (if (org-with-limited-levels (org-at-heading-p))
22709 (unless (org-up-heading-safe) (error "No surrounding element"))
22710 (let* ((elem (org-element-at-point))
22711 (parent (org-element-property :parent elem)))
22712 (if parent (goto-char (org-element-property :begin parent))
22713 (if (org-with-limited-levels (org-before-first-heading-p))
22714 (error "No surrounding element")
22715 (org-with-limited-levels (org-back-to-heading)))))))
22717 (defvar org-element-greater-elements)
22718 (defun org-down-element ()
22719 "Move to inner element."
22720 (interactive)
22721 (let ((element (org-element-at-point)))
22722 (cond
22723 ((memq (org-element-type element) '(plain-list table))
22724 (goto-char (org-element-property :contents-begin element))
22725 (forward-char))
22726 ((memq (org-element-type element) org-element-greater-elements)
22727 ;; If contents are hidden, first disclose them.
22728 (when (org-element-property :hiddenp element) (org-cycle))
22729 (goto-char (or (org-element-property :contents-begin element)
22730 (error "No content for this element"))))
22731 (t (error "No inner element")))))
22733 (defun org-drag-element-backward ()
22734 "Move backward element at point."
22735 (interactive)
22736 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22737 (let* ((trail (org-element-at-point 'keep-trail))
22738 (elem (car trail))
22739 (prev-elem (nth 1 trail)))
22740 ;; Error out if no previous element or previous element is
22741 ;; a parent of the current one.
22742 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22743 (error "Cannot drag element backward")
22744 (let ((pos (point)))
22745 (org-element-swap-A-B prev-elem elem)
22746 (goto-char (+ (org-element-property :begin prev-elem)
22747 (- pos (org-element-property :begin elem)))))))))
22749 (defun org-drag-element-forward ()
22750 "Move forward element at point."
22751 (interactive)
22752 (let* ((pos (point))
22753 (elem (org-element-at-point)))
22754 (when (= (point-max) (org-element-property :end elem))
22755 (error "Cannot drag element forward"))
22756 (goto-char (org-element-property :end elem))
22757 (let ((next-elem (org-element-at-point)))
22758 (when (or (org-element-nested-p elem next-elem)
22759 (and (eq (org-element-type next-elem) 'headline)
22760 (not (eq (org-element-type elem) 'headline))))
22761 (goto-char pos)
22762 (error "Cannot drag element forward"))
22763 ;; Compute new position of point: it's shifted by NEXT-ELEM
22764 ;; body's length (without final blanks) and by the length of
22765 ;; blanks between ELEM and NEXT-ELEM.
22766 (let ((size-next (- (save-excursion
22767 (goto-char (org-element-property :end next-elem))
22768 (skip-chars-backward " \r\t\n")
22769 (forward-line)
22770 ;; Small correction if buffer doesn't end
22771 ;; with a newline character.
22772 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22773 (org-element-property :begin next-elem)))
22774 (size-blank (- (org-element-property :end elem)
22775 (save-excursion
22776 (goto-char (org-element-property :end elem))
22777 (skip-chars-backward " \r\t\n")
22778 (forward-line)
22779 (point)))))
22780 (org-element-swap-A-B elem next-elem)
22781 (goto-char (+ pos size-next size-blank))))))
22783 (defun org-mark-element ()
22784 "Put point at beginning of this element, mark at end.
22786 Interactively, if this command is repeated or (in Transient Mark
22787 mode) if the mark is active, it marks the next element after the
22788 ones already marked."
22789 (interactive)
22790 (let (deactivate-mark)
22791 (if (and (org-called-interactively-p 'any)
22792 (or (and (eq last-command this-command) (mark t))
22793 (and transient-mark-mode mark-active)))
22794 (set-mark
22795 (save-excursion
22796 (goto-char (mark))
22797 (goto-char (org-element-property :end (org-element-at-point)))))
22798 (let ((element (org-element-at-point)))
22799 (end-of-line)
22800 (push-mark (org-element-property :end element) t t)
22801 (goto-char (org-element-property :begin element))))))
22803 (defun org-narrow-to-element ()
22804 "Narrow buffer to current element."
22805 (interactive)
22806 (let ((elem (org-element-at-point)))
22807 (cond
22808 ((eq (car elem) 'headline)
22809 (narrow-to-region
22810 (org-element-property :begin elem)
22811 (org-element-property :end elem)))
22812 ((memq (car elem) org-element-greater-elements)
22813 (narrow-to-region
22814 (org-element-property :contents-begin elem)
22815 (org-element-property :contents-end elem)))
22817 (narrow-to-region
22818 (org-element-property :begin elem)
22819 (org-element-property :end elem))))))
22821 (defun org-transpose-words ()
22822 "Transpose words, using `org-mode' syntax table."
22823 (interactive)
22824 (with-syntax-table org-syntax-table
22825 (call-interactively 'transpose-words)))
22826 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22828 (defun org-transpose-element ()
22829 "Transpose current and previous elements, keeping blank lines between.
22830 Point is moved after both elements."
22831 (interactive)
22832 (org-skip-whitespace)
22833 (let ((end (org-element-property :end (org-element-at-point))))
22834 (org-drag-element-backward)
22835 (goto-char end)))
22837 (defun org-unindent-buffer ()
22838 "Un-indent the visible part of the buffer.
22839 Relative indentation (between items, inside blocks, etc.) isn't
22840 modified."
22841 (interactive)
22842 (unless (eq major-mode 'org-mode)
22843 (error "Cannot un-indent a buffer not in Org mode"))
22844 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22845 unindent-tree ; For byte-compiler.
22846 (unindent-tree
22847 (function
22848 (lambda (contents)
22849 (mapc
22850 (lambda (element)
22851 (if (memq (org-element-type element) '(headline section))
22852 (funcall unindent-tree (org-element-contents element))
22853 (save-excursion
22854 (save-restriction
22855 (narrow-to-region
22856 (org-element-property :begin element)
22857 (org-element-property :end element))
22858 (org-do-remove-indentation)))))
22859 (reverse contents))))))
22860 (funcall unindent-tree (org-element-contents parse-tree))))
22862 (defun org-show-subtree ()
22863 "Show everything after this heading at deeper levels."
22864 (interactive)
22865 (outline-flag-region
22866 (point)
22867 (save-excursion
22868 (org-end-of-subtree t t))
22869 nil))
22871 (defun org-show-entry ()
22872 "Show the body directly following this heading.
22873 Show the heading too, if it is currently invisible."
22874 (interactive)
22875 (save-excursion
22876 (condition-case nil
22877 (progn
22878 (org-back-to-heading t)
22879 (outline-flag-region
22880 (max (point-min) (1- (point)))
22881 (save-excursion
22882 (if (re-search-forward
22883 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22884 (match-beginning 1)
22885 (point-max)))
22886 nil)
22887 (org-cycle-hide-drawers 'children))
22888 (error nil))))
22890 (defun org-make-options-regexp (kwds &optional extra)
22891 "Make a regular expression for keyword lines."
22892 (concat
22893 "^#\\+\\("
22894 (mapconcat 'regexp-quote kwds "\\|")
22895 (if extra (concat "\\|" extra))
22896 "\\):[ \t]*\\(.*\\)"))
22898 ;; Make isearch reveal the necessary context
22899 (defun org-isearch-end ()
22900 "Reveal context after isearch exits."
22901 (when isearch-success ; only if search was successful
22902 (if (featurep 'xemacs)
22903 ;; Under XEmacs, the hook is run in the correct place,
22904 ;; we directly show the context.
22905 (org-show-context 'isearch)
22906 ;; In Emacs the hook runs *before* restoring the overlays.
22907 ;; So we have to use a one-time post-command-hook to do this.
22908 ;; (Emacs 22 has a special variable, see function `org-mode')
22909 (unless (and (boundp 'isearch-mode-end-hook-quit)
22910 isearch-mode-end-hook-quit)
22911 ;; Only when the isearch was not quitted.
22912 (org-add-hook 'post-command-hook 'org-isearch-post-command
22913 'append 'local)))))
22915 (defun org-isearch-post-command ()
22916 "Remove self from hook, and show context."
22917 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22918 (org-show-context 'isearch))
22921 ;;;; Integration with and fixes for other packages
22923 ;;; Imenu support
22925 (defvar org-imenu-markers nil
22926 "All markers currently used by Imenu.")
22927 (make-variable-buffer-local 'org-imenu-markers)
22929 (defun org-imenu-new-marker (&optional pos)
22930 "Return a new marker for use by Imenu, and remember the marker."
22931 (let ((m (make-marker)))
22932 (move-marker m (or pos (point)))
22933 (push m org-imenu-markers)
22936 (defun org-imenu-get-tree ()
22937 "Produce the index for Imenu."
22938 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22939 (setq org-imenu-markers nil)
22940 (let* ((n org-imenu-depth)
22941 (re (concat "^" (org-get-limited-outline-regexp)))
22942 (subs (make-vector (1+ n) nil))
22943 (last-level 0)
22944 m level head)
22945 (save-excursion
22946 (save-restriction
22947 (widen)
22948 (goto-char (point-max))
22949 (while (re-search-backward re nil t)
22950 (setq level (org-reduced-level (funcall outline-level)))
22951 (when (and (<= level n)
22952 (looking-at org-complex-heading-regexp))
22953 (setq head (org-link-display-format
22954 (org-match-string-no-properties 4))
22955 m (org-imenu-new-marker))
22956 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22957 (if (>= level last-level)
22958 (push (cons head m) (aref subs level))
22959 (push (cons head (aref subs (1+ level))) (aref subs level))
22960 (loop for i from (1+ level) to n do (aset subs i nil)))
22961 (setq last-level level)))))
22962 (aref subs 1)))
22964 (eval-after-load "imenu"
22965 '(progn
22966 (add-hook 'imenu-after-jump-hook
22967 (lambda ()
22968 (if (derived-mode-p 'org-mode)
22969 (org-show-context 'org-goto))))))
22971 (defun org-link-display-format (link)
22972 "Replace a link with either the description, or the link target
22973 if no description is present"
22974 (save-match-data
22975 (if (string-match org-bracket-link-analytic-regexp link)
22976 (replace-match (if (match-end 5)
22977 (match-string 5 link)
22978 (concat (match-string 1 link)
22979 (match-string 3 link)))
22980 nil t link)
22981 link)))
22983 (defun org-toggle-link-display ()
22984 "Toggle the literal or descriptive display of links."
22985 (interactive)
22986 (if org-descriptive-links
22987 (progn (org-remove-from-invisibility-spec '(org-link))
22988 (org-restart-font-lock)
22989 (setq org-descriptive-links nil))
22990 (progn (add-to-invisibility-spec '(org-link))
22991 (org-restart-font-lock)
22992 (setq org-descriptive-links t))))
22994 ;; Speedbar support
22996 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22997 "Overlay marking the agenda restriction line in speedbar.")
22998 (overlay-put org-speedbar-restriction-lock-overlay
22999 'face 'org-agenda-restriction-lock)
23000 (overlay-put org-speedbar-restriction-lock-overlay
23001 'help-echo "Agendas are currently limited to this item.")
23002 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23004 (defun org-speedbar-set-agenda-restriction ()
23005 "Restrict future agenda commands to the location at point in speedbar.
23006 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23007 (interactive)
23008 (require 'org-agenda)
23009 (let (p m tp np dir txt)
23010 (cond
23011 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23012 'org-imenu t))
23013 (setq m (get-text-property p 'org-imenu-marker))
23014 (with-current-buffer (marker-buffer m)
23015 (goto-char m)
23016 (org-agenda-set-restriction-lock 'subtree)))
23017 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23018 'speedbar-function 'speedbar-find-file))
23019 (setq tp (previous-single-property-change
23020 (1+ p) 'speedbar-function)
23021 np (next-single-property-change
23022 tp 'speedbar-function)
23023 dir (speedbar-line-directory)
23024 txt (buffer-substring-no-properties (or tp (point-min))
23025 (or np (point-max))))
23026 (with-current-buffer (find-file-noselect
23027 (let ((default-directory dir))
23028 (expand-file-name txt)))
23029 (unless (derived-mode-p 'org-mode)
23030 (error "Cannot restrict to non-Org-mode file"))
23031 (org-agenda-set-restriction-lock 'file)))
23032 (t (error "Don't know how to restrict Org-mode's agenda")))
23033 (move-overlay org-speedbar-restriction-lock-overlay
23034 (point-at-bol) (point-at-eol))
23035 (setq current-prefix-arg nil)
23036 (org-agenda-maybe-redo)))
23038 (eval-after-load "speedbar"
23039 '(progn
23040 (speedbar-add-supported-extension ".org")
23041 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23042 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23043 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23044 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23045 (add-hook 'speedbar-visiting-tag-hook
23046 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23048 ;;; Fixes and Hacks for problems with other packages
23050 ;; Make flyspell not check words in links, to not mess up our keymap
23051 (defvar org-element-affiliated-keywords) ; From org-element.el
23052 (defvar org-element-block-name-alist) ; From org-element.el
23053 (defun org-mode-flyspell-verify ()
23054 "Don't let flyspell put overlays at active buttons, or on
23055 {todo,all-time,additional-option-like}-keywords."
23056 (let ((pos (max (1- (point)) (point-min)))
23057 (word (thing-at-point 'word)))
23058 (and (not (get-text-property pos 'keymap))
23059 (not (get-text-property pos 'org-no-flyspell))
23060 (not (member word org-todo-keywords-1))
23061 (not (member word org-all-time-keywords))
23062 (not (member word org-options-keywords))
23063 (not (member word (mapcar 'car org-startup-options)))
23064 (not (member-ignore-case word org-element-affiliated-keywords))
23065 (not (member-ignore-case word (org-get-export-keywords)))
23066 (not (member-ignore-case
23067 word (mapcar 'car org-element-block-name-alist)))
23068 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23070 (defun org-remove-flyspell-overlays-in (beg end)
23071 "Remove flyspell overlays in region."
23072 (and (org-bound-and-true-p flyspell-mode)
23073 (fboundp 'flyspell-delete-region-overlays)
23074 (flyspell-delete-region-overlays beg end))
23075 (add-text-properties beg end '(org-no-flyspell t)))
23077 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23078 (eval-after-load "bookmark"
23079 '(if (boundp 'bookmark-after-jump-hook)
23080 ;; We can use the hook
23081 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23082 ;; Hook not available, use advice
23083 (defadvice bookmark-jump (after org-make-visible activate)
23084 "Make the position visible."
23085 (org-bookmark-jump-unhide))))
23087 ;; Make sure saveplace shows the location if it was hidden
23088 (eval-after-load "saveplace"
23089 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23090 "Make the position visible."
23091 (org-bookmark-jump-unhide)))
23093 ;; Make sure ecb shows the location if it was hidden
23094 (eval-after-load "ecb"
23095 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23096 "Make hierarchy visible when jumping into location from ECB tree buffer."
23097 (if (derived-mode-p 'org-mode)
23098 (org-show-context))))
23100 (defun org-bookmark-jump-unhide ()
23101 "Unhide the current position, to show the bookmark location."
23102 (and (derived-mode-p 'org-mode)
23103 (or (outline-invisible-p)
23104 (save-excursion (goto-char (max (point-min) (1- (point))))
23105 (outline-invisible-p)))
23106 (org-show-context 'bookmark-jump)))
23108 ;; Make session.el ignore our circular variable
23109 (eval-after-load "session"
23110 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23112 ;;;; Experimental code
23114 (defun org-closed-in-range ()
23115 "Sparse tree of items closed in a certain time range.
23116 Still experimental, may disappear in the future."
23117 (interactive)
23118 ;; Get the time interval from the user.
23119 (let* ((time1 (org-float-time
23120 (org-read-date nil 'to-time nil "Starting date: ")))
23121 (time2 (org-float-time
23122 (org-read-date nil 'to-time nil "End date:")))
23123 ;; callback function
23124 (callback (lambda ()
23125 (let ((time
23126 (org-float-time
23127 (apply 'encode-time
23128 (org-parse-time-string
23129 (match-string 1))))))
23130 ;; check if time in interval
23131 (and (>= time time1) (<= time time2))))))
23132 ;; make tree, check each match with the callback
23133 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23135 ;;;; Finish up
23137 (provide 'org)
23139 (run-hooks 'org-load-hook)
23141 ;;; org.el ends here