org-agenda.el (org-agenda-refile): Enhance docstring. Allow to clear the refile...
[org-mode.git] / lisp / org.el
blob811506a4211c0816e0ec3c8817a1b3d4d0827938
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 a 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-clock-get-last-clock-out-time "org-clock" ())
121 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
122 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
123 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
125 (declare-function orgtbl-mode "org-table" (&optional arg))
126 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
127 (declare-function org-beamer-mode "ox-beamer" ())
128 (declare-function org-table-edit-field "org-table" (arg))
129 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-table-align "org-table" ())
135 (declare-function org-table-paste-rectangle "org-table" ())
136 (declare-function org-table-maybe-eval-formula "org-table" ())
137 (declare-function org-table-maybe-recalculate-line "org-table" ())
139 (declare-function org-element--parse-objects "org-element"
140 (beg end acc restriction))
141 (declare-function org-element-at-point "org-element" (&optional keep-trail))
142 (declare-function org-element-contents "org-element" (element))
143 (declare-function org-element-context "org-element" (&optional element))
144 (declare-function org-element-interpret-data "org-element"
145 (data &optional parent))
146 (declare-function org-element-map "org-element"
147 (data types fun &optional info first-match no-recursion))
148 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
149 (declare-function org-element-parse-buffer "org-element"
150 (&optional granularity visible-only))
151 (declare-function org-element-property "org-element" (property element))
152 (declare-function org-element-put-property "org-element"
153 (element property value))
154 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
155 (declare-function org-element--parse-objects "org-element"
156 (beg end acc restriction))
157 (declare-function org-element-parse-buffer "org-element"
158 (&optional granularity visible-only))
159 (declare-function org-element-restriction "org-element" (element))
160 (declare-function org-element-type "org-element" (element))
162 ;; load languages based on value of `org-babel-load-languages'
163 (defvar org-babel-load-languages)
165 ;;;###autoload
166 (defun org-babel-do-load-languages (sym value)
167 "Load the languages defined in `org-babel-load-languages'."
168 (set-default sym value)
169 (mapc (lambda (pair)
170 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
171 (if active
172 (progn
173 (require (intern (concat "ob-" lang))))
174 (progn
175 (funcall 'fmakunbound
176 (intern (concat "org-babel-execute:" lang)))
177 (funcall 'fmakunbound
178 (intern (concat "org-babel-expand-body:" lang)))))))
179 org-babel-load-languages))
181 (defcustom org-babel-load-languages '((emacs-lisp . t))
182 "Languages which can be evaluated in Org-mode buffers.
183 This list can be used to load support for any of the languages
184 below, note that each language will depend on a different set of
185 system executables and/or Emacs modes. When a language is
186 \"loaded\", then code blocks in that language can be evaluated
187 with `org-babel-execute-src-block' bound by default to C-c
188 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
189 be set to remove code block evaluation from the C-c C-c
190 keybinding. By default only Emacs Lisp (which has no
191 requirements) is loaded."
192 :group 'org-babel
193 :set 'org-babel-do-load-languages
194 :version "24.1"
195 :type '(alist :tag "Babel Languages"
196 :key-type
197 (choice
198 (const :tag "Awk" awk)
199 (const :tag "C" C)
200 (const :tag "R" R)
201 (const :tag "Asymptote" asymptote)
202 (const :tag "Calc" calc)
203 (const :tag "Clojure" clojure)
204 (const :tag "CSS" css)
205 (const :tag "Ditaa" ditaa)
206 (const :tag "Dot" dot)
207 (const :tag "Emacs Lisp" emacs-lisp)
208 (const :tag "Fortran" fortran)
209 (const :tag "Gnuplot" gnuplot)
210 (const :tag "Haskell" haskell)
211 (const :tag "IO" io)
212 (const :tag "Java" java)
213 (const :tag "Javascript" js)
214 (const :tag "LaTeX" latex)
215 (const :tag "Ledger" ledger)
216 (const :tag "Lilypond" lilypond)
217 (const :tag "Lisp" lisp)
218 (const :tag "Makefile" makefile)
219 (const :tag "Maxima" maxima)
220 (const :tag "Matlab" matlab)
221 (const :tag "Mscgen" mscgen)
222 (const :tag "Ocaml" ocaml)
223 (const :tag "Octave" octave)
224 (const :tag "Org" org)
225 (const :tag "Perl" perl)
226 (const :tag "Pico Lisp" picolisp)
227 (const :tag "PlantUML" plantuml)
228 (const :tag "Python" python)
229 (const :tag "Ruby" ruby)
230 (const :tag "Sass" sass)
231 (const :tag "Scala" scala)
232 (const :tag "Scheme" scheme)
233 (const :tag "Screen" screen)
234 (const :tag "Shell Script" sh)
235 (const :tag "Shen" shen)
236 (const :tag "Sql" sql)
237 (const :tag "Sqlite" sqlite))
238 :value-type (boolean :tag "Activate" :value t)))
240 ;;;; Customization variables
241 (defcustom org-clone-delete-id nil
242 "Remove ID property of clones of a subtree.
243 When non-nil, clones of a subtree don't inherit the ID property.
244 Otherwise they inherit the ID property with a new unique
245 identifier."
246 :type 'boolean
247 :version "24.1"
248 :group 'org-id)
250 ;;; Version
251 (org-check-version)
253 ;;;###autoload
254 (defun org-version (&optional here full message)
255 "Show the org-mode version in the echo area.
256 With prefix argument HERE, insert it at point.
257 When FULL is non-nil, use a verbose version string.
258 When MESSAGE is non-nil, display a message with the version."
259 (interactive "P")
260 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
261 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
262 (load-suffixes (list ".el"))
263 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
264 (org-trash (or
265 (and (fboundp 'org-release) (fboundp 'org-git-version))
266 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
267 (load-suffixes save-load-suffixes)
268 (org-version (org-release))
269 (git-version (org-git-version))
270 (version (format "Org-mode version %s (%s @ %s)"
271 org-version
272 git-version
273 (if org-install-dir
274 (if (string= org-dir org-install-dir)
275 org-install-dir
276 (concat "mixed installation! " org-install-dir " and " org-dir))
277 "org-loaddefs.el can not be found!")))
278 (_version (if full version org-version)))
279 (if (org-called-interactively-p 'interactive)
280 (if here
281 (insert version)
282 (message version))
283 (if message (message _version))
284 _version)))
286 (defconst org-version (org-version))
288 ;;; Compatibility constants
290 ;;; The custom variables
292 (defgroup org nil
293 "Outline-based notes management and organizer."
294 :tag "Org"
295 :group 'outlines
296 :group 'calendar)
298 (defcustom org-mode-hook nil
299 "Mode hook for Org-mode, run after the mode was turned on."
300 :group 'org
301 :type 'hook)
303 (defcustom org-load-hook nil
304 "Hook that is run after org.el has been loaded."
305 :group 'org
306 :type 'hook)
308 (defcustom org-log-buffer-setup-hook nil
309 "Hook that is run after an Org log buffer is created."
310 :group 'org
311 :version "24.1"
312 :type 'hook)
314 (defvar org-modules) ; defined below
315 (defvar org-modules-loaded nil
316 "Have the modules been loaded already?")
318 (defun org-load-modules-maybe (&optional force)
319 "Load all extensions listed in `org-modules'."
320 (when (or force (not org-modules-loaded))
321 (mapc (lambda (ext)
322 (condition-case nil (require ext)
323 (error (message "Problems while trying to load feature `%s'" ext))))
324 org-modules)
325 (setq org-modules-loaded t)))
327 (defun org-set-modules (var value)
328 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
329 (set var value)
330 (when (featurep 'org)
331 (org-load-modules-maybe 'force)))
333 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
334 "Modules that should always be loaded together with org.el.
336 If a description starts with <C>, the file is not part of Emacs
337 and loading it will require that you have downloaded and properly
338 installed the Org mode distribution.
340 You can also use this system to load external packages (i.e. neither Org
341 core modules, nor modules from the CONTRIB directory). Just add symbols
342 to the end of the list. If the package is called org-xyz.el, then you need
343 to add the symbol `xyz', and the package must have a call to:
345 \(provide 'org-xyz)
347 For export specific modules, see also `org-export-backends'."
348 :group 'org
349 :set 'org-set-modules
350 :version "24.4"
351 :package-version '(Org . "8.0")
352 :type
353 '(set :greedy t
354 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
355 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
356 (const :tag " crypt: Encryption of subtrees" org-crypt)
357 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
358 (const :tag " docview: Links to doc-view buffers" org-docview)
359 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
360 (const :tag " id: Global IDs for identifying entries" org-id)
361 (const :tag " info: Links to Info nodes" org-info)
362 (const :tag " habit: Track your consistency with habits" org-habit)
363 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
364 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
365 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
366 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
367 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
368 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
369 (const :tag " mouse: Additional mouse support" org-mouse)
371 (const :tag "C vm: Links to VM folders/messages" org-vm)
372 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
373 (const :tag "C w3m: Special cut/paste from w3m to Org-mode." org-w3m)
374 (const :tag "C mew: Links to Mew folders/messages" org-mew)
375 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
376 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
377 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
378 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
379 (const :tag "C collector: Collect properties into tables" org-collector)
380 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
381 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
382 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
383 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
384 (const :tag "C eval: Include command output as text" org-eval)
385 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
386 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
387 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
388 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
389 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
391 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
393 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
394 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
395 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
396 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
397 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
398 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
399 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
400 (const :tag "C mtags: Support for muse-like tags" org-mtags)
401 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
402 (const :tag "C registry: A registry for Org-mode links" org-registry)
403 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
404 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
405 (const :tag "C secretary: Team management with org-mode" org-secretary)
406 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
407 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
408 (const :tag "C track: Keep up with Org-mode development" org-track)
409 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
410 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
411 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
413 (defvar org-export-registered-backends) ; From ox.el
414 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
415 (defcustom org-export-backends '(ascii html icalendar latex)
416 "List of export back-ends that should be always available.
418 If a description starts with <C>, the file is not part of Emacs
419 and loading it will require that you have downloaded and properly
420 installed the Org mode distribution.
422 Unlike to `org-modules', libraries in this list will not be
423 loaded along with Org, but only once the export framework is
424 needed.
426 This variable needs to be set before org.el is loaded. If you
427 need to make a change while Emacs is running, use the customize
428 interface or run the following code, where VALUE stands for the
429 new value of the variable, after updating it:
431 \(progn
432 \(setq org-export-registered-backends
433 \(org-remove-if-not
434 \(lambda (backend)
435 \(or (memq backend val)
436 \(catch 'parentp
437 \(mapc
438 \(lambda (b)
439 \(and (org-export-derived-backend-p b (car backend))
440 \(throw 'parentp t)))
441 val)
442 nil)))
443 org-export-registered-backends))
444 \(let ((new-list (mapcar 'car org-export-registered-backends)))
445 \(dolist (backend val)
446 \(cond
447 \((not (load (format \"ox-%s\" backend) t t))
448 \(message \"Problems while trying to load export back-end `%s'\"
449 backend))
450 \((not (memq backend new-list)) (push backend new-list))))
451 \(set-default var new-list)))
453 Adding a back-end to this list will also pull the back-end it
454 depends on, if any."
455 :group 'org
456 :group 'org-export
457 :version "24.4"
458 :package-version '(Org . "8.0")
459 :initialize 'custom-initialize-set
460 :set (lambda (var val)
461 (if (not (featurep 'ox)) (set-default var val)
462 ;; Any back-end not required anymore (not present in VAL and not
463 ;; a parent of any back-end in the new value) is removed from the
464 ;; list of registered back-ends.
465 (setq org-export-registered-backends
466 (org-remove-if-not
467 (lambda (backend)
468 (or (memq backend val)
469 (catch 'parentp
470 (mapc
471 (lambda (b)
472 (and (org-export-derived-backend-p b (car backend))
473 (throw 'parentp t)))
474 val)
475 nil)))
476 org-export-registered-backends))
477 ;; Now build NEW-LIST of both new back-ends and required
478 ;; parents.
479 (let ((new-list (mapcar 'car org-export-registered-backends)))
480 (dolist (backend val)
481 (cond
482 ((not (load (format "ox-%s" backend) t t))
483 (message "Problems while trying to load export back-end `%s'"
484 backend))
485 ((not (memq backend new-list)) (push backend new-list))))
486 ;; Set VAR to that list with fixed dependencies.
487 (set-default var new-list))))
488 :type '(set :greedy t
489 (const :tag " ascii Export buffer to ASCII format" ascii)
490 (const :tag " beamer Export buffer to Beamer presentation" beamer)
491 (const :tag " html Export buffer to HTML format" html)
492 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
493 (const :tag " latex Export buffer to LaTeX format" latex)
494 (const :tag " man Export buffer to MAN format" man)
495 (const :tag " md Export buffer to Markdown format" md)
496 (const :tag " odt Export buffer to ODT format" odt)
497 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
498 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
499 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
500 (const :tag "C groff Export buffer to Groff format" groff)
501 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
502 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
504 (eval-after-load 'ox
505 '(mapc
506 (lambda (backend)
507 (condition-case nil (require (intern (format "ox-%s" backend)))
508 (error (message "Problems while trying to load export back-end `%s'"
509 backend))))
510 org-export-backends))
512 (defcustom org-support-shift-select nil
513 "Non-nil means make shift-cursor commands select text when possible.
515 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
516 start selecting a region, or enlarge regions started in this way.
517 In Org-mode, in special contexts, these same keys are used for
518 other purposes, important enough to compete with shift selection.
519 Org tries to balance these needs by supporting `shift-select-mode'
520 outside these special contexts, under control of this variable.
522 The default of this variable is nil, to avoid confusing behavior. Shifted
523 cursor keys will then execute Org commands in the following contexts:
524 - on a headline, changing TODO state (left/right) and priority (up/down)
525 - on a time stamp, changing the time
526 - in a plain list item, changing the bullet type
527 - in a property definition line, switching between allowed values
528 - in the BEGIN line of a clock table (changing the time block).
529 Outside these contexts, the commands will throw an error.
531 When this variable is t and the cursor is not in a special
532 context, Org-mode will support shift-selection for making and
533 enlarging regions. To make this more effective, the bullet
534 cycling will no longer happen anywhere in an item line, but only
535 if the cursor is exactly on the bullet.
537 If you set this variable to the symbol `always', then the keys
538 will not be special in headlines, property lines, and item lines,
539 to make shift selection work there as well. If this is what you
540 want, you can use the following alternative commands: `C-c C-t'
541 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
542 can be used to switch TODO sets, `C-c -' to cycle item bullet
543 types, and properties can be edited by hand or in column view.
545 However, when the cursor is on a timestamp, shift-cursor commands
546 will still edit the time stamp - this is just too good to give up.
548 XEmacs user should have this variable set to nil, because
549 `shift-select-mode' is in Emacs 23 or later only."
550 :group 'org
551 :type '(choice
552 (const :tag "Never" nil)
553 (const :tag "When outside special context" t)
554 (const :tag "Everywhere except timestamps" always)))
556 (defcustom org-loop-over-headlines-in-active-region nil
557 "Shall some commands act upon headlines in the active region?
559 When set to `t', some commands will be performed in all headlines
560 within the active region.
562 When set to `start-level', some commands will be performed in all
563 headlines within the active region, provided that these headlines
564 are of the same level than the first one.
566 When set to a string, those commands will be performed on the
567 matching headlines within the active region. Such string must be
568 a tags/property/todo match as it is used in the agenda tags view.
570 The list of commands is: `org-schedule', `org-deadline',
571 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
572 `org-archive-to-archive-sibling'. The archiving commands skip
573 already archived entries."
574 :type '(choice (const :tag "Don't loop" nil)
575 (const :tag "All headlines in active region" t)
576 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
577 (string :tag "Tags/Property/Todo matcher"))
578 :version "24.1"
579 :group 'org-todo
580 :group 'org-archive)
582 (defgroup org-startup nil
583 "Options concerning startup of Org-mode."
584 :tag "Org Startup"
585 :group 'org)
587 (defcustom org-startup-folded t
588 "Non-nil means entering Org-mode will switch to OVERVIEW.
589 This can also be configured on a per-file basis by adding one of
590 the following lines anywhere in the buffer:
592 #+STARTUP: fold (or `overview', this is equivalent)
593 #+STARTUP: nofold (or `showall', this is equivalent)
594 #+STARTUP: content
595 #+STARTUP: showeverything
597 By default, this option is ignored when Org opens agenda files
598 for the first time. If you want the agenda to honor the startup
599 option, set `org-agenda-inhibit-startup' to nil."
600 :group 'org-startup
601 :type '(choice
602 (const :tag "nofold: show all" nil)
603 (const :tag "fold: overview" t)
604 (const :tag "content: all headlines" content)
605 (const :tag "show everything, even drawers" showeverything)))
607 (defcustom org-startup-truncated t
608 "Non-nil means entering Org-mode will set `truncate-lines'.
609 This is useful since some lines containing links can be very long and
610 uninteresting. Also tables look terrible when wrapped."
611 :group 'org-startup
612 :type 'boolean)
614 (defcustom org-startup-indented nil
615 "Non-nil means turn on `org-indent-mode' on startup.
616 This can also be configured on a per-file basis by adding one of
617 the following lines anywhere in the buffer:
619 #+STARTUP: indent
620 #+STARTUP: noindent"
621 :group 'org-structure
622 :type '(choice
623 (const :tag "Not" nil)
624 (const :tag "Globally (slow on startup in large files)" t)))
626 (defcustom org-use-sub-superscripts t
627 "Non-nil means interpret \"_\" and \"^\" for display.
628 When this option is turned on, you can use TeX-like syntax for sub- and
629 superscripts. Several characters after \"_\" or \"^\" will be
630 considered as a single item - so grouping with {} is normally not
631 needed. For example, the following things will be parsed as single
632 sub- or superscripts.
634 10^24 or 10^tau several digits will be considered 1 item.
635 10^-12 or 10^-tau a leading sign with digits or a word
636 x^2-y^3 will be read as x^2 - y^3, because items are
637 terminated by almost any nonword/nondigit char.
638 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
640 Still, ambiguity is possible - so when in doubt use {} to enclose
641 the sub/superscript. If you set this variable to the symbol
642 `{}', the braces are *required* in order to trigger
643 interpretations as sub/superscript. This can be helpful in
644 documents that need \"_\" frequently in plain text."
645 :group 'org-startup
646 :version "24.1"
647 :type '(choice
648 (const :tag "Always interpret" t)
649 (const :tag "Only with braces" {})
650 (const :tag "Never interpret" nil)))
652 (defcustom org-startup-with-beamer-mode nil
653 "Non-nil means turn on `org-beamer-mode' on startup.
654 This can also be configured on a per-file basis by adding one of
655 the following lines anywhere in the buffer:
657 #+STARTUP: beamer"
658 :group 'org-startup
659 :version "24.1"
660 :type 'boolean)
662 (defcustom org-startup-align-all-tables nil
663 "Non-nil means align all tables when visiting a file.
664 This is useful when the column width in tables is forced with <N> cookies
665 in table fields. Such tables will look correct only after the first re-align.
666 This can also be configured on a per-file basis by adding one of
667 the following lines anywhere in the buffer:
668 #+STARTUP: align
669 #+STARTUP: noalign"
670 :group 'org-startup
671 :type 'boolean)
673 (defcustom org-startup-with-inline-images nil
674 "Non-nil means show inline images when loading a new Org file.
675 This can also be configured on a per-file basis by adding one of
676 the following lines anywhere in the buffer:
677 #+STARTUP: inlineimages
678 #+STARTUP: noinlineimages"
679 :group 'org-startup
680 :version "24.1"
681 :type 'boolean)
683 (defcustom org-startup-with-latex-preview nil
684 "Non-nil means preview LaTeX fragments when loading a new Org file.
686 This can also be configured on a per-file basis by adding one of
687 the followinglines anywhere in the buffer:
688 #+STARTUP: latexpreview
689 #+STARTUP: nolatexpreview"
690 :group 'org-startup
691 :version "24.4"
692 :package-version '(Org . "8.0")
693 :type 'boolean)
695 (defcustom org-insert-mode-line-in-empty-file nil
696 "Non-nil means insert the first line setting Org-mode in empty files.
697 When the function `org-mode' is called interactively in an empty file, this
698 normally means that the file name does not automatically trigger Org-mode.
699 To ensure that the file will always be in Org-mode in the future, a
700 line enforcing Org-mode will be inserted into the buffer, if this option
701 has been set."
702 :group 'org-startup
703 :type 'boolean)
705 (defcustom org-replace-disputed-keys nil
706 "Non-nil means use alternative key bindings for some keys.
707 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
708 These keys are also used by other packages like shift-selection-mode'
709 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
710 If you want to use Org-mode together with one of these other modes,
711 or more generally if you would like to move some Org-mode commands to
712 other keys, set this variable and configure the keys with the variable
713 `org-disputed-keys'.
715 This option is only relevant at load-time of Org-mode, and must be set
716 *before* org.el is loaded. Changing it requires a restart of Emacs to
717 become effective."
718 :group 'org-startup
719 :type 'boolean)
721 (defcustom org-use-extra-keys nil
722 "Non-nil means use extra key sequence definitions for certain commands.
723 This happens automatically if you run XEmacs or if `window-system'
724 is nil. This variable lets you do the same manually. You must
725 set it before loading org.
727 Example: on Carbon Emacs 22 running graphically, with an external
728 keyboard on a Powerbook, the default way of setting M-left might
729 not work for either Alt or ESC. Setting this variable will make
730 it work for ESC."
731 :group 'org-startup
732 :type 'boolean)
734 (if (fboundp 'defvaralias)
735 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
737 (defcustom org-disputed-keys
738 '(([(shift up)] . [(meta p)])
739 ([(shift down)] . [(meta n)])
740 ([(shift left)] . [(meta -)])
741 ([(shift right)] . [(meta +)])
742 ([(control shift right)] . [(meta shift +)])
743 ([(control shift left)] . [(meta shift -)]))
744 "Keys for which Org-mode and other modes compete.
745 This is an alist, cars are the default keys, second element specifies
746 the alternative to use when `org-replace-disputed-keys' is t.
748 Keys can be specified in any syntax supported by `define-key'.
749 The value of this option takes effect only at Org-mode's startup,
750 therefore you'll have to restart Emacs to apply it after changing."
751 :group 'org-startup
752 :type 'alist)
754 (defun org-key (key)
755 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
756 Or return the original if not disputed.
757 Also apply the translations defined in `org-xemacs-key-equivalents'."
758 (when org-replace-disputed-keys
759 (let* ((nkey (key-description key))
760 (x (org-find-if (lambda (x)
761 (equal (key-description (car x)) nkey))
762 org-disputed-keys)))
763 (setq key (if x (cdr x) key))))
764 (when (featurep 'xemacs)
765 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
766 key)
768 (defun org-find-if (predicate seq)
769 (catch 'exit
770 (while seq
771 (if (funcall predicate (car seq))
772 (throw 'exit (car seq))
773 (pop seq)))))
775 (defun org-defkey (keymap key def)
776 "Define a key, possibly translated, as returned by `org-key'."
777 (define-key keymap (org-key key) def))
779 (defcustom org-ellipsis nil
780 "The ellipsis to use in the Org-mode outline.
781 When nil, just use the standard three dots. When a string, use that instead,
782 When a face, use the standard 3 dots, but with the specified face.
783 The change affects only Org-mode (which will then use its own display table).
784 Changing this requires executing `M-x org-mode' in a buffer to become
785 effective."
786 :group 'org-startup
787 :type '(choice (const :tag "Default" nil)
788 (face :tag "Face" :value org-warning)
789 (string :tag "String" :value "...#")))
791 (defvar org-display-table nil
792 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
794 (defgroup org-keywords nil
795 "Keywords in Org-mode."
796 :tag "Org Keywords"
797 :group 'org)
799 (defcustom org-deadline-string "DEADLINE:"
800 "String to mark deadline entries.
801 A deadline is this string, followed by a time stamp. Should be a word,
802 terminated by a colon. You can insert a schedule keyword and
803 a timestamp with \\[org-deadline].
804 Changes become only effective after restarting Emacs."
805 :group 'org-keywords
806 :type 'string)
808 (defcustom org-scheduled-string "SCHEDULED:"
809 "String to mark scheduled TODO entries.
810 A schedule is this string, followed by a time stamp. Should be a word,
811 terminated by a colon. You can insert a schedule keyword and
812 a timestamp with \\[org-schedule].
813 Changes become only effective after restarting Emacs."
814 :group 'org-keywords
815 :type 'string)
817 (defcustom org-closed-string "CLOSED:"
818 "String used as the prefix for timestamps logging closing a TODO entry."
819 :group 'org-keywords
820 :type 'string)
822 (defcustom org-clock-string "CLOCK:"
823 "String used as prefix for timestamps clocking work hours on an item."
824 :group 'org-keywords
825 :type 'string)
827 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
828 org-scheduled-string "\\|"
829 org-deadline-string "\\|"
830 org-closed-string "\\|"
831 org-clock-string "\\)")
832 "Matches a line with planning or clock info.")
834 (defcustom org-comment-string "COMMENT"
835 "Entries starting with this keyword will never be exported.
836 An entry can be toggled between COMMENT and normal with
837 \\[org-toggle-comment].
838 Changes become only effective after restarting Emacs."
839 :group 'org-keywords
840 :type 'string)
842 (defcustom org-quote-string "QUOTE"
843 "Entries starting with this keyword will be exported in fixed-width font.
844 Quoting applies only to the text in the entry following the headline, and does
845 not extend beyond the next headline, even if that is lower level.
846 An entry can be toggled between QUOTE and normal with
847 \\[org-toggle-fixed-width-section]."
848 :group 'org-keywords
849 :type 'string)
851 (defconst org-repeat-re
852 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
853 "Regular expression for specifying repeated events.
854 After a match, group 1 contains the repeat expression.")
856 (defgroup org-structure nil
857 "Options concerning the general structure of Org-mode files."
858 :tag "Org Structure"
859 :group 'org)
861 (defgroup org-reveal-location nil
862 "Options about how to make context of a location visible."
863 :tag "Org Reveal Location"
864 :group 'org-structure)
866 (defconst org-context-choice
867 '(choice
868 (const :tag "Always" t)
869 (const :tag "Never" nil)
870 (repeat :greedy t :tag "Individual contexts"
871 (cons
872 (choice :tag "Context"
873 (const agenda)
874 (const org-goto)
875 (const occur-tree)
876 (const tags-tree)
877 (const link-search)
878 (const mark-goto)
879 (const bookmark-jump)
880 (const isearch)
881 (const default))
882 (boolean))))
883 "Contexts for the reveal options.")
885 (defcustom org-show-hierarchy-above '((default . t))
886 "Non-nil means show full hierarchy when revealing a location.
887 Org-mode often shows locations in an org-mode file which might have
888 been invisible before. When this is set, the hierarchy of headings
889 above the exposed location is shown.
890 Turning this off for example for sparse trees makes them very compact.
891 Instead of t, this can also be an alist specifying this option for different
892 contexts. Valid contexts are
893 agenda when exposing an entry from the agenda
894 org-goto when using the command `org-goto' on key C-c C-j
895 occur-tree when using the command `org-occur' on key C-c /
896 tags-tree when constructing a sparse tree based on tags matches
897 link-search when exposing search matches associated with a link
898 mark-goto when exposing the jump goal of a mark
899 bookmark-jump when exposing a bookmark location
900 isearch when exiting from an incremental search
901 default default for all contexts not set explicitly"
902 :group 'org-reveal-location
903 :type org-context-choice)
905 (defcustom org-show-following-heading '((default . nil))
906 "Non-nil means show following heading when revealing a location.
907 Org-mode often shows locations in an org-mode file which might have
908 been invisible before. When this is set, the heading following the
909 match is shown.
910 Turning this off for example for sparse trees makes them very compact,
911 but makes it harder to edit the location of the match. In such a case,
912 use the command \\[org-reveal] to show more context.
913 Instead of t, this can also be an alist specifying this option for different
914 contexts. See `org-show-hierarchy-above' for valid contexts."
915 :group 'org-reveal-location
916 :type org-context-choice)
918 (defcustom org-show-siblings '((default . nil) (isearch t))
919 "Non-nil means show all sibling heading when revealing a location.
920 Org-mode often shows locations in an org-mode file which might have
921 been invisible before. When this is set, the sibling of the current entry
922 heading are all made visible. If `org-show-hierarchy-above' is t,
923 the same happens on each level of the hierarchy above the current entry.
925 By default this is on for the isearch context, off for all other contexts.
926 Turning this off for example for sparse trees makes them very compact,
927 but makes it harder to edit the location of the match. In such a case,
928 use the command \\[org-reveal] to show more context.
929 Instead of t, this can also be an alist specifying this option for different
930 contexts. See `org-show-hierarchy-above' for valid contexts."
931 :group 'org-reveal-location
932 :type org-context-choice)
934 (defcustom org-show-entry-below '((default . nil))
935 "Non-nil means show the entry below a headline when revealing a location.
936 Org-mode often shows locations in an org-mode file which might have
937 been invisible before. When this is set, the text below the headline that is
938 exposed is also shown.
940 By default this is off for all contexts.
941 Instead of t, this can also be an alist specifying this option for different
942 contexts. See `org-show-hierarchy-above' for valid contexts."
943 :group 'org-reveal-location
944 :type org-context-choice)
946 (defcustom org-indirect-buffer-display 'other-window
947 "How should indirect tree buffers be displayed?
948 This applies to indirect buffers created with the commands
949 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
950 Valid values are:
951 current-window Display in the current window
952 other-window Just display in another window.
953 dedicated-frame Create one new frame, and re-use it each time.
954 new-frame Make a new frame each time. Note that in this case
955 previously-made indirect buffers are kept, and you need to
956 kill these buffers yourself."
957 :group 'org-structure
958 :group 'org-agenda-windows
959 :type '(choice
960 (const :tag "In current window" current-window)
961 (const :tag "In current frame, other window" other-window)
962 (const :tag "Each time a new frame" new-frame)
963 (const :tag "One dedicated frame" dedicated-frame)))
965 (defcustom org-use-speed-commands nil
966 "Non-nil means activate single letter commands at beginning of a headline.
967 This may also be a function to test for appropriate locations where speed
968 commands should be active."
969 :group 'org-structure
970 :type '(choice
971 (const :tag "Never" nil)
972 (const :tag "At beginning of headline stars" t)
973 (function)))
975 (defcustom org-speed-commands-user nil
976 "Alist of additional speed commands.
977 This list will be checked before `org-speed-commands-default'
978 when the variable `org-use-speed-commands' is non-nil
979 and when the cursor is at the beginning of a headline.
980 The car if each entry is a string with a single letter, which must
981 be assigned to `self-insert-command' in the global map.
982 The cdr is either a command to be called interactively, a function
983 to be called, or a form to be evaluated.
984 An entry that is just a list with a single string will be interpreted
985 as a descriptive headline that will be added when listing the speed
986 commands in the Help buffer using the `?' speed command."
987 :group 'org-structure
988 :type '(repeat :value ("k" . ignore)
989 (choice :value ("k" . ignore)
990 (list :tag "Descriptive Headline" (string :tag "Headline"))
991 (cons :tag "Letter and Command"
992 (string :tag "Command letter")
993 (choice
994 (function)
995 (sexp))))))
997 (defgroup org-cycle nil
998 "Options concerning visibility cycling in Org-mode."
999 :tag "Org Cycle"
1000 :group 'org-structure)
1002 (defcustom org-cycle-skip-children-state-if-no-children t
1003 "Non-nil means skip CHILDREN state in entries that don't have any."
1004 :group 'org-cycle
1005 :type 'boolean)
1007 (defcustom org-cycle-max-level nil
1008 "Maximum level which should still be subject to visibility cycling.
1009 Levels higher than this will, for cycling, be treated as text, not a headline.
1010 When `org-odd-levels-only' is set, a value of N in this variable actually
1011 means 2N-1 stars as the limiting headline.
1012 When nil, cycle all levels.
1013 Note that the limiting level of cycling is also influenced by
1014 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1015 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1016 than its value."
1017 :group 'org-cycle
1018 :type '(choice
1019 (const :tag "No limit" nil)
1020 (integer :tag "Maximum level")))
1022 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1023 "Names of drawers. Drawers are not opened by cycling on the headline above.
1024 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1025 this:
1026 :DRAWERNAME:
1027 .....
1028 :END:
1029 The drawer \"PROPERTIES\" is special for capturing properties through
1030 the property API.
1032 Drawers can be defined on the per-file basis with a line like:
1034 #+DRAWERS: HIDDEN STATE PROPERTIES"
1035 :group 'org-structure
1036 :group 'org-cycle
1037 :type '(repeat (string :tag "Drawer Name")))
1039 (defcustom org-hide-block-startup nil
1040 "Non-nil means entering Org-mode will fold all blocks.
1041 This can also be set in on a per-file basis with
1043 #+STARTUP: hideblocks
1044 #+STARTUP: showblocks"
1045 :group 'org-startup
1046 :group 'org-cycle
1047 :type 'boolean)
1049 (defcustom org-cycle-global-at-bob nil
1050 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1051 This makes it possible to do global cycling without having to use S-TAB or
1052 \\[universal-argument] TAB. For this special case to work, the first line
1053 of the buffer must not be a headline -- it may be empty or some other text.
1054 When used in this way, `org-cycle-hook' is disabled temporarily to make
1055 sure the cursor stays at the beginning of the buffer. When this option is
1056 nil, don't do anything special at the beginning of the buffer."
1057 :group 'org-cycle
1058 :type 'boolean)
1060 (defcustom org-cycle-level-after-item/entry-creation t
1061 "Non-nil means cycle entry level or item indentation in new empty entries.
1063 When the cursor is at the end of an empty headline, i.e., with only stars
1064 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1065 and then all possible ancestor states, before returning to the original state.
1066 This makes data entry extremely fast: M-RET to create a new headline,
1067 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1069 When the cursor is at the end of an empty plain list item, one TAB will
1070 make it a subitem, two or more tabs will back up to make this an item
1071 higher up in the item hierarchy."
1072 :group 'org-cycle
1073 :type 'boolean)
1075 (defcustom org-cycle-emulate-tab t
1076 "Where should `org-cycle' emulate TAB.
1077 nil Never
1078 white Only in completely white lines
1079 whitestart Only at the beginning of lines, before the first non-white char
1080 t Everywhere except in headlines
1081 exc-hl-bol Everywhere except at the start of a headline
1082 If TAB is used in a place where it does not emulate TAB, the current subtree
1083 visibility is cycled."
1084 :group 'org-cycle
1085 :type '(choice (const :tag "Never" nil)
1086 (const :tag "Only in completely white lines" white)
1087 (const :tag "Before first char in a line" whitestart)
1088 (const :tag "Everywhere except in headlines" t)
1089 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1092 (defcustom org-cycle-separator-lines 2
1093 "Number of empty lines needed to keep an empty line between collapsed trees.
1094 If you leave an empty line between the end of a subtree and the following
1095 headline, this empty line is hidden when the subtree is folded.
1096 Org-mode will leave (exactly) one empty line visible if the number of
1097 empty lines is equal or larger to the number given in this variable.
1098 So the default 2 means at least 2 empty lines after the end of a subtree
1099 are needed to produce free space between a collapsed subtree and the
1100 following headline.
1102 If the number is negative, and the number of empty lines is at least -N,
1103 all empty lines are shown.
1105 Special case: when 0, never leave empty lines in collapsed view."
1106 :group 'org-cycle
1107 :type 'integer)
1108 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1110 (defcustom org-pre-cycle-hook nil
1111 "Hook that is run before visibility cycling is happening.
1112 The function(s) in this hook must accept a single argument which indicates
1113 the new state that will be set right after running this hook. The
1114 argument is a symbol. Before a global state change, it can have the values
1115 `overview', `content', or `all'. Before a local state change, it can have
1116 the values `folded', `children', or `subtree'."
1117 :group 'org-cycle
1118 :type 'hook)
1120 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1121 org-cycle-hide-drawers
1122 org-cycle-hide-inline-tasks
1123 org-cycle-show-empty-lines
1124 org-optimize-window-after-visibility-change)
1125 "Hook that is run after `org-cycle' has changed the buffer visibility.
1126 The function(s) in this hook must accept a single argument which indicates
1127 the new state that was set by the most recent `org-cycle' command. The
1128 argument is a symbol. After a global state change, it can have the values
1129 `overview', `contents', or `all'. After a local state change, it can have
1130 the values `folded', `children', or `subtree'."
1131 :group 'org-cycle
1132 :type 'hook)
1134 (defgroup org-edit-structure nil
1135 "Options concerning structure editing in Org-mode."
1136 :tag "Org Edit Structure"
1137 :group 'org-structure)
1139 (defcustom org-odd-levels-only nil
1140 "Non-nil means skip even levels and only use odd levels for the outline.
1141 This has the effect that two stars are being added/taken away in
1142 promotion/demotion commands. It also influences how levels are
1143 handled by the exporters.
1144 Changing it requires restart of `font-lock-mode' to become effective
1145 for fontification also in regions already fontified.
1146 You may also set this on a per-file basis by adding one of the following
1147 lines to the buffer:
1149 #+STARTUP: odd
1150 #+STARTUP: oddeven"
1151 :group 'org-edit-structure
1152 :group 'org-appearance
1153 :type 'boolean)
1155 (defcustom org-adapt-indentation t
1156 "Non-nil means adapt indentation to outline node level.
1158 When this variable is set, Org assumes that you write outlines by
1159 indenting text in each node to align with the headline (after the stars).
1160 The following issues are influenced by this variable:
1162 - When this is set and the *entire* text in an entry is indented, the
1163 indentation is increased by one space in a demotion command, and
1164 decreased by one in a promotion command. If any line in the entry
1165 body starts with text at column 0, indentation is not changed at all.
1167 - Property drawers and planning information is inserted indented when
1168 this variable s set. When nil, they will not be indented.
1170 - TAB indents a line relative to context. The lines below a headline
1171 will be indented when this variable is set.
1173 Note that this is all about true indentation, by adding and removing
1174 space characters. See also `org-indent.el' which does level-dependent
1175 indentation in a virtual way, i.e. at display time in Emacs."
1176 :group 'org-edit-structure
1177 :type 'boolean)
1179 (defcustom org-special-ctrl-a/e nil
1180 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1182 When t, `C-a' will bring back the cursor to the beginning of the
1183 headline text, i.e. after the stars and after a possible TODO
1184 keyword. In an item, this will be the position after bullet and
1185 check-box, if any. When the cursor is already at that position,
1186 another `C-a' will bring it to the beginning of the line.
1188 `C-e' will jump to the end of the headline, ignoring the presence
1189 of tags in the headline. A second `C-e' will then jump to the
1190 true end of the line, after any tags. This also means that, when
1191 this variable is non-nil, `C-e' also will never jump beyond the
1192 end of the heading of a folded section, i.e. not after the
1193 ellipses.
1195 When set to the symbol `reversed', the first `C-a' or `C-e' works
1196 normally, going to the true line boundary first. Only a directly
1197 following, identical keypress will bring the cursor to the
1198 special positions.
1200 This may also be a cons cell where the behavior for `C-a' and
1201 `C-e' is set separately."
1202 :group 'org-edit-structure
1203 :type '(choice
1204 (const :tag "off" nil)
1205 (const :tag "on: after stars/bullet and before tags first" t)
1206 (const :tag "reversed: true line boundary first" reversed)
1207 (cons :tag "Set C-a and C-e separately"
1208 (choice :tag "Special C-a"
1209 (const :tag "off" nil)
1210 (const :tag "on: after stars/bullet first" t)
1211 (const :tag "reversed: before stars/bullet first" reversed))
1212 (choice :tag "Special C-e"
1213 (const :tag "off" nil)
1214 (const :tag "on: before tags first" t)
1215 (const :tag "reversed: after tags first" reversed)))))
1216 (if (fboundp 'defvaralias)
1217 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1219 (defcustom org-special-ctrl-k nil
1220 "Non-nil means `C-k' will behave specially in headlines.
1221 When nil, `C-k' will call the default `kill-line' command.
1222 When t, the following will happen while the cursor is in the headline:
1224 - When the cursor is at the beginning of a headline, kill the entire
1225 line and possible the folded subtree below the line.
1226 - When in the middle of the headline text, kill the headline up to the tags.
1227 - When after the headline text, kill the tags."
1228 :group 'org-edit-structure
1229 :type 'boolean)
1231 (defcustom org-ctrl-k-protect-subtree nil
1232 "Non-nil means, do not delete a hidden subtree with C-k.
1233 When set to the symbol `error', simply throw an error when C-k is
1234 used to kill (part-of) a headline that has hidden text behind it.
1235 Any other non-nil value will result in a query to the user, if it is
1236 OK to kill that hidden subtree. When nil, kill without remorse."
1237 :group 'org-edit-structure
1238 :version "24.1"
1239 :type '(choice
1240 (const :tag "Do not protect hidden subtrees" nil)
1241 (const :tag "Protect hidden subtrees with a security query" t)
1242 (const :tag "Never kill a hidden subtree with C-k" error)))
1244 (defcustom org-catch-invisible-edits nil
1245 "Check if in invisible region before inserting or deleting a character.
1246 Valid values are:
1248 nil Do not check, so just do invisible edits.
1249 error Throw an error and do nothing.
1250 show Make point visible, and do the requested edit.
1251 show-and-error Make point visible, then throw an error and abort the edit.
1252 smart Make point visible, and do insertion/deletion if it is
1253 adjacent to visible text and the change feels predictable.
1254 Never delete a previously invisible character or add in the
1255 middle or right after an invisible region. Basically, this
1256 allows insertion and backward-delete right before ellipses.
1257 FIXME: maybe in this case we should not even show?"
1258 :group 'org-edit-structure
1259 :version "24.1"
1260 :type '(choice
1261 (const :tag "Do not check" nil)
1262 (const :tag "Throw error when trying to edit" error)
1263 (const :tag "Unhide, but do not do the edit" show-and-error)
1264 (const :tag "Show invisible part and do the edit" show)
1265 (const :tag "Be smart and do the right thing" smart)))
1267 (defcustom org-yank-folded-subtrees t
1268 "Non-nil means when yanking subtrees, fold them.
1269 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1270 it starts with a heading and all other headings in it are either children
1271 or siblings, then fold all the subtrees. However, do this only if no
1272 text after the yank would be swallowed into a folded tree by this action."
1273 :group 'org-edit-structure
1274 :type 'boolean)
1276 (defcustom org-yank-adjusted-subtrees nil
1277 "Non-nil means when yanking subtrees, adjust the level.
1278 With this setting, `org-paste-subtree' is used to insert the subtree, see
1279 this function for details."
1280 :group 'org-edit-structure
1281 :type 'boolean)
1283 (defcustom org-M-RET-may-split-line '((default . t))
1284 "Non-nil means M-RET will split the line at the cursor position.
1285 When nil, it will go to the end of the line before making a
1286 new line.
1287 You may also set this option in a different way for different
1288 contexts. Valid contexts are:
1290 headline when creating a new headline
1291 item when creating a new item
1292 table in a table field
1293 default the value to be used for all contexts not explicitly
1294 customized"
1295 :group 'org-structure
1296 :group 'org-table
1297 :type '(choice
1298 (const :tag "Always" t)
1299 (const :tag "Never" nil)
1300 (repeat :greedy t :tag "Individual contexts"
1301 (cons
1302 (choice :tag "Context"
1303 (const headline)
1304 (const item)
1305 (const table)
1306 (const default))
1307 (boolean)))))
1310 (defcustom org-insert-heading-respect-content nil
1311 "Non-nil means insert new headings after the current subtree.
1312 When nil, the new heading is created directly after the current line.
1313 The commands \\[org-insert-heading-respect-content] and
1314 \\[org-insert-todo-heading-respect-content] turn this variable on
1315 for the duration of the command."
1316 :group 'org-structure
1317 :type 'boolean)
1319 (defcustom org-blank-before-new-entry '((heading . auto)
1320 (plain-list-item . auto))
1321 "Should `org-insert-heading' leave a blank line before new heading/item?
1322 The value is an alist, with `heading' and `plain-list-item' as CAR,
1323 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1324 which case Org will look at the surrounding headings/items and try to
1325 make an intelligent decision whether to insert a blank line or not.
1327 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1328 set, the setting here is ignored and no empty line is inserted, to avoid
1329 breaking the list structure."
1330 :group 'org-edit-structure
1331 :type '(list
1332 (cons (const heading)
1333 (choice (const :tag "Never" nil)
1334 (const :tag "Always" t)
1335 (const :tag "Auto" auto)))
1336 (cons (const plain-list-item)
1337 (choice (const :tag "Never" nil)
1338 (const :tag "Always" t)
1339 (const :tag "Auto" auto)))))
1341 (defcustom org-insert-heading-hook nil
1342 "Hook being run after inserting a new heading."
1343 :group 'org-edit-structure
1344 :type 'hook)
1346 (defcustom org-enable-fixed-width-editor t
1347 "Non-nil means lines starting with \":\" are treated as fixed-width.
1348 This currently only means they are never auto-wrapped.
1349 When nil, such lines will be treated like ordinary lines.
1350 See also the QUOTE keyword."
1351 :group 'org-edit-structure
1352 :type 'boolean)
1354 (defcustom org-goto-auto-isearch t
1355 "Non-nil means typing characters in `org-goto' starts incremental search.
1356 When nil, you can use these keybindings to navigate the buffer:
1358 q Quit the org-goto interface
1359 n Go to the next visible heading
1360 p Go to the previous visible heading
1361 f Go one heading forward on same level
1362 b Go one heading backward on same level
1363 u Go one heading up"
1364 :group 'org-edit-structure
1365 :type 'boolean)
1367 (defgroup org-sparse-trees nil
1368 "Options concerning sparse trees in Org-mode."
1369 :tag "Org Sparse Trees"
1370 :group 'org-structure)
1372 (defcustom org-highlight-sparse-tree-matches t
1373 "Non-nil means highlight all matches that define a sparse tree.
1374 The highlights will automatically disappear the next time the buffer is
1375 changed by an edit command."
1376 :group 'org-sparse-trees
1377 :type 'boolean)
1379 (defcustom org-remove-highlights-with-change t
1380 "Non-nil means any change to the buffer will remove temporary highlights.
1381 Such highlights are created by `org-occur' and `org-clock-display'.
1382 When nil, `C-c C-c needs to be used to get rid of the highlights.
1383 The highlights created by `org-preview-latex-fragment' always need
1384 `C-c C-c' to be removed."
1385 :group 'org-sparse-trees
1386 :group 'org-time
1387 :type 'boolean)
1390 (defcustom org-occur-hook '(org-first-headline-recenter)
1391 "Hook that is run after `org-occur' has constructed a sparse tree.
1392 This can be used to recenter the window to show as much of the structure
1393 as possible."
1394 :group 'org-sparse-trees
1395 :type 'hook)
1397 (defgroup org-imenu-and-speedbar nil
1398 "Options concerning imenu and speedbar in Org-mode."
1399 :tag "Org Imenu and Speedbar"
1400 :group 'org-structure)
1402 (defcustom org-imenu-depth 2
1403 "The maximum level for Imenu access to Org-mode headlines.
1404 This also applied for speedbar access."
1405 :group 'org-imenu-and-speedbar
1406 :type 'integer)
1408 (defgroup org-table nil
1409 "Options concerning tables in Org-mode."
1410 :tag "Org Table"
1411 :group 'org)
1413 (defcustom org-enable-table-editor 'optimized
1414 "Non-nil means lines starting with \"|\" are handled by the table editor.
1415 When nil, such lines will be treated like ordinary lines.
1417 When equal to the symbol `optimized', the table editor will be optimized to
1418 do the following:
1419 - Automatic overwrite mode in front of whitespace in table fields.
1420 This makes the structure of the table stay in tact as long as the edited
1421 field does not exceed the column width.
1422 - Minimize the number of realigns. Normally, the table is aligned each time
1423 TAB or RET are pressed to move to another field. With optimization this
1424 happens only if changes to a field might have changed the column width.
1425 Optimization requires replacing the functions `self-insert-command',
1426 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1427 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1428 very good at guessing when a re-align will be necessary, but you can always
1429 force one with \\[org-ctrl-c-ctrl-c].
1431 If you would like to use the optimized version in Org-mode, but the
1432 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1434 This variable can be used to turn on and off the table editor during a session,
1435 but in order to toggle optimization, a restart is required.
1437 See also the variable `org-table-auto-blank-field'."
1438 :group 'org-table
1439 :type '(choice
1440 (const :tag "off" nil)
1441 (const :tag "on" t)
1442 (const :tag "on, optimized" optimized)))
1444 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1445 (version<= emacs-version "24.1"))
1446 "Non-nil means cluster self-insert commands for undo when possible.
1447 If this is set, then, like in the Emacs command loop, 20 consecutive
1448 characters will be undone together.
1449 This is configurable, because there is some impact on typing performance."
1450 :group 'org-table
1451 :type 'boolean)
1453 (defcustom org-table-tab-recognizes-table.el t
1454 "Non-nil means TAB will automatically notice a table.el table.
1455 When it sees such a table, it moves point into it and - if necessary -
1456 calls `table-recognize-table'."
1457 :group 'org-table-editing
1458 :type 'boolean)
1460 (defgroup org-link nil
1461 "Options concerning links in Org-mode."
1462 :tag "Org Link"
1463 :group 'org)
1465 (defvar org-link-abbrev-alist-local nil
1466 "Buffer-local version of `org-link-abbrev-alist', which see.
1467 The value of this is taken from the #+LINK lines.")
1468 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1470 (defcustom org-link-abbrev-alist nil
1471 "Alist of link abbreviations.
1472 The car of each element is a string, to be replaced at the start of a link.
1473 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1474 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1476 [[linkkey:tag][description]]
1478 The 'linkkey' must be a word word, starting with a letter, followed
1479 by letters, numbers, '-' or '_'.
1481 If REPLACE is a string, the tag will simply be appended to create the link.
1482 If the string contains \"%s\", the tag will be inserted there. If the string
1483 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1484 at that point (see the function `url-hexify-string'). If the string contains
1485 the specifier \"%(my-function)\", then the custom function `my-function' will
1486 be invoked: this function takes the tag as its only argument and must return
1487 a string.
1489 REPLACE may also be a function that will be called with the tag as the
1490 only argument to create the link, which should be returned as a string.
1492 See the manual for examples."
1493 :group 'org-link
1494 :type '(repeat
1495 (cons
1496 (string :tag "Protocol")
1497 (choice
1498 (string :tag "Format")
1499 (function)))))
1501 (defcustom org-descriptive-links t
1502 "Non-nil means Org will display descriptive links.
1503 E.g. [[http://orgmode.org][Org website]] will be displayed as
1504 \"Org Website\", hiding the link itself and just displaying its
1505 description. When set to `nil', Org will display the full links
1506 literally.
1508 You can interactively set the value of this variable by calling
1509 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1510 :group 'org-link
1511 :type 'boolean)
1513 (defcustom org-link-file-path-type 'adaptive
1514 "How the path name in file links should be stored.
1515 Valid values are:
1517 relative Relative to the current directory, i.e. the directory of the file
1518 into which the link is being inserted.
1519 absolute Absolute path, if possible with ~ for home directory.
1520 noabbrev Absolute path, no abbreviation of home directory.
1521 adaptive Use relative path for files in the current directory and sub-
1522 directories of it. For other files, use an absolute path."
1523 :group 'org-link
1524 :type '(choice
1525 (const relative)
1526 (const absolute)
1527 (const noabbrev)
1528 (const adaptive)))
1530 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1531 "Types of links that should be activated in Org-mode files.
1532 This is a list of symbols, each leading to the activation of a certain link
1533 type. In principle, it does not hurt to turn on most link types - there may
1534 be a small gain when turning off unused link types. The types are:
1536 bracket The recommended [[link][description]] or [[link]] links with hiding.
1537 angle Links in angular brackets that may contain whitespace like
1538 <bbdb:Carsten Dominik>.
1539 plain Plain links in normal text, no whitespace, like http://google.com.
1540 radio Text that is matched by a radio target, see manual for details.
1541 tag Tag settings in a headline (link to tag search).
1542 date Time stamps (link to calendar).
1543 footnote Footnote labels.
1545 Changing this variable requires a restart of Emacs to become effective."
1546 :group 'org-link
1547 :type '(set :greedy t
1548 (const :tag "Double bracket links" bracket)
1549 (const :tag "Angular bracket links" angle)
1550 (const :tag "Plain text links" plain)
1551 (const :tag "Radio target matches" radio)
1552 (const :tag "Tags" tag)
1553 (const :tag "Timestamps" date)
1554 (const :tag "Footnotes" footnote)))
1556 (defcustom org-make-link-description-function nil
1557 "Function to use for generating link descriptions from links.
1558 When nil, the link location will be used. This function must take
1559 two parameters: the first one is the link, the second one is the
1560 description generated by `org-insert-link'. The function should
1561 return the description to use."
1562 :group 'org-link
1563 :type 'function)
1565 (defgroup org-link-store nil
1566 "Options concerning storing links in Org-mode."
1567 :tag "Org Store Link"
1568 :group 'org-link)
1570 (defcustom org-url-hexify-p t
1571 "When non-nil, hexify URL when creating a link."
1572 :type 'boolean
1573 :version "24.3"
1574 :group 'org-link-store)
1576 (defcustom org-email-link-description-format "Email %c: %.30s"
1577 "Format of the description part of a link to an email or usenet message.
1578 The following %-escapes will be replaced by corresponding information:
1580 %F full \"From\" field
1581 %f name, taken from \"From\" field, address if no name
1582 %T full \"To\" field
1583 %t first name in \"To\" field, address if no name
1584 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1585 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1586 %s subject
1587 %d date
1588 %m message-id.
1590 You may use normal field width specification between the % and the letter.
1591 This is for example useful to limit the length of the subject.
1593 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1594 :group 'org-link-store
1595 :type 'string)
1597 (defcustom org-from-is-user-regexp
1598 (let (r1 r2)
1599 (when (and user-mail-address (not (string= user-mail-address "")))
1600 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1601 (when (and user-full-name (not (string= user-full-name "")))
1602 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1603 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1604 "Regexp matched against the \"From:\" header of an email or usenet message.
1605 It should match if the message is from the user him/herself."
1606 :group 'org-link-store
1607 :type 'regexp)
1609 (defcustom org-context-in-file-links t
1610 "Non-nil means file links from `org-store-link' contain context.
1611 A search string will be added to the file name with :: as separator and
1612 used to find the context when the link is activated by the command
1613 `org-open-at-point'. When this option is t, the entire active region
1614 will be placed in the search string of the file link. If set to a
1615 positive integer, only the first n lines of context will be stored.
1617 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1618 negates this setting for the duration of the command."
1619 :group 'org-link-store
1620 :type '(choice boolean integer))
1622 (defcustom org-keep-stored-link-after-insertion nil
1623 "Non-nil means keep link in list for entire session.
1625 The command `org-store-link' adds a link pointing to the current
1626 location to an internal list. These links accumulate during a session.
1627 The command `org-insert-link' can be used to insert links into any
1628 Org-mode file (offering completion for all stored links). When this
1629 option is nil, every link which has been inserted once using \\[org-insert-link]
1630 will be removed from the list, to make completing the unused links
1631 more efficient."
1632 :group 'org-link-store
1633 :type 'boolean)
1635 (defgroup org-link-follow nil
1636 "Options concerning following links in Org-mode."
1637 :tag "Org Follow Link"
1638 :group 'org-link)
1640 (defcustom org-link-translation-function nil
1641 "Function to translate links with different syntax to Org syntax.
1642 This can be used to translate links created for example by the Planner
1643 or emacs-wiki packages to Org syntax.
1644 The function must accept two parameters, a TYPE containing the link
1645 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1646 which is everything after the link protocol. It should return a cons
1647 with possibly modified values of type and path.
1648 Org contains a function for this, so if you set this variable to
1649 `org-translate-link-from-planner', you should be able follow many
1650 links created by planner."
1651 :group 'org-link-follow
1652 :type 'function)
1654 (defcustom org-follow-link-hook nil
1655 "Hook that is run after a link has been followed."
1656 :group 'org-link-follow
1657 :type 'hook)
1659 (defcustom org-tab-follows-link nil
1660 "Non-nil means on links TAB will follow the link.
1661 Needs to be set before org.el is loaded.
1662 This really should not be used, it does not make sense, and the
1663 implementation is bad."
1664 :group 'org-link-follow
1665 :type 'boolean)
1667 (defcustom org-return-follows-link nil
1668 "Non-nil means on links RET will follow the link.
1669 In tables, the special behavior of RET has precedence."
1670 :group 'org-link-follow
1671 :type 'boolean)
1673 (defcustom org-mouse-1-follows-link
1674 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1675 "Non-nil means mouse-1 on a link will follow the link.
1676 A longer mouse click will still set point. Does not work on XEmacs.
1677 Needs to be set before org.el is loaded."
1678 :group 'org-link-follow
1679 :type 'boolean)
1681 (defcustom org-mark-ring-length 4
1682 "Number of different positions to be recorded in the ring.
1683 Changing this requires a restart of Emacs to work correctly."
1684 :group 'org-link-follow
1685 :type 'integer)
1687 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1688 "Non-nil means internal links in Org files must exactly match a headline.
1689 When nil, the link search tries to match a phrase with all words
1690 in the search text."
1691 :group 'org-link-follow
1692 :version "24.1"
1693 :type '(choice
1694 (const :tag "Use fuzzy text search" nil)
1695 (const :tag "Match only exact headline" t)
1696 (const :tag "Match exact headline or query to create it"
1697 query-to-create)))
1699 (defcustom org-link-frame-setup
1700 '((vm . vm-visit-folder-other-frame)
1701 (vm-imap . vm-visit-imap-folder-other-frame)
1702 (gnus . org-gnus-no-new-news)
1703 (file . find-file-other-window)
1704 (wl . wl-other-frame))
1705 "Setup the frame configuration for following links.
1706 When following a link with Emacs, it may often be useful to display
1707 this link in another window or frame. This variable can be used to
1708 set this up for the different types of links.
1709 For VM, use any of
1710 `vm-visit-folder'
1711 `vm-visit-folder-other-window'
1712 `vm-visit-folder-other-frame'
1713 For Gnus, use any of
1714 `gnus'
1715 `gnus-other-frame'
1716 `org-gnus-no-new-news'
1717 For FILE, use any of
1718 `find-file'
1719 `find-file-other-window'
1720 `find-file-other-frame'
1721 For Wanderlust use any of
1722 `wl'
1723 `wl-other-frame'
1724 For the calendar, use the variable `calendar-setup'.
1725 For BBDB, it is currently only possible to display the matches in
1726 another window."
1727 :group 'org-link-follow
1728 :type '(list
1729 (cons (const vm)
1730 (choice
1731 (const vm-visit-folder)
1732 (const vm-visit-folder-other-window)
1733 (const vm-visit-folder-other-frame)))
1734 (cons (const gnus)
1735 (choice
1736 (const gnus)
1737 (const gnus-other-frame)
1738 (const org-gnus-no-new-news)))
1739 (cons (const file)
1740 (choice
1741 (const find-file)
1742 (const find-file-other-window)
1743 (const find-file-other-frame)))
1744 (cons (const wl)
1745 (choice
1746 (const wl)
1747 (const wl-other-frame)))))
1749 (defcustom org-display-internal-link-with-indirect-buffer nil
1750 "Non-nil means use indirect buffer to display infile links.
1751 Activating internal links (from one location in a file to another location
1752 in the same file) normally just jumps to the location. When the link is
1753 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1754 is displayed in
1755 another window. When this option is set, the other window actually displays
1756 an indirect buffer clone of the current buffer, to avoid any visibility
1757 changes to the current buffer."
1758 :group 'org-link-follow
1759 :type 'boolean)
1761 (defcustom org-open-non-existing-files nil
1762 "Non-nil means `org-open-file' will open non-existing files.
1763 When nil, an error will be generated.
1764 This variable applies only to external applications because they
1765 might choke on non-existing files. If the link is to a file that
1766 will be opened in Emacs, the variable is ignored."
1767 :group 'org-link-follow
1768 :type 'boolean)
1770 (defcustom org-open-directory-means-index-dot-org nil
1771 "Non-nil means a link to a directory really means to index.org.
1772 When nil, following a directory link will run dired or open a finder/explorer
1773 window on that directory."
1774 :group 'org-link-follow
1775 :type 'boolean)
1777 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1778 "Function and arguments to call for following mailto links.
1779 This is a list with the first element being a Lisp function, and the
1780 remaining elements being arguments to the function. In string arguments,
1781 %a will be replaced by the address, and %s will be replaced by the subject
1782 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1783 :group 'org-link-follow
1784 :type '(choice
1785 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1786 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1787 (const :tag "message-mail" (message-mail "%a" "%s"))
1788 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1790 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1791 "Non-nil means ask for confirmation before executing shell links.
1792 Shell links can be dangerous: just think about a link
1794 [[shell:rm -rf ~/*][Google Search]]
1796 This link would show up in your Org-mode document as \"Google Search\",
1797 but really it would remove your entire home directory.
1798 Therefore we advise against setting this variable to nil.
1799 Just change it to `y-or-n-p' if you want to confirm with a
1800 single keystroke rather than having to type \"yes\"."
1801 :group 'org-link-follow
1802 :type '(choice
1803 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1804 (const :tag "with y-or-n (faster)" y-or-n-p)
1805 (const :tag "no confirmation (dangerous)" nil)))
1806 (put 'org-confirm-shell-link-function
1807 'safe-local-variable
1808 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1810 (defcustom org-confirm-shell-link-not-regexp ""
1811 "A regexp to skip confirmation for shell links."
1812 :group 'org-link-follow
1813 :version "24.1"
1814 :type 'regexp)
1816 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1817 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1818 Elisp links can be dangerous: just think about a link
1820 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1822 This link would show up in your Org-mode document as \"Google Search\",
1823 but really it would remove your entire home directory.
1824 Therefore we advise against setting this variable to nil.
1825 Just change it to `y-or-n-p' if you want to confirm with a
1826 single keystroke rather than having to type \"yes\"."
1827 :group 'org-link-follow
1828 :type '(choice
1829 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1830 (const :tag "with y-or-n (faster)" y-or-n-p)
1831 (const :tag "no confirmation (dangerous)" nil)))
1832 (put 'org-confirm-shell-link-function
1833 'safe-local-variable
1834 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1836 (defcustom org-confirm-elisp-link-not-regexp ""
1837 "A regexp to skip confirmation for Elisp links."
1838 :group 'org-link-follow
1839 :version "24.1"
1840 :type 'regexp)
1842 (defconst org-file-apps-defaults-gnu
1843 '((remote . emacs)
1844 (system . mailcap)
1845 (t . mailcap))
1846 "Default file applications on a UNIX or GNU/Linux system.
1847 See `org-file-apps'.")
1849 (defconst org-file-apps-defaults-macosx
1850 '((remote . emacs)
1851 (t . "open %s")
1852 (system . "open %s")
1853 ("ps.gz" . "gv %s")
1854 ("eps.gz" . "gv %s")
1855 ("dvi" . "xdvi %s")
1856 ("fig" . "xfig %s"))
1857 "Default file applications on a MacOS X system.
1858 The system \"open\" is known as a default, but we use X11 applications
1859 for some files for which the OS does not have a good default.
1860 See `org-file-apps'.")
1862 (defconst org-file-apps-defaults-windowsnt
1863 (list
1864 '(remote . emacs)
1865 (cons t
1866 (list (if (featurep 'xemacs)
1867 'mswindows-shell-execute
1868 'w32-shell-execute)
1869 "open" 'file))
1870 (cons 'system
1871 (list (if (featurep 'xemacs)
1872 'mswindows-shell-execute
1873 'w32-shell-execute)
1874 "open" 'file)))
1875 "Default file applications on a Windows NT system.
1876 The system \"open\" is used for most files.
1877 See `org-file-apps'.")
1879 (defcustom org-file-apps
1881 (auto-mode . emacs)
1882 ("\\.mm\\'" . default)
1883 ("\\.x?html?\\'" . default)
1884 ("\\.pdf\\'" . default)
1886 "External applications for opening `file:path' items in a document.
1887 Org-mode uses system defaults for different file types, but
1888 you can use this variable to set the application for a given file
1889 extension. The entries in this list are cons cells where the car identifies
1890 files and the cdr the corresponding command. Possible values for the
1891 file identifier are
1892 \"string\" A string as a file identifier can be interpreted in different
1893 ways, depending on its contents:
1895 - Alphanumeric characters only:
1896 Match links with this file extension.
1897 Example: (\"pdf\" . \"evince %s\")
1898 to open PDFs with evince.
1900 - Regular expression: Match links where the
1901 filename matches the regexp. If you want to
1902 use groups here, use shy groups.
1904 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1905 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1906 to open *.html and *.xhtml with firefox.
1908 - Regular expression which contains (non-shy) groups:
1909 Match links where the whole link, including \"::\", and
1910 anything after that, matches the regexp.
1911 In a custom command string, %1, %2, etc. are replaced with
1912 the parts of the link that were matched by the groups.
1913 For backwards compatibility, if a command string is given
1914 that does not use any of the group matches, this case is
1915 handled identically to the second one (i.e. match against
1916 file name only).
1917 In a custom lisp form, you can access the group matches with
1918 (match-string n link).
1920 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1921 to open [[file:document.pdf::5]] with evince at page 5.
1923 `directory' Matches a directory
1924 `remote' Matches a remote file, accessible through tramp or efs.
1925 Remote files most likely should be visited through Emacs
1926 because external applications cannot handle such paths.
1927 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1928 so all files Emacs knows how to handle. Using this with
1929 command `emacs' will open most files in Emacs. Beware that this
1930 will also open html files inside Emacs, unless you add
1931 (\"html\" . default) to the list as well.
1932 t Default for files not matched by any of the other options.
1933 `system' The system command to open files, like `open' on Windows
1934 and Mac OS X, and mailcap under GNU/Linux. This is the command
1935 that will be selected if you call `C-c C-o' with a double
1936 \\[universal-argument] \\[universal-argument] prefix.
1938 Possible values for the command are:
1939 `emacs' The file will be visited by the current Emacs process.
1940 `default' Use the default application for this file type, which is the
1941 association for t in the list, most likely in the system-specific
1942 part.
1943 This can be used to overrule an unwanted setting in the
1944 system-specific variable.
1945 `system' Use the system command for opening files, like \"open\".
1946 This command is specified by the entry whose car is `system'.
1947 Most likely, the system-specific version of this variable
1948 does define this command, but you can overrule/replace it
1949 here.
1950 string A command to be executed by a shell; %s will be replaced
1951 by the path to the file.
1952 sexp A Lisp form which will be evaluated. The file path will
1953 be available in the Lisp variable `file'.
1954 For more examples, see the system specific constants
1955 `org-file-apps-defaults-macosx'
1956 `org-file-apps-defaults-windowsnt'
1957 `org-file-apps-defaults-gnu'."
1958 :group 'org-link-follow
1959 :type '(repeat
1960 (cons (choice :value ""
1961 (string :tag "Extension")
1962 (const :tag "System command to open files" system)
1963 (const :tag "Default for unrecognized files" t)
1964 (const :tag "Remote file" remote)
1965 (const :tag "Links to a directory" directory)
1966 (const :tag "Any files that have Emacs modes"
1967 auto-mode))
1968 (choice :value ""
1969 (const :tag "Visit with Emacs" emacs)
1970 (const :tag "Use default" default)
1971 (const :tag "Use the system command" system)
1972 (string :tag "Command")
1973 (sexp :tag "Lisp form")))))
1975 (defcustom org-doi-server-url "http://dx.doi.org/"
1976 "The URL of the DOI server."
1977 :type 'string
1978 :version "24.3"
1979 :group 'org-link-follow)
1981 (defgroup org-refile nil
1982 "Options concerning refiling entries in Org-mode."
1983 :tag "Org Refile"
1984 :group 'org)
1986 (defcustom org-directory "~/org"
1987 "Directory with org files.
1988 This is just a default location to look for Org files. There is no need
1989 at all to put your files into this directory. It is only used in the
1990 following situations:
1992 1. When a capture template specifies a target file that is not an
1993 absolute path. The path will then be interpreted relative to
1994 `org-directory'
1995 2. When a capture note is filed away in an interactive way (when exiting the
1996 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1997 with `org-directory' as the default path."
1998 :group 'org-refile
1999 :group 'org-remember
2000 :group 'org-capture
2001 :type 'directory)
2003 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2004 "Default target for storing notes.
2005 Used as a fall back file for org-remember.el and org-capture.el, for
2006 templates that do not specify a target file."
2007 :group 'org-refile
2008 :group 'org-remember
2009 :group 'org-capture
2010 :type '(choice
2011 (const :tag "Default from remember-data-file" nil)
2012 file))
2014 (defcustom org-goto-interface 'outline
2015 "The default interface to be used for `org-goto'.
2016 Allowed values are:
2017 outline The interface shows an outline of the relevant file
2018 and the correct heading is found by moving through
2019 the outline or by searching with incremental search.
2020 outline-path-completion Headlines in the current buffer are offered via
2021 completion. This is the interface also used by
2022 the refile command."
2023 :group 'org-refile
2024 :type '(choice
2025 (const :tag "Outline" outline)
2026 (const :tag "Outline-path-completion" outline-path-completion)))
2028 (defcustom org-goto-max-level 5
2029 "Maximum target level when running `org-goto' with refile interface."
2030 :group 'org-refile
2031 :type 'integer)
2033 (defcustom org-reverse-note-order nil
2034 "Non-nil means store new notes at the beginning of a file or entry.
2035 When nil, new notes will be filed to the end of a file or entry.
2036 This can also be a list with cons cells of regular expressions that
2037 are matched against file names, and values."
2038 :group 'org-remember
2039 :group 'org-capture
2040 :group 'org-refile
2041 :type '(choice
2042 (const :tag "Reverse always" t)
2043 (const :tag "Reverse never" nil)
2044 (repeat :tag "By file name regexp"
2045 (cons regexp boolean))))
2047 (defcustom org-log-refile nil
2048 "Information to record when a task is refiled.
2050 Possible values are:
2052 nil Don't add anything
2053 time Add a time stamp to the task
2054 note Prompt for a note and add it with template `org-log-note-headings'
2056 This option can also be set with on a per-file-basis with
2058 #+STARTUP: nologrefile
2059 #+STARTUP: logrefile
2060 #+STARTUP: lognoterefile
2062 You can have local logging settings for a subtree by setting the LOGGING
2063 property to one or more of these keywords.
2065 When bulk-refiling from the agenda, the value `note' is forbidden and
2066 will temporarily be changed to `time'."
2067 :group 'org-refile
2068 :group 'org-progress
2069 :version "24.1"
2070 :type '(choice
2071 (const :tag "No logging" nil)
2072 (const :tag "Record timestamp" time)
2073 (const :tag "Record timestamp with note." note)))
2075 (defcustom org-refile-targets nil
2076 "Targets for refiling entries with \\[org-refile].
2077 This is a list of cons cells. Each cell contains:
2078 - a specification of the files to be considered, either a list of files,
2079 or a symbol whose function or variable value will be used to retrieve
2080 a file name or a list of file names. If you use `org-agenda-files' for
2081 that, all agenda files will be scanned for targets. Nil means consider
2082 headings in the current buffer.
2083 - A specification of how to find candidate refile targets. This may be
2084 any of:
2085 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2086 This tag has to be present in all target headlines, inheritance will
2087 not be considered.
2088 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2089 todo keyword.
2090 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2091 headlines that are refiling targets.
2092 - a cons cell (:level . N). Any headline of level N is considered a target.
2093 Note that, when `org-odd-levels-only' is set, level corresponds to
2094 order in hierarchy, not to the number of stars.
2095 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2096 Note that, when `org-odd-levels-only' is set, level corresponds to
2097 order in hierarchy, not to the number of stars.
2099 Each element of this list generates a set of possible targets.
2100 The union of these sets is presented (with completion) to
2101 the user by `org-refile'.
2103 You can set the variable `org-refile-target-verify-function' to a function
2104 to verify each headline found by the simple criteria above.
2106 When this variable is nil, all top-level headlines in the current buffer
2107 are used, equivalent to the value `((nil . (:level . 1))'."
2108 :group 'org-refile
2109 :type '(repeat
2110 (cons
2111 (choice :value org-agenda-files
2112 (const :tag "All agenda files" org-agenda-files)
2113 (const :tag "Current buffer" nil)
2114 (function) (variable) (file))
2115 (choice :tag "Identify target headline by"
2116 (cons :tag "Specific tag" (const :value :tag) (string))
2117 (cons :tag "TODO keyword" (const :value :todo) (string))
2118 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2119 (cons :tag "Level number" (const :value :level) (integer))
2120 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2122 (defcustom org-refile-target-verify-function nil
2123 "Function to verify if the headline at point should be a refile target.
2124 The function will be called without arguments, with point at the
2125 beginning of the headline. It should return t and leave point
2126 where it is if the headline is a valid target for refiling.
2128 If the target should not be selected, the function must return nil.
2129 In addition to this, it may move point to a place from where the search
2130 should be continued. For example, the function may decide that the entire
2131 subtree of the current entry should be excluded and move point to the end
2132 of the subtree."
2133 :group 'org-refile
2134 :type 'function)
2136 (defcustom org-refile-use-cache nil
2137 "Non-nil means cache refile targets to speed up the process.
2138 The cache for a particular file will be updated automatically when
2139 the buffer has been killed, or when any of the marker used for flagging
2140 refile targets no longer points at a live buffer.
2141 If you have added new entries to a buffer that might themselves be targets,
2142 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2143 find that easier, `C-u C-u C-u C-c C-w'."
2144 :group 'org-refile
2145 :version "24.1"
2146 :type 'boolean)
2148 (defcustom org-refile-use-outline-path nil
2149 "Non-nil means provide refile targets as paths.
2150 So a level 3 headline will be available as level1/level2/level3.
2152 When the value is `file', also include the file name (without directory)
2153 into the path. In this case, you can also stop the completion after
2154 the file name, to get entries inserted as top level in the file.
2156 When `full-file-path', include the full file path."
2157 :group 'org-refile
2158 :type '(choice
2159 (const :tag "Not" nil)
2160 (const :tag "Yes" t)
2161 (const :tag "Start with file name" file)
2162 (const :tag "Start with full file path" full-file-path)))
2164 (defcustom org-outline-path-complete-in-steps t
2165 "Non-nil means complete the outline path in hierarchical steps.
2166 When Org-mode uses the refile interface to select an outline path
2167 \(see variable `org-refile-use-outline-path'), the completion of
2168 the path can be done is a single go, or if can be done in steps down
2169 the headline hierarchy. Going in steps is probably the best if you
2170 do not use a special completion package like `ido' or `icicles'.
2171 However, when using these packages, going in one step can be very
2172 fast, while still showing the whole path to the entry."
2173 :group 'org-refile
2174 :type 'boolean)
2176 (defcustom org-refile-allow-creating-parent-nodes nil
2177 "Non-nil means allow to create new nodes as refile targets.
2178 New nodes are then created by adding \"/new node name\" to the completion
2179 of an existing node. When the value of this variable is `confirm',
2180 new node creation must be confirmed by the user (recommended)
2181 When nil, the completion must match an existing entry.
2183 Note that, if the new heading is not seen by the criteria
2184 listed in `org-refile-targets', multiple instances of the same
2185 heading would be created by trying again to file under the new
2186 heading."
2187 :group 'org-refile
2188 :type '(choice
2189 (const :tag "Never" nil)
2190 (const :tag "Always" t)
2191 (const :tag "Prompt for confirmation" confirm)))
2193 (defcustom org-refile-active-region-within-subtree nil
2194 "Non-nil means also refile active region within a subtree.
2196 By default `org-refile' doesn't allow refiling regions if they
2197 don't contain a set of subtrees, but it might be convenient to
2198 do so sometimes: in that case, the first line of the region is
2199 converted to a headline before refiling."
2200 :group 'org-refile
2201 :version "24.1"
2202 :type 'boolean)
2204 (defgroup org-todo nil
2205 "Options concerning TODO items in Org-mode."
2206 :tag "Org TODO"
2207 :group 'org)
2209 (defgroup org-progress nil
2210 "Options concerning Progress logging in Org-mode."
2211 :tag "Org Progress"
2212 :group 'org-time)
2214 (defvar org-todo-interpretation-widgets
2215 '((:tag "Sequence (cycling hits every state)" sequence)
2216 (:tag "Type (cycling directly to DONE)" type))
2217 "The available interpretation symbols for customizing `org-todo-keywords'.
2218 Interested libraries should add to this list.")
2220 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2221 "List of TODO entry keyword sequences and their interpretation.
2222 \\<org-mode-map>This is a list of sequences.
2224 Each sequence starts with a symbol, either `sequence' or `type',
2225 indicating if the keywords should be interpreted as a sequence of
2226 action steps, or as different types of TODO items. The first
2227 keywords are states requiring action - these states will select a headline
2228 for inclusion into the global TODO list Org-mode produces. If one of
2229 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2230 signify that no further action is necessary. If \"|\" is not found,
2231 the last keyword is treated as the only DONE state of the sequence.
2233 The command \\[org-todo] cycles an entry through these states, and one
2234 additional state where no keyword is present. For details about this
2235 cycling, see the manual.
2237 TODO keywords and interpretation can also be set on a per-file basis with
2238 the special #+SEQ_TODO and #+TYP_TODO lines.
2240 Each keyword can optionally specify a character for fast state selection
2241 \(in combination with the variable `org-use-fast-todo-selection')
2242 and specifiers for state change logging, using the same syntax that
2243 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2244 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2245 indicates to record a time stamp each time this state is selected.
2247 Each keyword may also specify if a timestamp or a note should be
2248 recorded when entering or leaving the state, by adding additional
2249 characters in the parenthesis after the keyword. This looks like this:
2250 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2251 record only the time of the state change. With X and Y being either
2252 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2253 Y when leaving the state if and only if the *target* state does not
2254 define X. You may omit any of the fast-selection key or X or /Y,
2255 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2257 For backward compatibility, this variable may also be just a list
2258 of keywords. In this case the interpretation (sequence or type) will be
2259 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2260 :group 'org-todo
2261 :group 'org-keywords
2262 :type '(choice
2263 (repeat :tag "Old syntax, just keywords"
2264 (string :tag "Keyword"))
2265 (repeat :tag "New syntax"
2266 (cons
2267 (choice
2268 :tag "Interpretation"
2269 ;;Quick and dirty way to see
2270 ;;`org-todo-interpretations'. This takes the
2271 ;;place of item arguments
2272 :convert-widget
2273 (lambda (widget)
2274 (widget-put widget
2275 :args (mapcar
2276 #'(lambda (x)
2277 (widget-convert
2278 (cons 'const x)))
2279 org-todo-interpretation-widgets))
2280 widget))
2281 (repeat
2282 (string :tag "Keyword"))))))
2284 (defvar org-todo-keywords-1 nil
2285 "All TODO and DONE keywords active in a buffer.")
2286 (make-variable-buffer-local 'org-todo-keywords-1)
2287 (defvar org-todo-keywords-for-agenda nil)
2288 (defvar org-done-keywords-for-agenda nil)
2289 (defvar org-drawers-for-agenda nil)
2290 (defvar org-todo-keyword-alist-for-agenda nil)
2291 (defvar org-tag-alist-for-agenda nil)
2292 (defvar org-agenda-contributing-files nil)
2293 (defvar org-not-done-keywords nil)
2294 (make-variable-buffer-local 'org-not-done-keywords)
2295 (defvar org-done-keywords nil)
2296 (make-variable-buffer-local 'org-done-keywords)
2297 (defvar org-todo-heads nil)
2298 (make-variable-buffer-local 'org-todo-heads)
2299 (defvar org-todo-sets nil)
2300 (make-variable-buffer-local 'org-todo-sets)
2301 (defvar org-todo-log-states nil)
2302 (make-variable-buffer-local 'org-todo-log-states)
2303 (defvar org-todo-kwd-alist nil)
2304 (make-variable-buffer-local 'org-todo-kwd-alist)
2305 (defvar org-todo-key-alist nil)
2306 (make-variable-buffer-local 'org-todo-key-alist)
2307 (defvar org-todo-key-trigger nil)
2308 (make-variable-buffer-local 'org-todo-key-trigger)
2310 (defcustom org-todo-interpretation 'sequence
2311 "Controls how TODO keywords are interpreted.
2312 This variable is in principle obsolete and is only used for
2313 backward compatibility, if the interpretation of todo keywords is
2314 not given already in `org-todo-keywords'. See that variable for
2315 more information."
2316 :group 'org-todo
2317 :group 'org-keywords
2318 :type '(choice (const sequence)
2319 (const type)))
2321 (defcustom org-use-fast-todo-selection t
2322 "Non-nil means use the fast todo selection scheme with C-c C-t.
2323 This variable describes if and under what circumstances the cycling
2324 mechanism for TODO keywords will be replaced by a single-key, direct
2325 selection scheme.
2327 When nil, fast selection is never used.
2329 When the symbol `prefix', it will be used when `org-todo' is called
2330 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2331 `C-u t' in an agenda buffer.
2333 When t, fast selection is used by default. In this case, the prefix
2334 argument forces cycling instead.
2336 In all cases, the special interface is only used if access keys have
2337 actually been assigned by the user, i.e. if keywords in the configuration
2338 are followed by a letter in parenthesis, like TODO(t)."
2339 :group 'org-todo
2340 :type '(choice
2341 (const :tag "Never" nil)
2342 (const :tag "By default" t)
2343 (const :tag "Only with C-u C-c C-t" prefix)))
2345 (defcustom org-provide-todo-statistics t
2346 "Non-nil means update todo statistics after insert and toggle.
2347 ALL-HEADLINES means update todo statistics by including headlines
2348 with no TODO keyword as well, counting them as not done.
2349 A list of TODO keywords means the same, but skip keywords that are
2350 not in this list.
2352 When this is set, todo statistics is updated in the parent of the
2353 current entry each time a todo state is changed."
2354 :group 'org-todo
2355 :type '(choice
2356 (const :tag "Yes, only for TODO entries" t)
2357 (const :tag "Yes, including all entries" 'all-headlines)
2358 (repeat :tag "Yes, for TODOs in this list"
2359 (string :tag "TODO keyword"))
2360 (other :tag "No TODO statistics" nil)))
2362 (defcustom org-hierarchical-todo-statistics t
2363 "Non-nil means TODO statistics covers just direct children.
2364 When nil, all entries in the subtree are considered.
2365 This has only an effect if `org-provide-todo-statistics' is set.
2366 To set this to nil for only a single subtree, use a COOKIE_DATA
2367 property and include the word \"recursive\" into the value."
2368 :group 'org-todo
2369 :type 'boolean)
2371 (defcustom org-after-todo-state-change-hook nil
2372 "Hook which is run after the state of a TODO item was changed.
2373 The new state (a string with a TODO keyword, or nil) is available in the
2374 Lisp variable `org-state'."
2375 :group 'org-todo
2376 :type 'hook)
2378 (defvar org-blocker-hook nil
2379 "Hook for functions that are allowed to block a state change.
2381 Functions in this hook should not modify the buffer.
2382 Each function gets as its single argument a property list,
2383 see `org-trigger-hook' for more information about this list.
2385 If any of the functions in this hook returns nil, the state change
2386 is blocked.")
2388 (defvar org-trigger-hook nil
2389 "Hook for functions that are triggered by a state change.
2391 Each function gets as its single argument a property list with at
2392 least the following elements:
2394 (:type type-of-change :position pos-at-entry-start
2395 :from old-state :to new-state)
2397 Depending on the type, more properties may be present.
2399 This mechanism is currently implemented for:
2401 TODO state changes
2402 ------------------
2403 :type todo-state-change
2404 :from previous state (keyword as a string), or nil, or a symbol
2405 'todo' or 'done', to indicate the general type of state.
2406 :to new state, like in :from")
2408 (defcustom org-enforce-todo-dependencies nil
2409 "Non-nil means undone TODO entries will block switching the parent to DONE.
2410 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2411 be blocked if any prior sibling is not yet done.
2412 Finally, if the parent is blocked because of ordered siblings of its own,
2413 the child will also be blocked."
2414 :set (lambda (var val)
2415 (set var val)
2416 (if val
2417 (add-hook 'org-blocker-hook
2418 'org-block-todo-from-children-or-siblings-or-parent)
2419 (remove-hook 'org-blocker-hook
2420 'org-block-todo-from-children-or-siblings-or-parent)))
2421 :group 'org-todo
2422 :type 'boolean)
2424 (defcustom org-enforce-todo-checkbox-dependencies nil
2425 "Non-nil means unchecked boxes will block switching the parent to DONE.
2426 When this is nil, checkboxes have no influence on switching TODO states.
2427 When non-nil, you first need to check off all check boxes before the TODO
2428 entry can be switched to DONE.
2429 This variable needs to be set before org.el is loaded, and you need to
2430 restart Emacs after a change to make the change effective. The only way
2431 to change is while Emacs is running is through the customize interface."
2432 :set (lambda (var val)
2433 (set var val)
2434 (if val
2435 (add-hook 'org-blocker-hook
2436 'org-block-todo-from-checkboxes)
2437 (remove-hook 'org-blocker-hook
2438 'org-block-todo-from-checkboxes)))
2439 :group 'org-todo
2440 :type 'boolean)
2442 (defcustom org-treat-insert-todo-heading-as-state-change nil
2443 "Non-nil means inserting a TODO heading is treated as state change.
2444 So when the command \\[org-insert-todo-heading] is used, state change
2445 logging will apply if appropriate. When nil, the new TODO item will
2446 be inserted directly, and no logging will take place."
2447 :group 'org-todo
2448 :type 'boolean)
2450 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2451 "Non-nil means switching TODO states with S-cursor counts as state change.
2452 This is the default behavior. However, setting this to nil allows a
2453 convenient way to select a TODO state and bypass any logging associated
2454 with that."
2455 :group 'org-todo
2456 :type 'boolean)
2458 (defcustom org-todo-state-tags-triggers nil
2459 "Tag changes that should be triggered by TODO state changes.
2460 This is a list. Each entry is
2462 (state-change (tag . flag) .......)
2464 State-change can be a string with a state, and empty string to indicate the
2465 state that has no TODO keyword, or it can be one of the symbols `todo'
2466 or `done', meaning any not-done or done state, respectively."
2467 :group 'org-todo
2468 :group 'org-tags
2469 :type '(repeat
2470 (cons (choice :tag "When changing to"
2471 (const :tag "Not-done state" todo)
2472 (const :tag "Done state" done)
2473 (string :tag "State"))
2474 (repeat
2475 (cons :tag "Tag action"
2476 (string :tag "Tag")
2477 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2479 (defcustom org-log-done nil
2480 "Information to record when a task moves to the DONE state.
2482 Possible values are:
2484 nil Don't add anything, just change the keyword
2485 time Add a time stamp to the task
2486 note Prompt for a note and add it with template `org-log-note-headings'
2488 This option can also be set with on a per-file-basis with
2490 #+STARTUP: nologdone
2491 #+STARTUP: logdone
2492 #+STARTUP: lognotedone
2494 You can have local logging settings for a subtree by setting the LOGGING
2495 property to one or more of these keywords."
2496 :group 'org-todo
2497 :group 'org-progress
2498 :type '(choice
2499 (const :tag "No logging" nil)
2500 (const :tag "Record CLOSED timestamp" time)
2501 (const :tag "Record CLOSED timestamp with note." note)))
2503 ;; Normalize old uses of org-log-done.
2504 (cond
2505 ((eq org-log-done t) (setq org-log-done 'time))
2506 ((and (listp org-log-done) (memq 'done org-log-done))
2507 (setq org-log-done 'note)))
2509 (defcustom org-log-reschedule nil
2510 "Information to record when the scheduling date of a tasks is modified.
2512 Possible values are:
2514 nil Don't add anything, just change the date
2515 time Add a time stamp to the task
2516 note Prompt for a note and add it with template `org-log-note-headings'
2518 This option can also be set with on a per-file-basis with
2520 #+STARTUP: nologreschedule
2521 #+STARTUP: logreschedule
2522 #+STARTUP: lognotereschedule"
2523 :group 'org-todo
2524 :group 'org-progress
2525 :type '(choice
2526 (const :tag "No logging" nil)
2527 (const :tag "Record timestamp" time)
2528 (const :tag "Record timestamp with note." note)))
2530 (defcustom org-log-redeadline nil
2531 "Information to record when the deadline date of a tasks is modified.
2533 Possible values are:
2535 nil Don't add anything, just change the date
2536 time Add a time stamp to the task
2537 note Prompt for a note and add it with template `org-log-note-headings'
2539 This option can also be set with on a per-file-basis with
2541 #+STARTUP: nologredeadline
2542 #+STARTUP: logredeadline
2543 #+STARTUP: lognoteredeadline
2545 You can have local logging settings for a subtree by setting the LOGGING
2546 property to one or more of these keywords."
2547 :group 'org-todo
2548 :group 'org-progress
2549 :type '(choice
2550 (const :tag "No logging" nil)
2551 (const :tag "Record timestamp" time)
2552 (const :tag "Record timestamp with note." note)))
2554 (defcustom org-log-note-clock-out nil
2555 "Non-nil means record a note when clocking out of an item.
2556 This can also be configured on a per-file basis by adding one of
2557 the following lines anywhere in the buffer:
2559 #+STARTUP: lognoteclock-out
2560 #+STARTUP: nolognoteclock-out"
2561 :group 'org-todo
2562 :group 'org-progress
2563 :type 'boolean)
2565 (defcustom org-log-done-with-time t
2566 "Non-nil means the CLOSED time stamp will contain date and time.
2567 When nil, only the date will be recorded."
2568 :group 'org-progress
2569 :type 'boolean)
2571 (defcustom org-log-note-headings
2572 '((done . "CLOSING NOTE %t")
2573 (state . "State %-12s from %-12S %t")
2574 (note . "Note taken on %t")
2575 (reschedule . "Rescheduled from %S on %t")
2576 (delschedule . "Not scheduled, was %S on %t")
2577 (redeadline . "New deadline from %S on %t")
2578 (deldeadline . "Removed deadline, was %S on %t")
2579 (refile . "Refiled on %t")
2580 (clock-out . ""))
2581 "Headings for notes added to entries.
2582 The value is an alist, with the car being a symbol indicating the note
2583 context, and the cdr is the heading to be used. The heading may also be the
2584 empty string.
2585 %t in the heading will be replaced by a time stamp.
2586 %T will be an active time stamp instead the default inactive one
2587 %d will be replaced by a short-format time stamp.
2588 %D will be replaced by an active short-format time stamp.
2589 %s will be replaced by the new TODO state, in double quotes.
2590 %S will be replaced by the old TODO state, in double quotes.
2591 %u will be replaced by the user name.
2592 %U will be replaced by the full user name.
2594 In fact, it is not a good idea to change the `state' entry, because
2595 agenda log mode depends on the format of these entries."
2596 :group 'org-todo
2597 :group 'org-progress
2598 :type '(list :greedy t
2599 (cons (const :tag "Heading when closing an item" done) string)
2600 (cons (const :tag
2601 "Heading when changing todo state (todo sequence only)"
2602 state) string)
2603 (cons (const :tag "Heading when just taking a note" note) string)
2604 (cons (const :tag "Heading when clocking out" clock-out) string)
2605 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2606 (cons (const :tag "Heading when rescheduling" reschedule) string)
2607 (cons (const :tag "Heading when changing deadline" redeadline) string)
2608 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2609 (cons (const :tag "Heading when refiling" refile) string)))
2611 (unless (assq 'note org-log-note-headings)
2612 (push '(note . "%t") org-log-note-headings))
2614 (defcustom org-log-into-drawer nil
2615 "Non-nil means insert state change notes and time stamps into a drawer.
2616 When nil, state changes notes will be inserted after the headline and
2617 any scheduling and clock lines, but not inside a drawer.
2619 The value of this variable should be the name of the drawer to use.
2620 LOGBOOK is proposed as the default drawer for this purpose, you can
2621 also set this to a string to define the drawer of your choice.
2623 A value of t is also allowed, representing \"LOGBOOK\".
2625 A value of t or nil can also be set with on a per-file-basis with
2627 #+STARTUP: logdrawer
2628 #+STARTUP: nologdrawer
2630 If this variable is set, `org-log-state-notes-insert-after-drawers'
2631 will be ignored.
2633 You can set the property LOG_INTO_DRAWER to overrule this setting for
2634 a subtree."
2635 :group 'org-todo
2636 :group 'org-progress
2637 :type '(choice
2638 (const :tag "Not into a drawer" nil)
2639 (const :tag "LOGBOOK" t)
2640 (string :tag "Other")))
2642 (if (fboundp 'defvaralias)
2643 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2645 (defun org-log-into-drawer ()
2646 "Return the value of `org-log-into-drawer', but let properties overrule.
2647 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2648 used instead of the default value."
2649 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2650 (cond
2651 ((not p) org-log-into-drawer)
2652 ((equal p "nil") nil)
2653 ((equal p "t") "LOGBOOK")
2654 (t p))))
2656 (defcustom org-log-state-notes-insert-after-drawers nil
2657 "Non-nil means insert state change notes after any drawers in entry.
2658 Only the drawers that *immediately* follow the headline and the
2659 deadline/scheduled line are skipped.
2660 When nil, insert notes right after the heading and perhaps the line
2661 with deadline/scheduling if present.
2663 This variable will have no effect if `org-log-into-drawer' is
2664 set."
2665 :group 'org-todo
2666 :group 'org-progress
2667 :type 'boolean)
2669 (defcustom org-log-states-order-reversed t
2670 "Non-nil means the latest state note will be directly after heading.
2671 When nil, the state change notes will be ordered according to time.
2673 This option can also be set with on a per-file-basis with
2675 #+STARTUP: logstatesreversed
2676 #+STARTUP: nologstatesreversed"
2677 :group 'org-todo
2678 :group 'org-progress
2679 :type 'boolean)
2681 (defcustom org-todo-repeat-to-state nil
2682 "The TODO state to which a repeater should return the repeating task.
2683 By default this is the first task in a TODO sequence, or the previous state
2684 in a TODO_TYP set. But you can specify another task here.
2685 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2686 :group 'org-todo
2687 :version "24.1"
2688 :type '(choice (const :tag "Head of sequence" nil)
2689 (string :tag "Specific state")))
2691 (defcustom org-log-repeat 'time
2692 "Non-nil means record moving through the DONE state when triggering repeat.
2693 An auto-repeating task is immediately switched back to TODO when
2694 marked DONE. If you are not logging state changes (by adding \"@\"
2695 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2696 record a closing note, there will be no record of the task moving
2697 through DONE. This variable forces taking a note anyway.
2699 nil Don't force a record
2700 time Record a time stamp
2701 note Prompt for a note and add it with template `org-log-note-headings'
2703 This option can also be set with on a per-file-basis with
2705 #+STARTUP: nologrepeat
2706 #+STARTUP: logrepeat
2707 #+STARTUP: lognoterepeat
2709 You can have local logging settings for a subtree by setting the LOGGING
2710 property to one or more of these keywords."
2711 :group 'org-todo
2712 :group 'org-progress
2713 :type '(choice
2714 (const :tag "Don't force a record" nil)
2715 (const :tag "Force recording the DONE state" time)
2716 (const :tag "Force recording a note with the DONE state" note)))
2719 (defgroup org-priorities nil
2720 "Priorities in Org-mode."
2721 :tag "Org Priorities"
2722 :group 'org-todo)
2724 (defcustom org-enable-priority-commands t
2725 "Non-nil means priority commands are active.
2726 When nil, these commands will be disabled, so that you never accidentally
2727 set a priority."
2728 :group 'org-priorities
2729 :type 'boolean)
2731 (defcustom org-highest-priority ?A
2732 "The highest priority of TODO items. A character like ?A, ?B etc.
2733 Must have a smaller ASCII number than `org-lowest-priority'."
2734 :group 'org-priorities
2735 :type 'character)
2737 (defcustom org-lowest-priority ?C
2738 "The lowest priority of TODO items. A character like ?A, ?B etc.
2739 Must have a larger ASCII number than `org-highest-priority'."
2740 :group 'org-priorities
2741 :type 'character)
2743 (defcustom org-default-priority ?B
2744 "The default priority of TODO items.
2745 This is the priority an item gets if no explicit priority is given.
2746 When starting to cycle on an empty priority the first step in the cycle
2747 depends on `org-priority-start-cycle-with-default'. The resulting first
2748 step priority must not exceed the range from `org-highest-priority' to
2749 `org-lowest-priority' which means that `org-default-priority' has to be
2750 in this range exclusive or inclusive the range boundaries. Else the
2751 first step refuses to set the default and the second will fall back
2752 to (depending on the command used) the highest or lowest priority."
2753 :group 'org-priorities
2754 :type 'character)
2756 (defcustom org-priority-start-cycle-with-default t
2757 "Non-nil means start with default priority when starting to cycle.
2758 When this is nil, the first step in the cycle will be (depending on the
2759 command used) one higher or lower than the default priority.
2760 See also `org-default-priority'."
2761 :group 'org-priorities
2762 :type 'boolean)
2764 (defcustom org-get-priority-function nil
2765 "Function to extract the priority from a string.
2766 The string is normally the headline. If this is nil Org computes the
2767 priority from the priority cookie like [#A] in the headline. It returns
2768 an integer, increasing by 1000 for each priority level.
2769 The user can set a different function here, which should take a string
2770 as an argument and return the numeric priority."
2771 :group 'org-priorities
2772 :version "24.1"
2773 :type 'function)
2775 (defgroup org-time nil
2776 "Options concerning time stamps and deadlines in Org-mode."
2777 :tag "Org Time"
2778 :group 'org)
2780 (defcustom org-insert-labeled-timestamps-at-point nil
2781 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2782 When nil, these labeled time stamps are forces into the second line of an
2783 entry, just after the headline. When scheduling from the global TODO list,
2784 the time stamp will always be forced into the second line."
2785 :group 'org-time
2786 :type 'boolean)
2788 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2789 "Formats for `format-time-string' which are used for time stamps.
2790 It is not recommended to change this constant.")
2792 (defcustom org-time-stamp-rounding-minutes '(0 5)
2793 "Number of minutes to round time stamps to.
2794 These are two values, the first applies when first creating a time stamp.
2795 The second applies when changing it with the commands `S-up' and `S-down'.
2796 When changing the time stamp, this means that it will change in steps
2797 of N minutes, as given by the second value.
2799 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2800 numbers should be factors of 60, so for example 5, 10, 15.
2802 When this is larger than 1, you can still force an exact time stamp by using
2803 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2804 and by using a prefix arg to `S-up/down' to specify the exact number
2805 of minutes to shift."
2806 :group 'org-time
2807 :get #'(lambda (var) ; Make sure both elements are there
2808 (if (integerp (default-value var))
2809 (list (default-value var) 5)
2810 (default-value var)))
2811 :type '(list
2812 (integer :tag "when inserting times")
2813 (integer :tag "when modifying times")))
2815 ;; Normalize old customizations of this variable.
2816 (when (integerp org-time-stamp-rounding-minutes)
2817 (setq org-time-stamp-rounding-minutes
2818 (list org-time-stamp-rounding-minutes
2819 org-time-stamp-rounding-minutes)))
2821 (defcustom org-display-custom-times nil
2822 "Non-nil means overlay custom formats over all time stamps.
2823 The formats are defined through the variable `org-time-stamp-custom-formats'.
2824 To turn this on on a per-file basis, insert anywhere in the file:
2825 #+STARTUP: customtime"
2826 :group 'org-time
2827 :set 'set-default
2828 :type 'sexp)
2829 (make-variable-buffer-local 'org-display-custom-times)
2831 (defcustom org-time-stamp-custom-formats
2832 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2833 "Custom formats for time stamps. See `format-time-string' for the syntax.
2834 These are overlaid over the default ISO format if the variable
2835 `org-display-custom-times' is set. Time like %H:%M should be at the
2836 end of the second format. The custom formats are also honored by export
2837 commands, if custom time display is turned on at the time of export."
2838 :group 'org-time
2839 :type 'sexp)
2841 (defun org-time-stamp-format (&optional long inactive)
2842 "Get the right format for a time string."
2843 (let ((f (if long (cdr org-time-stamp-formats)
2844 (car org-time-stamp-formats))))
2845 (if inactive
2846 (concat "[" (substring f 1 -1) "]")
2847 f)))
2849 (defcustom org-time-clocksum-format
2850 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2851 "The format string used when creating CLOCKSUM lines.
2852 This is also used when Org mode generates a time duration.
2854 The value can be a single format string containing two
2855 %-sequences, which will be filled with the number of hours and
2856 minutes in that order.
2858 Alternatively, the value can be a plist associating any of the
2859 keys :years, :months, :weeks, :days, :hours or :minutes with
2860 format strings. The time duration is formatted using only the
2861 time components that are needed and concatenating the results.
2862 If a time unit in absent, it falls back to the next smallest
2863 unit.
2865 The keys :require-years, :require-months, :require-days,
2866 :require-weeks, :require-hours, :require-minutes are also
2867 meaningful. A non-nil value for these keys indicates that the
2868 corresponding time component should always be included, even if
2869 its value is 0.
2872 For example,
2874 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2875 :require-minutes t)
2877 means durations longer than a day will be expressed in days,
2878 hours and minutes, and durations less than a day will always be
2879 expressed in hours and minutes (even for durations less than an
2880 hour).
2882 The value
2884 \(:days \"%dd\" :minutes \"%dm\")
2886 means durations longer than a day will be expressed in days and
2887 minutes, and durations less than a day will be expressed entirely
2888 in minutes (even for durations longer than an hour)."
2889 :group 'org-time
2890 :group 'org-clock
2891 :version "24.4"
2892 :package-version '(Org . "8.0")
2893 :type '(choice (string :tag "Format string")
2894 (set :tag "Plist"
2895 (group :inline t (const :tag "Years" :years)
2896 (string :tag "Format string"))
2897 (group :inline t
2898 (const :tag "Always show years" :require-years)
2899 (const t))
2900 (group :inline t (const :tag "Months" :months)
2901 (string :tag "Format string"))
2902 (group :inline t
2903 (const :tag "Always show months" :require-months)
2904 (const t))
2905 (group :inline t (const :tag "Weeks" :weeks)
2906 (string :tag "Format string"))
2907 (group :inline t
2908 (const :tag "Always show weeks" :require-weeks)
2909 (const t))
2910 (group :inline t (const :tag "Days" :days)
2911 (string :tag "Format string"))
2912 (group :inline t
2913 (const :tag "Always show days" :require-days)
2914 (const t))
2915 (group :inline t (const :tag "Hours" :hours)
2916 (string :tag "Format string"))
2917 (group :inline t
2918 (const :tag "Always show hours" :require-hours)
2919 (const t))
2920 (group :inline t (const :tag "Minutes" :minutes)
2921 (string :tag "Format string"))
2922 (group :inline t
2923 (const :tag "Always show minutes" :require-minutes)
2924 (const t)))))
2926 (defcustom org-time-clocksum-use-fractional nil
2927 "When non-nil, \\[org-clock-display] uses fractional times.
2928 See `org-time-clocksum-format' for more on time clock formats."
2929 :group 'org-time
2930 :group 'org-clock
2931 :version "24.3"
2932 :type 'boolean)
2934 (defcustom org-time-clocksum-use-effort-durations nil
2935 "When non-nil, \\[org-clock-display] uses effort durations.
2936 E.g. by default, one day is considered to be a 8 hours effort,
2937 so a task that has been clocked for 16 hours will be displayed
2938 as during 2 days in the clock display or in the clocktable.
2940 See `org-effort-durations' on how to set effort durations
2941 and `org-time-clocksum-format' for more on time clock formats."
2942 :group 'org-time
2943 :group 'org-clock
2944 :version "24.4"
2945 :package-version '(Org . "8.0")
2946 :type 'boolean)
2948 (defcustom org-time-clocksum-fractional-format "%.2f"
2949 "The format string used when creating CLOCKSUM lines,
2950 or when Org mode generates a time duration, if
2951 `org-time-clocksum-use-fractional' is enabled.
2953 The value can be a single format string containing one
2954 %-sequence, which will be filled with the number of hours as
2955 a float.
2957 Alternatively, the value can be a plist associating any of the
2958 keys :years, :months, :weeks, :days, :hours or :minutes with
2959 a format string. The time duration is formatted using the
2960 largest time unit which gives a non-zero integer part. If all
2961 specified formats have zero integer part, the smallest time unit
2962 is used."
2963 :group 'org-time
2964 :type '(choice (string :tag "Format string")
2965 (set (group :inline t (const :tag "Years" :years)
2966 (string :tag "Format string"))
2967 (group :inline t (const :tag "Months" :months)
2968 (string :tag "Format string"))
2969 (group :inline t (const :tag "Weeks" :weeks)
2970 (string :tag "Format string"))
2971 (group :inline t (const :tag "Days" :days)
2972 (string :tag "Format string"))
2973 (group :inline t (const :tag "Hours" :hours)
2974 (string :tag "Format string"))
2975 (group :inline t (const :tag "Minutes" :minutes)
2976 (string :tag "Format string")))))
2978 (defcustom org-deadline-warning-days 14
2979 "Number of days before expiration during which a deadline becomes active.
2980 This variable governs the display in sparse trees and in the agenda.
2981 When 0 or negative, it means use this number (the absolute value of it)
2982 even if a deadline has a different individual lead time specified.
2984 Custom commands can set this variable in the options section."
2985 :group 'org-time
2986 :group 'org-agenda-daily/weekly
2987 :type 'integer)
2989 (defcustom org-scheduled-delay-days 0
2990 "Number of days before a scheduled item becomes active.
2991 This variable governs the display in sparse trees and in the agenda.
2992 The default value (i.e. 0) means: don't delay scheduled item.
2993 When negative, it means use this number (the absolute value of it)
2994 even if a scheduled item has a different individual delay time
2995 specified.
2997 Custom commands can set this variable in the options section."
2998 :group 'org-time
2999 :group 'org-agenda-daily/weekly
3000 :version "24.4"
3001 :package-version '(Org . "8.0")
3002 :type 'integer)
3004 (defcustom org-read-date-prefer-future t
3005 "Non-nil means assume future for incomplete date input from user.
3006 This affects the following situations:
3007 1. The user gives a month but not a year.
3008 For example, if it is April and you enter \"feb 2\", this will be read
3009 as Feb 2, *next* year. \"May 5\", however, will be this year.
3010 2. The user gives a day, but no month.
3011 For example, if today is the 15th, and you enter \"3\", Org-mode will
3012 read this as the third of *next* month. However, if you enter \"17\",
3013 it will be considered as *this* month.
3015 If you set this variable to the symbol `time', then also the following
3016 will work:
3018 3. If the user gives a time.
3019 If the time is before now, it will be interpreted as tomorrow.
3021 Currently none of this works for ISO week specifications.
3023 When this option is nil, the current day, month and year will always be
3024 used as defaults.
3026 See also `org-agenda-jump-prefer-future'."
3027 :group 'org-time
3028 :type '(choice
3029 (const :tag "Never" nil)
3030 (const :tag "Check month and day" t)
3031 (const :tag "Check month, day, and time" time)))
3033 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3034 "Should the agenda jump command prefer the future for incomplete dates?
3035 The default is to do the same as configured in `org-read-date-prefer-future'.
3036 But you can also set a deviating value here.
3037 This may t or nil, or the symbol `org-read-date-prefer-future'."
3038 :group 'org-agenda
3039 :group 'org-time
3040 :version "24.1"
3041 :type '(choice
3042 (const :tag "Use org-read-date-prefer-future"
3043 org-read-date-prefer-future)
3044 (const :tag "Never" nil)
3045 (const :tag "Always" t)))
3047 (defcustom org-read-date-force-compatible-dates t
3048 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3050 Depending on the system Emacs is running on, certain dates cannot
3051 be represented with the type used internally to represent time.
3052 Dates between 1970-1-1 and 2038-1-1 can always be represented
3053 correctly. Some systems allow for earlier dates, some for later,
3054 some for both. One way to find out it to insert any date into an
3055 Org buffer, putting the cursor on the year and hitting S-up and
3056 S-down to test the range.
3058 When this variable is set to t, the date/time prompt will not let
3059 you specify dates outside the 1970-2037 range, so it is certain that
3060 these dates will work in whatever version of Emacs you are
3061 running, and also that you can move a file from one Emacs implementation
3062 to another. WHenever Org is forcing the year for you, it will display
3063 a message and beep.
3065 When this variable is nil, Org will check if the date is
3066 representable in the specific Emacs implementation you are using.
3067 If not, it will force a year, usually the current year, and beep
3068 to remind you. Currently this setting is not recommended because
3069 the likelihood that you will open your Org files in an Emacs that
3070 has limited date range is not negligible.
3072 A workaround for this problem is to use diary sexp dates for time
3073 stamps outside of this range."
3074 :group 'org-time
3075 :version "24.1"
3076 :type 'boolean)
3078 (defcustom org-read-date-display-live t
3079 "Non-nil means display current interpretation of date prompt live.
3080 This display will be in an overlay, in the minibuffer."
3081 :group 'org-time
3082 :type 'boolean)
3084 (defcustom org-read-date-popup-calendar t
3085 "Non-nil means pop up a calendar when prompting for a date.
3086 In the calendar, the date can be selected with mouse-1. However, the
3087 minibuffer will also be active, and you can simply enter the date as well.
3088 When nil, only the minibuffer will be available."
3089 :group 'org-time
3090 :type 'boolean)
3091 (if (fboundp 'defvaralias)
3092 (defvaralias 'org-popup-calendar-for-date-prompt
3093 'org-read-date-popup-calendar))
3095 (make-obsolete-variable
3096 'org-read-date-minibuffer-setup-hook
3097 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3098 (defcustom org-read-date-minibuffer-setup-hook nil
3099 "Hook to be used to set up keys for the date/time interface.
3100 Add key definitions to `minibuffer-local-map', which will be a
3101 temporary copy.
3103 WARNING: This option is obsolete, you should use
3104 `org-read-date-minibuffer-local-map' to set up keys."
3105 :group 'org-time
3106 :type 'hook)
3108 (defcustom org-extend-today-until 0
3109 "The hour when your day really ends. Must be an integer.
3110 This has influence for the following applications:
3111 - When switching the agenda to \"today\". It it is still earlier than
3112 the time given here, the day recognized as TODAY is actually yesterday.
3113 - When a date is read from the user and it is still before the time given
3114 here, the current date and time will be assumed to be yesterday, 23:59.
3115 Also, timestamps inserted in capture templates follow this rule.
3117 IMPORTANT: This is a feature whose implementation is and likely will
3118 remain incomplete. Really, it is only here because past midnight seems to
3119 be the favorite working time of John Wiegley :-)"
3120 :group 'org-time
3121 :type 'integer)
3123 (defcustom org-use-effective-time nil
3124 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3125 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3126 \"effective time\" of any timestamps between midnight and 8am will be
3127 23:59 of the previous day."
3128 :group 'org-time
3129 :version "24.1"
3130 :type 'boolean)
3132 (defcustom org-use-last-clock-out-time-as-effective-time nil
3133 "When non-nil, use the last clock out time for `org-todo'.
3134 Note that this option has precedence over the combined use of
3135 `org-use-effective-time' and `org-extend-today-until'."
3136 :group 'org-time
3137 :version "24.4"
3138 :package-version '(Org . "8.0")
3139 :type 'boolean)
3141 (defcustom org-edit-timestamp-down-means-later nil
3142 "Non-nil means S-down will increase the time in a time stamp.
3143 When nil, S-up will increase."
3144 :group 'org-time
3145 :type 'boolean)
3147 (defcustom org-calendar-follow-timestamp-change t
3148 "Non-nil means make the calendar window follow timestamp changes.
3149 When a timestamp is modified and the calendar window is visible, it will be
3150 moved to the new date."
3151 :group 'org-time
3152 :type 'boolean)
3154 (defgroup org-tags nil
3155 "Options concerning tags in Org-mode."
3156 :tag "Org Tags"
3157 :group 'org)
3159 (defcustom org-tag-alist nil
3160 "List of tags allowed in Org-mode files.
3161 When this list is nil, Org-mode will base TAG input on what is already in the
3162 buffer.
3163 The value of this variable is an alist, the car of each entry must be a
3164 keyword as a string, the cdr may be a character that is used to select
3165 that tag through the fast-tag-selection interface.
3166 See the manual for details."
3167 :group 'org-tags
3168 :type '(repeat
3169 (choice
3170 (cons (string :tag "Tag name")
3171 (character :tag "Access char"))
3172 (list :tag "Start radio group"
3173 (const :startgroup)
3174 (option (string :tag "Group description")))
3175 (list :tag "End radio group"
3176 (const :endgroup)
3177 (option (string :tag "Group description")))
3178 (const :tag "New line" (:newline)))))
3180 (defcustom org-tag-persistent-alist nil
3181 "List of tags that will always appear in all Org-mode files.
3182 This is in addition to any in buffer settings or customizations
3183 of `org-tag-alist'.
3184 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3185 The value of this variable is an alist, the car of each entry must be a
3186 keyword as a string, the cdr may be a character that is used to select
3187 that tag through the fast-tag-selection interface.
3188 See the manual for details.
3189 To disable these tags on a per-file basis, insert anywhere in the file:
3190 #+STARTUP: noptag"
3191 :group 'org-tags
3192 :type '(repeat
3193 (choice
3194 (cons (string :tag "Tag name")
3195 (character :tag "Access char"))
3196 (const :tag "Start radio group" (:startgroup))
3197 (const :tag "End radio group" (:endgroup))
3198 (const :tag "New line" (:newline)))))
3200 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3201 "If non-nil, always offer completion for all tags of all agenda files.
3202 Instead of customizing this variable directly, you might want to
3203 set it locally for capture buffers, because there no list of
3204 tags in that file can be created dynamically (there are none).
3206 (add-hook 'org-capture-mode-hook
3207 (lambda ()
3208 (set (make-local-variable
3209 'org-complete-tags-always-offer-all-agenda-tags)
3210 t)))"
3211 :group 'org-tags
3212 :version "24.1"
3213 :type 'boolean)
3215 (defvar org-file-tags nil
3216 "List of tags that can be inherited by all entries in the file.
3217 The tags will be inherited if the variable `org-use-tag-inheritance'
3218 says they should be.
3219 This variable is populated from #+FILETAGS lines.")
3221 (defcustom org-use-fast-tag-selection 'auto
3222 "Non-nil means use fast tag selection scheme.
3223 This is a special interface to select and deselect tags with single keys.
3224 When nil, fast selection is never used.
3225 When the symbol `auto', fast selection is used if and only if selection
3226 characters for tags have been configured, either through the variable
3227 `org-tag-alist' or through a #+TAGS line in the buffer.
3228 When t, fast selection is always used and selection keys are assigned
3229 automatically if necessary."
3230 :group 'org-tags
3231 :type '(choice
3232 (const :tag "Always" t)
3233 (const :tag "Never" nil)
3234 (const :tag "When selection characters are configured" 'auto)))
3236 (defcustom org-fast-tag-selection-single-key nil
3237 "Non-nil means fast tag selection exits after first change.
3238 When nil, you have to press RET to exit it.
3239 During fast tag selection, you can toggle this flag with `C-c'.
3240 This variable can also have the value `expert'. In this case, the window
3241 displaying the tags menu is not even shown, until you press C-c again."
3242 :group 'org-tags
3243 :type '(choice
3244 (const :tag "No" nil)
3245 (const :tag "Yes" t)
3246 (const :tag "Expert" expert)))
3248 (defvar org-fast-tag-selection-include-todo nil
3249 "Non-nil means fast tags selection interface will also offer TODO states.
3250 This is an undocumented feature, you should not rely on it.")
3252 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3253 "The column to which tags should be indented in a headline.
3254 If this number is positive, it specifies the column. If it is negative,
3255 it means that the tags should be flushright to that column. For example,
3256 -80 works well for a normal 80 character screen.
3257 When 0, place tags directly after headline text, with only one space in
3258 between."
3259 :group 'org-tags
3260 :type 'integer)
3262 (defcustom org-auto-align-tags t
3263 "Non-nil keeps tags aligned when modifying headlines.
3264 Some operations (i.e. demoting) change the length of a headline and
3265 therefore shift the tags around. With this option turned on, after
3266 each such operation the tags are again aligned to `org-tags-column'."
3267 :group 'org-tags
3268 :type 'boolean)
3270 (defcustom org-use-tag-inheritance t
3271 "Non-nil means tags in levels apply also for sublevels.
3272 When nil, only the tags directly given in a specific line apply there.
3273 This may also be a list of tags that should be inherited, or a regexp that
3274 matches tags that should be inherited. Additional control is possible
3275 with the variable `org-tags-exclude-from-inheritance' which gives an
3276 explicit list of tags to be excluded from inheritance, even if the value of
3277 `org-use-tag-inheritance' would select it for inheritance.
3279 If this option is t, a match early-on in a tree can lead to a large
3280 number of matches in the subtree when constructing the agenda or creating
3281 a sparse tree. If you only want to see the first match in a tree during
3282 a search, check out the variable `org-tags-match-list-sublevels'."
3283 :group 'org-tags
3284 :type '(choice
3285 (const :tag "Not" nil)
3286 (const :tag "Always" t)
3287 (repeat :tag "Specific tags" (string :tag "Tag"))
3288 (regexp :tag "Tags matched by regexp")))
3290 (defcustom org-tags-exclude-from-inheritance nil
3291 "List of tags that should never be inherited.
3292 This is a way to exclude a few tags from inheritance. For way to do
3293 the opposite, to actively allow inheritance for selected tags,
3294 see the variable `org-use-tag-inheritance'."
3295 :group 'org-tags
3296 :type '(repeat (string :tag "Tag")))
3298 (defun org-tag-inherit-p (tag)
3299 "Check if TAG is one that should be inherited."
3300 (cond
3301 ((member tag org-tags-exclude-from-inheritance) nil)
3302 ((eq org-use-tag-inheritance t) t)
3303 ((not org-use-tag-inheritance) nil)
3304 ((stringp org-use-tag-inheritance)
3305 (string-match org-use-tag-inheritance tag))
3306 ((listp org-use-tag-inheritance)
3307 (member tag org-use-tag-inheritance))
3308 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3310 (defcustom org-tags-match-list-sublevels t
3311 "Non-nil means list also sublevels of headlines matching a search.
3312 This variable applies to tags/property searches, and also to stuck
3313 projects because this search is based on a tags match as well.
3315 When set to the symbol `indented', sublevels are indented with
3316 leading dots.
3318 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3319 the sublevels of a headline matching a tag search often also match
3320 the same search. Listing all of them can create very long lists.
3321 Setting this variable to nil causes subtrees of a match to be skipped.
3323 This variable is semi-obsolete and probably should always be true. It
3324 is better to limit inheritance to certain tags using the variables
3325 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3326 :group 'org-tags
3327 :type '(choice
3328 (const :tag "No, don't list them" nil)
3329 (const :tag "Yes, do list them" t)
3330 (const :tag "List them, indented with leading dots" indented)))
3332 (defcustom org-tags-sort-function nil
3333 "When set, tags are sorted using this function as a comparator."
3334 :group 'org-tags
3335 :type '(choice
3336 (const :tag "No sorting" nil)
3337 (const :tag "Alphabetical" string<)
3338 (const :tag "Reverse alphabetical" string>)
3339 (function :tag "Custom function" nil)))
3341 (defvar org-tags-history nil
3342 "History of minibuffer reads for tags.")
3343 (defvar org-last-tags-completion-table nil
3344 "The last used completion table for tags.")
3345 (defvar org-after-tags-change-hook nil
3346 "Hook that is run after the tags in a line have changed.")
3348 (defgroup org-properties nil
3349 "Options concerning properties in Org-mode."
3350 :tag "Org Properties"
3351 :group 'org)
3353 (defcustom org-property-format "%-10s %s"
3354 "How property key/value pairs should be formatted by `indent-line'.
3355 When `indent-line' hits a property definition, it will format the line
3356 according to this format, mainly to make sure that the values are
3357 lined-up with respect to each other."
3358 :group 'org-properties
3359 :type 'string)
3361 (defcustom org-properties-postprocess-alist nil
3362 "Alist of properties and functions to adjust inserted values.
3363 Elements of this alist must be of the form
3365 ([string] [function])
3367 where [string] must be a property name and [function] must be a
3368 lambda expression: this lambda expression must take one argument,
3369 the value to adjust, and return the new value as a string.
3371 For example, this element will allow the property \"Remaining\"
3372 to be updated wrt the relation between the \"Effort\" property
3373 and the clock summary:
3375 ((\"Remaining\" (lambda(value)
3376 (let ((clocksum (org-clock-sum-current-item))
3377 (effort (org-duration-string-to-minutes
3378 (org-entry-get (point) \"Effort\"))))
3379 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3380 :group 'org-properties
3381 :version "24.1"
3382 :type '(alist :key-type (string :tag "Property")
3383 :value-type (function :tag "Function")))
3385 (defcustom org-use-property-inheritance nil
3386 "Non-nil means properties apply also for sublevels.
3388 This setting is chiefly used during property searches. Turning it on can
3389 cause significant overhead when doing a search, which is why it is not
3390 on by default.
3392 When nil, only the properties directly given in the current entry count.
3393 When t, every property is inherited. The value may also be a list of
3394 properties that should have inheritance, or a regular expression matching
3395 properties that should be inherited.
3397 However, note that some special properties use inheritance under special
3398 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3399 and the properties ending in \"_ALL\" when they are used as descriptor
3400 for valid values of a property.
3402 Note for programmers:
3403 When querying an entry with `org-entry-get', you can control if inheritance
3404 should be used. By default, `org-entry-get' looks only at the local
3405 properties. You can request inheritance by setting the inherit argument
3406 to t (to force inheritance) or to `selective' (to respect the setting
3407 in this variable)."
3408 :group 'org-properties
3409 :type '(choice
3410 (const :tag "Not" nil)
3411 (const :tag "Always" t)
3412 (repeat :tag "Specific properties" (string :tag "Property"))
3413 (regexp :tag "Properties matched by regexp")))
3415 (defun org-property-inherit-p (property)
3416 "Check if PROPERTY is one that should be inherited."
3417 (cond
3418 ((eq org-use-property-inheritance t) t)
3419 ((not org-use-property-inheritance) nil)
3420 ((stringp org-use-property-inheritance)
3421 (string-match org-use-property-inheritance property))
3422 ((listp org-use-property-inheritance)
3423 (member property org-use-property-inheritance))
3424 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3426 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3427 "The default column format, if no other format has been defined.
3428 This variable can be set on the per-file basis by inserting a line
3430 #+COLUMNS: %25ITEM ....."
3431 :group 'org-properties
3432 :type 'string)
3434 (defcustom org-columns-ellipses ".."
3435 "The ellipses to be used when a field in column view is truncated.
3436 When this is the empty string, as many characters as possible are shown,
3437 but then there will be no visual indication that the field has been truncated.
3438 When this is a string of length N, the last N characters of a truncated
3439 field are replaced by this string. If the column is narrower than the
3440 ellipses string, only part of the ellipses string will be shown."
3441 :group 'org-properties
3442 :type 'string)
3444 (defcustom org-columns-modify-value-for-display-function nil
3445 "Function that modifies values for display in column view.
3446 For example, it can be used to cut out a certain part from a time stamp.
3447 The function must take 2 arguments:
3449 column-title The title of the column (*not* the property name)
3450 value The value that should be modified.
3452 The function should return the value that should be displayed,
3453 or nil if the normal value should be used."
3454 :group 'org-properties
3455 :type 'function)
3457 (defcustom org-effort-property "Effort"
3458 "The property that is being used to keep track of effort estimates.
3459 Effort estimates given in this property need to have the format H:MM."
3460 :group 'org-properties
3461 :group 'org-progress
3462 :type '(string :tag "Property"))
3464 (defconst org-global-properties-fixed
3465 '(("VISIBILITY_ALL" . "folded children content all")
3466 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3467 "List of property/value pairs that can be inherited by any entry.
3469 These are fixed values, for the preset properties. The user variable
3470 that can be used to add to this list is `org-global-properties'.
3472 The entries in this list are cons cells where the car is a property
3473 name and cdr is a string with the value. If the value represents
3474 multiple items like an \"_ALL\" property, separate the items by
3475 spaces.")
3477 (defcustom org-global-properties nil
3478 "List of property/value pairs that can be inherited by any entry.
3480 This list will be combined with the constant `org-global-properties-fixed'.
3482 The entries in this list are cons cells where the car is a property
3483 name and cdr is a string with the value.
3485 You can set buffer-local values for the same purpose in the variable
3486 `org-file-properties' this by adding lines like
3488 #+PROPERTY: NAME VALUE"
3489 :group 'org-properties
3490 :type '(repeat
3491 (cons (string :tag "Property")
3492 (string :tag "Value"))))
3494 (defvar org-file-properties nil
3495 "List of property/value pairs that can be inherited by any entry.
3496 Valid for the current buffer.
3497 This variable is populated from #+PROPERTY lines.")
3498 (make-variable-buffer-local 'org-file-properties)
3500 (defgroup org-agenda nil
3501 "Options concerning agenda views in Org-mode."
3502 :tag "Org Agenda"
3503 :group 'org)
3505 (defvar org-category nil
3506 "Variable used by org files to set a category for agenda display.
3507 Such files should use a file variable to set it, for example
3509 # -*- mode: org; org-category: \"ELisp\"
3511 or contain a special line
3513 #+CATEGORY: ELisp
3515 If the file does not specify a category, then file's base name
3516 is used instead.")
3517 (make-variable-buffer-local 'org-category)
3518 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3520 (defcustom org-agenda-files nil
3521 "The files to be used for agenda display.
3522 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3523 \\[org-remove-file]. You can also use customize to edit the list.
3525 If an entry is a directory, all files in that directory that are matched by
3526 `org-agenda-file-regexp' will be part of the file list.
3528 If the value of the variable is not a list but a single file name, then
3529 the list of agenda files is actually stored and maintained in that file, one
3530 agenda file per line. In this file paths can be given relative to
3531 `org-directory'. Tilde expansion and environment variable substitution
3532 are also made."
3533 :group 'org-agenda
3534 :type '(choice
3535 (repeat :tag "List of files and directories" file)
3536 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3538 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3539 "Regular expression to match files for `org-agenda-files'.
3540 If any element in the list in that variable contains a directory instead
3541 of a normal file, all files in that directory that are matched by this
3542 regular expression will be included."
3543 :group 'org-agenda
3544 :type 'regexp)
3546 (defcustom org-agenda-text-search-extra-files nil
3547 "List of extra files to be searched by text search commands.
3548 These files will be search in addition to the agenda files by the
3549 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3550 Note that these files will only be searched for text search commands,
3551 not for the other agenda views like todo lists, tag searches or the weekly
3552 agenda. This variable is intended to list notes and possibly archive files
3553 that should also be searched by these two commands.
3554 In fact, if the first element in the list is the symbol `agenda-archives',
3555 than all archive files of all agenda files will be added to the search
3556 scope."
3557 :group 'org-agenda
3558 :type '(set :greedy t
3559 (const :tag "Agenda Archives" agenda-archives)
3560 (repeat :inline t (file))))
3562 (if (fboundp 'defvaralias)
3563 (defvaralias 'org-agenda-multi-occur-extra-files
3564 'org-agenda-text-search-extra-files))
3566 (defcustom org-agenda-skip-unavailable-files nil
3567 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3568 A nil value means to remove them, after a query, from the list."
3569 :group 'org-agenda
3570 :type 'boolean)
3572 (defcustom org-calendar-to-agenda-key [?c]
3573 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3574 The command `org-calendar-goto-agenda' will be bound to this key. The
3575 default is the character `c' because then `c' can be used to switch back and
3576 forth between agenda and calendar."
3577 :group 'org-agenda
3578 :type 'sexp)
3580 (defcustom org-calendar-insert-diary-entry-key [?i]
3581 "The key to be installed in `calendar-mode-map' for adding diary entries.
3582 This option is irrelevant until `org-agenda-diary-file' has been configured
3583 to point to an Org-mode file. When that is the case, the command
3584 `org-agenda-diary-entry' will be bound to the key given here, by default
3585 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3586 if you want to continue doing this, you need to change this to a different
3587 key."
3588 :group 'org-agenda
3589 :type 'sexp)
3591 (defcustom org-agenda-diary-file 'diary-file
3592 "File to which to add new entries with the `i' key in agenda and calendar.
3593 When this is the symbol `diary-file', the functionality in the Emacs
3594 calendar will be used to add entries to the `diary-file'. But when this
3595 points to a file, `org-agenda-diary-entry' will be used instead."
3596 :group 'org-agenda
3597 :type '(choice
3598 (const :tag "The standard Emacs diary file" diary-file)
3599 (file :tag "Special Org file diary entries")))
3601 (eval-after-load "calendar"
3602 '(progn
3603 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3604 'org-calendar-goto-agenda)
3605 (add-hook 'calendar-mode-hook
3606 (lambda ()
3607 (unless (eq org-agenda-diary-file 'diary-file)
3608 (define-key calendar-mode-map
3609 org-calendar-insert-diary-entry-key
3610 'org-agenda-diary-entry))))))
3612 (defgroup org-latex nil
3613 "Options for embedding LaTeX code into Org-mode."
3614 :tag "Org LaTeX"
3615 :group 'org)
3617 (defcustom org-format-latex-options
3618 '(:foreground default :background default :scale 1.0
3619 :html-foreground "Black" :html-background "Transparent"
3620 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3621 "Options for creating images from LaTeX fragments.
3622 This is a property list with the following properties:
3623 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3624 `default' means use the foreground of the default face.
3625 `auto' means use the foreground from the text face.
3626 :background the background color, or \"Transparent\".
3627 `default' means use the background of the default face.
3628 `auto' means use the background from the text face.
3629 :scale a scaling factor for the size of the images, to get more pixels
3630 :html-foreground, :html-background, :html-scale
3631 the same numbers for HTML export.
3632 :matchers a list indicating which matchers should be used to
3633 find LaTeX fragments. Valid members of this list are:
3634 \"begin\" find environments
3635 \"$1\" find single characters surrounded by $.$
3636 \"$\" find math expressions surrounded by $...$
3637 \"$$\" find math expressions surrounded by $$....$$
3638 \"\\(\" find math expressions surrounded by \\(...\\)
3639 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3640 :group 'org-latex
3641 :type 'plist)
3643 (defcustom org-format-latex-signal-error t
3644 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3645 When nil, just push out a message."
3646 :group 'org-latex
3647 :version "24.1"
3648 :type 'boolean)
3650 (defcustom org-latex-to-mathml-jar-file nil
3651 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3652 Use this to specify additional executable file say a jar file.
3654 When using MathToWeb as the converter, specify the full-path to
3655 your mathtoweb.jar file."
3656 :group 'org-latex
3657 :version "24.1"
3658 :type '(choice
3659 (const :tag "None" nil)
3660 (file :tag "JAR file" :must-match t)))
3662 (defcustom org-latex-to-mathml-convert-command nil
3663 "Command to convert LaTeX fragments to MathML.
3664 Replace format-specifiers in the command as noted below and use
3665 `shell-command' to convert LaTeX to MathML.
3666 %j: Executable file in fully expanded form as specified by
3667 `org-latex-to-mathml-jar-file'.
3668 %I: Input LaTeX file in fully expanded form
3669 %o: Output MathML file
3670 This command is used by `org-create-math-formula'.
3672 When using MathToWeb as the converter, set this to
3673 \"java -jar %j -unicode -force -df %o %I\"."
3674 :group 'org-latex
3675 :version "24.1"
3676 :type '(choice
3677 (const :tag "None" nil)
3678 (string :tag "\nShell command")))
3680 (defcustom org-latex-create-formula-image-program 'dvipng
3681 "Program to convert LaTeX fragments with.
3683 dvipng Process the LaTeX fragments to dvi file, then convert
3684 dvi files to png files using dvipng.
3685 This will also include processing of non-math environments.
3686 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3687 to convert pdf files to png files"
3688 :group 'org-latex
3689 :version "24.1"
3690 :type '(choice
3691 (const :tag "dvipng" dvipng)
3692 (const :tag "imagemagick" imagemagick)))
3694 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3695 "Path to store latex preview images.
3696 A relative path here creates many directories relative to the
3697 processed org files paths. An absolute path puts all preview
3698 images at the same place."
3699 :group 'org-latex
3700 :version "24.3"
3701 :type 'string)
3703 (defun org-format-latex-mathml-available-p ()
3704 "Return t if `org-latex-to-mathml-convert-command' is usable."
3705 (save-match-data
3706 (when (and (boundp 'org-latex-to-mathml-convert-command)
3707 org-latex-to-mathml-convert-command)
3708 (let ((executable (car (split-string
3709 org-latex-to-mathml-convert-command))))
3710 (when (executable-find executable)
3711 (if (string-match
3712 "%j" org-latex-to-mathml-convert-command)
3713 (file-readable-p org-latex-to-mathml-jar-file)
3714 t))))))
3716 (defcustom org-format-latex-header "\\documentclass{article}
3717 \\usepackage[usenames]{color}
3718 \\usepackage{amsmath}
3719 \\usepackage[mathscr]{eucal}
3720 \\pagestyle{empty} % do not remove
3721 \[PACKAGES]
3722 \[DEFAULT-PACKAGES]
3723 % The settings below are copied from fullpage.sty
3724 \\setlength{\\textwidth}{\\paperwidth}
3725 \\addtolength{\\textwidth}{-3cm}
3726 \\setlength{\\oddsidemargin}{1.5cm}
3727 \\addtolength{\\oddsidemargin}{-2.54cm}
3728 \\setlength{\\evensidemargin}{\\oddsidemargin}
3729 \\setlength{\\textheight}{\\paperheight}
3730 \\addtolength{\\textheight}{-\\headheight}
3731 \\addtolength{\\textheight}{-\\headsep}
3732 \\addtolength{\\textheight}{-\\footskip}
3733 \\addtolength{\\textheight}{-3cm}
3734 \\setlength{\\topmargin}{1.5cm}
3735 \\addtolength{\\topmargin}{-2.54cm}"
3736 "The document header used for processing LaTeX fragments.
3737 It is imperative that this header make sure that no page number
3738 appears on the page. The package defined in the variables
3739 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3740 will either replace the placeholder \"[PACKAGES]\" in this
3741 header, or they will be appended."
3742 :group 'org-latex
3743 :type 'string)
3745 (defun org-set-packages-alist (var val)
3746 "Set the packages alist and make sure it has 3 elements per entry."
3747 (set var (mapcar (lambda (x)
3748 (if (and (consp x) (= (length x) 2))
3749 (list (car x) (nth 1 x) t)
3751 val)))
3753 (defun org-get-packages-alist (var)
3754 "Get the packages alist and make sure it has 3 elements per entry."
3755 (mapcar (lambda (x)
3756 (if (and (consp x) (= (length x) 2))
3757 (list (car x) (nth 1 x) t)
3759 (default-value var)))
3761 (defcustom org-latex-default-packages-alist
3762 '(("AUTO" "inputenc" t)
3763 ("T1" "fontenc" t)
3764 ("" "fixltx2e" nil)
3765 ("" "graphicx" t)
3766 ("" "longtable" nil)
3767 ("" "float" nil)
3768 ("" "wrapfig" nil)
3769 ("" "soul" t)
3770 ("" "textcomp" t)
3771 ("" "marvosym" t)
3772 ("" "wasysym" t)
3773 ("" "latexsym" t)
3774 ("" "amssymb" t)
3775 ("" "hyperref" nil)
3776 "\\tolerance=1000")
3777 "Alist of default packages to be inserted in the header.
3779 Change this only if one of the packages here causes an
3780 incompatibility with another package you are using.
3782 The packages in this list are needed by one part or another of
3783 Org mode to function properly:
3785 - inputenc, fontenc: for basic font and character selection
3786 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3787 symbols used for interpreting the entities in `org-entities'.
3788 You can skip some of these packages if you don't use any of the
3789 symbols in it.
3790 - graphicx: for including images
3791 - float, wrapfig: for figure placement
3792 - longtable: for long tables
3793 - hyperref: for cross references
3795 Therefore you should not modify this variable unless you know
3796 what you are doing. The one reason to change it anyway is that
3797 you might be loading some other package that conflicts with one
3798 of the default packages. Each cell is of the format
3799 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3800 the package also needs to be included when compiling LaTeX
3801 snippets into images for inclusion into non-LaTeX output."
3802 :group 'org-latex
3803 :group 'org-export-latex
3804 :set 'org-set-packages-alist
3805 :get 'org-get-packages-alist
3806 :version "24.1"
3807 :type '(repeat
3808 (choice
3809 (list :tag "options/package pair"
3810 (string :tag "options")
3811 (string :tag "package")
3812 (boolean :tag "Snippet"))
3813 (string :tag "A line of LaTeX"))))
3815 (defcustom org-latex-packages-alist nil
3816 "Alist of packages to be inserted in every LaTeX header.
3818 These will be inserted after `org-latex-default-packages-alist'.
3819 Each cell is of the format:
3821 \(\"options\" \"package\" snippet-flag)
3823 SNIPPET-FLAG, when t, indicates that this package is also needed
3824 when turning LaTeX snippets into images for inclusion into
3825 non-LaTeX output.
3827 Make sure that you only list packages here which:
3829 - you want in every file
3830 - do not conflict with the setup in `org-format-latex-header'.
3831 - do not conflict with the default packages in
3832 `org-latex-default-packages-alist'."
3833 :group 'org-latex
3834 :group 'org-export-latex
3835 :set 'org-set-packages-alist
3836 :get 'org-get-packages-alist
3837 :type '(repeat
3838 (choice
3839 (list :tag "options/package pair"
3840 (string :tag "options")
3841 (string :tag "package")
3842 (boolean :tag "Snippet"))
3843 (string :tag "A line of LaTeX"))))
3845 (defgroup org-appearance nil
3846 "Settings for Org-mode appearance."
3847 :tag "Org Appearance"
3848 :group 'org)
3850 (defcustom org-level-color-stars-only nil
3851 "Non-nil means fontify only the stars in each headline.
3852 When nil, the entire headline is fontified.
3853 Changing it requires restart of `font-lock-mode' to become effective
3854 also in regions already fontified."
3855 :group 'org-appearance
3856 :type 'boolean)
3858 (defcustom org-hide-leading-stars nil
3859 "Non-nil means hide the first N-1 stars in a headline.
3860 This works by using the face `org-hide' for these stars. This
3861 face is white for a light background, and black for a dark
3862 background. You may have to customize the face `org-hide' to
3863 make this work.
3864 Changing it requires restart of `font-lock-mode' to become effective
3865 also in regions already fontified.
3866 You may also set this on a per-file basis by adding one of the following
3867 lines to the buffer:
3869 #+STARTUP: hidestars
3870 #+STARTUP: showstars"
3871 :group 'org-appearance
3872 :type 'boolean)
3874 (defcustom org-hidden-keywords nil
3875 "List of symbols corresponding to keywords to be hidden the org buffer.
3876 For example, a value '(title) for this list will make the document's title
3877 appear in the buffer without the initial #+TITLE: keyword."
3878 :group 'org-appearance
3879 :version "24.1"
3880 :type '(set (const :tag "#+AUTHOR" author)
3881 (const :tag "#+DATE" date)
3882 (const :tag "#+EMAIL" email)
3883 (const :tag "#+TITLE" title)))
3885 (defcustom org-custom-properties nil
3886 "List of properties (as strings) with a special meaning.
3887 The default use of these custom properties is to let the user
3888 hide them with `org-toggle-custom-properties-visibility'."
3889 :group 'org-properties
3890 :group 'org-appearance
3891 :version "24.3"
3892 :type '(repeat (string :tag "Property Name")))
3894 (defcustom org-fontify-done-headline nil
3895 "Non-nil means change the face of a headline if it is marked DONE.
3896 Normally, only the TODO/DONE keyword indicates the state of a headline.
3897 When this is non-nil, the headline after the keyword is set to the
3898 `org-headline-done' as an additional indication."
3899 :group 'org-appearance
3900 :type 'boolean)
3902 (defcustom org-fontify-emphasized-text t
3903 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3904 Changing this variable requires a restart of Emacs to take effect."
3905 :group 'org-appearance
3906 :type 'boolean)
3908 (defcustom org-fontify-whole-heading-line nil
3909 "Non-nil means fontify the whole line for headings.
3910 This is useful when setting a background color for the
3911 org-level-* faces."
3912 :group 'org-appearance
3913 :type 'boolean)
3915 (defcustom org-highlight-latex-and-related nil
3916 "Non-nil means highlight LaTeX related syntax in the buffer.
3917 When non nil, the value should be a list containing any of the
3918 following symbols:
3919 `latex' Highlight LaTeX snippets and environments.
3920 `script' Highlight subscript and superscript.
3921 `entities' Highlight entities."
3922 :group 'org-appearance
3923 :version "24.4"
3924 :package-version '(Org . "8.0")
3925 :type '(choice
3926 (const :tag "No highlighting" nil)
3927 (set :greedy t :tag "Highlight"
3928 (const :tag "LaTeX snippets and environments" latex)
3929 (const :tag "Subscript and superscript" script)
3930 (const :tag "Entities" entities))))
3932 (defcustom org-hide-emphasis-markers nil
3933 "Non-nil mean font-lock should hide the emphasis marker characters."
3934 :group 'org-appearance
3935 :type 'boolean)
3937 (defcustom org-pretty-entities nil
3938 "Non-nil means show entities as UTF8 characters.
3939 When nil, the \\name form remains in the buffer."
3940 :group 'org-appearance
3941 :version "24.1"
3942 :type 'boolean)
3944 (defcustom org-pretty-entities-include-sub-superscripts t
3945 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3946 :group 'org-appearance
3947 :version "24.1"
3948 :type 'boolean)
3950 (defvar org-emph-re nil
3951 "Regular expression for matching emphasis.
3952 After a match, the match groups contain these elements:
3953 0 The match of the full regular expression, including the characters
3954 before and after the proper match
3955 1 The character before the proper match, or empty at beginning of line
3956 2 The proper match, including the leading and trailing markers
3957 3 The leading marker like * or /, indicating the type of highlighting
3958 4 The text between the emphasis markers, not including the markers
3959 5 The character after the match, empty at the end of a line")
3960 (defvar org-verbatim-re nil
3961 "Regular expression for matching verbatim text.")
3962 (defvar org-emphasis-regexp-components) ; defined just below
3963 (defvar org-emphasis-alist) ; defined just below
3964 (defun org-set-emph-re (var val)
3965 "Set variable and compute the emphasis regular expression."
3966 (set var val)
3967 (when (and (boundp 'org-emphasis-alist)
3968 (boundp 'org-emphasis-regexp-components)
3969 org-emphasis-alist org-emphasis-regexp-components)
3970 (let* ((e org-emphasis-regexp-components)
3971 (pre (car e))
3972 (post (nth 1 e))
3973 (border (nth 2 e))
3974 (body (nth 3 e))
3975 (nl (nth 4 e))
3976 (body1 (concat body "*?"))
3977 (markers (mapconcat 'car org-emphasis-alist ""))
3978 (vmarkers (mapconcat
3979 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3980 org-emphasis-alist "")))
3981 ;; make sure special characters appear at the right position in the class
3982 (if (string-match "\\^" markers)
3983 (setq markers (concat (replace-match "" t t markers) "^")))
3984 (if (string-match "-" markers)
3985 (setq markers (concat (replace-match "" t t markers) "-")))
3986 (if (string-match "\\^" vmarkers)
3987 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3988 (if (string-match "-" vmarkers)
3989 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3990 (if (> nl 0)
3991 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3992 (int-to-string nl) "\\}")))
3993 ;; Make the regexp
3994 (setq org-emph-re
3995 (concat "\\([" pre "]\\|^\\)"
3996 "\\("
3997 "\\([" markers "]\\)"
3998 "\\("
3999 "[^" border "]\\|"
4000 "[^" border "]"
4001 body1
4002 "[^" border "]"
4003 "\\)"
4004 "\\3\\)"
4005 "\\([" post "]\\|$\\)"))
4006 (setq org-verbatim-re
4007 (concat "\\([" pre "]\\|^\\)"
4008 "\\("
4009 "\\([" vmarkers "]\\)"
4010 "\\("
4011 "[^" border "]\\|"
4012 "[^" border "]"
4013 body1
4014 "[^" border "]"
4015 "\\)"
4016 "\\3\\)"
4017 "\\([" post "]\\|$\\)")))))
4019 (defcustom org-emphasis-regexp-components
4020 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4021 "Components used to build the regular expression for emphasis.
4022 This is a list with five entries. Terminology: In an emphasis string
4023 like \" *strong word* \", we call the initial space PREMATCH, the final
4024 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4025 and \"trong wor\" is the body. The different components in this variable
4026 specify what is allowed/forbidden in each part:
4028 pre Chars allowed as prematch. Beginning of line will be allowed too.
4029 post Chars allowed as postmatch. End of line will be allowed too.
4030 border The chars *forbidden* as border characters.
4031 body-regexp A regexp like \".\" to match a body character. Don't use
4032 non-shy groups here, and don't allow newline here.
4033 newline The maximum number of newlines allowed in an emphasis exp.
4035 Use customize to modify this, or restart Emacs after changing it."
4036 :group 'org-appearance
4037 :set 'org-set-emph-re
4038 :type '(list
4039 (sexp :tag "Allowed chars in pre ")
4040 (sexp :tag "Allowed chars in post ")
4041 (sexp :tag "Forbidden chars in border ")
4042 (sexp :tag "Regexp for body ")
4043 (integer :tag "number of newlines allowed")
4044 (option (boolean :tag "Please ignore this button"))))
4046 (defcustom org-emphasis-alist
4047 `(("*" bold "<b>" "</b>")
4048 ("/" italic "<i>" "</i>")
4049 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4050 ("=" org-code "<code>" "</code>" verbatim)
4051 ("~" org-verbatim "<code>" "</code>" verbatim)
4052 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4053 "<del>" "</del>")
4055 "Special syntax for emphasized text.
4056 Text starting and ending with a special character will be emphasized, for
4057 example *bold*, _underlined_ and /italic/. This variable sets the marker
4058 characters, the face to be used by font-lock for highlighting in Org-mode
4059 Emacs buffers, and the HTML tags to be used for this.
4060 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4061 Use customize to modify this, or restart Emacs after changing it."
4062 :group 'org-appearance
4063 :set 'org-set-emph-re
4064 :type '(repeat
4065 (list
4066 (string :tag "Marker character")
4067 (choice
4068 (face :tag "Font-lock-face")
4069 (plist :tag "Face property list"))
4070 (string :tag "HTML start tag")
4071 (string :tag "HTML end tag")
4072 (option (const verbatim)))))
4074 (defvar org-protecting-blocks
4075 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4076 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4077 This is needed for font-lock setup.")
4079 ;;; Miscellaneous options
4081 (defgroup org-completion nil
4082 "Completion in Org-mode."
4083 :tag "Org Completion"
4084 :group 'org)
4086 (defcustom org-completion-use-ido nil
4087 "Non-nil means use ido completion wherever possible.
4088 Note that `ido-mode' must be active for this variable to be relevant.
4089 If you decide to turn this variable on, you might well want to turn off
4090 `org-outline-path-complete-in-steps'.
4091 See also `org-completion-use-iswitchb'."
4092 :group 'org-completion
4093 :type 'boolean)
4095 (defcustom org-completion-use-iswitchb nil
4096 "Non-nil means use iswitchb completion wherever possible.
4097 Note that `iswitchb-mode' must be active for this variable to be relevant.
4098 If you decide to turn this variable on, you might well want to turn off
4099 `org-outline-path-complete-in-steps'.
4100 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4101 :group 'org-completion
4102 :type 'boolean)
4104 (defcustom org-completion-fallback-command 'hippie-expand
4105 "The expansion command called by \\[pcomplete] in normal context.
4106 Normal means, no org-mode-specific context."
4107 :group 'org-completion
4108 :type 'function)
4110 ;;; Functions and variables from their packages
4111 ;; Declared here to avoid compiler warnings
4113 ;; XEmacs only
4114 (defvar outline-mode-menu-heading)
4115 (defvar outline-mode-menu-show)
4116 (defvar outline-mode-menu-hide)
4117 (defvar zmacs-regions) ; XEmacs regions
4119 ;; Emacs only
4120 (defvar mark-active)
4122 ;; Various packages
4123 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4124 (declare-function calendar-forward-day "cal-move" (arg))
4125 (declare-function calendar-goto-date "cal-move" (date))
4126 (declare-function calendar-goto-today "cal-move" ())
4127 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4128 (defvar calc-embedded-close-formula)
4129 (defvar calc-embedded-open-formula)
4130 (declare-function cdlatex-tab "ext:cdlatex" ())
4131 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4132 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4133 (defvar font-lock-unfontify-region-function)
4134 (declare-function iswitchb-read-buffer "iswitchb"
4135 (prompt &optional default require-match start matches-set))
4136 (defvar iswitchb-temp-buflist)
4137 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4138 (defvar org-agenda-tags-todo-honor-ignore-options)
4139 (declare-function org-agenda-skip "org-agenda" ())
4140 (declare-function
4141 org-agenda-format-item "org-agenda"
4142 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4143 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4144 (declare-function org-agenda-change-all-lines "org-agenda"
4145 (newhead hdmarker &optional fixface just-this))
4146 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4147 (declare-function org-agenda-maybe-redo "org-agenda" ())
4148 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4149 (beg end))
4150 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4151 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4152 "org-agenda" (&optional end))
4153 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4154 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4155 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4156 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4157 (declare-function org-indent-mode "org-indent" (&optional arg))
4158 (declare-function parse-time-string "parse-time" (string))
4159 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4160 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4161 (defvar remember-data-file)
4162 (defvar texmathp-why)
4163 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4164 (declare-function table--at-cell-p "table" (position &optional object at-column))
4166 (defvar org-latex-regexps)
4168 ;;; Autoload and prepare some org modules
4170 ;; Some table stuff that needs to be defined here, because it is used
4171 ;; by the functions setting up org-mode or checking for table context.
4173 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4174 "Detect an org-type or table-type table.")
4175 (defconst org-table-line-regexp "^[ \t]*|"
4176 "Detect an org-type table line.")
4177 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4178 "Detect an org-type table line.")
4179 (defconst org-table-hline-regexp "^[ \t]*|-"
4180 "Detect an org-type table hline.")
4181 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4182 "Detect a table-type table hline.")
4183 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4184 "Detect the first line outside a table when searching from within it.
4185 This works for both table types.")
4187 ;; Autoload the functions in org-table.el that are needed by functions here.
4189 (eval-and-compile
4190 (org-autoload "org-table"
4191 '(org-table-begin org-table-blank-field org-table-end)))
4193 ;;;###autoload
4194 (defun turn-on-orgtbl ()
4195 "Unconditionally turn on `orgtbl-mode'."
4196 (require 'org-table)
4197 (orgtbl-mode 1))
4199 (defun org-at-table-p (&optional table-type)
4200 "Return t if the cursor is inside an org-type table.
4201 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4202 (if org-enable-table-editor
4203 (save-excursion
4204 (beginning-of-line 1)
4205 (looking-at (if table-type org-table-any-line-regexp
4206 org-table-line-regexp)))
4207 nil))
4208 (defsubst org-table-p () (org-at-table-p))
4210 (defun org-at-table.el-p ()
4211 "Return t if and only if we are at a table.el table."
4212 (and (org-at-table-p 'any)
4213 (save-excursion
4214 (goto-char (org-table-begin 'any))
4215 (looking-at org-table1-hline-regexp))))
4217 (defun org-table-recognize-table.el ()
4218 "If there is a table.el table nearby, recognize it and move into it."
4219 (if org-table-tab-recognizes-table.el
4220 (if (org-at-table.el-p)
4221 (progn
4222 (beginning-of-line 1)
4223 (if (looking-at org-table-dataline-regexp)
4225 (if (looking-at org-table1-hline-regexp)
4226 (progn
4227 (beginning-of-line 2)
4228 (if (looking-at org-table-any-border-regexp)
4229 (beginning-of-line -1)))))
4230 (if (re-search-forward "|" (org-table-end t) t)
4231 (progn
4232 (require 'table)
4233 (if (table--at-cell-p (point))
4235 (message "recognizing table.el table...")
4236 (table-recognize-table)
4237 (message "recognizing table.el table...done")))
4238 (error "This should not happen"))
4240 nil)
4241 nil))
4243 (defun org-at-table-hline-p ()
4244 "Return t if the cursor is inside a hline in a table."
4245 (if org-enable-table-editor
4246 (save-excursion
4247 (beginning-of-line 1)
4248 (looking-at org-table-hline-regexp))
4249 nil))
4251 (defvar org-table-clean-did-remove-column nil)
4252 (defun org-table-map-tables (function &optional quietly)
4253 "Apply FUNCTION to the start of all tables in the buffer."
4254 (save-excursion
4255 (save-restriction
4256 (widen)
4257 (goto-char (point-min))
4258 (while (re-search-forward org-table-any-line-regexp nil t)
4259 (unless quietly
4260 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4261 (beginning-of-line 1)
4262 (when (and (looking-at org-table-line-regexp)
4263 ;; Exclude tables in src/example/verbatim/clocktable blocks
4264 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4265 (save-excursion (funcall function))
4266 (or (looking-at org-table-line-regexp)
4267 (forward-char 1)))
4268 (re-search-forward org-table-any-border-regexp nil 1))))
4269 (unless quietly (message "Mapping tables: done")))
4271 ;; Declare and autoload functions from ox.el and al.
4273 (declare-function org-export-get-environment "ox"
4274 (&optional backend subtreep ext-plist))
4275 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4277 ;; Declare and autoload functions from org-agenda.el
4279 (eval-and-compile
4280 (org-autoload "org-agenda"
4281 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4283 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4284 (declare-function org-clock-update-mode-line "org-clock" ())
4285 (declare-function org-resolve-clocks "org-clock"
4286 (&optional also-non-dangling-p prompt last-valid))
4287 (defvar org-clock-start-time)
4288 (defvar org-clock-marker (make-marker)
4289 "Marker recording the last clock-in.")
4290 (defvar org-clock-hd-marker (make-marker)
4291 "Marker recording the last clock-in, but the headline position.")
4292 (defvar org-clock-heading ""
4293 "The heading of the current clock entry.")
4294 (defun org-clock-is-active ()
4295 "Return non-nil if clock is currently running.
4296 The return value is actually the clock marker."
4297 (marker-buffer org-clock-marker))
4299 (eval-and-compile
4300 (org-autoload "org-clock" '(org-clock-remove-overlays
4301 org-clock-update-time-maybe
4302 org-clocktable-shift)))
4304 (defun org-check-running-clock ()
4305 "Check if the current buffer contains the running clock.
4306 If yes, offer to stop it and to save the buffer with the changes."
4307 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4308 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4309 (buffer-name))))
4310 (org-clock-out)
4311 (when (y-or-n-p "Save changed buffer?")
4312 (save-buffer))))
4314 (defun org-clocktable-try-shift (dir n)
4315 "Check if this line starts a clock table, if yes, shift the time block."
4316 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4317 (org-clocktable-shift dir n)))
4319 ;;;###autoload
4320 (defun org-clock-persistence-insinuate ()
4321 "Set up hooks for clock persistence."
4322 (require 'org-clock)
4323 (add-hook 'org-mode-hook 'org-clock-load)
4324 (add-hook 'kill-emacs-hook 'org-clock-save))
4326 ;; Define the variable already here, to make sure we have it.
4327 (defvar org-indent-mode nil
4328 "Non-nil if Org-Indent mode is enabled.
4329 Use the command `org-indent-mode' to change this variable.")
4331 ;; Autoload archiving code
4332 ;; The stuff that is needed for cycling and tags has to be defined here.
4334 (defgroup org-archive nil
4335 "Options concerning archiving in Org-mode."
4336 :tag "Org Archive"
4337 :group 'org-structure)
4339 (defcustom org-archive-location "%s_archive::"
4340 "The location where subtrees should be archived.
4342 The value of this variable is a string, consisting of two parts,
4343 separated by a double-colon. The first part is a filename and
4344 the second part is a headline.
4346 When the filename is omitted, archiving happens in the same file.
4347 %s in the filename will be replaced by the current file
4348 name (without the directory part). Archiving to a different file
4349 is useful to keep archived entries from contributing to the
4350 Org-mode Agenda.
4352 The archived entries will be filed as subtrees of the specified
4353 headline. When the headline is omitted, the subtrees are simply
4354 filed away at the end of the file, as top-level entries. Also in
4355 the heading you can use %s to represent the file name, this can be
4356 useful when using the same archive for a number of different files.
4358 Here are a few examples:
4359 \"%s_archive::\"
4360 If the current file is Projects.org, archive in file
4361 Projects.org_archive, as top-level trees. This is the default.
4363 \"::* Archived Tasks\"
4364 Archive in the current file, under the top-level headline
4365 \"* Archived Tasks\".
4367 \"~/org/archive.org::\"
4368 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4370 \"~/org/archive.org::* From %s\"
4371 Archive in file ~/org/archive.org (absolute path), under headlines
4372 \"From FILENAME\" where file name is the current file name.
4374 \"~/org/datetree.org::datetree/* Finished Tasks\"
4375 The \"datetree/\" string is special, signifying to archive
4376 items to the datetree. Items are placed in either the CLOSED
4377 date of the item, or the current date if there is no CLOSED date.
4378 The heading will be a subentry to the current date. There doesn't
4379 need to be a heading, but there always needs to be a slash after
4380 datetree. For example, to store archived items directly in the
4381 datetree, use \"~/org/datetree.org::datetree/\".
4383 \"basement::** Finished Tasks\"
4384 Archive in file ./basement (relative path), as level 3 trees
4385 below the level 2 heading \"** Finished Tasks\".
4387 You may set this option on a per-file basis by adding to the buffer a
4388 line like
4390 #+ARCHIVE: basement::** Finished Tasks
4392 You may also define it locally for a subtree by setting an ARCHIVE property
4393 in the entry. If such a property is found in an entry, or anywhere up
4394 the hierarchy, it will be used."
4395 :group 'org-archive
4396 :type 'string)
4398 (defcustom org-archive-tag "ARCHIVE"
4399 "The tag that marks a subtree as archived.
4400 An archived subtree does not open during visibility cycling, and does
4401 not contribute to the agenda listings.
4402 After changing this, font-lock must be restarted in the relevant buffers to
4403 get the proper fontification."
4404 :group 'org-archive
4405 :group 'org-keywords
4406 :type 'string)
4408 (defcustom org-agenda-skip-archived-trees t
4409 "Non-nil means the agenda will skip any items located in archived trees.
4410 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4411 variable is no longer recommended, you should leave it at the value t.
4412 Instead, use the key `v' to cycle the archives-mode in the agenda."
4413 :group 'org-archive
4414 :group 'org-agenda-skip
4415 :type 'boolean)
4417 (defcustom org-columns-skip-archived-trees t
4418 "Non-nil means ignore archived trees when creating column view."
4419 :group 'org-archive
4420 :group 'org-properties
4421 :type 'boolean)
4423 (defcustom org-cycle-open-archived-trees nil
4424 "Non-nil means `org-cycle' will open archived trees.
4425 An archived tree is a tree marked with the tag ARCHIVE.
4426 When nil, archived trees will stay folded. You can still open them with
4427 normal outline commands like `show-all', but not with the cycling commands."
4428 :group 'org-archive
4429 :group 'org-cycle
4430 :type 'boolean)
4432 (defcustom org-sparse-tree-open-archived-trees nil
4433 "Non-nil means sparse tree construction shows matches in archived trees.
4434 When nil, matches in these trees are highlighted, but the trees are kept in
4435 collapsed state."
4436 :group 'org-archive
4437 :group 'org-sparse-trees
4438 :type 'boolean)
4440 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4441 "The default date type when building a sparse tree.
4442 When this is nil, a date is a scheduled or a deadline timestamp.
4443 Otherwise, these types are allowed:
4445 all: all timestamps
4446 active: only active timestamps (<...>)
4447 inactive: only inactive timestamps (<...)
4448 scheduled: only scheduled timestamps
4449 deadline: only deadline timestamps"
4450 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4451 (const :tag "All timestamps" all)
4452 (const :tag "Only active timestamps" active)
4453 (const :tag "Only inactive timestamps" inactive)
4454 (const :tag "Only scheduled timestamps" scheduled)
4455 (const :tag "Only deadline timestamps" deadline))
4456 :version "24.3"
4457 :group 'org-sparse-trees)
4459 (defun org-cycle-hide-archived-subtrees (state)
4460 "Re-hide all archived subtrees after a visibility state change."
4461 (when (and (not org-cycle-open-archived-trees)
4462 (not (memq state '(overview folded))))
4463 (save-excursion
4464 (let* ((globalp (memq state '(contents all)))
4465 (beg (if globalp (point-min) (point)))
4466 (end (if globalp (point-max) (org-end-of-subtree t))))
4467 (org-hide-archived-subtrees beg end)
4468 (goto-char beg)
4469 (if (looking-at (concat ".*:" org-archive-tag ":"))
4470 (message "%s" (substitute-command-keys
4471 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4473 (defun org-force-cycle-archived ()
4474 "Cycle subtree even if it is archived."
4475 (interactive)
4476 (setq this-command 'org-cycle)
4477 (let ((org-cycle-open-archived-trees t))
4478 (call-interactively 'org-cycle)))
4480 (defun org-hide-archived-subtrees (beg end)
4481 "Re-hide all archived subtrees after a visibility state change."
4482 (save-excursion
4483 (let* ((re (concat ":" org-archive-tag ":")))
4484 (goto-char beg)
4485 (while (re-search-forward re end t)
4486 (when (org-at-heading-p)
4487 (org-flag-subtree t)
4488 (org-end-of-subtree t))))))
4490 (declare-function outline-end-of-heading "outline" ())
4491 (declare-function outline-flag-region "outline" (from to flag))
4492 (defun org-flag-subtree (flag)
4493 (save-excursion
4494 (org-back-to-heading t)
4495 (outline-end-of-heading)
4496 (outline-flag-region (point)
4497 (progn (org-end-of-subtree t) (point))
4498 flag)))
4500 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4502 (eval-and-compile
4503 (org-autoload "org-archive"
4504 '(org-add-archive-files)))
4506 ;; Autoload Column View Code
4508 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4509 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4510 (declare-function org-columns-compute "org-colview" (property))
4512 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4513 '(org-columns-number-to-string
4514 org-columns-get-format-and-top-level
4515 org-columns-compute
4516 org-columns-remove-overlays))
4518 ;; Autoload ID code
4520 (declare-function org-id-store-link "org-id")
4521 (declare-function org-id-locations-load "org-id")
4522 (declare-function org-id-locations-save "org-id")
4523 (defvar org-id-track-globally)
4524 (org-autoload "org-id"
4525 '(org-id-new
4526 org-id-copy
4527 org-id-get-with-outline-path-completion
4528 org-id-get-with-outline-drilling))
4530 ;;; Variables for pre-computed regular expressions, all buffer local
4532 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4533 "Matches first line of a hidden block.")
4534 (make-variable-buffer-local 'org-drawer-regexp)
4535 (defvar org-todo-regexp nil
4536 "Matches any of the TODO state keywords.")
4537 (make-variable-buffer-local 'org-todo-regexp)
4538 (defvar org-not-done-regexp nil
4539 "Matches any of the TODO state keywords except the last one.")
4540 (make-variable-buffer-local 'org-not-done-regexp)
4541 (defvar org-not-done-heading-regexp nil
4542 "Matches a TODO headline that is not done.")
4543 (make-variable-buffer-local 'org-not-done-regexp)
4544 (defvar org-todo-line-regexp nil
4545 "Matches a headline and puts TODO state into group 2 if present.")
4546 (make-variable-buffer-local 'org-todo-line-regexp)
4547 (defvar org-complex-heading-regexp nil
4548 "Matches a headline and puts everything into groups:
4549 group 1: the stars
4550 group 2: The todo keyword, maybe
4551 group 3: Priority cookie
4552 group 4: True headline
4553 group 5: Tags")
4554 (make-variable-buffer-local 'org-complex-heading-regexp)
4555 (defvar org-complex-heading-regexp-format nil
4556 "Printf format to make regexp to match an exact headline.
4557 This regexp will match the headline of any node which has the
4558 exact headline text that is put into the format, but may have any
4559 TODO state, priority and tags.")
4560 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4561 (defvar org-todo-line-tags-regexp nil
4562 "Matches a headline and puts TODO state into group 2 if present.
4563 Also put tags into group 4 if tags are present.")
4564 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4565 (defvar org-ds-keyword-length 12
4566 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4567 (make-variable-buffer-local 'org-ds-keyword-length)
4568 (defvar org-deadline-regexp nil
4569 "Matches the DEADLINE keyword.")
4570 (make-variable-buffer-local 'org-deadline-regexp)
4571 (defvar org-deadline-time-regexp nil
4572 "Matches the DEADLINE keyword together with a time stamp.")
4573 (make-variable-buffer-local 'org-deadline-time-regexp)
4574 (defvar org-deadline-line-regexp nil
4575 "Matches the DEADLINE keyword and the rest of the line.")
4576 (make-variable-buffer-local 'org-deadline-line-regexp)
4577 (defvar org-scheduled-regexp nil
4578 "Matches the SCHEDULED keyword.")
4579 (make-variable-buffer-local 'org-scheduled-regexp)
4580 (defvar org-scheduled-time-regexp nil
4581 "Matches the SCHEDULED keyword together with a time stamp.")
4582 (make-variable-buffer-local 'org-scheduled-time-regexp)
4583 (defvar org-closed-time-regexp nil
4584 "Matches the CLOSED keyword together with a time stamp.")
4585 (make-variable-buffer-local 'org-closed-time-regexp)
4587 (defvar org-keyword-time-regexp nil
4588 "Matches any of the 4 keywords, together with the time stamp.")
4589 (make-variable-buffer-local 'org-keyword-time-regexp)
4590 (defvar org-keyword-time-not-clock-regexp nil
4591 "Matches any of the 3 keywords, together with the time stamp.")
4592 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4593 (defvar org-maybe-keyword-time-regexp nil
4594 "Matches a timestamp, possibly preceded by a keyword.")
4595 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4596 (defvar org-all-time-keywords nil
4597 "List of time keywords.")
4598 (make-variable-buffer-local 'org-all-time-keywords)
4600 (defconst org-plain-time-of-day-regexp
4601 (concat
4602 "\\(\\<[012]?[0-9]"
4603 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4604 "\\(--?"
4605 "\\(\\<[012]?[0-9]"
4606 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4607 "\\)?")
4608 "Regular expression to match a plain time or time range.
4609 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4610 groups carry important information:
4611 0 the full match
4612 1 the first time, range or not
4613 8 the second time, if it is a range.")
4615 (defconst org-plain-time-extension-regexp
4616 (concat
4617 "\\(\\<[012]?[0-9]"
4618 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4619 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4620 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4621 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4622 groups carry important information:
4623 0 the full match
4624 7 hours of duration
4625 9 minutes of duration")
4627 (defconst org-stamp-time-of-day-regexp
4628 (concat
4629 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4630 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4631 "\\(--?"
4632 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4633 "Regular expression to match a timestamp time or time range.
4634 After a match, the following groups carry important information:
4635 0 the full match
4636 1 date plus weekday, for back referencing to make sure both times are on the same day
4637 2 the first time, range or not
4638 4 the second time, if it is a range.")
4640 (defconst org-startup-options
4641 '(("fold" org-startup-folded t)
4642 ("overview" org-startup-folded t)
4643 ("nofold" org-startup-folded nil)
4644 ("showall" org-startup-folded nil)
4645 ("showeverything" org-startup-folded showeverything)
4646 ("content" org-startup-folded content)
4647 ("indent" org-startup-indented t)
4648 ("noindent" org-startup-indented nil)
4649 ("hidestars" org-hide-leading-stars t)
4650 ("showstars" org-hide-leading-stars nil)
4651 ("odd" org-odd-levels-only t)
4652 ("oddeven" org-odd-levels-only nil)
4653 ("align" org-startup-align-all-tables t)
4654 ("noalign" org-startup-align-all-tables nil)
4655 ("inlineimages" org-startup-with-inline-images t)
4656 ("noinlineimages" org-startup-with-inline-images nil)
4657 ("latexpreview" org-startup-with-latex-preview t)
4658 ("nolatexpreview" org-startup-with-latex-preview nil)
4659 ("customtime" org-display-custom-times t)
4660 ("logdone" org-log-done time)
4661 ("lognotedone" org-log-done note)
4662 ("nologdone" org-log-done nil)
4663 ("lognoteclock-out" org-log-note-clock-out t)
4664 ("nolognoteclock-out" org-log-note-clock-out nil)
4665 ("logrepeat" org-log-repeat state)
4666 ("lognoterepeat" org-log-repeat note)
4667 ("logdrawer" org-log-into-drawer t)
4668 ("nologdrawer" org-log-into-drawer nil)
4669 ("logstatesreversed" org-log-states-order-reversed t)
4670 ("nologstatesreversed" org-log-states-order-reversed nil)
4671 ("nologrepeat" org-log-repeat nil)
4672 ("logreschedule" org-log-reschedule time)
4673 ("lognotereschedule" org-log-reschedule note)
4674 ("nologreschedule" org-log-reschedule nil)
4675 ("logredeadline" org-log-redeadline time)
4676 ("lognoteredeadline" org-log-redeadline note)
4677 ("nologredeadline" org-log-redeadline nil)
4678 ("logrefile" org-log-refile time)
4679 ("lognoterefile" org-log-refile note)
4680 ("nologrefile" org-log-refile nil)
4681 ("fninline" org-footnote-define-inline t)
4682 ("nofninline" org-footnote-define-inline nil)
4683 ("fnlocal" org-footnote-section nil)
4684 ("fnauto" org-footnote-auto-label t)
4685 ("fnprompt" org-footnote-auto-label nil)
4686 ("fnconfirm" org-footnote-auto-label confirm)
4687 ("fnplain" org-footnote-auto-label plain)
4688 ("fnadjust" org-footnote-auto-adjust t)
4689 ("nofnadjust" org-footnote-auto-adjust nil)
4690 ("constcgs" constants-unit-system cgs)
4691 ("constSI" constants-unit-system SI)
4692 ("noptag" org-tag-persistent-alist nil)
4693 ("hideblocks" org-hide-block-startup t)
4694 ("nohideblocks" org-hide-block-startup nil)
4695 ("beamer" org-startup-with-beamer-mode t)
4696 ("entitiespretty" org-pretty-entities t)
4697 ("entitiesplain" org-pretty-entities nil))
4698 "Variable associated with STARTUP options for org-mode.
4699 Each element is a list of three items: the startup options (as written
4700 in the #+STARTUP line), the corresponding variable, and the value to set
4701 this variable to if the option is found. An optional forth element PUSH
4702 means to push this value onto the list in the variable.")
4704 (defun org-update-property-plist (key val props)
4705 "Update PROPS with KEY and VAL."
4706 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4707 (key (if appending (substring key 0 (- (length key) 1)) key))
4708 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4709 (previous (cdr (assoc key props))))
4710 (if appending
4711 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4712 (cons (cons key val) remainder))))
4714 (defconst org-block-regexp
4715 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4716 "Regular expression for hiding blocks.")
4717 (defconst org-heading-keyword-regexp-format
4718 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4719 "Printf format for a regexp matching a headline with some keyword.
4720 This regexp will match the headline of any node which has the
4721 exact keyword that is put into the format. The keyword isn't in
4722 any group by default, but the stars and the body are.")
4723 (defconst org-heading-keyword-maybe-regexp-format
4724 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4725 "Printf format for a regexp matching a headline, possibly with some keyword.
4726 This regexp can match any headline with the specified keyword, or
4727 without a keyword. The keyword isn't in any group by default,
4728 but the stars and the body are.")
4730 (defun org-set-regexps-and-options ()
4731 "Precompute regular expressions for current buffer."
4732 (when (derived-mode-p 'org-mode)
4733 (org-set-local 'org-todo-kwd-alist nil)
4734 (org-set-local 'org-todo-key-alist nil)
4735 (org-set-local 'org-todo-key-trigger nil)
4736 (org-set-local 'org-todo-keywords-1 nil)
4737 (org-set-local 'org-done-keywords nil)
4738 (org-set-local 'org-todo-heads nil)
4739 (org-set-local 'org-todo-sets nil)
4740 (org-set-local 'org-todo-log-states nil)
4741 (org-set-local 'org-file-properties nil)
4742 (org-set-local 'org-file-tags nil)
4743 (let ((re (org-make-options-regexp
4744 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE" "FILETAGS"
4745 "TAGS" "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4746 "SETUPFILE" "OPTIONS")
4747 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4748 (splitre "[ \t]+")
4749 (scripts org-use-sub-superscripts)
4750 kwds kws0 kwsa key log value cat arch tags const links hw dws
4751 tail sep kws1 prio props ftags drawers ext-setup-or-nil setup-contents
4752 (start 0))
4753 (save-excursion
4754 (save-restriction
4755 (widen)
4756 (goto-char (point-min))
4757 (while (or (and ext-setup-or-nil
4758 (string-match re ext-setup-or-nil start)
4759 (setq start (match-end 0)))
4760 (and (setq ext-setup-or-nil nil start 0)
4761 (re-search-forward re nil t)))
4762 (setq key (upcase (match-string 1 ext-setup-or-nil))
4763 value (org-match-string-no-properties 2 ext-setup-or-nil))
4764 (if (stringp value) (setq value (org-trim value)))
4765 (cond
4766 ((equal key "CATEGORY")
4767 (setq cat value))
4768 ((member key '("SEQ_TODO" "TODO"))
4769 (push (cons 'sequence (org-split-string value splitre)) kwds))
4770 ((equal key "TYP_TODO")
4771 (push (cons 'type (org-split-string value splitre)) kwds))
4772 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4773 ;; general TODO-like setup
4774 (push (cons (intern (downcase (match-string 1 key)))
4775 (org-split-string value splitre)) kwds))
4776 ((equal key "TAGS")
4777 (setq tags (append tags (if tags '("\\n") nil)
4778 (org-split-string value splitre))))
4779 ((equal key "COLUMNS")
4780 (org-set-local 'org-columns-default-format value))
4781 ((equal key "LINK")
4782 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4783 (push (cons (match-string 1 value)
4784 (org-trim (match-string 2 value)))
4785 links)))
4786 ((equal key "PRIORITIES")
4787 (setq prio (org-split-string value " +")))
4788 ((equal key "PROPERTY")
4789 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4790 (setq props (org-update-property-plist (match-string 1 value)
4791 (match-string 2 value)
4792 props))))
4793 ((equal key "FILETAGS")
4794 (when (string-match "\\S-" value)
4795 (setq ftags
4796 (append
4797 ftags
4798 (apply 'append
4799 (mapcar (lambda (x) (org-split-string x ":"))
4800 (org-split-string value)))))))
4801 ((equal key "DRAWERS")
4802 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4803 ((equal key "CONSTANTS")
4804 (setq const (append const (org-split-string value splitre))))
4805 ((equal key "STARTUP")
4806 (let ((opts (org-split-string value splitre))
4807 l var val)
4808 (while (setq l (pop opts))
4809 (when (setq l (assoc l org-startup-options))
4810 (setq var (nth 1 l) val (nth 2 l))
4811 (if (not (nth 3 l))
4812 (set (make-local-variable var) val)
4813 (if (not (listp (symbol-value var)))
4814 (set (make-local-variable var) nil))
4815 (set (make-local-variable var) (symbol-value var))
4816 (add-to-list var val))))))
4817 ((equal key "ARCHIVE")
4818 (setq arch value)
4819 (remove-text-properties 0 (length arch)
4820 '(face t fontified t) arch))
4821 ((equal key "OPTIONS")
4822 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4823 (setq scripts (read (match-string 2 value)))))
4824 ((equal key "SETUPFILE")
4825 (setq setup-contents (org-file-contents
4826 (expand-file-name
4827 (org-remove-double-quotes value))
4828 'noerror))
4829 (if (not ext-setup-or-nil)
4830 (setq ext-setup-or-nil setup-contents start 0)
4831 (setq ext-setup-or-nil
4832 (concat (substring ext-setup-or-nil 0 start)
4833 "\n" setup-contents "\n"
4834 (substring ext-setup-or-nil start)))))))
4835 ;; search for property blocks
4836 (goto-char (point-min))
4837 (while (re-search-forward org-block-regexp nil t)
4838 (when (equal "PROPERTY" (upcase (match-string 1)))
4839 (setq value (replace-regexp-in-string
4840 "[\n\r]" " " (match-string 4)))
4841 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4842 (setq props (org-update-property-plist (match-string 1 value)
4843 (match-string 2 value)
4844 props)))))))
4845 (org-set-local 'org-use-sub-superscripts scripts)
4846 (when cat
4847 (org-set-local 'org-category (intern cat))
4848 (push (cons "CATEGORY" cat) props))
4849 (when prio
4850 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4851 (setq prio (mapcar 'string-to-char prio))
4852 (org-set-local 'org-highest-priority (nth 0 prio))
4853 (org-set-local 'org-lowest-priority (nth 1 prio))
4854 (org-set-local 'org-default-priority (nth 2 prio)))
4855 (and props (org-set-local 'org-file-properties (nreverse props)))
4856 (and ftags (org-set-local 'org-file-tags
4857 (mapcar 'org-add-prop-inherited ftags)))
4858 (and drawers (org-set-local 'org-drawers drawers))
4859 (and arch (org-set-local 'org-archive-location arch))
4860 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4861 ;; Process the TODO keywords
4862 (unless kwds
4863 ;; Use the global values as if they had been given locally.
4864 (setq kwds (default-value 'org-todo-keywords))
4865 (if (stringp (car kwds))
4866 (setq kwds (list (cons org-todo-interpretation
4867 (default-value 'org-todo-keywords)))))
4868 (setq kwds (reverse kwds)))
4869 (setq kwds (nreverse kwds))
4870 (let (inter kws kw)
4871 (while (setq kws (pop kwds))
4872 (let ((kws (or
4873 (run-hook-with-args-until-success
4874 'org-todo-setup-filter-hook kws)
4875 kws)))
4876 (setq inter (pop kws) sep (member "|" kws)
4877 kws0 (delete "|" (copy-sequence kws))
4878 kwsa nil
4879 kws1 (mapcar
4880 (lambda (x)
4881 ;; 1 2
4882 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4883 (progn
4884 (setq kw (match-string 1 x)
4885 key (and (match-end 2) (match-string 2 x))
4886 log (org-extract-log-state-settings x))
4887 (push (cons kw (and key (string-to-char key))) kwsa)
4888 (and log (push log org-todo-log-states))
4890 (error "Invalid TODO keyword %s" x)))
4891 kws0)
4892 kwsa (if kwsa (append '((:startgroup))
4893 (nreverse kwsa)
4894 '((:endgroup))))
4895 hw (car kws1)
4896 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4897 tail (list inter hw (car dws) (org-last dws))))
4898 (add-to-list 'org-todo-heads hw 'append)
4899 (push kws1 org-todo-sets)
4900 (setq org-done-keywords (append org-done-keywords dws nil))
4901 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4902 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4903 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4904 (setq org-todo-sets (nreverse org-todo-sets)
4905 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4906 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4907 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4908 ;; Process the constants
4909 (when const
4910 (let (e cst)
4911 (while (setq e (pop const))
4912 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4913 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4914 (setq org-table-formula-constants-local cst)))
4916 ;; Process the tags.
4917 (when tags
4918 (let (e tgs)
4919 (while (setq e (pop tags))
4920 (cond
4921 ((equal e "{") (push '(:startgroup) tgs))
4922 ((equal e "}") (push '(:endgroup) tgs))
4923 ((equal e "\\n") (push '(:newline) tgs))
4924 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4925 (push (cons (match-string 1 e)
4926 (string-to-char (match-string 2 e)))
4927 tgs))
4928 (t (push (list e) tgs))))
4929 (org-set-local 'org-tag-alist nil)
4930 (while (setq e (pop tgs))
4931 (or (and (stringp (car e))
4932 (assoc (car e) org-tag-alist))
4933 (push e org-tag-alist)))))
4935 ;; Compute the regular expressions and other local variables.
4936 ;; Using `org-outline-regexp-bol' would complicate them much,
4937 ;; because of the fixed white space at the end of that string.
4938 (if (not org-done-keywords)
4939 (setq org-done-keywords (and org-todo-keywords-1
4940 (list (org-last org-todo-keywords-1)))))
4941 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4942 (length org-scheduled-string)
4943 (length org-clock-string)
4944 (length org-closed-string)))
4945 org-drawer-regexp
4946 (concat "^[ \t]*:\\("
4947 (mapconcat 'regexp-quote org-drawers "\\|")
4948 "\\):[ \t]*$")
4949 org-not-done-keywords
4950 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4951 org-todo-regexp
4952 (concat "\\("
4953 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4954 "\\)")
4955 org-not-done-regexp
4956 (concat "\\("
4957 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4958 "\\)")
4959 org-not-done-heading-regexp
4960 (format org-heading-keyword-regexp-format org-not-done-regexp)
4961 org-todo-line-regexp
4962 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4963 org-complex-heading-regexp
4964 (concat "^\\(\\*+\\)"
4965 "\\(?: +" org-todo-regexp "\\)?"
4966 "\\(?: +\\(\\[#.\\]\\)\\)?"
4967 "\\(?: +\\(.*?\\)\\)??"
4968 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4969 "[ \t]*$")
4970 org-complex-heading-regexp-format
4971 (concat "^\\(\\*+\\)"
4972 "\\(?: +" org-todo-regexp "\\)?"
4973 "\\(?: +\\(\\[#.\\]\\)\\)?"
4974 "\\(?: +"
4975 ;; Stats cookies can be stuck to body.
4976 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4977 "\\(%s\\)"
4978 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4979 "\\)"
4980 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4981 "[ \t]*$")
4982 org-todo-line-tags-regexp
4983 (concat "^\\(\\*+\\)"
4984 "\\(?: +" org-todo-regexp "\\)?"
4985 "\\(?: +\\(.*?\\)\\)??"
4986 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4987 "[ \t]*$")
4988 org-deadline-regexp (concat "\\<" org-deadline-string)
4989 org-deadline-time-regexp
4990 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4991 org-deadline-line-regexp
4992 (concat "\\<\\(" org-deadline-string "\\).*")
4993 org-scheduled-regexp
4994 (concat "\\<" org-scheduled-string)
4995 org-scheduled-time-regexp
4996 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4997 org-closed-time-regexp
4998 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4999 org-keyword-time-regexp
5000 (concat "\\<\\(" org-scheduled-string
5001 "\\|" org-deadline-string
5002 "\\|" org-closed-string
5003 "\\|" org-clock-string "\\)"
5004 " *[[<]\\([^]>]+\\)[]>]")
5005 org-keyword-time-not-clock-regexp
5006 (concat "\\<\\(" org-scheduled-string
5007 "\\|" org-deadline-string
5008 "\\|" org-closed-string
5009 "\\)"
5010 " *[[<]\\([^]>]+\\)[]>]")
5011 org-maybe-keyword-time-regexp
5012 (concat "\\(\\<\\(" org-scheduled-string
5013 "\\|" org-deadline-string
5014 "\\|" org-closed-string
5015 "\\|" org-clock-string "\\)\\)?"
5016 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5017 org-all-time-keywords
5018 (mapcar (lambda (w) (substring w 0 -1))
5019 (list org-scheduled-string org-deadline-string
5020 org-clock-string org-closed-string)))
5021 (org-compute-latex-and-related-regexp)
5022 (org-set-font-lock-defaults))))
5024 (defun org-file-contents (file &optional noerror)
5025 "Return the contents of FILE, as a string."
5026 (if (or (not file)
5027 (not (file-readable-p file)))
5028 (if noerror
5029 (progn
5030 (message "Cannot read file \"%s\"" file)
5031 (ding) (sit-for 2)
5033 (error "Cannot read file \"%s\"" file))
5034 (with-temp-buffer
5035 (insert-file-contents file)
5036 (buffer-string))))
5038 (defun org-extract-log-state-settings (x)
5039 "Extract the log state setting from a TODO keyword string.
5040 This will extract info from a string like \"WAIT(w@/!)\"."
5041 (let (kw key log1 log2)
5042 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5043 (setq kw (match-string 1 x)
5044 key (and (match-end 2) (match-string 2 x))
5045 log1 (and (match-end 3) (match-string 3 x))
5046 log2 (and (match-end 4) (match-string 4 x)))
5047 (and (or log1 log2)
5048 (list kw
5049 (and log1 (if (equal log1 "!") 'time 'note))
5050 (and log2 (if (equal log2 "!") 'time 'note)))))))
5052 (defun org-remove-keyword-keys (list)
5053 "Remove a pair of parenthesis at the end of each string in LIST."
5054 (mapcar (lambda (x)
5055 (if (string-match "(.*)$" x)
5056 (substring x 0 (match-beginning 0))
5058 list))
5060 (defun org-assign-fast-keys (alist)
5061 "Assign fast keys to a keyword-key alist.
5062 Respect keys that are already there."
5063 (let (new e (alt ?0))
5064 (while (setq e (pop alist))
5065 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5066 (cdr e)) ;; Key already assigned.
5067 (push e new)
5068 (let ((clist (string-to-list (downcase (car e))))
5069 (used (append new alist)))
5070 (when (= (car clist) ?@)
5071 (pop clist))
5072 (while (and clist (rassoc (car clist) used))
5073 (pop clist))
5074 (unless clist
5075 (while (rassoc alt used)
5076 (incf alt)))
5077 (push (cons (car e) (or (car clist) alt)) new))))
5078 (nreverse new)))
5080 ;;; Some variables used in various places
5082 (defvar org-window-configuration nil
5083 "Used in various places to store a window configuration.")
5084 (defvar org-selected-window nil
5085 "Used in various places to store a window configuration.")
5086 (defvar org-finish-function nil
5087 "Function to be called when `C-c C-c' is used.
5088 This is for getting out of special buffers like capture.")
5091 ;; FIXME: Occasionally check by commenting these, to make sure
5092 ;; no other functions uses these, forgetting to let-bind them.
5093 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5094 (defvar org-last-state)
5095 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5097 ;; Defined somewhere in this file, but used before definition.
5098 (defvar org-entities) ;; defined in org-entities.el
5099 (defvar org-struct-menu)
5100 (defvar org-org-menu)
5101 (defvar org-tbl-menu)
5103 ;;;; Define the Org-mode
5105 ;; We use a before-change function to check if a table might need
5106 ;; an update.
5107 (defvar org-table-may-need-update t
5108 "Indicates that a table might need an update.
5109 This variable is set by `org-before-change-function'.
5110 `org-table-align' sets it back to nil.")
5111 (defun org-before-change-function (beg end)
5112 "Every change indicates that a table might need an update."
5113 (setq org-table-may-need-update t))
5114 (defvar org-mode-map)
5115 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5116 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5117 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5118 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5119 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5120 (defvar org-table-buffer-is-an nil)
5122 (defvar bidi-paragraph-direction)
5123 (defvar buffer-face-mode-face)
5125 (require 'outline)
5126 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5127 (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"))
5128 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5130 ;; Other stuff we need.
5131 (require 'time-date)
5132 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5133 (require 'easymenu)
5134 (require 'overlay)
5136 ;; (require 'org-macs) moved higher up in the file before it is first used
5137 (require 'org-entities)
5138 ;; (require 'org-compat) moved higher up in the file before it is first used
5139 (require 'org-faces)
5140 (require 'org-list)
5141 (require 'org-pcomplete)
5142 (require 'org-src)
5143 (require 'org-footnote)
5144 (require 'org-macro)
5146 ;; babel
5147 (require 'ob)
5149 ;;;###autoload
5150 (define-derived-mode org-mode outline-mode "Org"
5151 "Outline-based notes management and organizer, alias
5152 \"Carsten's outline-mode for keeping track of everything.\"
5154 Org-mode develops organizational tasks around a NOTES file which
5155 contains information about projects as plain text. Org-mode is
5156 implemented on top of outline-mode, which is ideal to keep the content
5157 of large files well structured. It supports ToDo items, deadlines and
5158 time stamps, which magically appear in the diary listing of the Emacs
5159 calendar. Tables are easily created with a built-in table editor.
5160 Plain text URL-like links connect to websites, emails (VM), Usenet
5161 messages (Gnus), BBDB entries, and any files related to the project.
5162 For printing and sharing of notes, an Org-mode file (or a part of it)
5163 can be exported as a structured ASCII or HTML file.
5165 The following commands are available:
5167 \\{org-mode-map}"
5169 ;; Get rid of Outline menus, they are not needed
5170 ;; Need to do this here because define-derived-mode sets up
5171 ;; the keymap so late. Still, it is a waste to call this each time
5172 ;; we switch another buffer into org-mode.
5173 (if (featurep 'xemacs)
5174 (when (boundp 'outline-mode-menu-heading)
5175 ;; Assume this is Greg's port, it uses easymenu
5176 (easy-menu-remove outline-mode-menu-heading)
5177 (easy-menu-remove outline-mode-menu-show)
5178 (easy-menu-remove outline-mode-menu-hide))
5179 (define-key org-mode-map [menu-bar headings] 'undefined)
5180 (define-key org-mode-map [menu-bar hide] 'undefined)
5181 (define-key org-mode-map [menu-bar show] 'undefined))
5183 (org-load-modules-maybe)
5184 (easy-menu-add org-org-menu)
5185 (easy-menu-add org-tbl-menu)
5186 (org-install-agenda-files-menu)
5187 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5188 (add-to-invisibility-spec '(org-cwidth))
5189 (add-to-invisibility-spec '(org-hide-block . t))
5190 (when (featurep 'xemacs)
5191 (org-set-local 'line-move-ignore-invisible t))
5192 (org-set-local 'outline-regexp org-outline-regexp)
5193 (org-set-local 'outline-level 'org-outline-level)
5194 (setq bidi-paragraph-direction 'left-to-right)
5195 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5196 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5197 (when (and org-ellipsis
5198 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5199 (fboundp 'make-glyph-code))
5200 (unless org-display-table
5201 (setq org-display-table (make-display-table)))
5202 (set-display-table-slot
5203 org-display-table 4
5204 (vconcat (mapcar
5205 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5206 org-ellipsis)))
5207 (if (stringp org-ellipsis) org-ellipsis "..."))))
5208 (setq buffer-display-table org-display-table))
5209 (org-set-regexps-and-options)
5210 (when (and org-tag-faces (not org-tags-special-faces-re))
5211 ;; tag faces set outside customize.... force initialization.
5212 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5213 ;; Calc embedded
5214 (org-set-local 'calc-embedded-open-mode "# ")
5215 ;; Modify a few syntax entries
5216 (modify-syntax-entry ?@ "w")
5217 (modify-syntax-entry ?\" "\"")
5218 (if org-startup-truncated (setq truncate-lines t))
5219 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5220 (org-set-local 'font-lock-unfontify-region-function
5221 'org-unfontify-region)
5222 ;; Activate before-change-function
5223 (org-set-local 'org-table-may-need-update t)
5224 (org-add-hook 'before-change-functions 'org-before-change-function nil
5225 'local)
5226 ;; Check for running clock before killing a buffer
5227 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5228 ;; Initialize macros templates.
5229 (org-macro-initialize-templates)
5230 ;; Initialize radio targets.
5231 (org-update-radio-target-regexp)
5232 ;; Indentation.
5233 (org-set-local 'indent-line-function 'org-indent-line)
5234 (org-set-local 'indent-region-function 'org-indent-region)
5235 ;; Filling and auto-filling.
5236 (org-setup-filling)
5237 ;; Comments.
5238 (org-setup-comments-handling)
5239 ;; Beginning/end of defun
5240 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5241 (org-set-local 'end-of-defun-function 'org-forward-element)
5242 ;; Next error for sparse trees
5243 (org-set-local 'next-error-function 'org-occur-next-match)
5244 ;; Make sure dependence stuff works reliably, even for users who set it
5245 ;; too late :-(
5246 (if org-enforce-todo-dependencies
5247 (add-hook 'org-blocker-hook
5248 'org-block-todo-from-children-or-siblings-or-parent)
5249 (remove-hook 'org-blocker-hook
5250 'org-block-todo-from-children-or-siblings-or-parent))
5251 (if org-enforce-todo-checkbox-dependencies
5252 (add-hook 'org-blocker-hook
5253 'org-block-todo-from-checkboxes)
5254 (remove-hook 'org-blocker-hook
5255 'org-block-todo-from-checkboxes))
5257 ;; Align options lines
5258 (org-set-local
5259 'align-mode-rules-list
5260 '((org-in-buffer-settings
5261 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5262 (modes . '(org-mode)))))
5264 ;; Imenu
5265 (org-set-local 'imenu-create-index-function
5266 'org-imenu-get-tree)
5268 ;; Make isearch reveal context
5269 (if (or (featurep 'xemacs)
5270 (not (boundp 'outline-isearch-open-invisible-function)))
5271 ;; Emacs 21 and XEmacs make use of the hook
5272 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5273 ;; Emacs 22 deals with this through a special variable
5274 (org-set-local 'outline-isearch-open-invisible-function
5275 (lambda (&rest ignore) (org-show-context 'isearch)))
5276 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5278 ;; Setup the pcomplete hooks
5279 (set (make-local-variable 'pcomplete-command-completion-function)
5280 'org-pcomplete-initial)
5281 (set (make-local-variable 'pcomplete-command-name-function)
5282 'org-command-at-point)
5283 (set (make-local-variable 'pcomplete-default-completion-function)
5284 'ignore)
5285 (set (make-local-variable 'pcomplete-parse-arguments-function)
5286 'org-parse-arguments)
5287 (set (make-local-variable 'pcomplete-termination-string) "")
5288 (when (>= emacs-major-version 23)
5289 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5291 ;; If empty file that did not turn on org-mode automatically, make it to.
5292 (if (and org-insert-mode-line-in-empty-file
5293 (org-called-interactively-p 'any)
5294 (= (point-min) (point-max)))
5295 (insert "# -*- mode: org -*-\n\n"))
5296 (unless org-inhibit-startup
5297 (org-unmodified
5298 (and org-startup-with-beamer-mode (org-beamer-mode))
5299 (when org-startup-align-all-tables
5300 (org-table-map-tables 'org-table-align 'quietly))
5301 (when org-startup-with-inline-images
5302 (org-display-inline-images))
5303 (when org-startup-with-latex-preview
5304 (org-preview-latex-fragment))
5305 (unless org-inhibit-startup-visibility-stuff
5306 (org-set-startup-visibility))))
5307 ;; Try to set org-hide correctly
5308 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5310 ;; Update `customize-package-emacs-version-alist'
5311 (add-to-list 'customize-package-emacs-version-alist
5312 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5313 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5314 ("8.0" . "24.4")))
5316 (defvar org-mode-transpose-word-syntax-table
5317 (let ((st (make-syntax-table)))
5318 (mapc (lambda(c) (modify-syntax-entry
5319 (string-to-char (car c)) "w p" st))
5320 org-emphasis-alist)
5321 st))
5323 (when (fboundp 'abbrev-table-put)
5324 (abbrev-table-put org-mode-abbrev-table
5325 :parents (list text-mode-abbrev-table)))
5327 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5329 (defsubst org-fix-ellipsis-at-bol ()
5330 (save-excursion (goto-char (window-start)) (recenter 0)))
5332 (defun org-find-invisible-foreground ()
5333 (let ((candidates (remove
5334 "unspecified-bg"
5335 (nconc
5336 (list (face-background 'default)
5337 (face-background 'org-default))
5338 (mapcar
5339 (lambda (alist)
5340 (when (boundp alist)
5341 (cdr (assoc 'background-color (symbol-value alist)))))
5342 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5343 (list (face-foreground 'org-hide))))))
5344 (car (remove nil candidates))))
5346 (defun org-current-time (&optional rounding-minutes past)
5347 "Current time, possibly rounded to ROUNDING-MINUTES.
5348 When ROUNDING-MINUTES is not an integer, fall back on the car of
5349 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5350 the rounding returns a past time."
5351 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5352 (car org-time-stamp-rounding-minutes)))
5353 (time (decode-time)) res)
5354 (if (< r 1)
5355 (current-time)
5356 (setq res
5357 (apply 'encode-time
5358 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5359 (nthcdr 2 time))))
5360 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5361 (seconds-to-time (- (org-float-time res) (* r 60)))
5362 res))))
5364 (defun org-today ()
5365 "Return today date, considering `org-extend-today-until'."
5366 (time-to-days
5367 (time-subtract (current-time)
5368 (list 0 (* 3600 org-extend-today-until) 0))))
5370 ;;;; Font-Lock stuff, including the activators
5372 (defvar org-mouse-map (make-sparse-keymap))
5373 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5374 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5375 (when org-mouse-1-follows-link
5376 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5377 (when org-tab-follows-link
5378 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5379 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5381 (require 'font-lock)
5383 (defconst org-non-link-chars "]\t\n\r<>")
5384 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5385 "shell" "elisp" "doi" "message"))
5386 (defvar org-link-types-re nil
5387 "Matches a link that has a url-like prefix like \"http:\"")
5388 (defvar org-link-re-with-space nil
5389 "Matches a link with spaces, optional angular brackets around it.")
5390 (defvar org-link-re-with-space2 nil
5391 "Matches a link with spaces, optional angular brackets around it.")
5392 (defvar org-link-re-with-space3 nil
5393 "Matches a link with spaces, only for internal part in bracket links.")
5394 (defvar org-angle-link-re nil
5395 "Matches link with angular brackets, spaces are allowed.")
5396 (defvar org-plain-link-re nil
5397 "Matches plain link, without spaces.")
5398 (defvar org-bracket-link-regexp nil
5399 "Matches a link in double brackets.")
5400 (defvar org-bracket-link-analytic-regexp nil
5401 "Regular expression used to analyze links.
5402 Here is what the match groups contain after a match:
5403 1: http:
5404 2: http
5405 3: path
5406 4: [desc]
5407 5: desc")
5408 (defvar org-bracket-link-analytic-regexp++ nil
5409 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5410 (defvar org-any-link-re nil
5411 "Regular expression matching any link.")
5413 (defconst org-match-sexp-depth 3
5414 "Number of stacked braces for sub/superscript matching.")
5416 (defun org-create-multibrace-regexp (left right n)
5417 "Create a regular expression which will match a balanced sexp.
5418 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5419 as single character strings.
5420 The regexp returned will match the entire expression including the
5421 delimiters. It will also define a single group which contains the
5422 match except for the outermost delimiters. The maximum depth of
5423 stacked delimiters is N. Escaping delimiters is not possible."
5424 (let* ((nothing (concat "[^" left right "]*?"))
5425 (or "\\|")
5426 (re nothing)
5427 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5428 (while (> n 1)
5429 (setq n (1- n)
5430 re (concat re or next)
5431 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5432 (concat left "\\(" re "\\)" right)))
5434 (defvar org-match-substring-regexp
5435 (concat
5436 "\\(\\S-\\)\\([_^]\\)\\("
5437 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5438 "\\|"
5439 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5440 "\\|"
5441 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5442 "The regular expression matching a sub- or superscript.")
5444 (defvar org-match-substring-with-braces-regexp
5445 (concat
5446 "\\(\\S-\\)\\([_^]\\)\\("
5447 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5448 "\\)")
5449 "The regular expression matching a sub- or superscript, forcing braces.")
5451 (defun org-make-link-regexps ()
5452 "Update the link regular expressions.
5453 This should be called after the variable `org-link-types' has changed."
5454 (setq org-link-types-re
5455 (concat
5456 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5457 org-link-re-with-space
5458 (concat
5459 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5460 "\\([^" org-non-link-chars " ]"
5461 "[^" org-non-link-chars "]*"
5462 "[^" org-non-link-chars " ]\\)>?")
5463 org-link-re-with-space2
5464 (concat
5465 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5466 "\\([^" org-non-link-chars " ]"
5467 "[^\t\n\r]*"
5468 "[^" org-non-link-chars " ]\\)>?")
5469 org-link-re-with-space3
5470 (concat
5471 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5472 "\\([^" org-non-link-chars " ]"
5473 "[^\t\n\r]*\\)")
5474 org-angle-link-re
5475 (concat
5476 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5477 "\\([^" org-non-link-chars " ]"
5478 "[^" org-non-link-chars "]*"
5479 "\\)>")
5480 org-plain-link-re
5481 (concat
5482 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5483 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5484 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5485 org-bracket-link-regexp
5486 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5487 org-bracket-link-analytic-regexp
5488 (concat
5489 "\\[\\["
5490 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5491 "\\([^]]+\\)"
5492 "\\]"
5493 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5494 "\\]")
5495 org-bracket-link-analytic-regexp++
5496 (concat
5497 "\\[\\["
5498 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5499 "\\([^]]+\\)"
5500 "\\]"
5501 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5502 "\\]")
5503 org-any-link-re
5504 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5505 org-angle-link-re "\\)\\|\\("
5506 org-plain-link-re "\\)")))
5508 (org-make-link-regexps)
5510 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5511 "Regular expression for fast time stamp matching.")
5512 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5513 "Regular expression for fast time stamp matching.")
5514 (defconst org-ts-regexp0
5515 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5516 "Regular expression matching time strings for analysis.
5517 This one does not require the space after the date, so it can be used
5518 on a string that terminates immediately after the date.")
5519 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5520 "Regular expression matching time strings for analysis.")
5521 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5522 "Regular expression matching time stamps, with groups.")
5523 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5524 "Regular expression matching time stamps (also [..]), with groups.")
5525 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5526 "Regular expression matching a time stamp range.")
5527 (defconst org-tr-regexp-both
5528 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5529 "Regular expression matching a time stamp range.")
5530 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5531 org-ts-regexp "\\)?")
5532 "Regular expression matching a time stamp or time stamp range.")
5533 (defconst org-tsr-regexp-both
5534 (concat org-ts-regexp-both "\\(--?-?"
5535 org-ts-regexp-both "\\)?")
5536 "Regular expression matching a time stamp or time stamp range.
5537 The time stamps may be either active or inactive.")
5539 (defvar org-emph-face nil)
5541 (defun org-do-emphasis-faces (limit)
5542 "Run through the buffer and add overlays to emphasized strings."
5543 (let (rtn a)
5544 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5545 (if (not (= (char-after (match-beginning 3))
5546 (char-after (match-beginning 4))))
5547 (progn
5548 (setq rtn t)
5549 (setq a (assoc (match-string 3) org-emphasis-alist))
5550 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5551 'face
5552 (nth 1 a))
5553 (and (nth 4 a)
5554 (org-remove-flyspell-overlays-in
5555 (match-beginning 0) (match-end 0)))
5556 (add-text-properties (match-beginning 2) (match-end 2)
5557 '(font-lock-multiline t org-emphasis t))
5558 (when org-hide-emphasis-markers
5559 (add-text-properties (match-end 4) (match-beginning 5)
5560 '(invisible org-link))
5561 (add-text-properties (match-beginning 3) (match-end 3)
5562 '(invisible org-link)))))
5563 (backward-char 1))
5564 rtn))
5566 (defun org-emphasize (&optional char)
5567 "Insert or change an emphasis, i.e. a font like bold or italic.
5568 If there is an active region, change that region to a new emphasis.
5569 If there is no region, just insert the marker characters and position
5570 the cursor between them.
5571 CHAR should be either the marker character, or the first character of the
5572 HTML tag associated with that emphasis. If CHAR is a space, the means
5573 to remove the emphasis of the selected region.
5574 If char is not given (for example in an interactive call) it
5575 will be prompted for."
5576 (interactive)
5577 (let ((eal org-emphasis-alist) e det
5578 (erc org-emphasis-regexp-components)
5579 (prompt "")
5580 (string "") beg end move tag c s)
5581 (if (org-region-active-p)
5582 (setq beg (region-beginning) end (region-end)
5583 string (buffer-substring beg end))
5584 (setq move t))
5586 (while (setq e (pop eal))
5587 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5588 c (aref tag 0))
5589 (push (cons c (string-to-char (car e))) det)
5590 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5591 (substring tag 1)))))
5592 (setq det (nreverse det))
5593 (unless char
5594 (message "%s" (concat "Emphasis marker or tag:" prompt))
5595 (setq char (read-char-exclusive)))
5596 (setq char (or (cdr (assoc char det)) char))
5597 (if (equal char ?\ )
5598 (setq s "" move nil)
5599 (unless (assoc (char-to-string char) org-emphasis-alist)
5600 (error "No such emphasis marker: \"%c\"" char))
5601 (setq s (char-to-string char)))
5602 (while (and (> (length string) 1)
5603 (equal (substring string 0 1) (substring string -1))
5604 (assoc (substring string 0 1) org-emphasis-alist))
5605 (setq string (substring string 1 -1)))
5606 (setq string (concat s string s))
5607 (if beg (delete-region beg end))
5608 (unless (or (bolp)
5609 (string-match (concat "[" (nth 0 erc) "\n]")
5610 (char-to-string (char-before (point)))))
5611 (insert " "))
5612 (unless (or (eobp)
5613 (string-match (concat "[" (nth 1 erc) "\n]")
5614 (char-to-string (char-after (point)))))
5615 (insert " ") (backward-char 1))
5616 (insert string)
5617 (and move (backward-char 1))))
5619 (defconst org-nonsticky-props
5620 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5622 (defsubst org-rear-nonsticky-at (pos)
5623 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5625 (defun org-activate-plain-links (limit)
5626 "Run through the buffer and add overlays to links."
5627 (let (f hl)
5628 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5629 (not (org-in-src-block-p)))
5630 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5631 (setq f (get-text-property (match-beginning 0) 'face))
5632 (setq hl (org-match-string-no-properties 0))
5633 (if (or (eq f 'org-tag)
5634 (and (listp f) (memq 'org-tag f)))
5636 (add-text-properties (match-beginning 0) (match-end 0)
5637 (list 'mouse-face 'highlight
5638 'face 'org-link
5639 'htmlize-link `(:uri ,hl)
5640 'keymap org-mouse-map))
5641 (org-rear-nonsticky-at (match-end 0)))
5642 t)))
5644 (defun org-activate-code (limit)
5645 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5646 (progn
5647 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5648 (remove-text-properties (match-beginning 0) (match-end 0)
5649 '(display t invisible t intangible t))
5650 t)))
5652 (defcustom org-src-fontify-natively nil
5653 "When non-nil, fontify code in code blocks."
5654 :type 'boolean
5655 :version "24.1"
5656 :group 'org-appearance
5657 :group 'org-babel)
5659 (defcustom org-allow-promoting-top-level-subtree nil
5660 "When non-nil, allow promoting a top level subtree.
5661 The leading star of the top level headline will be replaced
5662 by a #."
5663 :type 'boolean
5664 :version "24.1"
5665 :group 'org-appearance)
5667 (defun org-fontify-meta-lines-and-blocks (limit)
5668 (condition-case nil
5669 (org-fontify-meta-lines-and-blocks-1 limit)
5670 (error (message "org-mode fontification error"))))
5672 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5673 "Fontify #+ lines and blocks, in the correct ways."
5674 (let ((case-fold-search t))
5675 (if (re-search-forward
5676 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5677 limit t)
5678 (let ((beg (match-beginning 0))
5679 (block-start (match-end 0))
5680 (block-end nil)
5681 (lang (match-string 7))
5682 (beg1 (line-beginning-position 2))
5683 (dc1 (downcase (match-string 2)))
5684 (dc3 (downcase (match-string 3)))
5685 end end1 quoting block-type ovl)
5686 (cond
5687 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5688 ;; a single line of backend-specific content
5689 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5690 (remove-text-properties (match-beginning 0) (match-end 0)
5691 '(display t invisible t intangible t))
5692 (add-text-properties (match-beginning 1) (match-end 3)
5693 '(font-lock-fontified t face org-meta-line))
5694 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5695 '(font-lock-fontified t face org-block))
5696 ; for backend-specific code
5698 ((and (match-end 4) (equal dc3 "+begin"))
5699 ;; Truly a block
5700 (setq block-type (downcase (match-string 5))
5701 quoting (member block-type org-protecting-blocks))
5702 (when (re-search-forward
5703 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5704 nil t) ;; on purpose, we look further than LIMIT
5705 (setq end (min (point-max) (match-end 0))
5706 end1 (min (point-max) (1- (match-beginning 0))))
5707 (setq block-end (match-beginning 0))
5708 (when quoting
5709 (remove-text-properties beg end
5710 '(display t invisible t intangible t)))
5711 (add-text-properties
5712 beg end
5713 '(font-lock-fontified t font-lock-multiline t))
5714 (add-text-properties beg beg1 '(face org-meta-line))
5715 (add-text-properties end1 (min (point-max) (1+ end))
5716 '(face org-meta-line)) ; for end_src
5717 (cond
5718 ((and lang (not (string= lang "")) org-src-fontify-natively)
5719 (org-src-font-lock-fontify-block lang block-start block-end)
5720 ;; remove old background overlays
5721 (mapc (lambda (ov)
5722 (if (eq (overlay-get ov 'face) 'org-block-background)
5723 (delete-overlay ov)))
5724 (overlays-at (/ (+ beg1 block-end) 2)))
5725 ;; add a background overlay
5726 (setq ovl (make-overlay beg1 block-end))
5727 (overlay-put ovl 'face 'org-block-background)
5728 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5729 (quoting
5730 (add-text-properties beg1 (min (point-max) (1+ end1))
5731 '(face org-block))) ; end of source block
5732 ((not org-fontify-quote-and-verse-blocks))
5733 ((string= block-type "quote")
5734 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5735 ((string= block-type "verse")
5736 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5737 (add-text-properties beg beg1 '(face org-block-begin-line))
5738 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5739 '(face org-block-end-line))
5741 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5742 (add-text-properties
5743 beg (match-end 3)
5744 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5745 '(font-lock-fontified t invisible t)
5746 '(font-lock-fontified t face org-document-info-keyword)))
5747 (add-text-properties
5748 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5749 (if (string-equal dc1 "+title:")
5750 '(font-lock-fontified t face org-document-title)
5751 '(font-lock-fontified t face org-document-info))))
5752 ((or (equal dc1 "+results")
5753 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5754 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5755 "+call:" "+header:" "+headers:" "+name:"))
5756 (and (match-end 4) (equal dc3 "+attr")))
5757 (add-text-properties
5758 beg (match-end 0)
5759 '(font-lock-fontified t face org-meta-line))
5761 ((member dc3 '(" " ""))
5762 (add-text-properties
5763 beg (match-end 0)
5764 '(font-lock-fontified t face font-lock-comment-face)))
5765 ((not (member (char-after beg) '(?\ ?\t)))
5766 ;; just any other in-buffer setting, but not indented
5767 (add-text-properties
5768 beg (match-end 0)
5769 '(font-lock-fontified t face org-meta-line))
5771 (t nil))))))
5773 (defun org-activate-angle-links (limit)
5774 "Run through the buffer and add overlays to links."
5775 (if (and (re-search-forward org-angle-link-re limit t)
5776 (not (org-in-src-block-p)))
5777 (progn
5778 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5779 (add-text-properties (match-beginning 0) (match-end 0)
5780 (list 'mouse-face 'highlight
5781 'keymap org-mouse-map))
5782 (org-rear-nonsticky-at (match-end 0))
5783 t)))
5785 (defun org-activate-footnote-links (limit)
5786 "Run through the buffer and add overlays to footnotes."
5787 (let ((fn (org-footnote-next-reference-or-definition limit)))
5788 (when fn
5789 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5790 (org-remove-flyspell-overlays-in beg end)
5791 (add-text-properties beg end
5792 (list 'mouse-face 'highlight
5793 'keymap org-mouse-map
5794 'help-echo
5795 (if (= (point-at-bol) beg)
5796 "Footnote definition"
5797 "Footnote reference")
5798 'font-lock-fontified t
5799 'font-lock-multiline t
5800 'face 'org-footnote))))))
5802 (defun org-activate-bracket-links (limit)
5803 "Run through the buffer and add overlays to bracketed links."
5804 (if (and (re-search-forward org-bracket-link-regexp limit t)
5805 (not (org-in-src-block-p)))
5806 (let* ((hl (org-match-string-no-properties 1))
5807 (help (concat "LINK: " hl))
5808 ;; FIXME: Above we should remove the escapes. But that
5809 ;; requires another match, protecting match data, a lot
5810 ;; of overhead for font-lock.
5811 (ip (org-maybe-intangible
5812 (list 'invisible 'org-link
5813 'keymap org-mouse-map 'mouse-face 'highlight
5814 'font-lock-multiline t 'help-echo help
5815 'htmlize-link `(:uri ,hl))))
5816 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5817 'font-lock-multiline t 'help-echo help
5818 'htmlize-link `(:uri ,hl))))
5819 ;; We need to remove the invisible property here. Table narrowing
5820 ;; may have made some of this invisible.
5821 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5822 (remove-text-properties (match-beginning 0) (match-end 0)
5823 '(invisible nil))
5824 (if (match-end 3)
5825 (progn
5826 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5827 (org-rear-nonsticky-at (match-beginning 3))
5828 (add-text-properties (match-beginning 3) (match-end 3) vp)
5829 (org-rear-nonsticky-at (match-end 3))
5830 (add-text-properties (match-end 3) (match-end 0) ip)
5831 (org-rear-nonsticky-at (match-end 0)))
5832 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5833 (org-rear-nonsticky-at (match-beginning 1))
5834 (add-text-properties (match-beginning 1) (match-end 1) vp)
5835 (org-rear-nonsticky-at (match-end 1))
5836 (add-text-properties (match-end 1) (match-end 0) ip)
5837 (org-rear-nonsticky-at (match-end 0)))
5838 t)))
5840 (defun org-activate-dates (limit)
5841 "Run through the buffer and add overlays to dates."
5842 (if (and (re-search-forward org-tsr-regexp-both limit t)
5843 (not (equal (char-before (match-beginning 0)) 91)))
5844 (progn
5845 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5846 (add-text-properties (match-beginning 0) (match-end 0)
5847 (list 'mouse-face 'highlight
5848 'keymap org-mouse-map))
5849 (org-rear-nonsticky-at (match-end 0))
5850 (when org-display-custom-times
5851 (if (match-end 3)
5852 (org-display-custom-time (match-beginning 3) (match-end 3)))
5853 (org-display-custom-time (match-beginning 1) (match-end 1)))
5854 t)))
5856 (defvar org-target-link-regexp nil
5857 "Regular expression matching radio targets in plain text.")
5858 (make-variable-buffer-local 'org-target-link-regexp)
5859 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5860 "Regular expression matching a link target.")
5861 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5862 "Regular expression matching a radio target.")
5863 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5864 "Regular expression matching any target.")
5866 (defun org-activate-target-links (limit)
5867 "Run through the buffer and add overlays to target matches."
5868 (when org-target-link-regexp
5869 (let ((case-fold-search t))
5870 (if (re-search-forward org-target-link-regexp limit t)
5871 (progn
5872 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5873 (add-text-properties (match-beginning 0) (match-end 0)
5874 (list 'mouse-face 'highlight
5875 'keymap org-mouse-map
5876 'help-echo "Radio target link"
5877 'org-linked-text t))
5878 (org-rear-nonsticky-at (match-end 0))
5879 t)))))
5881 (defun org-update-radio-target-regexp ()
5882 "Find all radio targets in this file and update the regular expression."
5883 (interactive)
5884 (when (memq 'radio org-activate-links)
5885 (setq org-target-link-regexp
5886 (org-make-target-link-regexp (org-all-targets 'radio)))
5887 (org-restart-font-lock)))
5889 (defun org-hide-wide-columns (limit)
5890 (let (s e)
5891 (setq s (text-property-any (point) (or limit (point-max))
5892 'org-cwidth t))
5893 (when s
5894 (setq e (next-single-property-change s 'org-cwidth))
5895 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5896 (goto-char e)
5897 t)))
5899 (defvar org-latex-and-related-regexp nil
5900 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5901 (defvar org-match-substring-regexp)
5902 (defvar org-match-substring-with-braces-regexp)
5904 (defun org-compute-latex-and-related-regexp ()
5905 "Compute regular expression for LaTeX, entities and sub/superscript.
5906 Result depends on variable `org-highlight-latex-and-related'."
5907 (org-set-local
5908 'org-latex-and-related-regexp
5909 (let* ((re-sub
5910 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5911 ((eq org-use-sub-superscripts '{})
5912 (list org-match-substring-with-braces-regexp))
5913 (org-use-sub-superscripts (list org-match-substring-regexp))))
5914 (re-latex
5915 (when (memq 'latex org-highlight-latex-and-related)
5916 (let ((matchers (plist-get org-format-latex-options :matchers)))
5917 (delq nil
5918 (mapcar (lambda (x)
5919 (and (member (car x) matchers) (nth 1 x)))
5920 org-latex-regexps)))))
5921 (re-entities
5922 (when (memq 'entities org-highlight-latex-and-related)
5923 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5924 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
5926 (defun org-do-latex-and-related (limit)
5927 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5928 LIMIT bounds the search for syntax to highlight. Stop at first
5929 highlighted object, if any. Return t if some highlighting was
5930 done, nil otherwise."
5931 (when (org-string-nw-p org-latex-and-related-regexp)
5932 (catch 'found
5933 (while (re-search-forward org-latex-and-related-regexp limit t)
5934 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
5935 'face))
5936 '(org-code org-verbatim underline))
5937 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
5938 '(?_ ?^))
5940 0)))
5941 (font-lock-prepend-text-property
5942 (+ offset (match-beginning 0)) (match-end 0)
5943 'face 'org-latex-and-related)
5944 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
5945 '(font-lock-multiline t)))
5946 (throw 'found t)))
5947 nil)))
5949 (defun org-restart-font-lock ()
5950 "Restart `font-lock-mode', to force refontification."
5951 (when (and (boundp 'font-lock-mode) font-lock-mode)
5952 (font-lock-mode -1)
5953 (font-lock-mode 1)))
5955 (defun org-all-targets (&optional radio)
5956 "Return a list of all targets in this file.
5957 When optional argument RADIO is non-nil, only find radio
5958 targets."
5959 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5960 (save-excursion
5961 (goto-char (point-min))
5962 (while (re-search-forward re nil t)
5963 ;; Make sure point is really within the object.
5964 (backward-char)
5965 (let ((obj (org-element-context)))
5966 (when (memq (org-element-type obj) '(radio-target target))
5967 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5968 rtn)))
5970 (defun org-make-target-link-regexp (targets)
5971 "Make regular expression matching all strings in TARGETS.
5972 The regular expression finds the targets also if there is a line break
5973 between words."
5974 (and targets
5975 (concat
5976 "\\<\\("
5977 (mapconcat
5978 (lambda (x)
5979 (setq x (regexp-quote x))
5980 (while (string-match " +" x)
5981 (setq x (replace-match "\\s-+" t t x)))
5983 targets
5984 "\\|")
5985 "\\)\\>")))
5987 (defun org-activate-tags (limit)
5988 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5989 (progn
5990 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5991 (add-text-properties (match-beginning 1) (match-end 1)
5992 (list 'mouse-face 'highlight
5993 'keymap org-mouse-map))
5994 (org-rear-nonsticky-at (match-end 1))
5995 t)))
5997 (defun org-outline-level ()
5998 "Compute the outline level of the heading at point.
5999 If this is called at a normal headline, the level is the number of stars.
6000 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6001 (save-excursion
6002 (if (not (condition-case nil
6003 (org-back-to-heading t)
6004 (error nil)))
6006 (looking-at org-outline-regexp)
6007 (1- (- (match-end 0) (match-beginning 0))))))
6009 (defvar org-font-lock-keywords nil)
6011 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6012 "Regular expression matching a property line.")
6014 (defvar org-font-lock-hook nil
6015 "Functions to be called for special font lock stuff.")
6017 (defvar org-font-lock-set-keywords-hook nil
6018 "Functions that can manipulate `org-font-lock-extra-keywords'.
6019 This is called after `org-font-lock-extra-keywords' is defined, but before
6020 it is installed to be used by font lock. This can be useful if something
6021 needs to be inserted at a specific position in the font-lock sequence.")
6023 (defun org-font-lock-hook (limit)
6024 "Run `org-font-lock-hook' within LIMIT."
6025 (run-hook-with-args 'org-font-lock-hook limit))
6027 (defun org-set-font-lock-defaults ()
6028 "Set font lock defaults for the current buffer."
6029 (let* ((em org-fontify-emphasized-text)
6030 (lk org-activate-links)
6031 (org-font-lock-extra-keywords
6032 (list
6033 ;; Call the hook
6034 '(org-font-lock-hook)
6035 ;; Headlines
6036 `(,(if org-fontify-whole-heading-line
6037 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6038 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6039 (1 (org-get-level-face 1))
6040 (2 (org-get-level-face 2))
6041 (3 (org-get-level-face 3)))
6042 ;; Table lines
6043 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6044 (1 'org-table t))
6045 ;; Table internals
6046 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6047 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6048 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6049 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6050 ;; Drawers
6051 (list org-drawer-regexp '(0 'org-special-keyword t))
6052 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6053 ;; Properties
6054 (list org-property-re
6055 '(1 'org-special-keyword t)
6056 '(3 'org-property-value t))
6057 ;; Links
6058 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6059 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6060 (if (memq 'plain lk) '(org-activate-plain-links))
6061 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6062 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6063 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6064 (if (memq 'footnote lk) '(org-activate-footnote-links))
6065 ;; Targets.
6066 (list org-any-target-regexp '(0 'org-target t))
6067 ;; Diary sexps.
6068 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6069 '(org-hide-wide-columns (0 nil append))
6070 ;; TODO keyword
6071 (list (format org-heading-keyword-regexp-format
6072 org-todo-regexp)
6073 '(2 (org-get-todo-face 2) t))
6074 ;; DONE
6075 (if org-fontify-done-headline
6076 (list (format org-heading-keyword-regexp-format
6077 (concat
6078 "\\(?:"
6079 (mapconcat 'regexp-quote org-done-keywords "\\|")
6080 "\\)"))
6081 '(2 'org-headline-done t))
6082 nil)
6083 ;; Priorities
6084 '(org-font-lock-add-priority-faces)
6085 ;; Tags
6086 '(org-font-lock-add-tag-faces)
6087 ;; Special keywords
6088 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6089 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6090 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6091 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6092 ;; Emphasis
6093 (if em
6094 (if (featurep 'xemacs)
6095 '(org-do-emphasis-faces (0 nil append))
6096 '(org-do-emphasis-faces)))
6097 ;; Checkboxes
6098 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6099 1 'org-checkbox prepend)
6100 (if (cdr (assq 'checkbox org-list-automatic-rules))
6101 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6102 (0 (org-get-checkbox-statistics-face) t)))
6103 ;; Description list items
6104 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6105 1 'org-list-dt prepend)
6106 ;; ARCHIVEd headings
6107 (list (concat
6108 org-outline-regexp-bol
6109 "\\(.*:" org-archive-tag ":.*\\)")
6110 '(1 'org-archived prepend))
6111 ;; Specials
6112 '(org-do-latex-and-related)
6113 '(org-fontify-entities)
6114 '(org-raise-scripts)
6115 ;; Code
6116 '(org-activate-code (1 'org-code t))
6117 ;; COMMENT
6118 (list (format org-heading-keyword-regexp-format
6119 (concat "\\("
6120 org-comment-string "\\|" org-quote-string
6121 "\\)"))
6122 '(2 'org-special-keyword t))
6123 ;; Blocks and meta lines
6124 '(org-fontify-meta-lines-and-blocks)
6126 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6127 (run-hooks 'org-font-lock-set-keywords-hook)
6128 ;; Now set the full font-lock-keywords
6129 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6130 (org-set-local 'font-lock-defaults
6131 '(org-font-lock-keywords t nil nil backward-paragraph))
6132 (kill-local-variable 'font-lock-keywords) nil))
6134 (defun org-toggle-pretty-entities ()
6135 "Toggle the composition display of entities as UTF8 characters."
6136 (interactive)
6137 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6138 (org-restart-font-lock)
6139 (if org-pretty-entities
6140 (message "Entities are displayed as UTF8 characters")
6141 (save-restriction
6142 (widen)
6143 (org-decompose-region (point-min) (point-max))
6144 (message "Entities are displayed plain"))))
6146 (defvar org-custom-properties-overlays nil
6147 "List of overlays used for custom properties.")
6148 (make-variable-buffer-local 'org-custom-properties-overlays)
6150 (defun org-toggle-custom-properties-visibility ()
6151 "Display or hide properties in `org-custom-properties'."
6152 (interactive)
6153 (if org-custom-properties-overlays
6154 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6155 (setq org-custom-properties-overlays nil))
6156 (unless (not org-custom-properties)
6157 (save-excursion
6158 (save-restriction
6159 (widen)
6160 (goto-char (point-min))
6161 (while (re-search-forward org-property-re nil t)
6162 (mapc (lambda(p)
6163 (when (equal p (substring (match-string 1) 1 -1))
6164 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6165 (overlay-put o 'invisible t)
6166 (overlay-put o 'org-custom-property t)
6167 (push o org-custom-properties-overlays))))
6168 org-custom-properties)))))))
6170 (defun org-fontify-entities (limit)
6171 "Find an entity to fontify."
6172 (let (ee)
6173 (when org-pretty-entities
6174 (catch 'match
6175 (while (re-search-forward
6176 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6177 limit t)
6178 (if (and (not (org-in-indented-comment-line))
6179 (setq ee (org-entity-get (match-string 1)))
6180 (= (length (nth 6 ee)) 1))
6181 (let*
6182 ((end (if (equal (match-string 2) "{}")
6183 (match-end 2)
6184 (match-end 1))))
6185 (add-text-properties
6186 (match-beginning 0) end
6187 (list 'font-lock-fontified t))
6188 (compose-region (match-beginning 0) end
6189 (nth 6 ee) nil)
6190 (backward-char 1)
6191 (throw 'match t))))
6192 nil))))
6194 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6195 "Fontify string S like in Org-mode."
6196 (with-temp-buffer
6197 (insert s)
6198 (let ((org-odd-levels-only odd-levels))
6199 (org-mode)
6200 (font-lock-fontify-buffer)
6201 (buffer-string))))
6203 (defvar org-m nil)
6204 (defvar org-l nil)
6205 (defvar org-f nil)
6206 (defun org-get-level-face (n)
6207 "Get the right face for match N in font-lock matching of headlines."
6208 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6209 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6210 (if org-cycle-level-faces
6211 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6212 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6213 (cond
6214 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6215 ((eq n 2) org-f)
6216 (t (if org-level-color-stars-only nil org-f))))
6219 (defun org-get-todo-face (kwd)
6220 "Get the right face for a TODO keyword KWD.
6221 If KWD is a number, get the corresponding match group."
6222 (if (numberp kwd) (setq kwd (match-string kwd)))
6223 (or (org-face-from-face-or-color
6224 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6225 (and (member kwd org-done-keywords) 'org-done)
6226 'org-todo))
6228 (defun org-face-from-face-or-color (context inherit face-or-color)
6229 "Create a face list that inherits INHERIT, but sets the foreground color.
6230 When FACE-OR-COLOR is not a string, just return it."
6231 (if (stringp face-or-color)
6232 (list :inherit inherit
6233 (cdr (assoc context org-faces-easy-properties))
6234 face-or-color)
6235 face-or-color))
6237 (defun org-font-lock-add-tag-faces (limit)
6238 "Add the special tag faces."
6239 (when (and org-tag-faces org-tags-special-faces-re)
6240 (while (re-search-forward org-tags-special-faces-re limit t)
6241 (add-text-properties (match-beginning 1) (match-end 1)
6242 (list 'face (org-get-tag-face 1)
6243 'font-lock-fontified t))
6244 (backward-char 1))))
6246 (defun org-font-lock-add-priority-faces (limit)
6247 "Add the special priority faces."
6248 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6249 (when (save-match-data (org-at-heading-p))
6250 (add-text-properties
6251 (match-beginning 0) (match-end 0)
6252 (list 'face (or (org-face-from-face-or-color
6253 'priority 'org-priority
6254 (cdr (assoc (char-after (match-beginning 1))
6255 org-priority-faces)))
6256 'org-priority)
6257 'font-lock-fontified t)))))
6259 (defun org-get-tag-face (kwd)
6260 "Get the right face for a TODO keyword KWD.
6261 If KWD is a number, get the corresponding match group."
6262 (if (numberp kwd) (setq kwd (match-string kwd)))
6263 (or (org-face-from-face-or-color
6264 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6265 'org-tag))
6267 (defun org-unfontify-region (beg end &optional maybe_loudly)
6268 "Remove fontification and activation overlays from links."
6269 (font-lock-default-unfontify-region beg end)
6270 (let* ((buffer-undo-list t)
6271 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6272 (inhibit-modification-hooks t)
6273 deactivate-mark buffer-file-name buffer-file-truename)
6274 (org-decompose-region beg end)
6275 (remove-text-properties beg end
6276 '(mouse-face t keymap t org-linked-text t
6277 invisible t intangible t
6278 org-no-flyspell t org-emphasis t))
6279 (org-remove-font-lock-display-properties beg end)))
6281 (defconst org-script-display '(((raise -0.3) (height 0.7))
6282 ((raise 0.3) (height 0.7))
6283 ((raise -0.5))
6284 ((raise 0.5)))
6285 "Display properties for showing superscripts and subscripts.")
6287 (defun org-remove-font-lock-display-properties (beg end)
6288 "Remove specific display properties that have been added by font lock.
6289 The will remove the raise properties that are used to show superscripts
6290 and subscripts."
6291 (let (next prop)
6292 (while (< beg end)
6293 (setq next (next-single-property-change beg 'display nil end)
6294 prop (get-text-property beg 'display))
6295 (if (member prop org-script-display)
6296 (put-text-property beg next 'display nil))
6297 (setq beg next))))
6299 (defun org-raise-scripts (limit)
6300 "Add raise properties to sub/superscripts."
6301 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6302 (if (re-search-forward
6303 (if (eq org-use-sub-superscripts t)
6304 org-match-substring-regexp
6305 org-match-substring-with-braces-regexp)
6306 limit t)
6307 (let* ((pos (point)) table-p comment-p
6308 (mpos (match-beginning 3))
6309 (emph-p (get-text-property mpos 'org-emphasis))
6310 (link-p (get-text-property mpos 'mouse-face))
6311 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6312 (goto-char (point-at-bol))
6313 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6314 comment-p (org-looking-at-p "[ \t]*#"))
6315 (goto-char pos)
6316 ;; FIXME: Should we go back one character here, for a_b^c
6317 ;; (goto-char (1- pos)) ;????????????????????
6318 (if (or comment-p emph-p link-p keyw-p)
6320 (put-text-property (match-beginning 3) (match-end 0)
6321 'display
6322 (if (equal (char-after (match-beginning 2)) ?^)
6323 (nth (if table-p 3 1) org-script-display)
6324 (nth (if table-p 2 0) org-script-display)))
6325 (add-text-properties (match-beginning 2) (match-end 2)
6326 (list 'invisible t
6327 'org-dwidth t 'org-dwidth-n 1))
6328 (if (and (eq (char-after (match-beginning 3)) ?{)
6329 (eq (char-before (match-end 3)) ?}))
6330 (progn
6331 (add-text-properties
6332 (match-beginning 3) (1+ (match-beginning 3))
6333 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6334 (add-text-properties
6335 (1- (match-end 3)) (match-end 3)
6336 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6337 t)))))
6339 ;;;; Visibility cycling, including org-goto and indirect buffer
6341 ;;; Cycling
6343 (defvar org-cycle-global-status nil)
6344 (make-variable-buffer-local 'org-cycle-global-status)
6345 (put 'org-cycle-global-status 'org-state t)
6346 (defvar org-cycle-subtree-status nil)
6347 (make-variable-buffer-local 'org-cycle-subtree-status)
6348 (put 'org-cycle-subtree-status 'org-state t)
6350 (defvar org-inlinetask-min-level)
6352 ;;;###autoload
6353 (defun org-cycle (&optional arg)
6354 "TAB-action and visibility cycling for Org-mode.
6356 This is the command invoked in Org-mode by the TAB key. Its main purpose
6357 is outline visibility cycling, but it also invokes other actions
6358 in special contexts.
6360 - When this function is called with a prefix argument, rotate the entire
6361 buffer through 3 states (global cycling)
6362 1. OVERVIEW: Show only top-level headlines.
6363 2. CONTENTS: Show all headlines of all levels, but no body text.
6364 3. SHOW ALL: Show everything.
6365 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6366 determined by the variable `org-startup-folded', and by any VISIBILITY
6367 properties in the buffer.
6368 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6369 including any drawers.
6371 - When inside a table, re-align the table and move to the next field.
6373 - When point is at the beginning of a headline, rotate the subtree started
6374 by this line through 3 different states (local cycling)
6375 1. FOLDED: Only the main headline is shown.
6376 2. CHILDREN: The main headline and the direct children are shown.
6377 From this state, you can move to one of the children
6378 and zoom in further.
6379 3. SUBTREE: Show the entire subtree, including body text.
6380 If there is no subtree, switch directly from CHILDREN to FOLDED.
6382 - When point is at the beginning of an empty headline and the variable
6383 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6384 of the headline by demoting and promoting it to likely levels. This
6385 speeds up creation document structure by pressing TAB once or several
6386 times right after creating a new headline.
6388 - When there is a numeric prefix, go up to a heading with level ARG, do
6389 a `show-subtree' and return to the previous cursor position. If ARG
6390 is negative, go up that many levels.
6392 - When point is not at the beginning of a headline, execute the global
6393 binding for TAB, which is re-indenting the line. See the option
6394 `org-cycle-emulate-tab' for details.
6396 - Special case: if point is at the beginning of the buffer and there is
6397 no headline in line 1, this function will act as if called with prefix arg
6398 (C-u TAB, same as S-TAB) also when called without prefix arg.
6399 But only if also the variable `org-cycle-global-at-bob' is t."
6400 (interactive "P")
6401 (org-load-modules-maybe)
6402 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6403 (and org-cycle-level-after-item/entry-creation
6404 (or (org-cycle-level)
6405 (org-cycle-item-indentation))))
6406 (let* (message-log-max ; Don't populate the *Messages* buffer
6407 (limit-level
6408 (or org-cycle-max-level
6409 (and (boundp 'org-inlinetask-min-level)
6410 org-inlinetask-min-level
6411 (1- org-inlinetask-min-level))))
6412 (nstars (and limit-level
6413 (if org-odd-levels-only
6414 (and limit-level (1- (* limit-level 2)))
6415 limit-level)))
6416 (org-outline-regexp
6417 (if (not (derived-mode-p 'org-mode))
6418 outline-regexp
6419 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6420 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6421 (not (looking-at org-outline-regexp))))
6422 (org-cycle-hook
6423 (if bob-special
6424 (delq 'org-optimize-window-after-visibility-change
6425 (copy-sequence org-cycle-hook))
6426 org-cycle-hook))
6427 (pos (point)))
6429 (if (or bob-special (equal arg '(4)))
6430 ;; special case: use global cycling
6431 (setq arg t))
6433 (cond
6435 ((equal arg '(16))
6436 (setq last-command 'dummy)
6437 (org-set-startup-visibility)
6438 (message "Startup visibility, plus VISIBILITY properties"))
6440 ((equal arg '(64))
6441 (show-all)
6442 (message "Entire buffer visible, including drawers"))
6444 ;; Table: enter it or move to the next field.
6445 ((org-at-table-p 'any)
6446 (if (org-at-table.el-p)
6447 (message "Use C-c ' to edit table.el tables")
6448 (if arg (org-table-edit-field t)
6449 (org-table-justify-field-maybe)
6450 (call-interactively 'org-table-next-field))))
6452 ((run-hook-with-args-until-success
6453 'org-tab-after-check-for-table-hook))
6455 ;; Global cycling: delegate to `org-cycle-internal-global'.
6456 ((eq arg t) (org-cycle-internal-global))
6458 ;; Drawers: delegate to `org-flag-drawer'.
6459 ((and org-drawers org-drawer-regexp
6460 (save-excursion
6461 (beginning-of-line 1)
6462 (looking-at org-drawer-regexp)))
6463 (org-flag-drawer ; toggle block visibility
6464 (not (get-char-property (match-end 0) 'invisible))))
6466 ;; Show-subtree, ARG levels up from here.
6467 ((integerp arg)
6468 (save-excursion
6469 (org-back-to-heading)
6470 (outline-up-heading (if (< arg 0) (- arg)
6471 (- (funcall outline-level) arg)))
6472 (org-show-subtree)))
6474 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6475 ((and (featurep 'org-inlinetask)
6476 (org-inlinetask-at-task-p)
6477 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6478 (org-inlinetask-toggle-visibility))
6480 ((org-try-cdlatex-tab))
6482 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6483 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6484 (save-excursion (beginning-of-line 1)
6485 (looking-at org-outline-regexp)))
6486 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6487 (org-cycle-internal-local))
6489 ;; From there: TAB emulation and template completion.
6490 (buffer-read-only (org-back-to-heading))
6492 ((run-hook-with-args-until-success
6493 'org-tab-after-check-for-cycling-hook))
6495 ((org-try-structure-completion))
6497 ((run-hook-with-args-until-success
6498 'org-tab-before-tab-emulation-hook))
6500 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6501 (or (not (bolp))
6502 (not (looking-at org-outline-regexp))))
6503 (call-interactively (global-key-binding "\t")))
6505 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6506 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6507 (or (and (eq org-cycle-emulate-tab 'white)
6508 (= (match-end 0) (point-at-eol)))
6509 (and (eq org-cycle-emulate-tab 'whitestart)
6510 (>= (match-end 0) pos))))
6512 (eq org-cycle-emulate-tab t))
6513 (call-interactively (global-key-binding "\t")))
6515 (t (save-excursion
6516 (org-back-to-heading)
6517 (org-cycle)))))))
6519 (defun org-cycle-internal-global ()
6520 "Do the global cycling action."
6521 ;; Hack to avoid display of messages for .org attachments in Gnus
6522 (let (message-log-max ; Don't populate the *Messages* buffer
6523 (ga (string-match "\\*fontification" (buffer-name))))
6524 (cond
6525 ((and (eq last-command this-command)
6526 (eq org-cycle-global-status 'overview))
6527 ;; We just created the overview - now do table of contents
6528 ;; This can be slow in very large buffers, so indicate action
6529 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6530 (unless ga (message "CONTENTS..."))
6531 (org-content)
6532 (unless ga (message "CONTENTS...done"))
6533 (setq org-cycle-global-status 'contents)
6534 (run-hook-with-args 'org-cycle-hook 'contents))
6536 ((and (eq last-command this-command)
6537 (eq org-cycle-global-status 'contents))
6538 ;; We just showed the table of contents - now show everything
6539 (run-hook-with-args 'org-pre-cycle-hook 'all)
6540 (show-all)
6541 (unless ga (message "SHOW ALL"))
6542 (setq org-cycle-global-status 'all)
6543 (run-hook-with-args 'org-cycle-hook 'all))
6546 ;; Default action: go to overview
6547 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6548 (org-overview)
6549 (unless ga (message "OVERVIEW"))
6550 (setq org-cycle-global-status 'overview)
6551 (run-hook-with-args 'org-cycle-hook 'overview)))))
6553 (defun org-cycle-internal-local ()
6554 "Do the local cycling action."
6555 (let (message-log-max ; Don't populate the *Messages* buffer
6556 (goal-column 0) eoh eol eos has-children children-skipped struct)
6557 ;; First, determine end of headline (EOH), end of subtree or item
6558 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6559 (save-excursion
6560 (if (org-at-item-p)
6561 (progn
6562 (beginning-of-line)
6563 (setq struct (org-list-struct))
6564 (setq eoh (point-at-eol))
6565 (setq eos (org-list-get-item-end-before-blank (point) struct))
6566 (setq has-children (org-list-has-child-p (point) struct)))
6567 (org-back-to-heading)
6568 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6569 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6570 (setq has-children
6571 (or (save-excursion
6572 (let ((level (funcall outline-level)))
6573 (outline-next-heading)
6574 (and (org-at-heading-p t)
6575 (> (funcall outline-level) level))))
6576 (save-excursion
6577 (org-list-search-forward (org-item-beginning-re) eos t)))))
6578 ;; Determine end invisible part of buffer (EOL)
6579 (beginning-of-line 2)
6580 ;; XEmacs doesn't have `next-single-char-property-change'
6581 (if (featurep 'xemacs)
6582 (while (and (not (eobp)) ;; this is like `next-line'
6583 (get-char-property (1- (point)) 'invisible))
6584 (beginning-of-line 2))
6585 (while (and (not (eobp)) ;; this is like `next-line'
6586 (get-char-property (1- (point)) 'invisible))
6587 (goto-char (next-single-char-property-change (point) 'invisible))
6588 (and (eolp) (beginning-of-line 2))))
6589 (setq eol (point)))
6590 ;; Find out what to do next and set `this-command'
6591 (cond
6592 ((= eos eoh)
6593 ;; Nothing is hidden behind this heading
6594 (unless (org-before-first-heading-p)
6595 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6596 (message "EMPTY ENTRY")
6597 (setq org-cycle-subtree-status nil)
6598 (save-excursion
6599 (goto-char eos)
6600 (outline-next-heading)
6601 (if (outline-invisible-p) (org-flag-heading nil))))
6602 ((and (or (>= eol eos)
6603 (not (string-match "\\S-" (buffer-substring eol eos))))
6604 (or has-children
6605 (not (setq children-skipped
6606 org-cycle-skip-children-state-if-no-children))))
6607 ;; Entire subtree is hidden in one line: children view
6608 (unless (org-before-first-heading-p)
6609 (run-hook-with-args 'org-pre-cycle-hook 'children))
6610 (if (org-at-item-p)
6611 (org-list-set-item-visibility (point-at-bol) struct 'children)
6612 (org-show-entry)
6613 (org-with-limited-levels (show-children))
6614 ;; FIXME: This slows down the func way too much.
6615 ;; How keep drawers hidden in subtree anyway?
6616 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6617 ;; (org-cycle-hide-drawers 'subtree))
6619 ;; Fold every list in subtree to top-level items.
6620 (when (eq org-cycle-include-plain-lists 'integrate)
6621 (save-excursion
6622 (org-back-to-heading)
6623 (while (org-list-search-forward (org-item-beginning-re) eos t)
6624 (beginning-of-line 1)
6625 (let* ((struct (org-list-struct))
6626 (prevs (org-list-prevs-alist struct))
6627 (end (org-list-get-bottom-point struct)))
6628 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6629 (org-list-get-all-items (point) struct prevs))
6630 (goto-char end))))))
6631 (message "CHILDREN")
6632 (save-excursion
6633 (goto-char eos)
6634 (outline-next-heading)
6635 (if (outline-invisible-p) (org-flag-heading nil)))
6636 (setq org-cycle-subtree-status 'children)
6637 (unless (org-before-first-heading-p)
6638 (run-hook-with-args 'org-cycle-hook 'children)))
6639 ((or children-skipped
6640 (and (eq last-command this-command)
6641 (eq org-cycle-subtree-status 'children)))
6642 ;; We just showed the children, or no children are there,
6643 ;; now show everything.
6644 (unless (org-before-first-heading-p)
6645 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6646 (outline-flag-region eoh eos nil)
6647 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6648 (setq org-cycle-subtree-status 'subtree)
6649 (unless (org-before-first-heading-p)
6650 (run-hook-with-args 'org-cycle-hook 'subtree)))
6652 ;; Default action: hide the subtree.
6653 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6654 (outline-flag-region eoh eos t)
6655 (message "FOLDED")
6656 (setq org-cycle-subtree-status 'folded)
6657 (unless (org-before-first-heading-p)
6658 (run-hook-with-args 'org-cycle-hook 'folded))))))
6660 ;;;###autoload
6661 (defun org-global-cycle (&optional arg)
6662 "Cycle the global visibility. For details see `org-cycle'.
6663 With \\[universal-argument] prefix arg, switch to startup visibility.
6664 With a numeric prefix, show all headlines up to that level."
6665 (interactive "P")
6666 (let ((org-cycle-include-plain-lists
6667 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6668 (cond
6669 ((integerp arg)
6670 (show-all)
6671 (hide-sublevels arg)
6672 (setq org-cycle-global-status 'contents))
6673 ((equal arg '(4))
6674 (org-set-startup-visibility)
6675 (message "Startup visibility, plus VISIBILITY properties."))
6677 (org-cycle '(4))))))
6679 (defun org-set-startup-visibility ()
6680 "Set the visibility required by startup options and properties."
6681 (cond
6682 ((eq org-startup-folded t)
6683 (org-cycle '(4)))
6684 ((eq org-startup-folded 'content)
6685 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6686 (org-cycle '(4)) (org-cycle '(4)))))
6687 (unless (eq org-startup-folded 'showeverything)
6688 (if org-hide-block-startup (org-hide-block-all))
6689 (org-set-visibility-according-to-property 'no-cleanup)
6690 (org-cycle-hide-archived-subtrees 'all)
6691 (org-cycle-hide-drawers 'all)
6692 (org-cycle-show-empty-lines t)))
6694 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6695 "Switch subtree visibilities according to :VISIBILITY: property."
6696 (interactive)
6697 (let (org-show-entry-below state)
6698 (save-excursion
6699 (goto-char (point-min))
6700 (while (re-search-forward
6701 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6702 nil t)
6703 (setq state (match-string 1))
6704 (save-excursion
6705 (org-back-to-heading t)
6706 (hide-subtree)
6707 (org-reveal)
6708 (cond
6709 ((equal state '("fold" "folded"))
6710 (hide-subtree))
6711 ((equal state "children")
6712 (org-show-hidden-entry)
6713 (show-children))
6714 ((equal state "content")
6715 (save-excursion
6716 (save-restriction
6717 (org-narrow-to-subtree)
6718 (org-content))))
6719 ((member state '("all" "showall"))
6720 (show-subtree)))))
6721 (unless no-cleanup
6722 (org-cycle-hide-archived-subtrees 'all)
6723 (org-cycle-hide-drawers 'all)
6724 (org-cycle-show-empty-lines 'all)))))
6726 ;; This function uses outline-regexp instead of the more fundamental
6727 ;; org-outline-regexp so that org-cycle-global works outside of Org
6728 ;; buffers, where outline-regexp is needed.
6729 (defun org-overview ()
6730 "Switch to overview mode, showing only top-level headlines.
6731 Really, this shows all headlines with level equal or greater than the level
6732 of the first headline in the buffer. This is important, because if the
6733 first headline is not level one, then (hide-sublevels 1) gives confusing
6734 results."
6735 (interactive)
6736 (let ((l (org-current-line))
6737 (level (save-excursion
6738 (goto-char (point-min))
6739 (if (re-search-forward (concat "^" outline-regexp) nil t)
6740 (progn
6741 (goto-char (match-beginning 0))
6742 (funcall outline-level))))))
6743 (and level (hide-sublevels level))
6744 (recenter '(4))
6745 (org-goto-line l)))
6747 (defun org-content (&optional arg)
6748 "Show all headlines in the buffer, like a table of contents.
6749 With numerical argument N, show content up to level N."
6750 (interactive "P")
6751 (save-excursion
6752 ;; Visit all headings and show their offspring
6753 (and (integerp arg) (org-overview))
6754 (goto-char (point-max))
6755 (catch 'exit
6756 (while (and (progn (condition-case nil
6757 (outline-previous-visible-heading 1)
6758 (error (goto-char (point-min))))
6760 (looking-at org-outline-regexp))
6761 (if (integerp arg)
6762 (show-children (1- arg))
6763 (show-branches))
6764 (if (bobp) (throw 'exit nil))))))
6767 (defun org-optimize-window-after-visibility-change (state)
6768 "Adjust the window after a change in outline visibility.
6769 This function is the default value of the hook `org-cycle-hook'."
6770 (when (get-buffer-window (current-buffer))
6771 (cond
6772 ((eq state 'content) nil)
6773 ((eq state 'all) nil)
6774 ((eq state 'folded) nil)
6775 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6776 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6778 (defun org-remove-empty-overlays-at (pos)
6779 "Remove outline overlays that do not contain non-white stuff."
6780 (mapc
6781 (lambda (o)
6782 (and (eq 'outline (overlay-get o 'invisible))
6783 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6784 (overlay-end o))))
6785 (delete-overlay o)))
6786 (overlays-at pos)))
6788 (defun org-clean-visibility-after-subtree-move ()
6789 "Fix visibility issues after moving a subtree."
6790 ;; First, find a reasonable region to look at:
6791 ;; Start two siblings above, end three below
6792 (let* ((beg (save-excursion
6793 (and (org-get-last-sibling)
6794 (org-get-last-sibling))
6795 (point)))
6796 (end (save-excursion
6797 (and (org-get-next-sibling)
6798 (org-get-next-sibling)
6799 (org-get-next-sibling))
6800 (if (org-at-heading-p)
6801 (point-at-eol)
6802 (point))))
6803 (level (looking-at "\\*+"))
6804 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6805 (save-excursion
6806 (save-restriction
6807 (narrow-to-region beg end)
6808 (when re
6809 ;; Properly fold already folded siblings
6810 (goto-char (point-min))
6811 (while (re-search-forward re nil t)
6812 (if (and (not (outline-invisible-p))
6813 (save-excursion
6814 (goto-char (point-at-eol)) (outline-invisible-p)))
6815 (hide-entry))))
6816 (org-cycle-show-empty-lines 'overview)
6817 (org-cycle-hide-drawers 'overview)))))
6819 (defun org-cycle-show-empty-lines (state)
6820 "Show empty lines above all visible headlines.
6821 The region to be covered depends on STATE when called through
6822 `org-cycle-hook'. Lisp program can use t for STATE to get the
6823 entire buffer covered. Note that an empty line is only shown if there
6824 are at least `org-cycle-separator-lines' empty lines before the headline."
6825 (when (not (= org-cycle-separator-lines 0))
6826 (save-excursion
6827 (let* ((n (abs org-cycle-separator-lines))
6828 (re (cond
6829 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6830 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6831 (t (let ((ns (number-to-string (- n 2))))
6832 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6833 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6834 beg end b e)
6835 (cond
6836 ((memq state '(overview contents t))
6837 (setq beg (point-min) end (point-max)))
6838 ((memq state '(children folded))
6839 (setq beg (point) end (progn (org-end-of-subtree t t)
6840 (beginning-of-line 2)
6841 (point)))))
6842 (when beg
6843 (goto-char beg)
6844 (while (re-search-forward re end t)
6845 (unless (get-char-property (match-end 1) 'invisible)
6846 (setq e (match-end 1))
6847 (if (< org-cycle-separator-lines 0)
6848 (setq b (save-excursion
6849 (goto-char (match-beginning 0))
6850 (org-back-over-empty-lines)
6851 (if (save-excursion
6852 (goto-char (max (point-min) (1- (point))))
6853 (org-at-heading-p))
6854 (1- (point))
6855 (point))))
6856 (setq b (match-beginning 1)))
6857 (outline-flag-region b e nil)))))))
6858 ;; Never hide empty lines at the end of the file.
6859 (save-excursion
6860 (goto-char (point-max))
6861 (outline-previous-heading)
6862 (outline-end-of-heading)
6863 (if (and (looking-at "[ \t\n]+")
6864 (= (match-end 0) (point-max)))
6865 (outline-flag-region (point) (match-end 0) nil))))
6867 (defun org-show-empty-lines-in-parent ()
6868 "Move to the parent and re-show empty lines before visible headlines."
6869 (save-excursion
6870 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6871 (org-cycle-show-empty-lines context))))
6873 (defun org-files-list ()
6874 "Return `org-agenda-files' list, plus all open org-mode files.
6875 This is useful for operations that need to scan all of a user's
6876 open and agenda-wise Org files."
6877 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6878 (dolist (buf (buffer-list))
6879 (with-current-buffer buf
6880 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6881 (let ((file (expand-file-name (buffer-file-name))))
6882 (unless (member file files)
6883 (push file files))))))
6884 files))
6886 (defsubst org-entry-beginning-position ()
6887 "Return the beginning position of the current entry."
6888 (save-excursion (outline-back-to-heading t) (point)))
6890 (defsubst org-entry-end-position ()
6891 "Return the end position of the current entry."
6892 (save-excursion (outline-next-heading) (point)))
6894 (defun org-cycle-hide-drawers (state)
6895 "Re-hide all drawers after a visibility state change."
6896 (when (and (derived-mode-p 'org-mode)
6897 (not (memq state '(overview folded contents))))
6898 (save-excursion
6899 (let* ((globalp (memq state '(contents all)))
6900 (beg (if globalp (point-min) (point)))
6901 (end (if globalp (point-max)
6902 (if (eq state 'children)
6903 (save-excursion (outline-next-heading) (point))
6904 (org-end-of-subtree t)))))
6905 (goto-char beg)
6906 (while (re-search-forward org-drawer-regexp end t)
6907 (org-flag-drawer t))))))
6909 (defun org-cycle-hide-inline-tasks (state)
6910 "Re-hide inline task when switching to 'contents visibility state."
6911 (when (and (eq state 'contents)
6912 (boundp 'org-inlinetask-min-level)
6913 org-inlinetask-min-level)
6914 (hide-sublevels (1- org-inlinetask-min-level))))
6916 (defun org-flag-drawer (flag)
6917 "When FLAG is non-nil, hide the drawer we are within.
6918 Otherwise make it visible."
6919 (save-excursion
6920 (beginning-of-line 1)
6921 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6922 (let ((b (match-end 0)))
6923 (if (re-search-forward
6924 "^[ \t]*:END:"
6925 (save-excursion (outline-next-heading) (point)) t)
6926 (outline-flag-region b (point-at-eol) flag)
6927 (error ":END: line missing at position %s" b))))))
6929 (defun org-subtree-end-visible-p ()
6930 "Is the end of the current subtree visible?"
6931 (pos-visible-in-window-p
6932 (save-excursion (org-end-of-subtree t) (point))))
6934 (defun org-first-headline-recenter (&optional N)
6935 "Move cursor to the first headline and recenter the headline.
6936 Optional argument N means put the headline into the Nth line of the window."
6937 (goto-char (point-min))
6938 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6939 (beginning-of-line)
6940 (recenter (prefix-numeric-value N))))
6942 ;;; Saving and restoring visibility
6944 (defun org-outline-overlay-data (&optional use-markers)
6945 "Return a list of the locations of all outline overlays.
6946 These are overlays with the `invisible' property value `outline'.
6947 The return value is a list of cons cells, with start and stop
6948 positions for each overlay.
6949 If USE-MARKERS is set, return the positions as markers."
6950 (let (beg end)
6951 (save-excursion
6952 (save-restriction
6953 (widen)
6954 (delq nil
6955 (mapcar (lambda (o)
6956 (when (eq (overlay-get o 'invisible) 'outline)
6957 (setq beg (overlay-start o)
6958 end (overlay-end o))
6959 (and beg end (> end beg)
6960 (if use-markers
6961 (cons (move-marker (make-marker) beg)
6962 (move-marker (make-marker) end))
6963 (cons beg end)))))
6964 (overlays-in (point-min) (point-max))))))))
6966 (defun org-set-outline-overlay-data (data)
6967 "Create visibility overlays for all positions in DATA.
6968 DATA should have been made by `org-outline-overlay-data'."
6969 (let (o)
6970 (save-excursion
6971 (save-restriction
6972 (widen)
6973 (show-all)
6974 (mapc (lambda (c)
6975 (outline-flag-region (car c) (cdr c) t))
6976 data)))))
6978 ;;; Folding of blocks
6980 (defvar org-hide-block-overlays nil
6981 "Overlays hiding blocks.")
6982 (make-variable-buffer-local 'org-hide-block-overlays)
6984 (defun org-block-map (function &optional start end)
6985 "Call FUNCTION at the head of all source blocks in the current buffer.
6986 Optional arguments START and END can be used to limit the range."
6987 (let ((start (or start (point-min)))
6988 (end (or end (point-max))))
6989 (save-excursion
6990 (goto-char start)
6991 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6992 (save-excursion
6993 (save-match-data
6994 (goto-char (match-beginning 0))
6995 (funcall function)))))))
6997 (defun org-hide-block-toggle-all ()
6998 "Toggle the visibility of all blocks in the current buffer."
6999 (org-block-map #'org-hide-block-toggle))
7001 (defun org-hide-block-all ()
7002 "Fold all blocks in the current buffer."
7003 (interactive)
7004 (org-show-block-all)
7005 (org-block-map #'org-hide-block-toggle-maybe))
7007 (defun org-show-block-all ()
7008 "Unfold all blocks in the current buffer."
7009 (interactive)
7010 (mapc 'delete-overlay org-hide-block-overlays)
7011 (setq org-hide-block-overlays nil))
7013 (defun org-hide-block-toggle-maybe ()
7014 "Toggle visibility of block at point."
7015 (interactive)
7016 (let ((case-fold-search t))
7017 (if (save-excursion
7018 (beginning-of-line 1)
7019 (looking-at org-block-regexp))
7020 (progn (org-hide-block-toggle)
7021 t) ;; to signal that we took action
7022 nil))) ;; to signal that we did not
7024 (defun org-hide-block-toggle (&optional force)
7025 "Toggle the visibility of the current block."
7026 (interactive)
7027 (save-excursion
7028 (beginning-of-line)
7029 (if (re-search-forward org-block-regexp nil t)
7030 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7031 (end (match-end 0)) ;; end of entire body
7033 (if (memq t (mapcar (lambda (overlay)
7034 (eq (overlay-get overlay 'invisible)
7035 'org-hide-block))
7036 (overlays-at start)))
7037 (if (or (not force) (eq force 'off))
7038 (mapc (lambda (ov)
7039 (when (member ov org-hide-block-overlays)
7040 (setq org-hide-block-overlays
7041 (delq ov org-hide-block-overlays)))
7042 (when (eq (overlay-get ov 'invisible)
7043 'org-hide-block)
7044 (delete-overlay ov)))
7045 (overlays-at start)))
7046 (setq ov (make-overlay start end))
7047 (overlay-put ov 'invisible 'org-hide-block)
7048 ;; make the block accessible to isearch
7049 (overlay-put
7050 ov 'isearch-open-invisible
7051 (lambda (ov)
7052 (when (member ov org-hide-block-overlays)
7053 (setq org-hide-block-overlays
7054 (delq ov org-hide-block-overlays)))
7055 (when (eq (overlay-get ov 'invisible)
7056 'org-hide-block)
7057 (delete-overlay ov))))
7058 (push ov org-hide-block-overlays)))
7059 (error "Not looking at a source block"))))
7061 ;; org-tab-after-check-for-cycling-hook
7062 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7063 ;; Remove overlays when changing major mode
7064 (add-hook 'org-mode-hook
7065 (lambda () (org-add-hook 'change-major-mode-hook
7066 'org-show-block-all 'append 'local)))
7068 ;;; Org-goto
7070 (defvar org-goto-window-configuration nil)
7071 (defvar org-goto-marker nil)
7072 (defvar org-goto-map)
7073 (defun org-goto-map ()
7074 "Set the keymap `org-goto'."
7075 (setq org-goto-map
7076 (let ((map (make-sparse-keymap)))
7077 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7078 mouse-drag-region universal-argument org-occur))
7079 cmd)
7080 (while (setq cmd (pop cmds))
7081 (substitute-key-definition cmd cmd map global-map)))
7082 (suppress-keymap map)
7083 (org-defkey map "\C-m" 'org-goto-ret)
7084 (org-defkey map [(return)] 'org-goto-ret)
7085 (org-defkey map [(left)] 'org-goto-left)
7086 (org-defkey map [(right)] 'org-goto-right)
7087 (org-defkey map [(control ?g)] 'org-goto-quit)
7088 (org-defkey map "\C-i" 'org-cycle)
7089 (org-defkey map [(tab)] 'org-cycle)
7090 (org-defkey map [(down)] 'outline-next-visible-heading)
7091 (org-defkey map [(up)] 'outline-previous-visible-heading)
7092 (if org-goto-auto-isearch
7093 (if (fboundp 'define-key-after)
7094 (define-key-after map [t] 'org-goto-local-auto-isearch)
7095 nil)
7096 (org-defkey map "q" 'org-goto-quit)
7097 (org-defkey map "n" 'outline-next-visible-heading)
7098 (org-defkey map "p" 'outline-previous-visible-heading)
7099 (org-defkey map "f" 'outline-forward-same-level)
7100 (org-defkey map "b" 'outline-backward-same-level)
7101 (org-defkey map "u" 'outline-up-heading))
7102 (org-defkey map "/" 'org-occur)
7103 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7104 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7105 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7106 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7107 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7108 map)))
7110 (defconst org-goto-help
7111 "Browse buffer copy, to find location or copy text.%s
7112 RET=jump to location C-g=quit and return to previous location
7113 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7115 (defvar org-goto-start-pos) ; dynamically scoped parameter
7117 ;; FIXME: Docstring does not mention both interfaces
7118 (defun org-goto (&optional alternative-interface)
7119 "Look up a different location in the current file, keeping current visibility.
7121 When you want look-up or go to a different location in a
7122 document, the fastest way is often to fold the entire buffer and
7123 then dive into the tree. This method has the disadvantage, that
7124 the previous location will be folded, which may not be what you
7125 want.
7127 This command works around this by showing a copy of the current
7128 buffer in an indirect buffer, in overview mode. You can dive
7129 into the tree in that copy, use org-occur and incremental search
7130 to find a location. When pressing RET or `Q', the command
7131 returns to the original buffer in which the visibility is still
7132 unchanged. After RET it will also jump to the location selected
7133 in the indirect buffer and expose the headline hierarchy above.
7135 With a prefix argument, use the alternative interface: e.g. if
7136 `org-goto-interface' is 'outline use 'outline-path-completion."
7137 (interactive "P")
7138 (org-goto-map)
7139 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7140 (org-refile-use-outline-path t)
7141 (org-refile-target-verify-function nil)
7142 (interface
7143 (if (not alternative-interface)
7144 org-goto-interface
7145 (if (eq org-goto-interface 'outline)
7146 'outline-path-completion
7147 'outline)))
7148 (org-goto-start-pos (point))
7149 (selected-point
7150 (if (eq interface 'outline)
7151 (car (org-get-location (current-buffer) org-goto-help))
7152 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7153 (org-refile-check-position pa)
7154 (nth 3 pa)))))
7155 (if selected-point
7156 (progn
7157 (org-mark-ring-push org-goto-start-pos)
7158 (goto-char selected-point)
7159 (if (or (outline-invisible-p) (org-invisible-p2))
7160 (org-show-context 'org-goto)))
7161 (message "Quit"))))
7163 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7164 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7165 (defvar org-goto-local-auto-isearch-map) ; defined below
7167 (defun org-get-location (buf help)
7168 "Let the user select a location in the Org-mode buffer BUF.
7169 This function uses a recursive edit. It returns the selected position
7170 or nil."
7171 (org-no-popups
7172 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7173 (isearch-hide-immediately nil)
7174 (isearch-search-fun-function
7175 (lambda () 'org-goto-local-search-headings))
7176 (org-goto-selected-point org-goto-exit-command))
7177 (save-excursion
7178 (save-window-excursion
7179 (delete-other-windows)
7180 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7181 (org-pop-to-buffer-same-window
7182 (condition-case nil
7183 (make-indirect-buffer (current-buffer) "*org-goto*")
7184 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7185 (with-output-to-temp-buffer "*Org Help*"
7186 (princ (format help (if org-goto-auto-isearch
7187 " Just type for auto-isearch."
7188 " n/p/f/b/u to navigate, q to quit."))))
7189 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7190 (setq buffer-read-only nil)
7191 (let ((org-startup-truncated t)
7192 (org-startup-folded nil)
7193 (org-startup-align-all-tables nil))
7194 (org-mode)
7195 (org-overview))
7196 (setq buffer-read-only t)
7197 (if (and (boundp 'org-goto-start-pos)
7198 (integer-or-marker-p org-goto-start-pos))
7199 (let ((org-show-hierarchy-above t)
7200 (org-show-siblings t)
7201 (org-show-following-heading t))
7202 (goto-char org-goto-start-pos)
7203 (and (outline-invisible-p) (org-show-context)))
7204 (goto-char (point-min)))
7205 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7206 (message "Select location and press RET")
7207 (use-local-map org-goto-map)
7208 (recursive-edit)))
7209 (kill-buffer "*org-goto*")
7210 (cons org-goto-selected-point org-goto-exit-command))))
7212 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7213 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7214 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7215 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7217 (defun org-goto-local-search-headings (string bound noerror)
7218 "Search and make sure that any matches are in headlines."
7219 (catch 'return
7220 (while (if isearch-forward
7221 (search-forward string bound noerror)
7222 (search-backward string bound noerror))
7223 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7224 (and (member :headline context)
7225 (not (member :tags context))))
7226 (throw 'return (point))))))
7228 (defun org-goto-local-auto-isearch ()
7229 "Start isearch."
7230 (interactive)
7231 (goto-char (point-min))
7232 (let ((keys (this-command-keys)))
7233 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7234 (isearch-mode t)
7235 (isearch-process-search-char (string-to-char keys)))))
7237 (defun org-goto-ret (&optional arg)
7238 "Finish `org-goto' by going to the new location."
7239 (interactive "P")
7240 (setq org-goto-selected-point (point)
7241 org-goto-exit-command 'return)
7242 (throw 'exit nil))
7244 (defun org-goto-left ()
7245 "Finish `org-goto' by going to the new location."
7246 (interactive)
7247 (if (org-at-heading-p)
7248 (progn
7249 (beginning-of-line 1)
7250 (setq org-goto-selected-point (point)
7251 org-goto-exit-command 'left)
7252 (throw 'exit nil))
7253 (error "Not on a heading")))
7255 (defun org-goto-right ()
7256 "Finish `org-goto' by going to the new location."
7257 (interactive)
7258 (if (org-at-heading-p)
7259 (progn
7260 (setq org-goto-selected-point (point)
7261 org-goto-exit-command 'right)
7262 (throw 'exit nil))
7263 (error "Not on a heading")))
7265 (defun org-goto-quit ()
7266 "Finish `org-goto' without cursor motion."
7267 (interactive)
7268 (setq org-goto-selected-point nil)
7269 (setq org-goto-exit-command 'quit)
7270 (throw 'exit nil))
7272 ;;; Indirect buffer display of subtrees
7274 (defvar org-indirect-dedicated-frame nil
7275 "This is the frame being used for indirect tree display.")
7276 (defvar org-last-indirect-buffer nil)
7278 (defun org-tree-to-indirect-buffer (&optional arg)
7279 "Create indirect buffer and narrow it to current subtree.
7280 With a numerical prefix ARG, go up to this level and then take that tree.
7281 If ARG is negative, go up that many levels.
7283 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7284 indirect buffer previously made with this command, to avoid proliferation of
7285 indirect buffers. However, when you call the command with a \
7286 \\[universal-argument] prefix, or
7287 when `org-indirect-buffer-display' is `new-frame', the last buffer
7288 is kept so that you can work with several indirect buffers at the same time.
7289 If `org-indirect-buffer-display' is `dedicated-frame', the \
7290 \\[universal-argument] prefix also
7291 requests that a new frame be made for the new buffer, so that the dedicated
7292 frame is not changed."
7293 (interactive "P")
7294 (let ((cbuf (current-buffer))
7295 (cwin (selected-window))
7296 (pos (point))
7297 beg end level heading ibuf)
7298 (save-excursion
7299 (org-back-to-heading t)
7300 (when (numberp arg)
7301 (setq level (org-outline-level))
7302 (if (< arg 0) (setq arg (+ level arg)))
7303 (while (> (setq level (org-outline-level)) arg)
7304 (org-up-heading-safe)))
7305 (setq beg (point)
7306 heading (org-get-heading))
7307 (org-end-of-subtree t t)
7308 (if (org-at-heading-p) (backward-char 1))
7309 (setq end (point)))
7310 (if (and (buffer-live-p org-last-indirect-buffer)
7311 (not (eq org-indirect-buffer-display 'new-frame))
7312 (not arg))
7313 (kill-buffer org-last-indirect-buffer))
7314 (setq ibuf (org-get-indirect-buffer cbuf)
7315 org-last-indirect-buffer ibuf)
7316 (cond
7317 ((or (eq org-indirect-buffer-display 'new-frame)
7318 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7319 (select-frame (make-frame))
7320 (delete-other-windows)
7321 (org-pop-to-buffer-same-window ibuf)
7322 (org-set-frame-title heading))
7323 ((eq org-indirect-buffer-display 'dedicated-frame)
7324 (raise-frame
7325 (select-frame (or (and org-indirect-dedicated-frame
7326 (frame-live-p org-indirect-dedicated-frame)
7327 org-indirect-dedicated-frame)
7328 (setq org-indirect-dedicated-frame (make-frame)))))
7329 (delete-other-windows)
7330 (org-pop-to-buffer-same-window ibuf)
7331 (org-set-frame-title (concat "Indirect: " heading)))
7332 ((eq org-indirect-buffer-display 'current-window)
7333 (org-pop-to-buffer-same-window ibuf))
7334 ((eq org-indirect-buffer-display 'other-window)
7335 (pop-to-buffer ibuf))
7336 (t (error "Invalid value")))
7337 (if (featurep 'xemacs)
7338 (save-excursion (org-mode) (turn-on-font-lock)))
7339 (narrow-to-region beg end)
7340 (show-all)
7341 (goto-char pos)
7342 (run-hook-with-args 'org-cycle-hook 'all)
7343 (and (window-live-p cwin) (select-window cwin))))
7345 (defun org-get-indirect-buffer (&optional buffer)
7346 (setq buffer (or buffer (current-buffer)))
7347 (let ((n 1) (base (buffer-name buffer)) bname)
7348 (while (buffer-live-p
7349 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7350 (setq n (1+ n)))
7351 (condition-case nil
7352 (make-indirect-buffer buffer bname 'clone)
7353 (error (make-indirect-buffer buffer bname)))))
7355 (defun org-set-frame-title (title)
7356 "Set the title of the current frame to the string TITLE."
7357 ;; FIXME: how to name a single frame in XEmacs???
7358 (unless (featurep 'xemacs)
7359 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7361 ;;;; Structure editing
7363 ;;; Inserting headlines
7365 (defun org-previous-line-empty-p (&optional next)
7366 "Is the previous line a blank line?
7367 When NEXT is non-nil, check the next line instead."
7368 (save-excursion
7369 (and (not (bobp))
7370 (or (beginning-of-line (if next 2 0)) t)
7371 (save-match-data
7372 (looking-at "[ \t]*$")))))
7374 (defun org-insert-heading (&optional arg invisible-ok)
7375 "Insert a new heading or item with same depth at point.
7376 If point is in a plain list and ARG is nil, create a new list item.
7377 With one universal prefix argument, insert a heading even in lists.
7378 With two universal prefix arguments, insert the heading at the end
7379 of the parent subtree.
7381 If point is at the beginning of a headline, insert a sibling before
7382 the current headline. If point is not at the beginning, split the line
7383 and create a new headline with the text in the current line after point
7384 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7386 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7387 This is important for non-interactive uses of the command."
7388 (interactive "P")
7389 (if (or (= (buffer-size) 0)
7390 (and (not (save-excursion
7391 (and (ignore-errors (org-back-to-heading invisible-ok))
7392 (org-at-heading-p))))
7393 (or arg (not (org-in-item-p)))))
7394 (progn
7395 (insert
7396 (if (org-previous-line-empty-p) "" "\n")
7397 (if (org-in-src-block-p) ",* " "* "))
7398 (run-hooks 'org-insert-heading-hook))
7399 (when (or arg
7400 (not (org-insert-item
7401 (save-excursion
7402 (beginning-of-line)
7403 (looking-at org-list-full-item-re)
7404 (match-string 3)))))
7405 (let* ((empty-line-p nil)
7406 (eops (equal arg '(16))) ; insert at end of parent subtree
7407 (org-insert-heading-respect-content
7408 (or (not (null arg)) org-insert-heading-respect-content))
7409 (level nil)
7410 (on-heading (org-at-heading-p))
7411 (head (save-excursion
7412 (condition-case nil
7413 (progn
7414 (org-back-to-heading invisible-ok)
7415 (when (and (not on-heading)
7416 (featurep 'org-inlinetask)
7417 (integerp org-inlinetask-min-level)
7418 (>= (length (match-string 0))
7419 org-inlinetask-min-level))
7420 ;; Find a heading level before the inline task
7421 (while (and (setq level (org-up-heading-safe))
7422 (>= level org-inlinetask-min-level)))
7423 (if (org-at-heading-p)
7424 (org-back-to-heading invisible-ok)
7425 (error "This should not happen")))
7426 (unless (and (save-excursion
7427 (save-match-data
7428 (org-backward-heading-same-level 1 invisible-ok))
7429 (= (point) (match-beginning 0)))
7430 (not (org-previous-line-empty-p t)))
7431 (setq empty-line-p (org-previous-line-empty-p)))
7432 (match-string 0))
7433 (error "* "))))
7434 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7435 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7436 pos hide-previous previous-pos)
7437 (cond
7438 ;; At the beginning of a heading, open a new line for insertiong
7439 ((and (bolp) (org-at-heading-p)
7440 (not eops)
7441 (or (bobp)
7442 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7443 (open-line (if blank 2 1)))
7445 (save-excursion
7446 (setq previous-pos (point-at-bol))
7447 (end-of-line)
7448 (setq hide-previous (outline-invisible-p)))
7449 (and org-insert-heading-respect-content
7450 (save-excursion
7451 (while (outline-invisible-p)
7452 (org-show-subtree)
7453 (org-up-heading-safe))))
7454 (let ((split
7455 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7456 (save-excursion
7457 (let ((p (point)))
7458 (goto-char (point-at-bol))
7459 (and (looking-at org-complex-heading-regexp)
7460 (match-beginning 4)
7461 (> p (match-beginning 4)))))))
7462 tags pos)
7463 (cond
7464 ;; Insert a new line, possibly at end of parent subtree
7465 (org-insert-heading-respect-content
7466 (if (not eops)
7467 (progn
7468 (org-end-of-subtree nil t)
7469 (and (looking-at "^\\*") (backward-char 1))
7470 (while (and (not (bobp))
7471 ;; Don't delete spaces in empty headlines
7472 (not (looking-back org-outline-regexp))
7473 (member (char-before) '(?\ ?\t ?\n)))
7474 (backward-delete-char 1)))
7475 (let ((p (point)))
7476 (org-up-heading-safe)
7477 (if (= p (point))
7478 (goto-char (point-max))
7479 (org-end-of-subtree nil t))))
7480 (when (featurep 'org-inlinetask)
7481 (while (and (not (eobp))
7482 (looking-at "\\(\\*+\\)[ \t]+")
7483 (>= (length (match-string 1))
7484 org-inlinetask-min-level))
7485 (org-end-of-subtree nil t)))
7486 (or (bolp) (newline))
7487 (or (org-previous-line-empty-p)
7488 (and blank (newline)))
7489 (if (or empty-line-p eops) (open-line 1)))
7490 ;; Insert a headling containing text after point
7491 ((org-at-heading-p)
7492 (when hide-previous
7493 (show-children)
7494 (org-show-entry))
7495 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7496 (setq tags (and (match-end 2) (match-string 2)))
7497 (and (match-end 1)
7498 (delete-region (match-beginning 1) (match-end 1)))
7499 (setq pos (point-at-bol))
7500 (or split (end-of-line 1))
7501 (delete-horizontal-space)
7502 (if (string-match "\\`\\*+\\'"
7503 (buffer-substring (point-at-bol) (point)))
7504 (insert " "))
7505 (newline (if blank 2 1))
7506 (when tags
7507 (save-excursion
7508 (goto-char pos)
7509 (end-of-line 1)
7510 (insert " " tags)
7511 (org-set-tags nil 'align))))
7513 (or split (end-of-line 1))
7514 (newline (if blank 2 1)))))))
7515 (insert head) (just-one-space)
7516 (setq pos (point))
7517 (end-of-line 1)
7518 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7519 (when (and org-insert-heading-respect-content hide-previous)
7520 (save-excursion
7521 (goto-char previous-pos)
7522 (hide-subtree)))
7523 (run-hooks 'org-insert-heading-hook)))))
7525 (defun org-get-heading (&optional no-tags no-todo)
7526 "Return the heading of the current entry, without the stars.
7527 When NO-TAGS is non-nil, don't include tags.
7528 When NO-TODO is non-nil, don't include TODO keywords."
7529 (save-excursion
7530 (org-back-to-heading t)
7531 (cond
7532 ((and no-tags no-todo)
7533 (looking-at org-complex-heading-regexp)
7534 (match-string 4))
7535 (no-tags
7536 (looking-at (concat org-outline-regexp
7537 "\\(.*?\\)"
7538 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7539 (match-string 1))
7540 (no-todo
7541 (looking-at org-todo-line-regexp)
7542 (match-string 3))
7543 (t (looking-at org-heading-regexp)
7544 (match-string 2)))))
7546 (defvar orgstruct-mode) ; defined below
7548 (defun org-heading-components ()
7549 "Return the components of the current heading.
7550 This is a list with the following elements:
7551 - the level as an integer
7552 - the reduced level, different if `org-odd-levels-only' is set.
7553 - the TODO keyword, or nil
7554 - the priority character, like ?A, or nil if no priority is given
7555 - the headline text itself, or the tags string if no headline text
7556 - the tags string, or nil."
7557 (save-excursion
7558 (org-back-to-heading t)
7559 (if (let (case-fold-search)
7560 (looking-at
7561 (if orgstruct-mode
7562 org-heading-regexp
7563 org-complex-heading-regexp)))
7564 (if orgstruct-mode
7565 (list (length (match-string 1))
7566 (org-reduced-level (length (match-string 1)))
7569 (match-string 2)
7570 nil)
7571 (list (length (match-string 1))
7572 (org-reduced-level (length (match-string 1)))
7573 (org-match-string-no-properties 2)
7574 (and (match-end 3) (aref (match-string 3) 2))
7575 (org-match-string-no-properties 4)
7576 (org-match-string-no-properties 5))))))
7578 (defun org-get-entry ()
7579 "Get the entry text, after heading, entire subtree."
7580 (save-excursion
7581 (org-back-to-heading t)
7582 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7584 (defun org-insert-heading-after-current ()
7585 "Insert a new heading with same level as current, after current subtree."
7586 (interactive)
7587 (org-back-to-heading)
7588 (org-insert-heading)
7589 (org-move-subtree-down)
7590 (end-of-line 1))
7592 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7593 "Insert heading with `org-insert-heading-respect-content' set to t."
7594 (interactive "P")
7595 (let ((org-insert-heading-respect-content t))
7596 (org-insert-heading arg invisible-ok)))
7598 (defun org-insert-todo-heading-respect-content (&optional force-state)
7599 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7600 (interactive "P")
7601 (let ((org-insert-heading-respect-content t))
7602 (org-insert-todo-heading force-state t)))
7604 (defun org-insert-todo-heading (arg &optional force-heading)
7605 "Insert a new heading with the same level and TODO state as current heading.
7606 If the heading has no TODO state, or if the state is DONE, use the first
7607 state (TODO by default). Also one prefix arg, force first state. With two
7608 prefix args, force inserting at the end of the parent subtree."
7609 (interactive "P")
7610 (when (or force-heading (not (org-insert-item 'checkbox)))
7611 (org-insert-heading (or (and (equal arg '(16)) '(16))
7612 force-heading))
7613 (save-excursion
7614 (org-back-to-heading)
7615 (outline-previous-heading)
7616 (looking-at org-todo-line-regexp))
7617 (let*
7618 ((new-mark-x
7619 (if (or arg
7620 (not (match-beginning 2))
7621 (member (match-string 2) org-done-keywords))
7622 (car org-todo-keywords-1)
7623 (match-string 2)))
7624 (new-mark
7626 (run-hook-with-args-until-success
7627 'org-todo-get-default-hook new-mark-x nil)
7628 new-mark-x)))
7629 (beginning-of-line 1)
7630 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7631 (if org-treat-insert-todo-heading-as-state-change
7632 (org-todo new-mark)
7633 (insert new-mark " "))))
7634 (when org-provide-todo-statistics
7635 (org-update-parent-todo-statistics))))
7637 (defun org-insert-subheading (arg)
7638 "Insert a new subheading and demote it.
7639 Works for outline headings and for plain lists alike."
7640 (interactive "P")
7641 (org-insert-heading arg)
7642 (cond
7643 ((org-at-heading-p) (org-do-demote))
7644 ((org-at-item-p) (org-indent-item))))
7646 (defun org-insert-todo-subheading (arg)
7647 "Insert a new subheading with TODO keyword or checkbox and demote it.
7648 Works for outline headings and for plain lists alike."
7649 (interactive "P")
7650 (org-insert-todo-heading arg)
7651 (cond
7652 ((org-at-heading-p) (org-do-demote))
7653 ((org-at-item-p) (org-indent-item))))
7655 ;;; Promotion and Demotion
7657 (defvar org-after-demote-entry-hook nil
7658 "Hook run after an entry has been demoted.
7659 The cursor will be at the beginning of the entry.
7660 When a subtree is being demoted, the hook will be called for each node.")
7662 (defvar org-after-promote-entry-hook nil
7663 "Hook run after an entry has been promoted.
7664 The cursor will be at the beginning of the entry.
7665 When a subtree is being promoted, the hook will be called for each node.")
7667 (defun org-promote-subtree ()
7668 "Promote the entire subtree.
7669 See also `org-promote'."
7670 (interactive)
7671 (save-excursion
7672 (org-with-limited-levels (org-map-tree 'org-promote)))
7673 (org-fix-position-after-promote))
7675 (defun org-demote-subtree ()
7676 "Demote the entire subtree. See `org-demote'.
7677 See also `org-promote'."
7678 (interactive)
7679 (save-excursion
7680 (org-with-limited-levels (org-map-tree 'org-demote)))
7681 (org-fix-position-after-promote))
7684 (defun org-do-promote ()
7685 "Promote the current heading higher up the tree.
7686 If the region is active in `transient-mark-mode', promote all headings
7687 in the region."
7688 (interactive)
7689 (save-excursion
7690 (if (org-region-active-p)
7691 (org-map-region 'org-promote (region-beginning) (region-end))
7692 (org-promote)))
7693 (org-fix-position-after-promote))
7695 (defun org-do-demote ()
7696 "Demote the current heading lower down the tree.
7697 If the region is active in `transient-mark-mode', demote all headings
7698 in the region."
7699 (interactive)
7700 (save-excursion
7701 (if (org-region-active-p)
7702 (org-map-region 'org-demote (region-beginning) (region-end))
7703 (org-demote)))
7704 (org-fix-position-after-promote))
7706 (defun org-fix-position-after-promote ()
7707 "Make sure that after pro/demotion cursor position is right."
7708 (let ((pos (point)))
7709 (when (save-excursion
7710 (beginning-of-line 1)
7711 (looking-at org-todo-line-regexp)
7712 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7713 (cond ((eobp) (insert " "))
7714 ((eolp) (insert " "))
7715 ((equal (char-after) ?\ ) (forward-char 1))))))
7717 (defun org-current-level ()
7718 "Return the level of the current entry, or nil if before the first headline.
7719 The level is the number of stars at the beginning of the headline."
7720 (save-excursion
7721 (org-with-limited-levels
7722 (if (ignore-errors (org-back-to-heading t))
7723 (funcall outline-level)))))
7725 (defun org-get-previous-line-level ()
7726 "Return the outline depth of the last headline before the current line.
7727 Returns 0 for the first headline in the buffer, and nil if before the
7728 first headline."
7729 (let ((current-level (org-current-level))
7730 (prev-level (when (> (line-number-at-pos) 1)
7731 (save-excursion
7732 (beginning-of-line 0)
7733 (org-current-level)))))
7734 (cond ((null current-level) nil) ; Before first headline
7735 ((null prev-level) 0) ; At first headline
7736 (prev-level))))
7738 (defun org-reduced-level (l)
7739 "Compute the effective level of a heading.
7740 This takes into account the setting of `org-odd-levels-only'."
7741 (cond
7742 ((zerop l) 0)
7743 (org-odd-levels-only (1+ (floor (/ l 2))))
7744 (t l)))
7746 (defun org-level-increment ()
7747 "Return the number of stars that will be added or removed at a
7748 time to headlines when structure editing, based on the value of
7749 `org-odd-levels-only'."
7750 (if org-odd-levels-only 2 1))
7752 (defun org-get-valid-level (level &optional change)
7753 "Rectify a level change under the influence of `org-odd-levels-only'
7754 LEVEL is a current level, CHANGE is by how much the level should be
7755 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7756 even level numbers will become the next higher odd number."
7757 (if org-odd-levels-only
7758 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7759 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7760 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7761 (max 1 (+ level (or change 0)))))
7763 (if (boundp 'define-obsolete-function-alias)
7764 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7765 (define-obsolete-function-alias 'org-get-legal-level
7766 'org-get-valid-level)
7767 (define-obsolete-function-alias 'org-get-legal-level
7768 'org-get-valid-level "23.1")))
7770 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7771 ;; ̀org-with-limited-levels'
7772 (defun org-promote ()
7773 "Promote the current heading higher up the tree.
7774 If the region is active in `transient-mark-mode', promote all headings
7775 in the region."
7776 (org-back-to-heading t)
7777 (let* ((level (save-match-data (funcall outline-level)))
7778 (after-change-functions (remove 'flyspell-after-change-function
7779 after-change-functions))
7780 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7781 (diff (abs (- level (length up-head) -1))))
7782 (cond ((and (= level 1) org-called-with-limited-levels
7783 org-allow-promoting-top-level-subtree)
7784 (replace-match "# " nil t))
7785 ((= level 1)
7786 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7787 (t (replace-match up-head nil t)))
7788 ;; Fixup tag positioning
7789 (unless (= level 1)
7790 (and org-auto-align-tags (org-set-tags nil t))
7791 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7792 (run-hooks 'org-after-promote-entry-hook)))
7794 (defun org-demote ()
7795 "Demote the current heading lower down the tree.
7796 If the region is active in `transient-mark-mode', demote all headings
7797 in the region."
7798 (org-back-to-heading t)
7799 (let* ((level (save-match-data (funcall outline-level)))
7800 (after-change-functions (remove 'flyspell-after-change-function
7801 after-change-functions))
7802 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7803 (diff (abs (- level (length down-head) -1))))
7804 (replace-match down-head nil t)
7805 ;; Fixup tag positioning
7806 (and org-auto-align-tags (org-set-tags nil t))
7807 (if org-adapt-indentation (org-fixup-indentation diff))
7808 (run-hooks 'org-after-demote-entry-hook)))
7810 (defun org-cycle-level ()
7811 "Cycle the level of an empty headline through possible states.
7812 This goes first to child, then to parent, level, then up the hierarchy.
7813 After top level, it switches back to sibling level."
7814 (interactive)
7815 (let ((org-adapt-indentation nil))
7816 (when (org-point-at-end-of-empty-headline)
7817 (setq this-command 'org-cycle-level) ; Only needed for caching
7818 (let ((cur-level (org-current-level))
7819 (prev-level (org-get-previous-line-level)))
7820 (cond
7821 ;; If first headline in file, promote to top-level.
7822 ((= prev-level 0)
7823 (loop repeat (/ (- cur-level 1) (org-level-increment))
7824 do (org-do-promote)))
7825 ;; If same level as prev, demote one.
7826 ((= prev-level cur-level)
7827 (org-do-demote))
7828 ;; If parent is top-level, promote to top level if not already.
7829 ((= prev-level 1)
7830 (loop repeat (/ (- cur-level 1) (org-level-increment))
7831 do (org-do-promote)))
7832 ;; If top-level, return to prev-level.
7833 ((= cur-level 1)
7834 (loop repeat (/ (- prev-level 1) (org-level-increment))
7835 do (org-do-demote)))
7836 ;; If less than prev-level, promote one.
7837 ((< cur-level prev-level)
7838 (org-do-promote))
7839 ;; If deeper than prev-level, promote until higher than
7840 ;; prev-level.
7841 ((> cur-level prev-level)
7842 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7843 do (org-do-promote))))
7844 t))))
7846 (defun org-map-tree (fun)
7847 "Call FUN for every heading underneath the current one."
7848 (org-back-to-heading)
7849 (let ((level (funcall outline-level)))
7850 (save-excursion
7851 (funcall fun)
7852 (while (and (progn
7853 (outline-next-heading)
7854 (> (funcall outline-level) level))
7855 (not (eobp)))
7856 (funcall fun)))))
7858 (defun org-map-region (fun beg end)
7859 "Call FUN for every heading between BEG and END."
7860 (let ((org-ignore-region t))
7861 (save-excursion
7862 (setq end (copy-marker end))
7863 (goto-char beg)
7864 (if (and (re-search-forward org-outline-regexp-bol nil t)
7865 (< (point) end))
7866 (funcall fun))
7867 (while (and (progn
7868 (outline-next-heading)
7869 (< (point) end))
7870 (not (eobp)))
7871 (funcall fun)))))
7873 (defvar org-property-end-re) ; silence byte-compiler
7874 (defun org-fixup-indentation (diff)
7875 "Change the indentation in the current entry by DIFF.
7876 However, if any line in the current entry has no indentation, or if it
7877 would end up with no indentation after the change, nothing at all is done."
7878 (save-excursion
7879 (let ((end (save-excursion (outline-next-heading)
7880 (point-marker)))
7881 (prohibit (if (> diff 0)
7882 "^\\S-"
7883 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7884 col)
7885 (unless (save-excursion (end-of-line 1)
7886 (re-search-forward prohibit end t))
7887 (while (and (< (point) end)
7888 (re-search-forward "^[ \t]+" end t))
7889 (goto-char (match-end 0))
7890 (setq col (current-column))
7891 (if (< diff 0) (replace-match ""))
7892 (org-indent-to-column (+ diff col))))
7893 (move-marker end nil))))
7895 (defun org-convert-to-odd-levels ()
7896 "Convert an org-mode file with all levels allowed to one with odd levels.
7897 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7898 level 5 etc."
7899 (interactive)
7900 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7901 (let ((outline-level 'org-outline-level)
7902 (org-odd-levels-only nil) n)
7903 (save-excursion
7904 (goto-char (point-min))
7905 (while (re-search-forward "^\\*\\*+ " nil t)
7906 (setq n (- (length (match-string 0)) 2))
7907 (while (>= (setq n (1- n)) 0)
7908 (org-demote))
7909 (end-of-line 1))))))
7911 (defun org-convert-to-oddeven-levels ()
7912 "Convert an org-mode file with only odd levels to one with odd/even levels.
7913 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7914 file contains a section with an even level, conversion would
7915 destroy the structure of the file. An error is signaled in this
7916 case."
7917 (interactive)
7918 (goto-char (point-min))
7919 ;; First check if there are no even levels
7920 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7921 (org-show-context t)
7922 (error "Not all levels are odd in this file. Conversion not possible"))
7923 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7924 (let ((outline-regexp org-outline-regexp)
7925 (outline-level 'org-outline-level)
7926 (org-odd-levels-only nil) n)
7927 (save-excursion
7928 (goto-char (point-min))
7929 (while (re-search-forward "^\\*\\*+ " nil t)
7930 (setq n (/ (1- (length (match-string 0))) 2))
7931 (while (>= (setq n (1- n)) 0)
7932 (org-promote))
7933 (end-of-line 1))))))
7935 (defun org-tr-level (n)
7936 "Make N odd if required."
7937 (if org-odd-levels-only (1+ (/ n 2)) n))
7939 ;;; Vertical tree motion, cutting and pasting of subtrees
7941 (defun org-move-subtree-up (&optional arg)
7942 "Move the current subtree up past ARG headlines of the same level."
7943 (interactive "p")
7944 (org-move-subtree-down (- (prefix-numeric-value arg))))
7946 (defun org-move-subtree-down (&optional arg)
7947 "Move the current subtree down past ARG headlines of the same level."
7948 (interactive "p")
7949 (setq arg (prefix-numeric-value arg))
7950 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7951 'org-get-last-sibling))
7952 (ins-point (make-marker))
7953 (cnt (abs arg))
7954 (col (current-column))
7955 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7956 ;; Select the tree
7957 (org-back-to-heading)
7958 (setq beg0 (point))
7959 (save-excursion
7960 (setq ne-beg (org-back-over-empty-lines))
7961 (setq beg (point)))
7962 (save-match-data
7963 (save-excursion (outline-end-of-heading)
7964 (setq folded (outline-invisible-p)))
7965 (outline-end-of-subtree))
7966 (outline-next-heading)
7967 (setq ne-end (org-back-over-empty-lines))
7968 (setq end (point))
7969 (goto-char beg0)
7970 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7971 ;; include less whitespace
7972 (save-excursion
7973 (goto-char beg)
7974 (forward-line (- ne-beg ne-end))
7975 (setq beg (point))))
7976 ;; Find insertion point, with error handling
7977 (while (> cnt 0)
7978 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7979 (progn (goto-char beg0)
7980 (user-error "Cannot move past superior level or buffer limit")))
7981 (setq cnt (1- cnt)))
7982 (if (> arg 0)
7983 ;; Moving forward - still need to move over subtree
7984 (progn (org-end-of-subtree t t)
7985 (save-excursion
7986 (org-back-over-empty-lines)
7987 (or (bolp) (newline)))))
7988 (setq ne-ins (org-back-over-empty-lines))
7989 (move-marker ins-point (point))
7990 (setq txt (buffer-substring beg end))
7991 (org-save-markers-in-region beg end)
7992 (delete-region beg end)
7993 (org-remove-empty-overlays-at beg)
7994 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7995 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7996 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7997 (let ((bbb (point)))
7998 (insert-before-markers txt)
7999 (org-reinstall-markers-in-region bbb)
8000 (move-marker ins-point bbb))
8001 (or (bolp) (insert "\n"))
8002 (setq ins-end (point))
8003 (goto-char ins-point)
8004 (org-skip-whitespace)
8005 (when (and (< arg 0)
8006 (org-first-sibling-p)
8007 (> ne-ins ne-beg))
8008 ;; Move whitespace back to beginning
8009 (save-excursion
8010 (goto-char ins-end)
8011 (let ((kill-whole-line t))
8012 (kill-line (- ne-ins ne-beg)) (point)))
8013 (insert (make-string (- ne-ins ne-beg) ?\n)))
8014 (move-marker ins-point nil)
8015 (if folded
8016 (hide-subtree)
8017 (org-show-entry)
8018 (show-children)
8019 (org-cycle-hide-drawers 'children))
8020 (org-clean-visibility-after-subtree-move)
8021 ;; move back to the initial column we were at
8022 (move-to-column col)))
8024 (defvar org-subtree-clip ""
8025 "Clipboard for cut and paste of subtrees.
8026 This is actually only a copy of the kill, because we use the normal kill
8027 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8029 (defvar org-subtree-clip-folded nil
8030 "Was the last copied subtree folded?
8031 This is used to fold the tree back after pasting.")
8033 (defun org-cut-subtree (&optional n)
8034 "Cut the current subtree into the clipboard.
8035 With prefix arg N, cut this many sequential subtrees.
8036 This is a short-hand for marking the subtree and then cutting it."
8037 (interactive "p")
8038 (org-copy-subtree n 'cut))
8040 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8041 "Cut the current subtree into the clipboard.
8042 With prefix arg N, cut this many sequential subtrees.
8043 This is a short-hand for marking the subtree and then copying it.
8044 If CUT is non-nil, actually cut the subtree.
8045 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8046 of some markers in the region, even if CUT is non-nil. This is
8047 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8048 (interactive "p")
8049 (let (beg end folded (beg0 (point)))
8050 (if (org-called-interactively-p 'any)
8051 (org-back-to-heading nil) ; take what looks like a subtree
8052 (org-back-to-heading t)) ; take what is really there
8053 (setq beg (point))
8054 (skip-chars-forward " \t\r\n")
8055 (save-match-data
8056 (if nosubtrees
8057 (outline-next-heading)
8058 (save-excursion (outline-end-of-heading)
8059 (setq folded (outline-invisible-p)))
8060 (condition-case nil
8061 (org-forward-heading-same-level (1- n) t)
8062 (error nil))
8063 (org-end-of-subtree t t)))
8064 (setq end (point))
8065 (goto-char beg0)
8066 (when (> end beg)
8067 (setq org-subtree-clip-folded folded)
8068 (when (or cut force-store-markers)
8069 (org-save-markers-in-region beg end))
8070 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8071 (setq org-subtree-clip (current-kill 0))
8072 (message "%s: Subtree(s) with %d characters"
8073 (if cut "Cut" "Copied")
8074 (length org-subtree-clip)))))
8076 (defun org-paste-subtree (&optional level tree for-yank)
8077 "Paste the clipboard as a subtree, with modification of headline level.
8078 The entire subtree is promoted or demoted in order to match a new headline
8079 level.
8081 If the cursor is at the beginning of a headline, the same level as
8082 that headline is used to paste the tree.
8084 If not, the new level is derived from the *visible* headings
8085 before and after the insertion point, and taken to be the inferior headline
8086 level of the two. So if the previous visible heading is level 3 and the
8087 next is level 4 (or vice versa), level 4 will be used for insertion.
8088 This makes sure that the subtree remains an independent subtree and does
8089 not swallow low level entries.
8091 You can also force a different level, either by using a numeric prefix
8092 argument, or by inserting the heading marker by hand. For example, if the
8093 cursor is after \"*****\", then the tree will be shifted to level 5.
8095 If optional TREE is given, use this text instead of the kill ring.
8097 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8098 move back over whitespace before inserting, and move point to the end of
8099 the inserted text when done."
8100 (interactive "P")
8101 (setq tree (or tree (and kill-ring (current-kill 0))))
8102 (unless (org-kill-is-subtree-p tree)
8103 (error "%s"
8104 (substitute-command-keys
8105 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8106 (org-with-limited-levels
8107 (let* ((visp (not (outline-invisible-p)))
8108 (txt tree)
8109 (^re_ "\\(\\*+\\)[ \t]*")
8110 (old-level (if (string-match org-outline-regexp-bol txt)
8111 (- (match-end 0) (match-beginning 0) 1)
8112 -1))
8113 (force-level (cond (level (prefix-numeric-value level))
8114 ((and (looking-at "[ \t]*$")
8115 (string-match
8116 "^\\*+$" (buffer-substring
8117 (point-at-bol) (point))))
8118 (- (match-end 1) (match-beginning 1)))
8119 ((and (bolp)
8120 (looking-at org-outline-regexp))
8121 (- (match-end 0) (point) 1))))
8122 (previous-level (save-excursion
8123 (condition-case nil
8124 (progn
8125 (outline-previous-visible-heading 1)
8126 (if (looking-at ^re_)
8127 (- (match-end 0) (match-beginning 0) 1)
8129 (error 1))))
8130 (next-level (save-excursion
8131 (condition-case nil
8132 (progn
8133 (or (looking-at org-outline-regexp)
8134 (outline-next-visible-heading 1))
8135 (if (looking-at ^re_)
8136 (- (match-end 0) (match-beginning 0) 1)
8138 (error 1))))
8139 (new-level (or force-level (max previous-level next-level)))
8140 (shift (if (or (= old-level -1)
8141 (= new-level -1)
8142 (= old-level new-level))
8144 (- new-level old-level)))
8145 (delta (if (> shift 0) -1 1))
8146 (func (if (> shift 0) 'org-demote 'org-promote))
8147 (org-odd-levels-only nil)
8148 beg end newend)
8149 ;; Remove the forced level indicator
8150 (if force-level
8151 (delete-region (point-at-bol) (point)))
8152 ;; Paste
8153 (beginning-of-line (if (bolp) 1 2))
8154 (setq beg (point))
8155 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8156 (insert-before-markers txt)
8157 (unless (string-match "\n\\'" txt) (insert "\n"))
8158 (setq newend (point))
8159 (org-reinstall-markers-in-region beg)
8160 (setq end (point))
8161 (goto-char beg)
8162 (skip-chars-forward " \t\n\r")
8163 (setq beg (point))
8164 (if (and (outline-invisible-p) visp)
8165 (save-excursion (outline-show-heading)))
8166 ;; Shift if necessary
8167 (unless (= shift 0)
8168 (save-restriction
8169 (narrow-to-region beg end)
8170 (while (not (= shift 0))
8171 (org-map-region func (point-min) (point-max))
8172 (setq shift (+ delta shift)))
8173 (goto-char (point-min))
8174 (setq newend (point-max))))
8175 (when (or (org-called-interactively-p 'interactive) for-yank)
8176 (message "Clipboard pasted as level %d subtree" new-level))
8177 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8178 kill-ring
8179 (eq org-subtree-clip (current-kill 0))
8180 org-subtree-clip-folded)
8181 ;; The tree was folded before it was killed/copied
8182 (hide-subtree))
8183 (and for-yank (goto-char newend)))))
8185 (defun org-kill-is-subtree-p (&optional txt)
8186 "Check if the current kill is an outline subtree, or a set of trees.
8187 Returns nil if kill does not start with a headline, or if the first
8188 headline level is not the largest headline level in the tree.
8189 So this will actually accept several entries of equal levels as well,
8190 which is OK for `org-paste-subtree'.
8191 If optional TXT is given, check this string instead of the current kill."
8192 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8193 (re (org-get-limited-outline-regexp))
8194 (^re (concat "^" re))
8195 (start-level (and kill
8196 (string-match
8197 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8198 kill)
8199 (- (match-end 2) (match-beginning 2) 1)))
8200 (start (1+ (or (match-beginning 2) -1))))
8201 (if (not start-level)
8202 (progn
8203 nil) ;; does not even start with a heading
8204 (catch 'exit
8205 (while (setq start (string-match ^re kill (1+ start)))
8206 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8207 (throw 'exit nil)))
8208 t))))
8210 (defvar org-markers-to-move nil
8211 "Markers that should be moved with a cut-and-paste operation.
8212 Those markers are stored together with their positions relative to
8213 the start of the region.")
8215 (defun org-save-markers-in-region (beg end)
8216 "Check markers in region.
8217 If these markers are between BEG and END, record their position relative
8218 to BEG, so that after moving the block of text, we can put the markers back
8219 into place.
8220 This function gets called just before an entry or tree gets cut from the
8221 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8222 called immediately, to move the markers with the entries."
8223 (setq org-markers-to-move nil)
8224 (when (featurep 'org-clock)
8225 (org-clock-save-markers-for-cut-and-paste beg end))
8226 (when (featurep 'org-agenda)
8227 (org-agenda-save-markers-for-cut-and-paste beg end)))
8229 (defun org-check-and-save-marker (marker beg end)
8230 "Check if MARKER is between BEG and END.
8231 If yes, remember the marker and the distance to BEG."
8232 (when (and (marker-buffer marker)
8233 (equal (marker-buffer marker) (current-buffer)))
8234 (if (and (>= marker beg) (< marker end))
8235 (push (cons marker (- marker beg)) org-markers-to-move))))
8237 (defun org-reinstall-markers-in-region (beg)
8238 "Move all remembered markers to their position relative to BEG."
8239 (mapc (lambda (x)
8240 (move-marker (car x) (+ beg (cdr x))))
8241 org-markers-to-move)
8242 (setq org-markers-to-move nil))
8244 (defun org-narrow-to-subtree ()
8245 "Narrow buffer to the current subtree."
8246 (interactive)
8247 (save-excursion
8248 (save-match-data
8249 (org-with-limited-levels
8250 (narrow-to-region
8251 (progn (org-back-to-heading t) (point))
8252 (progn (org-end-of-subtree t t)
8253 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8254 (point)))))))
8256 (defun org-narrow-to-block ()
8257 "Narrow buffer to the current block."
8258 (interactive)
8259 (let* ((case-fold-search t)
8260 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8261 "^[ \t]*#\\+end_.*")))
8262 (if blockp
8263 (narrow-to-region (car blockp) (cdr blockp))
8264 (error "Not in a block"))))
8266 (eval-when-compile
8267 (defvar org-property-drawer-re))
8269 (defvar org-property-start-re) ;; defined below
8270 (defun org-clone-subtree-with-time-shift (n &optional shift)
8271 "Clone the task (subtree) at point N times.
8272 The clones will be inserted as siblings.
8274 In interactive use, the user will be prompted for the number of
8275 clones to be produced, and for a time SHIFT, which may be a
8276 repeater as used in time stamps, for example `+3d'.
8278 When a valid repeater is given and the entry contains any time
8279 stamps, the clones will become a sequence in time, with time
8280 stamps in the subtree shifted for each clone produced. If SHIFT
8281 is nil or the empty string, time stamps will be left alone. The
8282 ID property of the original subtree is removed.
8284 If the original subtree did contain time stamps with a repeater,
8285 the following will happen:
8286 - the repeater will be removed in each clone
8287 - an additional clone will be produced, with the current, unshifted
8288 date(s) in the entry.
8289 - the original entry will be placed *after* all the clones, with
8290 repeater intact.
8291 - the start days in the repeater in the original entry will be shifted
8292 to past the last clone.
8293 In this way you can spell out a number of instances of a repeating task,
8294 and still retain the repeater to cover future instances of the task."
8295 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8296 (let (beg end template task idprop
8297 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8298 (drawer-re org-drawer-regexp))
8299 (if (not (and (integerp n) (> n 0)))
8300 (error "Invalid number of replications %s" n))
8301 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8302 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8303 shift)))
8304 (error "Invalid shift specification %s" shift))
8305 (when doshift
8306 (setq shift-n (string-to-number (match-string 1 shift))
8307 shift-what (cdr (assoc (match-string 2 shift)
8308 '(("d" . day) ("w" . week)
8309 ("m" . month) ("y" . year))))))
8310 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8311 (setq nmin 1 nmax n)
8312 (org-back-to-heading t)
8313 (setq beg (point))
8314 (setq idprop (org-entry-get nil "ID"))
8315 (org-end-of-subtree t t)
8316 (or (bolp) (insert "\n"))
8317 (setq end (point))
8318 (setq template (buffer-substring beg end))
8319 (when (and doshift
8320 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8321 (delete-region beg end)
8322 (setq end beg)
8323 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8324 (goto-char end)
8325 (loop for n from nmin to nmax do
8326 ;; prepare clone
8327 (with-temp-buffer
8328 (insert template)
8329 (org-mode)
8330 (goto-char (point-min))
8331 (org-show-subtree)
8332 (and idprop (if org-clone-delete-id
8333 (org-entry-delete nil "ID")
8334 (org-id-get-create t)))
8335 (unless (= n 0)
8336 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8337 (kill-whole-line))
8338 (goto-char (point-min))
8339 (while (re-search-forward drawer-re nil t)
8340 (mapc (lambda (d)
8341 (org-remove-empty-drawer-at d (point))) org-drawers)))
8342 (goto-char (point-min))
8343 (when doshift
8344 (while (re-search-forward org-ts-regexp-both nil t)
8345 (org-timestamp-change (* n shift-n) shift-what))
8346 (unless (= n n-no-remove)
8347 (goto-char (point-min))
8348 (while (re-search-forward org-ts-regexp nil t)
8349 (save-excursion
8350 (goto-char (match-beginning 0))
8351 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8352 (delete-region (match-beginning 1) (match-end 1)))))))
8353 (setq task (buffer-string)))
8354 (insert task))
8355 (goto-char beg)))
8357 ;;; Outline Sorting
8359 (defun org-sort (with-case)
8360 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8361 Optional argument WITH-CASE means sort case-sensitively."
8362 (interactive "P")
8363 (cond
8364 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8365 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8367 (org-call-with-arg 'org-sort-entries with-case))))
8369 (defun org-sort-remove-invisible (s)
8370 "Remove invisible links from string S."
8371 (remove-text-properties 0 (length s) org-rm-props s)
8372 (while (string-match org-bracket-link-regexp s)
8373 (setq s (replace-match (if (match-end 2)
8374 (match-string 3 s)
8375 (match-string 1 s)) t t s)))
8376 (let ((st (format " %s " s)))
8377 (while (string-match org-emph-re st)
8378 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8379 (setq s (substring st 1 -1)))
8382 (defvar org-priority-regexp) ; defined later in the file
8384 (defvar org-after-sorting-entries-or-items-hook nil
8385 "Hook that is run after a bunch of entries or items have been sorted.
8386 When children are sorted, the cursor is in the parent line when this
8387 hook gets called. When a region or a plain list is sorted, the cursor
8388 will be in the first entry of the sorted region/list.")
8390 (defun org-sort-entries
8391 (&optional with-case sorting-type getkey-func compare-func property)
8392 "Sort entries on a certain level of an outline tree.
8393 If there is an active region, the entries in the region are sorted.
8394 Else, if the cursor is before the first entry, sort the top-level items.
8395 Else, the children of the entry at point are sorted.
8397 Sorting can be alphabetically, numerically, by date/time as given by
8398 a time stamp, by a property, by priority order, or by a custom function.
8400 The command prompts for the sorting type unless it has been given to the
8401 function through the SORTING-TYPE argument, which needs to be a character,
8402 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8403 precise meaning of each character:
8405 n Numerically, by converting the beginning of the entry/item to a number.
8406 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8407 o By order of TODO keywords.
8408 t By date/time, either the first active time stamp in the entry, or, if
8409 none exist, by the first inactive one.
8410 s By the scheduled date/time.
8411 d By deadline date/time.
8412 c By creation time, which is assumed to be the first inactive time stamp
8413 at the beginning of a line.
8414 p By priority according to the cookie.
8415 r By the value of a property.
8417 Capital letters will reverse the sort order.
8419 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8420 called with point at the beginning of the record. It must return either
8421 a string or a number that should serve as the sorting key for that record.
8423 Comparing entries ignores case by default. However, with an optional argument
8424 WITH-CASE, the sorting considers case as well.
8426 Sorting is done against the visible part of the headlines, it ignores hidden
8427 links."
8428 (interactive "P")
8429 (let ((case-func (if with-case 'identity 'downcase))
8430 (cmstr
8431 ;; The clock marker is lost when using `sort-subr', let's
8432 ;; store the clocking string.
8433 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8434 (save-excursion
8435 (goto-char org-clock-marker)
8436 (looking-back "^.*") (match-string-no-properties 0))))
8437 start beg end stars re re2
8438 txt what tmp)
8439 ;; Find beginning and end of region to sort
8440 (cond
8441 ((org-region-active-p)
8442 ;; we will sort the region
8443 (setq end (region-end)
8444 what "region")
8445 (goto-char (region-beginning))
8446 (if (not (org-at-heading-p)) (outline-next-heading))
8447 (setq start (point)))
8448 ((or (org-at-heading-p)
8449 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8450 ;; we will sort the children of the current headline
8451 (org-back-to-heading)
8452 (setq start (point)
8453 end (progn (org-end-of-subtree t t)
8454 (or (bolp) (insert "\n"))
8455 (org-back-over-empty-lines)
8456 (point))
8457 what "children")
8458 (goto-char start)
8459 (show-subtree)
8460 (outline-next-heading))
8462 ;; we will sort the top-level entries in this file
8463 (goto-char (point-min))
8464 (or (org-at-heading-p) (outline-next-heading))
8465 (setq start (point))
8466 (goto-char (point-max))
8467 (beginning-of-line 1)
8468 (when (looking-at ".*?\\S-")
8469 ;; File ends in a non-white line
8470 (end-of-line 1)
8471 (insert "\n"))
8472 (setq end (point-max))
8473 (setq what "top-level")
8474 (goto-char start)
8475 (show-all)))
8477 (setq beg (point))
8478 (if (>= beg end) (error "Nothing to sort"))
8480 (looking-at "\\(\\*+\\)")
8481 (setq stars (match-string 1)
8482 re (concat "^" (regexp-quote stars) " +")
8483 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8484 txt (buffer-substring beg end))
8485 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8486 (if (and (not (equal stars "*")) (string-match re2 txt))
8487 (error "Region to sort contains a level above the first entry"))
8489 (unless sorting-type
8490 (message
8491 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8492 [t]ime [s]cheduled [d]eadline [c]reated
8493 A/N/P/R/O/F/T/S/D/C means reversed:"
8494 what)
8495 (setq sorting-type (read-char-exclusive))
8497 (unless getkey-func
8498 (and (= (downcase sorting-type) ?f)
8499 (setq getkey-func
8500 (org-icompleting-read "Sort using function: "
8501 obarray 'fboundp t nil nil))
8502 (setq getkey-func (intern getkey-func))))
8504 (and (= (downcase sorting-type) ?r)
8505 (not property)
8506 (setq property
8507 (org-icompleting-read "Property: "
8508 (mapcar 'list (org-buffer-property-keys t))
8509 nil t))))
8511 (message "Sorting entries...")
8513 (save-restriction
8514 (narrow-to-region start end)
8515 (let ((dcst (downcase sorting-type))
8516 (case-fold-search nil)
8517 (now (current-time)))
8518 (sort-subr
8519 (/= dcst sorting-type)
8520 ;; This function moves to the beginning character of the "record" to
8521 ;; be sorted.
8522 (lambda nil
8523 (if (re-search-forward re nil t)
8524 (goto-char (match-beginning 0))
8525 (goto-char (point-max))))
8526 ;; This function moves to the last character of the "record" being
8527 ;; sorted.
8528 (lambda nil
8529 (save-match-data
8530 (condition-case nil
8531 (outline-forward-same-level 1)
8532 (error
8533 (goto-char (point-max))))))
8534 ;; This function returns the value that gets sorted against.
8535 (lambda nil
8536 (cond
8537 ((= dcst ?n)
8538 (if (looking-at org-complex-heading-regexp)
8539 (string-to-number (org-sort-remove-invisible (match-string 4)))
8540 nil))
8541 ((= dcst ?a)
8542 (if (looking-at org-complex-heading-regexp)
8543 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8544 nil))
8545 ((= dcst ?t)
8546 (let ((end (save-excursion (outline-next-heading) (point))))
8547 (if (or (re-search-forward org-ts-regexp end t)
8548 (re-search-forward org-ts-regexp-both end t))
8549 (org-time-string-to-seconds (match-string 0))
8550 (org-float-time now))))
8551 ((= dcst ?c)
8552 (let ((end (save-excursion (outline-next-heading) (point))))
8553 (if (re-search-forward
8554 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8555 end t)
8556 (org-time-string-to-seconds (match-string 0))
8557 (org-float-time now))))
8558 ((= dcst ?s)
8559 (let ((end (save-excursion (outline-next-heading) (point))))
8560 (if (re-search-forward org-scheduled-time-regexp end t)
8561 (org-time-string-to-seconds (match-string 1))
8562 (org-float-time now))))
8563 ((= dcst ?d)
8564 (let ((end (save-excursion (outline-next-heading) (point))))
8565 (if (re-search-forward org-deadline-time-regexp end t)
8566 (org-time-string-to-seconds (match-string 1))
8567 (org-float-time now))))
8568 ((= dcst ?p)
8569 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8570 (string-to-char (match-string 2))
8571 org-default-priority))
8572 ((= dcst ?r)
8573 (or (org-entry-get nil property) ""))
8574 ((= dcst ?o)
8575 (if (looking-at org-complex-heading-regexp)
8576 (- 9999 (length (member (match-string 2)
8577 org-todo-keywords-1)))))
8578 ((= dcst ?f)
8579 (if getkey-func
8580 (progn
8581 (setq tmp (funcall getkey-func))
8582 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8583 tmp)
8584 (error "Invalid key function `%s'" getkey-func)))
8585 (t (error "Invalid sorting type `%c'" sorting-type))))
8587 (cond
8588 ((= dcst ?a) 'string<)
8589 ((= dcst ?f) compare-func)
8590 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8591 (run-hooks 'org-after-sorting-entries-or-items-hook)
8592 ;; Reset the clock marker if needed
8593 (when cmstr
8594 (save-excursion
8595 (goto-char start)
8596 (search-forward cmstr nil t)
8597 (move-marker org-clock-marker (point))))
8598 (message "Sorting entries...done")))
8600 (defun org-do-sort (table what &optional with-case sorting-type)
8601 "Sort TABLE of WHAT according to SORTING-TYPE.
8602 The user will be prompted for the SORTING-TYPE if the call to this
8603 function does not specify it. WHAT is only for the prompt, to indicate
8604 what is being sorted. The sorting key will be extracted from
8605 the car of the elements of the table.
8606 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8607 (unless sorting-type
8608 (message
8609 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8610 what)
8611 (setq sorting-type (read-char-exclusive)))
8612 (let ((dcst (downcase sorting-type))
8613 extractfun comparefun)
8614 ;; Define the appropriate functions
8615 (cond
8616 ((= dcst ?n)
8617 (setq extractfun 'string-to-number
8618 comparefun (if (= dcst sorting-type) '< '>)))
8619 ((= dcst ?a)
8620 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8621 (lambda(x) (downcase (org-sort-remove-invisible x))))
8622 comparefun (if (= dcst sorting-type)
8623 'string<
8624 (lambda (a b) (and (not (string< a b))
8625 (not (string= a b)))))))
8626 ((= dcst ?t)
8627 (setq extractfun
8628 (lambda (x)
8629 (if (or (string-match org-ts-regexp x)
8630 (string-match org-ts-regexp-both x))
8631 (org-float-time
8632 (org-time-string-to-time (match-string 0 x)))
8634 comparefun (if (= dcst sorting-type) '< '>)))
8635 (t (error "Invalid sorting type `%c'" sorting-type)))
8637 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8638 table)
8639 (lambda (a b) (funcall comparefun (car a) (car b))))))
8642 ;;; The orgstruct minor mode
8644 ;; Define a minor mode which can be used in other modes in order to
8645 ;; integrate the org-mode structure editing commands.
8647 ;; This is really a hack, because the org-mode structure commands use
8648 ;; keys which normally belong to the major mode. Here is how it
8649 ;; works: The minor mode defines all the keys necessary to operate the
8650 ;; structure commands, but wraps the commands into a function which
8651 ;; tests if the cursor is currently at a headline or a plain list
8652 ;; item. If that is the case, the structure command is used,
8653 ;; temporarily setting many Org-mode variables like regular
8654 ;; expressions for filling etc. However, when any of those keys is
8655 ;; used at a different location, function uses `key-binding' to look
8656 ;; up if the key has an associated command in another currently active
8657 ;; keymap (minor modes, major mode, global), and executes that
8658 ;; command. There might be problems if any of the keys is otherwise
8659 ;; used as a prefix key.
8661 (defcustom orgstruct-heading-prefix-regexp ""
8662 "Regexp that matches the custom prefix of Org headlines in
8663 orgstruct(++)-mode."
8664 :group 'org
8665 :version "24.4"
8666 :package-version '(Org . "8.0")
8667 :type 'string)
8668 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8670 (defcustom orgstruct-setup-hook nil
8671 "Hook run after orgstruct-mode-map is filled."
8672 :group 'org
8673 :version "24.4"
8674 :package-version '(Org . "8.0")
8675 :type 'hook)
8677 (defvar orgstruct-initialized nil)
8679 (defvar org-local-vars nil
8680 "List of local variables, for use by `orgstruct-mode'.")
8682 ;;;###autoload
8683 (define-minor-mode orgstruct-mode
8684 "Toggle the minor mode `orgstruct-mode'.
8685 This mode is for using Org-mode structure commands in other
8686 modes. The following keys behave as if Org-mode were active, if
8687 the cursor is on a headline, or on a plain list item (both as
8688 defined by Org-mode)."
8689 nil " OrgStruct" (make-sparse-keymap)
8690 (when orgstruct-mode
8691 (org-load-modules-maybe)
8692 (unless orgstruct-initialized
8693 (orgstruct-setup)
8694 (setq orgstruct-initialized t))))
8696 ;;;###autoload
8697 (defun turn-on-orgstruct ()
8698 "Unconditionally turn on `orgstruct-mode'."
8699 (orgstruct-mode 1))
8701 (defvar org-fb-vars nil)
8702 (make-variable-buffer-local 'org-fb-vars)
8703 (defun orgstruct++-mode (&optional arg)
8704 "Toggle `orgstruct-mode', the enhanced version of it.
8705 In addition to setting orgstruct-mode, this also exports all
8706 indentation and autofilling variables from org-mode into the
8707 buffer. It will also recognize item context in multiline items."
8708 (interactive "P")
8709 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8710 (if (< arg 1)
8711 (progn (orgstruct-mode -1)
8712 (mapc (lambda(v)
8713 (org-set-local (car v)
8714 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8715 org-fb-vars))
8716 (orgstruct-mode 1)
8717 (setq org-fb-vars nil)
8718 (let (var val)
8719 (mapc
8720 (lambda (x)
8721 (when (string-match
8722 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8723 (symbol-name (car x)))
8724 (setq var (car x) val (nth 1 x))
8725 (push (list var `(quote ,(eval var))) org-fb-vars)
8726 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8727 org-local-vars)
8728 (org-set-local 'orgstruct-is-++ t))))
8730 (defvar orgstruct-is-++ nil
8731 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8732 (make-variable-buffer-local 'orgstruct-is-++)
8734 ;;;###autoload
8735 (defun turn-on-orgstruct++ ()
8736 "Unconditionally turn on `orgstruct++-mode'."
8737 (orgstruct++-mode 1))
8739 (defun orgstruct-error ()
8740 "Error when there is no default binding for a structure key."
8741 (interactive)
8742 (error "This key has no function outside structure elements"))
8744 (defun orgstruct-setup ()
8745 "Setup orgstruct keymap."
8746 (dolist (f
8747 '("org-meta"
8748 "org-shift"
8749 "org-shiftmeta"
8750 org-shifttab
8751 org-backward-element
8752 org-backward-heading-same-level
8753 org-ctrl-c-ret
8754 org-ctrl-c-minus
8755 org-ctrl-c-star
8756 org-cycle
8757 org-forward-heading-same-level
8758 org-insert-heading
8759 org-insert-heading-respect-content
8760 org-kill-note-or-show-branches
8761 org-mark-subtree
8762 org-narrow-to-subtree
8763 org-promote-subtree
8764 org-reveal
8765 org-show-subtree
8766 org-sort
8767 org-up-element
8768 outline-demote
8769 outline-next-visible-heading
8770 outline-previous-visible-heading
8771 outline-promote
8772 outline-up-heading
8773 show-children))
8774 (dolist (f (if (stringp f)
8775 (let ((flist))
8776 (dolist (postfix
8777 '("-return" "tab" "left" "right" "up" "down")
8778 flist)
8779 (let ((f (intern (concat f postfix))))
8780 (when (fboundp f)
8781 (push f flist)))))
8782 (list f)))
8783 (dolist (binding (nconc (where-is-internal f org-mode-map)
8784 (where-is-internal f outline-mode-map)))
8785 ;; TODO use local-function-key-map
8786 (dolist (rep '(("<tab>" . "TAB")
8787 ("<return>" . "RET")
8788 ("<escape>" . "ESC")
8789 ("<delete>" . "DEL")))
8790 (setq binding (read-kbd-macro (replace-regexp-in-string
8791 (regexp-quote (car rep))
8792 (cdr rep)
8793 (key-description binding)))))
8794 (let ((key (lookup-key orgstruct-mode-map binding)))
8795 (when (or (not key) (numberp key))
8796 (condition-case nil
8797 (org-defkey orgstruct-mode-map
8798 binding
8799 (orgstruct-make-binding f binding))
8800 (error nil)))))))
8801 (run-hooks 'orgstruct-setup-hook))
8803 (defun orgstruct-make-binding (fun key)
8804 "Create a function for binding in the structure minor mode.
8805 FUN is the command to call inside a table. KEY is the key that
8806 should be checked in for a command to execute outside of tables."
8807 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8808 (let ((nname name)
8809 (i 0))
8810 (while (fboundp (intern nname))
8811 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8812 (setq name (intern nname)))
8813 (eval
8814 (let ((bindings '((org-heading-regexp
8815 (concat "^"
8816 orgstruct-heading-prefix-regexp
8817 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8818 (org-outline-regexp
8819 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8820 (org-outline-regexp-bol
8821 (concat "^" org-outline-regexp))
8822 (outline-regexp org-outline-regexp)
8823 (outline-heading-end-regexp "\n")
8824 (outline-level 'outline-level)
8825 (outline-heading-alist))))
8826 `(defun ,name (arg)
8827 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8828 "Outside of structure, run the binding of `"
8829 (key-description key) "'.")
8830 (interactive "p")
8831 (unless
8832 (let* ,bindings
8833 (when (org-context-p 'headline 'item
8834 ,(when (memq fun '(org-insert-heading))
8835 '(when orgstruct-is-++
8836 'item-body)))
8837 (org-run-like-in-org-mode
8838 (lambda ()
8839 (interactive)
8840 (let* ,bindings
8841 (call-interactively ',fun))))
8843 (let* ((orgstruct-mode)
8844 (binding (key-binding ,key)))
8845 (if (keymapp binding)
8846 (set-temporary-overlay-map binding)
8847 (call-interactively
8848 (or binding 'orgstruct-error))))))))
8849 name))
8851 (defun org-contextualize-keys (alist contexts)
8852 "Return valid elements in ALIST depending on CONTEXTS.
8854 `org-agenda-custom-commands' or `org-capture-templates' are the
8855 values used for ALIST, and `org-agenda-custom-commands-contexts'
8856 or `org-capture-templates-contexts' are the associated contexts
8857 definitions."
8858 (let ((contexts
8859 ;; normalize contexts
8860 (mapcar
8861 (lambda(c) (cond ((listp (cadr c))
8862 (list (car c) (car c) (cadr c)))
8863 ((string= "" (cadr c))
8864 (list (car c) (car c) (caddr c)))
8865 (t c))) contexts))
8866 (a alist) c r s)
8867 ;; loop over all commands or templates
8868 (while (setq c (pop a))
8869 (let (vrules repl)
8870 (cond
8871 ((not (assoc (car c) contexts))
8872 (push c r))
8873 ((and (assoc (car c) contexts)
8874 (setq vrules (org-contextualize-validate-key
8875 (car c) contexts)))
8876 (mapc (lambda (vr)
8877 (when (not (equal (car vr) (cadr vr)))
8878 (setq repl vr))) vrules)
8879 (if (not repl) (push c r)
8880 (push (cadr repl) s)
8881 (push
8882 (cons (car c)
8883 (cdr (or (assoc (cadr repl) alist)
8884 (error "Undefined key `%s' as contextual replacement for `%s'"
8885 (cadr repl) (car c)))))
8886 r))))))
8887 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8888 (delq
8890 (delete-dups
8891 (mapcar (lambda (x)
8892 (let ((tpl (car x)))
8893 (when (not (delq
8895 (mapcar (lambda(y)
8896 (equal y tpl)) s))) x)))
8897 (reverse r))))))
8899 (defun org-contextualize-validate-key (key contexts)
8900 "Check CONTEXTS for agenda or capture KEY."
8901 (let (r rr res)
8902 (while (setq r (pop contexts))
8903 (mapc
8904 (lambda (rr)
8905 (when
8906 (and (equal key (car r))
8907 (if (functionp rr) (funcall rr)
8908 (or (and (eq (car rr) 'in-file)
8909 (buffer-file-name)
8910 (string-match (cdr rr) (buffer-file-name)))
8911 (and (eq (car rr) 'in-mode)
8912 (string-match (cdr rr) (symbol-name major-mode)))
8913 (and (eq (car rr) 'in-buffer)
8914 (string-match (cdr rr) (buffer-name)))
8915 (when (and (eq (car rr) 'not-in-file)
8916 (buffer-file-name))
8917 (not (string-match (cdr rr) (buffer-file-name))))
8918 (when (eq (car rr) 'not-in-mode)
8919 (not (string-match (cdr rr) (symbol-name major-mode))))
8920 (when (eq (car rr) 'not-in-buffer)
8921 (not (string-match (cdr rr) (buffer-name)))))))
8922 (push r res)))
8923 (car (last r))))
8924 (delete-dups (delq nil res))))
8926 (defun org-context-p (&rest contexts)
8927 "Check if local context is any of CONTEXTS.
8928 Possible values in the list of contexts are `table', `headline', and `item'."
8929 (let ((pos (point)))
8930 (goto-char (point-at-bol))
8931 (prog1 (or (and (memq 'table contexts)
8932 (looking-at "[ \t]*|"))
8933 (and (memq 'headline contexts)
8934 (looking-at org-outline-regexp))
8935 (and (memq 'item contexts)
8936 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8937 (and (memq 'item-body contexts)
8938 (org-in-item-p)))
8939 (goto-char pos))))
8941 (defun org-get-local-variables ()
8942 "Return a list of all local variables in an Org mode buffer."
8943 (let (varlist)
8944 (with-current-buffer (get-buffer-create "*Org tmp*")
8945 (erase-buffer)
8946 (org-mode)
8947 (setq varlist (buffer-local-variables)))
8948 (kill-buffer "*Org tmp*")
8949 (delq nil
8950 (mapcar
8951 (lambda (x)
8952 (setq x
8953 (if (symbolp x)
8954 (list x)
8955 (list (car x) (cdr x))))
8956 (if (and (not (get (car x) 'org-state))
8957 (string-match
8958 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8959 (symbol-name (car x))))
8960 x nil))
8961 varlist))))
8963 (defun org-clone-local-variables (from-buffer &optional regexp)
8964 "Clone local variables from FROM-BUFFER.
8965 Optional argument REGEXP selects variables to clone."
8966 (mapc
8967 (lambda (pair)
8968 (and (symbolp (car pair))
8969 (or (null regexp)
8970 (string-match regexp (symbol-name (car pair))))
8971 (set (make-local-variable (car pair))
8972 (cdr pair))))
8973 (buffer-local-variables from-buffer)))
8975 ;;;###autoload
8976 (defun org-run-like-in-org-mode (cmd)
8977 "Run a command, pretending that the current buffer is in Org-mode.
8978 This will temporarily bind local variables that are typically bound in
8979 Org-mode to the values they have in Org-mode, and then interactively
8980 call CMD."
8981 (org-load-modules-maybe)
8982 (unless org-local-vars
8983 (setq org-local-vars (org-get-local-variables)))
8984 (let (binds)
8985 (dolist (var org-local-vars)
8986 (when (or (not (boundp (car var)))
8987 (eq (symbol-value (car var))
8988 (default-value (car var))))
8989 (push (list (car var) `(quote ,(cadr var))) binds)))
8990 (eval `(let ,binds
8991 (call-interactively (quote ,cmd))))))
8993 ;;;; Archiving
8995 (defun org-get-category (&optional pos force-refresh)
8996 "Get the category applying to position POS."
8997 (save-match-data
8998 (if force-refresh (org-refresh-category-properties))
8999 (let ((pos (or pos (point))))
9000 (or (get-text-property pos 'org-category)
9001 (progn (org-refresh-category-properties)
9002 (get-text-property pos 'org-category))))))
9004 (defun org-refresh-category-properties ()
9005 "Refresh category text properties in the buffer."
9006 (let ((case-fold-search t)
9007 (inhibit-read-only t)
9008 (def-cat (cond
9009 ((null org-category)
9010 (if buffer-file-name
9011 (file-name-sans-extension
9012 (file-name-nondirectory buffer-file-name))
9013 "???"))
9014 ((symbolp org-category) (symbol-name org-category))
9015 (t org-category)))
9016 beg end cat pos optionp)
9017 (org-with-silent-modifications
9018 (save-excursion
9019 (save-restriction
9020 (widen)
9021 (goto-char (point-min))
9022 (put-text-property (point) (point-max) 'org-category def-cat)
9023 (while (re-search-forward
9024 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9025 (setq pos (match-end 0)
9026 optionp (equal (char-after (match-beginning 0)) ?#)
9027 cat (org-trim (match-string 2)))
9028 (if optionp
9029 (setq beg (point-at-bol) end (point-max))
9030 (org-back-to-heading t)
9031 (setq beg (point) end (org-end-of-subtree t t)))
9032 (put-text-property beg end 'org-category cat)
9033 (put-text-property beg end 'org-category-position beg)
9034 (goto-char pos)))))))
9036 (defun org-refresh-properties (dprop tprop)
9037 "Refresh buffer text properties.
9038 DPROP is the drawer property and TPROP is the corresponding text
9039 property to set."
9040 (let ((case-fold-search t)
9041 (inhibit-read-only t) p)
9042 (org-with-silent-modifications
9043 (save-excursion
9044 (save-restriction
9045 (widen)
9046 (goto-char (point-min))
9047 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9048 (setq p (org-match-string-no-properties 1))
9049 (save-excursion
9050 (org-back-to-heading t)
9051 (put-text-property
9052 (point-at-bol) (point-at-eol) tprop p))))))))
9055 ;;;; Link Stuff
9057 ;;; Link abbreviations
9059 (defun org-link-expand-abbrev (link)
9060 "Apply replacements as defined in `org-link-abbrev-alist'."
9061 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9062 (let* ((key (match-string 1 link))
9063 (as (or (assoc key org-link-abbrev-alist-local)
9064 (assoc key org-link-abbrev-alist)))
9065 (tag (and (match-end 2) (match-string 3 link)))
9066 rpl)
9067 (if (not as)
9068 link
9069 (setq rpl (cdr as))
9070 (cond
9071 ((symbolp rpl) (funcall rpl tag))
9072 ((string-match "%(\\([^)]+\\))" rpl)
9073 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9074 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9075 ((string-match "%h" rpl)
9076 (replace-match (url-hexify-string (or tag "")) t t rpl))
9077 (t (concat rpl tag)))))
9078 link))
9080 ;;; Storing and inserting links
9082 (defvar org-insert-link-history nil
9083 "Minibuffer history for links inserted with `org-insert-link'.")
9085 (defvar org-stored-links nil
9086 "Contains the links stored with `org-store-link'.")
9088 (defvar org-store-link-plist nil
9089 "Plist with info about the most recently link created with `org-store-link'.")
9091 (defvar org-link-protocols nil
9092 "Link protocols added to Org-mode using `org-add-link-type'.")
9094 (defvar org-store-link-functions nil
9095 "List of functions that are called to create and store a link.
9096 Each function will be called in turn until one returns a non-nil
9097 value. Each function should check if it is responsible for creating
9098 this link (for example by looking at the major mode).
9099 If not, it must exit and return nil.
9100 If yes, it should return a non-nil value after a calling
9101 `org-store-link-props' with a list of properties and values.
9102 Special properties are:
9104 :type The link prefix, like \"http\". This must be given.
9105 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9106 This is obligatory as well.
9107 :description Optional default description for the second pair
9108 of brackets in an Org-mode link. The user can still change
9109 this when inserting this link into an Org-mode buffer.
9111 In addition to these, any additional properties can be specified
9112 and then used in capture templates.")
9114 (defun org-add-link-type (type &optional follow export)
9115 "Add TYPE to the list of `org-link-types'.
9116 Re-compute all regular expressions depending on `org-link-types'
9118 FOLLOW and EXPORT are two functions.
9120 FOLLOW should take the link path as the single argument and do whatever
9121 is necessary to follow the link, for example find a file or display
9122 a mail message.
9124 EXPORT should format the link path for export to one of the export formats.
9125 It should be a function accepting three arguments:
9127 path the path of the link, the text after the prefix (like \"http:\")
9128 desc the description of the link, if any, or a description added by
9129 org-export-normalize-links if there is none
9130 format the export format, a symbol like `html' or `latex' or `ascii'..
9132 The function may use the FORMAT information to return different values
9133 depending on the format. The return value will be put literally into
9134 the exported file. If the return value is nil, this means Org should
9135 do what it normally does with links which do not have EXPORT defined.
9137 Org-mode has a built-in default for exporting links. If you are happy with
9138 this default, there is no need to define an export function for the link
9139 type. For a simple example of an export function, see `org-bbdb.el'."
9140 (add-to-list 'org-link-types type t)
9141 (org-make-link-regexps)
9142 (if (assoc type org-link-protocols)
9143 (setcdr (assoc type org-link-protocols) (list follow export))
9144 (push (list type follow export) org-link-protocols)))
9146 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9147 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9149 ;;;###autoload
9150 (defun org-store-link (arg)
9151 "\\<org-mode-map>Store an org-link to the current location.
9152 This link is added to `org-stored-links' and can later be inserted
9153 into an org-buffer with \\[org-insert-link].
9155 For some link types, a prefix arg is interpreted.
9156 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9157 For file links, arg negates `org-context-in-file-links'.
9159 A double prefix arg force skipping storing functions that are not
9160 part of Org's core."
9161 (interactive "P")
9162 (org-load-modules-maybe)
9163 (setq org-store-link-plist nil) ; reset
9164 (org-with-limited-levels
9165 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9166 (cond
9167 ((and (not (equal arg '(16)))
9168 (setq sfuns
9169 (delq
9170 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9171 org-store-link-functions))
9172 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9173 (or (and (cdr sfuns)
9174 (funcall (intern
9175 (completing-read "Which function for creating the link? "
9176 sfunsn t (car sfunsn)))))
9177 (funcall (caar sfuns)))
9178 (setq link (plist-get org-store-link-plist :link)
9179 desc (or (plist-get org-store-link-plist :description) link))))
9180 ((org-src-edit-buffer-p)
9181 (let (label gc)
9182 (while (or (not label)
9183 (save-excursion
9184 (save-restriction
9185 (widen)
9186 (goto-char (point-min))
9187 (re-search-forward
9188 (regexp-quote (format org-coderef-label-format label))
9189 nil t))))
9190 (when label (message "Label exists already") (sit-for 2))
9191 (setq label (read-string "Code line label: " label)))
9192 (end-of-line 1)
9193 (setq link (format org-coderef-label-format label))
9194 (setq gc (- 79 (length link)))
9195 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9196 (insert link)
9197 (setq link (concat "(" label ")") desc nil)))
9199 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9200 ;; We are in the agenda, link to referenced location
9201 (let ((m (or (get-text-property (point) 'org-hd-marker)
9202 (get-text-property (point) 'org-marker))))
9203 (when m
9204 (org-with-point-at m
9205 (setq agenda-link
9206 (if (org-called-interactively-p 'any)
9207 (call-interactively 'org-store-link)
9208 (org-store-link nil)))))))
9210 ((eq major-mode 'calendar-mode)
9211 (let ((cd (calendar-cursor-to-date)))
9212 (setq link
9213 (format-time-string
9214 (car org-time-stamp-formats)
9215 (apply 'encode-time
9216 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9217 nil nil nil))))
9218 (org-store-link-props :type "calendar" :date cd)))
9220 ((eq major-mode 'help-mode)
9221 (setq link (concat "help:" (save-excursion
9222 (goto-char (point-min))
9223 (looking-at "^[^ ]+")
9224 (match-string 0))))
9225 (org-store-link-props :type "help"))
9227 ((eq major-mode 'w3-mode)
9228 (setq cpltxt (if (and (buffer-name)
9229 (not (string-match "Untitled" (buffer-name))))
9230 (buffer-name)
9231 (url-view-url t))
9232 link (url-view-url t))
9233 (org-store-link-props :type "w3" :url (url-view-url t)))
9235 ((setq search (run-hook-with-args-until-success
9236 'org-create-file-search-functions))
9237 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9238 "::" search))
9239 (setq cpltxt (or description link)))
9241 ((eq major-mode 'image-mode)
9242 (setq cpltxt (concat "file:"
9243 (abbreviate-file-name buffer-file-name))
9244 link cpltxt)
9245 (org-store-link-props :type "image" :file buffer-file-name))
9247 ((eq major-mode 'dired-mode)
9248 ;; link to the file in the current line
9249 (let ((file (dired-get-filename nil t)))
9250 (setq file (if file
9251 (abbreviate-file-name
9252 (expand-file-name (dired-get-filename nil t)))
9253 ;; otherwise, no file so use current directory.
9254 default-directory))
9255 (setq cpltxt (concat "file:" file)
9256 link cpltxt)))
9258 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9259 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9260 (cond
9261 ((org-in-regexp "<<\\(.*?\\)>>")
9262 (setq cpltxt
9263 (concat "file:"
9264 (abbreviate-file-name
9265 (buffer-file-name (buffer-base-buffer)))
9266 "::" (match-string 1))
9267 link cpltxt))
9268 ((and (featurep 'org-id)
9269 (or (eq org-id-link-to-org-use-id t)
9270 (and (org-called-interactively-p 'any)
9271 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9272 (and (eq org-id-link-to-org-use-id
9273 'create-if-interactive-and-no-custom-id)
9274 (not custom-id))))
9275 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9276 ;; We can make a link using the ID.
9277 (setq link (condition-case nil
9278 (prog1 (org-id-store-link)
9279 (setq desc (plist-get org-store-link-plist :description)))
9280 (error
9281 ;; probably before first headline, link to file only
9282 (concat "file:"
9283 (abbreviate-file-name
9284 (buffer-file-name (buffer-base-buffer))))))))
9286 ;; Just link to current headline
9287 (setq cpltxt (concat "file:"
9288 (abbreviate-file-name
9289 (buffer-file-name (buffer-base-buffer)))))
9290 ;; Add a context search string
9291 (when (org-xor org-context-in-file-links arg)
9292 (let* ((ee (org-element-at-point))
9293 (et (org-element-type ee))
9294 (ev (plist-get (cadr ee) :value)))
9295 (setq txt (cond
9296 ((org-at-heading-p) nil)
9297 ((eq et 'keyword) ev)
9298 ((org-region-active-p)
9299 (buffer-substring (region-beginning) (region-end)))))
9300 (when (or (null txt) (string-match "\\S-" txt))
9301 (setq cpltxt
9302 (concat cpltxt "::"
9303 (condition-case nil
9304 (org-make-org-heading-search-string txt)
9305 (error "")))
9306 desc (or (and (eq et 'keyword) ev)
9307 (nth 4 (ignore-errors (org-heading-components)))
9308 "NONE")))))
9309 (if (string-match "::\\'" cpltxt)
9310 (setq cpltxt (substring cpltxt 0 -2)))
9311 (setq link cpltxt))))
9313 ((buffer-file-name (buffer-base-buffer))
9314 ;; Just link to this file here.
9315 (setq cpltxt (concat "file:"
9316 (abbreviate-file-name
9317 (buffer-file-name (buffer-base-buffer)))))
9318 ;; Add a context string
9319 (when (org-xor org-context-in-file-links arg)
9320 (setq txt (if (org-region-active-p)
9321 (buffer-substring (region-beginning) (region-end))
9322 (buffer-substring (point-at-bol) (point-at-eol))))
9323 ;; Only use search option if there is some text.
9324 (when (string-match "\\S-" txt)
9325 (setq cpltxt
9326 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9327 desc "NONE")))
9328 (setq link cpltxt))
9330 ((org-called-interactively-p 'interactive)
9331 (user-error "No method for storing a link from this buffer"))
9333 (t (setq link nil)))
9335 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9336 (setq link (or link cpltxt)
9337 desc (or desc cpltxt))
9338 (cond ((equal desc "NONE") (setq desc nil))
9339 ((string-match org-bracket-link-regexp desc)
9340 (setq desc (replace-regexp-in-string
9341 org-bracket-link-regexp
9342 (concat "\\3" (if (equal (length (match-string 0 desc))
9343 (length desc)) "*" "")) desc))))
9345 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9346 (progn
9347 (setq org-stored-links
9348 (cons (list link desc) org-stored-links))
9349 (message "Stored: %s" (or desc link))
9350 (when custom-id
9351 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9352 "::#" custom-id))
9353 (setq org-stored-links
9354 (cons (list link desc) org-stored-links))))
9355 (or agenda-link (and link (org-make-link-string link desc)))))))
9357 (defun org-store-link-props (&rest plist)
9358 "Store link properties, extract names and addresses."
9359 (let (x adr)
9360 (when (setq x (plist-get plist :from))
9361 (setq adr (mail-extract-address-components x))
9362 (setq plist (plist-put plist :fromname (car adr)))
9363 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9364 (when (setq x (plist-get plist :to))
9365 (setq adr (mail-extract-address-components x))
9366 (setq plist (plist-put plist :toname (car adr)))
9367 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9368 (let ((from (plist-get plist :from))
9369 (to (plist-get plist :to)))
9370 (when (and from to org-from-is-user-regexp)
9371 (setq plist
9372 (plist-put plist :fromto
9373 (if (string-match org-from-is-user-regexp from)
9374 (concat "to %t")
9375 (concat "from %f"))))))
9376 (setq org-store-link-plist plist))
9378 (defun org-add-link-props (&rest plist)
9379 "Add these properties to the link property list."
9380 (let (key value)
9381 (while plist
9382 (setq key (pop plist) value (pop plist))
9383 (setq org-store-link-plist
9384 (plist-put org-store-link-plist key value)))))
9386 (defun org-email-link-description (&optional fmt)
9387 "Return the description part of an email link.
9388 This takes information from `org-store-link-plist' and formats it
9389 according to FMT (default from `org-email-link-description-format')."
9390 (setq fmt (or fmt org-email-link-description-format))
9391 (let* ((p org-store-link-plist)
9392 (to (plist-get p :toaddress))
9393 (from (plist-get p :fromaddress))
9394 (table
9395 (list
9396 (cons "%c" (plist-get p :fromto))
9397 (cons "%F" (plist-get p :from))
9398 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9399 (cons "%T" (plist-get p :to))
9400 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9401 (cons "%s" (plist-get p :subject))
9402 (cons "%d" (plist-get p :date))
9403 (cons "%m" (plist-get p :message-id)))))
9404 (when (string-match "%c" fmt)
9405 ;; Check if the user wrote this message
9406 (if (and org-from-is-user-regexp from to
9407 (save-match-data (string-match org-from-is-user-regexp from)))
9408 (setq fmt (replace-match "to %t" t t fmt))
9409 (setq fmt (replace-match "from %f" t t fmt))))
9410 (org-replace-escapes fmt table)))
9412 (defun org-make-org-heading-search-string (&optional string)
9413 "Make search string for the current headline or STRING."
9414 (let ((s (or string
9415 (and (derived-mode-p 'org-mode)
9416 (save-excursion
9417 (org-back-to-heading t)
9418 (org-element-property :raw-value (org-element-at-point))))))
9419 (lines org-context-in-file-links))
9420 (or string (setq s (concat "*" s))) ; Add * for headlines
9421 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9422 (when (and string (integerp lines) (> lines 0))
9423 (let ((slines (org-split-string s "\n")))
9424 (when (< lines (length slines))
9425 (setq s (mapconcat
9426 'identity
9427 (reverse (nthcdr (- (length slines) lines)
9428 (reverse slines))) "\n")))))
9429 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9431 (defun org-make-link-string (link &optional description)
9432 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9433 (unless (string-match "\\S-" link)
9434 (error "Empty link"))
9435 (when (and description
9436 (stringp description)
9437 (not (string-match "\\S-" description)))
9438 (setq description nil))
9439 (when (stringp description)
9440 ;; Remove brackets from the description, they are fatal.
9441 (while (string-match "\\[" description)
9442 (setq description (replace-match "{" t t description)))
9443 (while (string-match "\\]" description)
9444 (setq description (replace-match "}" t t description))))
9445 (when (equal link description)
9446 ;; No description needed, it is identical
9447 (setq description nil))
9448 (when (and (not description)
9449 (not (string-match (org-image-file-name-regexp) link))
9450 (not (equal link (org-link-escape link))))
9451 (setq description (org-extract-attributes link)))
9452 (setq link
9453 (cond ((string-match (org-image-file-name-regexp) link) link)
9454 ((string-match org-link-types-re link)
9455 (concat (match-string 1 link)
9456 (org-link-escape (substring link (match-end 1)))))
9457 (t (org-link-escape link))))
9458 (concat "[[" link "]"
9459 (if description (concat "[" description "]") "")
9460 "]"))
9462 (defconst org-link-escape-chars
9463 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9464 "List of characters that should be escaped in link.
9465 This is the list that is used for internal purposes.")
9467 (defconst org-link-escape-chars-browser
9468 '(?\ )
9469 "List of escapes for characters that are problematic in links.
9470 This is the list that is used before handing over to the browser.")
9472 (defun org-link-escape (text &optional table merge)
9473 "Return percent escaped representation of TEXT.
9474 TEXT is a string with the text to escape.
9475 Optional argument TABLE is a list with characters that should be
9476 escaped. When nil, `org-link-escape-chars' is used.
9477 If optional argument MERGE is set, merge TABLE into
9478 `org-link-escape-chars'."
9479 (cond
9480 ((and table merge)
9481 (mapc (lambda (defchr)
9482 (unless (member defchr table)
9483 (setq table (cons defchr table)))) org-link-escape-chars))
9484 ((null table)
9485 (setq table org-link-escape-chars)))
9486 (mapconcat
9487 (lambda (char)
9488 (if (or (member char table)
9489 (and (or (< char 32) (= char 37) (> char 126))
9490 org-url-hexify-p))
9491 (mapconcat (lambda (sequence-element)
9492 (format "%%%.2X" sequence-element))
9493 (or (encode-coding-char char 'utf-8)
9494 (error "Unable to percent escape character: %s"
9495 (char-to-string char))) "")
9496 (char-to-string char))) text ""))
9498 (defun org-link-unescape (str)
9499 "Unhex hexified Unicode strings as returned from the JavaScript function
9500 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9501 (unless (and (null str) (string= "" str))
9502 (let ((pos 0) (case-fold-search t) unhexed)
9503 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9504 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9505 (setq str (replace-match unhexed t t str))
9506 (setq pos (+ pos (length unhexed))))))
9507 str)
9509 (defun org-link-unescape-compound (hex)
9510 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9511 Note: this function also decodes single byte encodings like
9512 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9513 (save-match-data
9514 (let* ((bytes (cdr (split-string hex "%")))
9515 (ret "")
9516 (eat 0)
9517 (sum 0))
9518 (while bytes
9519 (let* ((val (string-to-number (pop bytes) 16))
9520 (shift-xor
9521 (if (= 0 eat)
9522 (cond
9523 ((>= val 252) (cons 6 252))
9524 ((>= val 248) (cons 5 248))
9525 ((>= val 240) (cons 4 240))
9526 ((>= val 224) (cons 3 224))
9527 ((>= val 192) (cons 2 192))
9528 (t (cons 0 0)))
9529 (cons 6 128))))
9530 (if (>= val 192) (setq eat (car shift-xor)))
9531 (setq val (logxor val (cdr shift-xor)))
9532 (setq sum (+ (lsh sum (car shift-xor)) val))
9533 (if (> eat 0) (setq eat (- eat 1)))
9534 (cond
9535 ((= 0 eat) ;multi byte
9536 (setq ret (concat ret (org-char-to-string sum)))
9537 (setq sum 0))
9538 ((not bytes) ; single byte(s)
9539 (setq ret (org-link-unescape-single-byte-sequence hex))))
9540 )) ;; end (while bytes
9541 ret )))
9543 (defun org-link-unescape-single-byte-sequence (hex)
9544 "Unhexify hex-encoded single byte character sequences."
9545 (mapconcat (lambda (byte)
9546 (char-to-string (string-to-number byte 16)))
9547 (cdr (split-string hex "%")) ""))
9549 (defun org-xor (a b)
9550 "Exclusive or."
9551 (if a (not b) b))
9553 (defun org-fixup-message-id-for-http (s)
9554 "Replace special characters in a message id, so it can be used in an http query."
9555 (when (string-match "%" s)
9556 (setq s (mapconcat (lambda (c)
9557 (if (eq c ?%)
9558 "%25"
9559 (char-to-string c)))
9560 s "")))
9561 (while (string-match "<" s)
9562 (setq s (replace-match "%3C" t t s)))
9563 (while (string-match ">" s)
9564 (setq s (replace-match "%3E" t t s)))
9565 (while (string-match "@" s)
9566 (setq s (replace-match "%40" t t s)))
9569 (defun org-link-prettify (link)
9570 "Return a human-readable representation of LINK.
9571 The car of LINK must be a raw link the cdr of LINK must be either
9572 a link description or nil."
9573 (let ((desc (or (cadr link) "<no description>")))
9574 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9575 "<" (car link) ">")))
9577 ;;;###autoload
9578 (defun org-insert-link-global ()
9579 "Insert a link like Org-mode does.
9580 This command can be called in any mode to insert a link in Org-mode syntax."
9581 (interactive)
9582 (org-load-modules-maybe)
9583 (org-run-like-in-org-mode 'org-insert-link))
9585 (defun org-insert-all-links (&optional keep)
9586 "Insert all links in `org-stored-links'."
9587 (interactive "P")
9588 (let ((links (copy-sequence org-stored-links)) l)
9589 (while (setq l (if keep (pop links) (pop org-stored-links)))
9590 (insert "- ")
9591 (org-insert-link nil (car l) (cadr l))
9592 (insert "\n"))))
9594 (defun org-link-fontify-links-to-this-file ()
9595 "Fontify links to the current file in `org-stored-links'."
9596 (let ((f (buffer-file-name)) a b)
9597 (setq a (mapcar (lambda(l)
9598 (let ((ll (car l)))
9599 (when (and (string-match "^file:\\(.+\\)::" ll)
9600 (equal f (expand-file-name (match-string 1 ll))))
9601 ll)))
9602 org-stored-links))
9603 (when (featurep 'org-id)
9604 (setq b (mapcar (lambda(l)
9605 (let ((ll (car l)))
9606 (when (and (string-match "^id:\\(.+\\)$" ll)
9607 (equal f (expand-file-name
9608 (or (org-id-find-id-file
9609 (match-string 1 ll)) ""))))
9610 ll)))
9611 org-stored-links)))
9612 (mapcar (lambda(l)
9613 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9614 (delq nil (append a b)))))
9616 (defvar org-link-links-in-this-file nil)
9617 (defun org-insert-link (&optional complete-file link-location default-description)
9618 "Insert a link. At the prompt, enter the link.
9620 Completion can be used to insert any of the link protocol prefixes like
9621 http or ftp in use.
9623 The history can be used to select a link previously stored with
9624 `org-store-link'. When the empty string is entered (i.e. if you just
9625 press RET at the prompt), the link defaults to the most recently
9626 stored link. As SPC triggers completion in the minibuffer, you need to
9627 use M-SPC or C-q SPC to force the insertion of a space character.
9629 You will also be prompted for a description, and if one is given, it will
9630 be displayed in the buffer instead of the link.
9632 If there is already a link at point, this command will allow you to edit link
9633 and description parts.
9635 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9636 be selected using completion. The path to the file will be relative to the
9637 current directory if the file is in the current directory or a subdirectory.
9638 Otherwise, the link will be the absolute path as completed in the minibuffer
9639 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9640 option `org-link-file-path-type'.
9642 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9643 the current directory or below.
9645 With three \\[universal-argument] prefixes, negate the meaning of
9646 `org-keep-stored-link-after-insertion'.
9648 If `org-make-link-description-function' is non-nil, this function will be
9649 called with the link target, and the result will be the default
9650 link description.
9652 If the LINK-LOCATION parameter is non-nil, this value will be
9653 used as the link location instead of reading one interactively.
9655 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9656 be used as the default description."
9657 (interactive "P")
9658 (let* ((wcf (current-window-configuration))
9659 (origbuf (current-buffer))
9660 (region (if (org-region-active-p)
9661 (buffer-substring (region-beginning) (region-end))))
9662 (remove (and region (list (region-beginning) (region-end))))
9663 (desc region)
9664 tmphist ; byte-compile incorrectly complains about this
9665 (link link-location)
9666 (abbrevs org-link-abbrev-alist-local)
9667 entry file all-prefixes auto-desc)
9668 (cond
9669 (link-location) ; specified by arg, just use it.
9670 ((org-in-regexp org-bracket-link-regexp 1)
9671 ;; We do have a link at point, and we are going to edit it.
9672 (setq remove (list (match-beginning 0) (match-end 0)))
9673 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9674 (setq link (read-string "Link: "
9675 (org-link-unescape
9676 (org-match-string-no-properties 1)))))
9677 ((or (org-in-regexp org-angle-link-re)
9678 (org-in-regexp org-plain-link-re))
9679 ;; Convert to bracket link
9680 (setq remove (list (match-beginning 0) (match-end 0))
9681 link (read-string "Link: "
9682 (org-remove-angle-brackets (match-string 0)))))
9683 ((member complete-file '((4) (16)))
9684 ;; Completing read for file names.
9685 (setq link (org-file-complete-link complete-file)))
9687 ;; Read link, with completion for stored links.
9688 (org-link-fontify-links-to-this-file)
9689 (org-switch-to-buffer-other-window "*Org Links*")
9690 (with-current-buffer "*Org Links*"
9691 (erase-buffer)
9692 (insert "Insert a link.
9693 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9694 (when org-stored-links
9695 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9696 (insert (mapconcat 'org-link-prettify
9697 (reverse org-stored-links) "\n")))
9698 (goto-char (point-min)))
9699 (let ((cw (selected-window)))
9700 (select-window (get-buffer-window "*Org Links*" 'visible))
9701 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9702 (unless (pos-visible-in-window-p (point-max))
9703 (org-fit-window-to-buffer))
9704 (and (window-live-p cw) (select-window cw)))
9705 ;; Fake a link history, containing the stored links.
9706 (setq tmphist (append (mapcar 'car org-stored-links)
9707 org-insert-link-history))
9708 (setq all-prefixes (append (mapcar 'car abbrevs)
9709 (mapcar 'car org-link-abbrev-alist)
9710 org-link-types))
9711 (unwind-protect
9712 (progn
9713 (setq link
9714 (org-completing-read
9715 "Link: "
9716 (append
9717 (mapcar (lambda (x) (concat x ":"))
9718 all-prefixes)
9719 (mapcar 'car org-stored-links))
9720 nil nil nil
9721 'tmphist
9722 (caar org-stored-links)))
9723 (if (not (string-match "\\S-" link))
9724 (error "No link selected"))
9725 (mapc (lambda(l)
9726 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9727 org-stored-links)
9728 (if (or (member link all-prefixes)
9729 (and (equal ":" (substring link -1))
9730 (member (substring link 0 -1) all-prefixes)
9731 (setq link (substring link 0 -1))))
9732 (setq link (with-current-buffer origbuf
9733 (org-link-try-special-completion link)))))
9734 (set-window-configuration wcf)
9735 (kill-buffer "*Org Links*"))
9736 (setq entry (assoc link org-stored-links))
9737 (or entry (push link org-insert-link-history))
9738 (setq desc (or desc (nth 1 entry)))))
9740 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9741 (not org-keep-stored-link-after-insertion))
9742 (setq org-stored-links (delq (assoc link org-stored-links)
9743 org-stored-links)))
9745 (if (string-match org-plain-link-re link)
9746 ;; URL-like link, normalize the use of angular brackets.
9747 (setq link (org-remove-angle-brackets link)))
9749 ;; Check if we are linking to the current file with a search
9750 ;; option If yes, simplify the link by using only the search
9751 ;; option.
9752 (when (and buffer-file-name
9753 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9754 (let* ((path (match-string 1 link))
9755 (case-fold-search nil)
9756 (search (match-string 2 link)))
9757 (save-match-data
9758 (if (equal (file-truename buffer-file-name) (file-truename path))
9759 ;; We are linking to this same file, with a search option
9760 (setq link search)))))
9762 ;; Check if we can/should use a relative path. If yes, simplify the link
9763 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9764 (let* ((type (match-string 1 link))
9765 (path (match-string 2 link))
9766 (origpath path)
9767 (case-fold-search nil))
9768 (cond
9769 ((or (eq org-link-file-path-type 'absolute)
9770 (equal complete-file '(16)))
9771 (setq path (abbreviate-file-name (expand-file-name path))))
9772 ((eq org-link-file-path-type 'noabbrev)
9773 (setq path (expand-file-name path)))
9774 ((eq org-link-file-path-type 'relative)
9775 (setq path (file-relative-name path)))
9777 (save-match-data
9778 (if (string-match (concat "^" (regexp-quote
9779 (expand-file-name
9780 (file-name-as-directory
9781 default-directory))))
9782 (expand-file-name path))
9783 ;; We are linking a file with relative path name.
9784 (setq path (substring (expand-file-name path)
9785 (match-end 0)))
9786 (setq path (abbreviate-file-name (expand-file-name path)))))))
9787 (setq link (concat type path))
9788 (if (equal desc origpath)
9789 (setq desc path))))
9791 (if org-make-link-description-function
9792 (setq desc
9793 (or (condition-case nil
9794 (funcall org-make-link-description-function link desc)
9795 (error (progn (message "Can't get link description from `%s'"
9796 (symbol-name org-make-link-description-function))
9797 (sit-for 2) nil)))
9798 (read-string "Description: " default-description)))
9799 (if default-description (setq desc default-description)
9800 (setq desc (or (and auto-desc desc)
9801 (read-string "Description: " desc)))))
9803 (unless (string-match "\\S-" desc) (setq desc nil))
9804 (if remove (apply 'delete-region remove))
9805 (insert (org-make-link-string link desc))))
9807 (defun org-link-try-special-completion (type)
9808 "If there is completion support for link type TYPE, offer it."
9809 (let ((fun (intern (concat "org-" type "-complete-link"))))
9810 (if (functionp fun)
9811 (funcall fun)
9812 (read-string "Link (no completion support): " (concat type ":")))))
9814 (defun org-file-complete-link (&optional arg)
9815 "Create a file link using completion."
9816 (let (file link)
9817 (setq file (org-iread-file-name "File: "))
9818 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9819 (pwd1 (file-name-as-directory (abbreviate-file-name
9820 (expand-file-name ".")))))
9821 (cond
9822 ((equal arg '(16))
9823 (setq link (concat
9824 "file:"
9825 (abbreviate-file-name (expand-file-name file)))))
9826 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9827 (setq link (concat "file:" (match-string 1 file))))
9828 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9829 (expand-file-name file))
9830 (setq link (concat
9831 "file:" (match-string 1 (expand-file-name file)))))
9832 (t (setq link (concat "file:" file)))))
9833 link))
9835 (defun org-iread-file-name (&rest args)
9836 "Read-file-name using `ido-mode' speedup if available.
9837 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9838 See `read-file-name' for a description of parameters."
9839 (org-without-partial-completion
9840 (if (and org-completion-use-ido
9841 (fboundp 'ido-read-file-name)
9842 (boundp 'ido-mode) ido-mode
9843 (listp (second args)))
9844 (let ((ido-enter-matching-directory nil))
9845 (apply 'ido-read-file-name args))
9846 (apply 'read-file-name args))))
9848 (defun org-completing-read (&rest args)
9849 "Completing-read with SPACE being a normal character."
9850 (let ((enable-recursive-minibuffers t)
9851 (minibuffer-local-completion-map
9852 (copy-keymap minibuffer-local-completion-map)))
9853 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9854 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9855 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9856 (apply 'org-icompleting-read args)))
9858 (defun org-completing-read-no-i (&rest args)
9859 (let (org-completion-use-ido org-completion-use-iswitchb)
9860 (apply 'org-completing-read args)))
9862 (defun org-iswitchb-completing-read (prompt choices &rest args)
9863 "Use iswitch as a completing-read replacement to choose from choices.
9864 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9865 from."
9866 (let* ((iswitchb-use-virtual-buffers nil)
9867 (iswitchb-make-buflist-hook
9868 (lambda ()
9869 (setq iswitchb-temp-buflist choices))))
9870 (iswitchb-read-buffer prompt)))
9872 (defun org-icompleting-read (&rest args)
9873 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9874 (org-without-partial-completion
9875 (if (and org-completion-use-ido
9876 (fboundp 'ido-completing-read)
9877 (boundp 'ido-mode) ido-mode
9878 (listp (second args)))
9879 (let ((ido-enter-matching-directory nil))
9880 (apply 'ido-completing-read (concat (car args))
9881 (if (consp (car (nth 1 args)))
9882 (mapcar 'car (nth 1 args))
9883 (nth 1 args))
9884 (cddr args)))
9885 (if (and org-completion-use-iswitchb
9886 (boundp 'iswitchb-mode) iswitchb-mode
9887 (listp (second args)))
9888 (apply 'org-iswitchb-completing-read (concat (car args))
9889 (if (consp (car (nth 1 args)))
9890 (mapcar 'car (nth 1 args))
9891 (nth 1 args))
9892 (cddr args))
9893 (apply 'completing-read args)))))
9895 (defun org-extract-attributes (s)
9896 "Extract the attributes cookie from a string and set as text property."
9897 (let (a attr (start 0) key value)
9898 (save-match-data
9899 (when (string-match "{{\\([^}]+\\)}}$" s)
9900 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9901 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9902 (setq key (match-string 1 a) value (match-string 2 a)
9903 start (match-end 0)
9904 attr (plist-put attr (intern key) value))))
9905 (org-add-props s nil 'org-attr attr))
9908 (defun org-extract-attributes-from-string (tag)
9909 (let (key value attr)
9910 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9911 (setq key (match-string 1 tag) value (match-string 2 tag)
9912 tag (replace-match "" t t tag)
9913 attr (plist-put attr (intern key) value)))
9914 (cons tag attr)))
9916 (defun org-attributes-to-string (plist)
9917 "Format a property list into an HTML attribute list."
9918 (let ((s "") key value)
9919 (while plist
9920 (setq key (pop plist) value (pop plist))
9921 (and value
9922 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9925 ;;; Opening/following a link
9927 (defvar org-link-search-failed nil)
9929 (defvar org-open-link-functions nil
9930 "Hook for functions finding a plain text link.
9931 These functions must take a single argument, the link content.
9932 They will be called for links that look like [[link text][description]]
9933 when LINK TEXT does not have a protocol like \"http:\" and does not look
9934 like a filename (e.g. \"./blue.png\").
9936 These functions will be called *before* Org attempts to resolve the
9937 link by doing text searches in the current buffer - so if you want a
9938 link \"[[target]]\" to still find \"<<target>>\", your function should
9939 handle this as a special case.
9941 When the function does handle the link, it must return a non-nil value.
9942 If it decides that it is not responsible for this link, it must return
9943 nil to indicate that that Org-mode can continue with other options
9944 like exact and fuzzy text search.")
9946 (defun org-next-link (&optional search-backward)
9947 "Move forward to the next link.
9948 If the link is in hidden text, expose it."
9949 (interactive "P")
9950 (when (and org-link-search-failed (eq this-command last-command))
9951 (goto-char (point-min))
9952 (message "Link search wrapped back to beginning of buffer"))
9953 (setq org-link-search-failed nil)
9954 (let* ((pos (point))
9955 (ct (org-context))
9956 (a (assoc :link ct))
9957 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9958 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9959 ((looking-at org-any-link-re)
9960 ;; Don't stay stuck at link without an org-link face
9961 (forward-char (if search-backward -1 1))))
9962 (if (funcall srch-fun org-any-link-re nil t)
9963 (progn
9964 (goto-char (match-beginning 0))
9965 (if (outline-invisible-p) (org-show-context)))
9966 (goto-char pos)
9967 (setq org-link-search-failed t)
9968 (message "No further link found"))))
9970 (defun org-previous-link ()
9971 "Move backward to the previous link.
9972 If the link is in hidden text, expose it."
9973 (interactive)
9974 (funcall 'org-next-link t))
9976 (defun org-translate-link (s)
9977 "Translate a link string if a translation function has been defined."
9978 (if (and org-link-translation-function
9979 (fboundp org-link-translation-function)
9980 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9981 (progn
9982 (setq s (funcall org-link-translation-function
9983 (match-string 1 s) (match-string 2 s)))
9984 (concat (car s) ":" (cdr s)))
9987 (defun org-translate-link-from-planner (type path)
9988 "Translate a link from Emacs Planner syntax so that Org can follow it.
9989 This is still an experimental function, your mileage may vary."
9990 (cond
9991 ((member type '("http" "https" "news" "ftp"))
9992 ;; standard Internet links are the same.
9993 nil)
9994 ((and (equal type "irc") (string-match "^//" path))
9995 ;; Planner has two / at the beginning of an irc link, we have 1.
9996 ;; We should have zero, actually....
9997 (setq path (substring path 1)))
9998 ((and (equal type "lisp") (string-match "^/" path))
9999 ;; Planner has a slash, we do not.
10000 (setq type "elisp" path (substring path 1)))
10001 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10002 ;; A typical message link. Planner has the id after the final slash,
10003 ;; we separate it with a hash mark
10004 (setq path (concat (match-string 1 path) "#"
10005 (org-remove-angle-brackets (match-string 2 path)))))
10007 (cons type path))
10009 (defun org-find-file-at-mouse (ev)
10010 "Open file link or URL at mouse."
10011 (interactive "e")
10012 (mouse-set-point ev)
10013 (org-open-at-point 'in-emacs))
10015 (defun org-open-at-mouse (ev)
10016 "Open file link or URL at mouse.
10017 See the docstring of `org-open-file' for details."
10018 (interactive "e")
10019 (mouse-set-point ev)
10020 (if (eq major-mode 'org-agenda-mode)
10021 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10022 (org-open-at-point))
10024 (defvar org-window-config-before-follow-link nil
10025 "The window configuration before following a link.
10026 This is saved in case the need arises to restore it.")
10028 (defvar org-open-link-marker (make-marker)
10029 "Marker pointing to the location where `org-open-at-point; was called.")
10031 ;;;###autoload
10032 (defun org-open-at-point-global ()
10033 "Follow a link like Org-mode does.
10034 This command can be called in any mode to follow a link that has
10035 Org-mode syntax."
10036 (interactive)
10037 (org-run-like-in-org-mode 'org-open-at-point))
10039 ;;;###autoload
10040 (defun org-open-link-from-string (s &optional arg reference-buffer)
10041 "Open a link in the string S, as if it was in Org-mode."
10042 (interactive "sLink: \nP")
10043 (let ((reference-buffer (or reference-buffer (current-buffer))))
10044 (with-temp-buffer
10045 (let ((org-inhibit-startup (not reference-buffer)))
10046 (org-mode)
10047 (insert s)
10048 (goto-char (point-min))
10049 (when reference-buffer
10050 (setq org-link-abbrev-alist-local
10051 (with-current-buffer reference-buffer
10052 org-link-abbrev-alist-local)))
10053 (org-open-at-point arg reference-buffer)))))
10055 (defvar org-open-at-point-functions nil
10056 "Hook that is run when following a link at point.
10058 Functions in this hook must return t if they identify and follow
10059 a link at point. If they don't find anything interesting at point,
10060 they must return nil.")
10062 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10063 (defun org-open-at-point (&optional arg reference-buffer)
10064 "Open link at or after point.
10065 If there is no link at point, this function will search forward up to
10066 the end of the current line.
10067 Normally, files will be opened by an appropriate application. If the
10068 optional prefix argument ARG is non-nil, Emacs will visit the file.
10069 With a double prefix argument, try to open outside of Emacs, in the
10070 application the system uses for this file type."
10071 (interactive "P")
10072 ;; if in a code block, then open the block's results
10073 (unless (call-interactively #'org-babel-open-src-block-result)
10074 (org-load-modules-maybe)
10075 (move-marker org-open-link-marker (point))
10076 (setq org-window-config-before-follow-link (current-window-configuration))
10077 (org-remove-occur-highlights nil nil t)
10078 (cond
10079 ((and (org-at-heading-p)
10080 (not (org-at-timestamp-p t))
10081 (not (org-in-regexp
10082 (concat org-plain-link-re "\\|"
10083 org-bracket-link-regexp "\\|"
10084 org-angle-link-re "\\|"
10085 "[ \t]:[^ \t\n]+:[ \t]*$")))
10086 (not (get-text-property (point) 'org-linked-text)))
10087 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10088 (lk0 (car lkall))
10089 (lk (if (stringp lk0) (list lk0) lk0))
10090 (lkend (cdr lkall)))
10091 (mapcar (lambda(l)
10092 (search-forward l nil lkend)
10093 (goto-char (match-beginning 0))
10094 (org-open-at-point))
10095 lk))
10096 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10097 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10098 ((and (org-at-timestamp-p t)
10099 (not (org-in-regexp org-bracket-link-regexp)))
10100 (org-follow-timestamp-link))
10101 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10102 (not (org-in-regexp org-any-link-re)))
10103 (org-footnote-action))
10105 (let (type path link line search (pos (point)))
10106 (catch 'match
10107 (save-excursion
10108 (skip-chars-forward "^]\n\r")
10109 (when (org-in-regexp org-bracket-link-regexp 1)
10110 (setq link (org-extract-attributes
10111 (org-link-unescape (org-match-string-no-properties 1))))
10112 (while (string-match " *\n *" link)
10113 (setq link (replace-match " " t t link)))
10114 (setq link (org-link-expand-abbrev link))
10115 (cond
10116 ((or (file-name-absolute-p link)
10117 (string-match "^\\.\\.?/" link))
10118 (setq type "file" path link))
10119 ((string-match org-link-re-with-space3 link)
10120 (setq type (match-string 1 link) path (match-string 2 link)))
10121 ((string-match "^help:+\\(.+\\)" link)
10122 (setq type "help" path (match-string 1 link)))
10123 (t (setq type "thisfile" path link)))
10124 (throw 'match t)))
10126 (when (get-text-property (point) 'org-linked-text)
10127 (setq type "thisfile"
10128 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10129 (1+ (point)) (point))
10130 path (buffer-substring
10131 (or (previous-single-property-change pos 'org-linked-text)
10132 (point-min))
10133 (or (next-single-property-change pos 'org-linked-text)
10134 (point-max))))
10135 (throw 'match t))
10137 (save-excursion
10138 (when (or (org-in-regexp org-angle-link-re)
10139 (let ((match (org-in-regexp org-plain-link-re)))
10140 ;; Check a plain link is not within a bracket link
10141 (and match
10142 (save-excursion
10143 (progn
10144 (goto-char (car match))
10145 (not (org-in-regexp org-bracket-link-regexp))))))
10146 (let ((line_ending (save-excursion (end-of-line) (point))))
10147 ;; We are in a line before a plain or bracket link
10148 (or (re-search-forward org-plain-link-re line_ending t)
10149 (re-search-forward org-bracket-link-regexp line_ending t))))
10150 (setq type (match-string 1)
10151 path (org-link-unescape (match-string 2)))
10152 (throw 'match t)))
10153 (save-excursion
10154 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10155 (setq type "tags"
10156 path (match-string 1))
10157 (while (string-match ":" path)
10158 (setq path (replace-match "+" t t path)))
10159 (throw 'match t)))
10160 (when (org-in-regexp "<\\([^><\n]+\\)>")
10161 (setq type "tree-match"
10162 path (match-string 1))
10163 (throw 'match t)))
10164 (unless path
10165 (user-error "No link found"))
10167 ;; switch back to reference buffer
10168 ;; needed when if called in a temporary buffer through
10169 ;; org-open-link-from-string
10170 (with-current-buffer (or reference-buffer (current-buffer))
10172 ;; Remove any trailing spaces in path
10173 (if (string-match " +\\'" path)
10174 (setq path (replace-match "" t t path)))
10175 (if (and org-link-translation-function
10176 (fboundp org-link-translation-function))
10177 ;; Check if we need to translate the link
10178 (let ((tmp (funcall org-link-translation-function type path)))
10179 (setq type (car tmp) path (cdr tmp))))
10181 (cond
10183 ((assoc type org-link-protocols)
10184 (funcall (nth 1 (assoc type org-link-protocols)) path))
10186 ((equal type "help")
10187 (let ((f-or-v (intern path)))
10188 (cond ((fboundp f-or-v)
10189 (describe-function f-or-v))
10190 ((boundp f-or-v)
10191 (describe-variable f-or-v))
10192 (t (error "Not a known function or variable")))))
10194 ((equal type "mailto")
10195 (let ((cmd (car org-link-mailto-program))
10196 (args (cdr org-link-mailto-program)) args1
10197 (address path) (subject "") a)
10198 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10199 (setq address (match-string 1 path)
10200 subject (org-link-escape (match-string 2 path))))
10201 (while args
10202 (cond
10203 ((not (stringp (car args))) (push (pop args) args1))
10204 (t (setq a (pop args))
10205 (if (string-match "%a" a)
10206 (setq a (replace-match address t t a)))
10207 (if (string-match "%s" a)
10208 (setq a (replace-match subject t t a)))
10209 (push a args1))))
10210 (apply cmd (nreverse args1))))
10212 ((member type '("http" "https" "ftp" "news"))
10213 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10214 (org-link-escape
10215 path org-link-escape-chars-browser)
10216 path))))
10218 ((string= type "doi")
10219 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10220 (org-link-escape
10221 path org-link-escape-chars-browser)
10222 path))))
10224 ((member type '("message"))
10225 (browse-url (concat type ":" path)))
10227 ((string= type "tags")
10228 (org-tags-view arg path))
10230 ((string= type "tree-match")
10231 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10233 ((string= type "file")
10234 (if (string-match "::\\([0-9]+\\)\\'" path)
10235 (setq line (string-to-number (match-string 1 path))
10236 path (substring path 0 (match-beginning 0)))
10237 (if (string-match "::\\(.+\\)\\'" path)
10238 (setq search (match-string 1 path)
10239 path (substring path 0 (match-beginning 0)))))
10240 (if (string-match "[*?{]" (file-name-nondirectory path))
10241 (dired path)
10242 (org-open-file path arg line search)))
10244 ((string= type "shell")
10245 (let ((buf (generate-new-buffer "*Org Shell Output"))
10246 (cmd path))
10247 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10248 (string-match org-confirm-shell-link-not-regexp cmd))
10249 (not org-confirm-shell-link-function)
10250 (funcall org-confirm-shell-link-function
10251 (format "Execute \"%s\" in shell? "
10252 (org-add-props cmd nil
10253 'face 'org-warning))))
10254 (progn
10255 (message "Executing %s" cmd)
10256 (shell-command cmd buf)
10257 (if (featurep 'midnight)
10258 (setq clean-buffer-list-kill-buffer-names
10259 (cons buf clean-buffer-list-kill-buffer-names))))
10260 (error "Abort"))))
10262 ((string= type "elisp")
10263 (let ((cmd path))
10264 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10265 (string-match org-confirm-elisp-link-not-regexp cmd))
10266 (not org-confirm-elisp-link-function)
10267 (funcall org-confirm-elisp-link-function
10268 (format "Execute \"%s\" as elisp? "
10269 (org-add-props cmd nil
10270 'face 'org-warning))))
10271 (message "%s => %s" cmd
10272 (if (equal (string-to-char cmd) ?\()
10273 (eval (read cmd))
10274 (call-interactively (read cmd))))
10275 (error "Abort"))))
10277 ((and (string= type "thisfile")
10278 (run-hook-with-args-until-success
10279 'org-open-link-functions path)))
10281 ((string= type "thisfile")
10282 (if arg
10283 (switch-to-buffer-other-window
10284 (org-get-buffer-for-internal-link (current-buffer)))
10285 (org-mark-ring-push))
10286 (let ((cmd `(org-link-search
10287 ,path
10288 ,(cond ((equal arg '(4)) ''occur)
10289 ((equal arg '(16)) ''org-occur))
10290 ,pos)))
10291 (condition-case nil (let ((org-link-search-inhibit-query t))
10292 (eval cmd))
10293 (error (progn (widen) (eval cmd))))))
10295 (t (browse-url-at-point)))))))
10296 (move-marker org-open-link-marker nil)
10297 (run-hook-with-args 'org-follow-link-hook)))
10299 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10300 "Offer links in the current entry and return the selected link.
10301 If there is only one link, return it.
10302 If NTH is an integer, return the NTH link found.
10303 If ZERO is a string, check also this string for a link, and if
10304 there is one, return it."
10305 (with-current-buffer buffer
10306 (save-excursion
10307 (save-restriction
10308 (widen)
10309 (goto-char marker)
10310 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10311 "\\(" org-angle-link-re "\\)\\|"
10312 "\\(" org-plain-link-re "\\)"))
10313 (cnt ?0)
10314 (in-emacs (if (integerp nth) nil nth))
10315 have-zero end links link c)
10316 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10317 (push (match-string 0 zero) links)
10318 (setq cnt (1- cnt) have-zero t))
10319 (save-excursion
10320 (org-back-to-heading t)
10321 (setq end (save-excursion (outline-next-heading) (point)))
10322 (while (re-search-forward re end t)
10323 (push (match-string 0) links))
10324 (setq links (org-uniquify (reverse links))))
10325 (cond
10326 ((null links)
10327 (message "No links"))
10328 ((equal (length links) 1)
10329 (setq link (car links)))
10330 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10331 (setq link (nth (if have-zero nth (1- nth)) links)))
10332 (t ; we have to select a link
10333 (save-excursion
10334 (save-window-excursion
10335 (delete-other-windows)
10336 (with-output-to-temp-buffer "*Select Link*"
10337 (mapc (lambda (l)
10338 (if (not (string-match org-bracket-link-regexp l))
10339 (princ (format "[%c] %s\n" (incf cnt)
10340 (org-remove-angle-brackets l)))
10341 (if (match-end 3)
10342 (princ (format "[%c] %s (%s)\n" (incf cnt)
10343 (match-string 3 l) (match-string 1 l)))
10344 (princ (format "[%c] %s\n" (incf cnt)
10345 (match-string 1 l))))))
10346 links))
10347 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10348 (message "Select link to open, RET to open all:")
10349 (setq c (read-char-exclusive))
10350 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10351 (when (equal c ?q) (error "Abort"))
10352 (if (equal c ?\C-m)
10353 (setq link links)
10354 (setq nth (- c ?0))
10355 (if have-zero (setq nth (1+ nth)))
10356 (unless (and (integerp nth) (>= (length links) nth))
10357 (error "Invalid link selection"))
10358 (setq link (nth (1- nth) links)))))
10359 (cons link end))))))
10361 ;; Add special file links that specify the way of opening
10363 (org-add-link-type "file+sys" 'org-open-file-with-system)
10364 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10365 (defun org-open-file-with-system (path)
10366 "Open file at PATH using the system way of opening it."
10367 (org-open-file path 'system))
10368 (defun org-open-file-with-emacs (path)
10369 "Open file at PATH in Emacs."
10370 (org-open-file path 'emacs))
10373 ;;; File search
10375 (defvar org-create-file-search-functions nil
10376 "List of functions to construct the right search string for a file link.
10377 These functions are called in turn with point at the location to
10378 which the link should point.
10380 A function in the hook should first test if it would like to
10381 handle this file type, for example by checking the `major-mode'
10382 or the file extension. If it decides not to handle this file, it
10383 should just return nil to give other functions a chance. If it
10384 does handle the file, it must return the search string to be used
10385 when following the link. The search string will be part of the
10386 file link, given after a double colon, and `org-open-at-point'
10387 will automatically search for it. If special measures must be
10388 taken to make the search successful, another function should be
10389 added to the companion hook `org-execute-file-search-functions',
10390 which see.
10392 A function in this hook may also use `setq' to set the variable
10393 `description' to provide a suggestion for the descriptive text to
10394 be used for this link when it gets inserted into an Org-mode
10395 buffer with \\[org-insert-link].")
10397 (defvar org-execute-file-search-functions nil
10398 "List of functions to execute a file search triggered by a link.
10400 Functions added to this hook must accept a single argument, the
10401 search string that was part of the file link, the part after the
10402 double colon. The function must first check if it would like to
10403 handle this search, for example by checking the `major-mode' or
10404 the file extension. If it decides not to handle this search, it
10405 should just return nil to give other functions a chance. If it
10406 does handle the search, it must return a non-nil value to keep
10407 other functions from trying.
10409 Each function can access the current prefix argument through the
10410 variable `current-prefix-argument'. Note that a single prefix is
10411 used to force opening a link in Emacs, so it may be good to only
10412 use a numeric or double prefix to guide the search function.
10414 In case this is needed, a function in this hook can also restore
10415 the window configuration before `org-open-at-point' was called using:
10417 (set-window-configuration org-window-config-before-follow-link)")
10419 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10420 (defun org-link-search (s &optional type avoid-pos stealth)
10421 "Search for a link search option.
10422 If S is surrounded by forward slashes, it is interpreted as a
10423 regular expression. In org-mode files, this will create an `org-occur'
10424 sparse tree. In ordinary files, `occur' will be used to list matches.
10425 If the current buffer is in `dired-mode', grep will be used to search
10426 in all files. If AVOID-POS is given, ignore matches near that position.
10428 When optional argument STEALTH is non-nil, do not modify
10429 visibility around point, thus ignoring
10430 `org-show-hierarchy-above', `org-show-following-heading' and
10431 `org-show-siblings' variables."
10432 (let ((case-fold-search t)
10433 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10434 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10435 (append '(("") (" ") ("\t") ("\n"))
10436 org-emphasis-alist)
10437 "\\|") "\\)"))
10438 (pos (point))
10439 (pre nil) (post nil)
10440 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10441 (cond
10442 ;; First check if there are any special search functions
10443 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10444 ;; Now try the builtin stuff
10445 ((and (equal (string-to-char s0) ?#)
10446 (> (length s0) 1)
10447 (save-excursion
10448 (goto-char (point-min))
10449 (and
10450 (re-search-forward
10451 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10452 (setq type 'dedicated
10453 pos (match-beginning 0))))
10454 ;; There is an exact target for this
10455 (goto-char pos)
10456 (org-back-to-heading t)))
10457 ((save-excursion
10458 (goto-char (point-min))
10459 (and
10460 (re-search-forward
10461 (concat "<<" (regexp-quote s0) ">>") nil t)
10462 (setq type 'dedicated
10463 pos (match-beginning 0))))
10464 ;; There is an exact target for this
10465 (goto-char pos))
10466 ((save-excursion
10467 (goto-char (point-min))
10468 (and
10469 (re-search-forward
10470 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10471 (setq type 'dedicated pos (match-beginning 0))))
10472 ;; Found an invisible target.
10473 (goto-char pos))
10474 ((save-excursion
10475 (goto-char (point-min))
10476 (and
10477 (re-search-forward
10478 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10479 (setq type 'dedicated pos (match-beginning 0))))
10480 ;; Found an element with a matching #+name affiliated keyword.
10481 (goto-char pos))
10482 ((and (string-match "^(\\(.*\\))$" s0)
10483 (save-excursion
10484 (goto-char (point-min))
10485 (and
10486 (re-search-forward
10487 (concat "[^[]" (regexp-quote
10488 (format org-coderef-label-format
10489 (match-string 1 s0))))
10490 nil t)
10491 (setq type 'dedicated
10492 pos (1+ (match-beginning 0))))))
10493 ;; There is a coderef target for this
10494 (goto-char pos))
10495 ((string-match "^/\\(.*\\)/$" s)
10496 ;; A regular expression
10497 (cond
10498 ((derived-mode-p 'org-mode)
10499 (org-occur (match-string 1 s)))
10500 (t (org-do-occur (match-string 1 s)))))
10501 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10502 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10503 (goto-char (point-min))
10504 (cond
10505 ((let (case-fold-search)
10506 (re-search-forward (format org-complex-heading-regexp-format
10507 (regexp-quote s))
10508 nil t))
10509 ;; OK, found a match
10510 (setq type 'dedicated)
10511 (goto-char (match-beginning 0)))
10512 ((and (not org-link-search-inhibit-query)
10513 (eq org-link-search-must-match-exact-headline 'query-to-create)
10514 (y-or-n-p "No match - create this as a new heading? "))
10515 (goto-char (point-max))
10516 (or (bolp) (newline))
10517 (insert "* " s "\n")
10518 (beginning-of-line 0))
10520 (goto-char pos)
10521 (error "No match"))))
10523 ;; A normal search string
10524 (when (equal (string-to-char s) ?*)
10525 ;; Anchor on headlines, post may include tags.
10526 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10527 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10528 s (substring s 1)))
10529 (remove-text-properties
10530 0 (length s)
10531 '(face nil mouse-face nil keymap nil fontified nil) s)
10532 ;; Make a series of regular expressions to find a match
10533 (setq words (org-split-string s "[ \n\r\t]+")
10535 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10536 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10537 "\\)" markers)
10538 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10539 re2a (concat "[ \t\r\n]" re2a_)
10540 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10541 re4 (concat "[^a-zA-Z_]" re4_)
10543 re1 (concat pre re2 post)
10544 re3 (concat pre (if pre re4_ re4) post)
10545 re5 (concat pre ".*" re4)
10546 re2 (concat pre re2)
10547 re2a (concat pre (if pre re2a_ re2a))
10548 re4 (concat pre (if pre re4_ re4))
10549 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10550 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10551 re5 "\\)"
10553 (cond
10554 ((eq type 'org-occur) (org-occur reall))
10555 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10556 (t (goto-char (point-min))
10557 (setq type 'fuzzy)
10558 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10559 (org-search-not-self 1 re1 nil t)
10560 (org-search-not-self 1 re2 nil t)
10561 (org-search-not-self 1 re2a nil t)
10562 (org-search-not-self 1 re3 nil t)
10563 (org-search-not-self 1 re4 nil t)
10564 (org-search-not-self 1 re5 nil t)
10566 (goto-char (match-beginning 1))
10567 (goto-char pos)
10568 (error "No match"))))))
10569 (and (derived-mode-p 'org-mode)
10570 (not stealth)
10571 (org-show-context 'link-search))
10572 type))
10574 (defun org-search-not-self (group &rest args)
10575 "Execute `re-search-forward', but only accept matches that do not
10576 enclose the position of `org-open-link-marker'."
10577 (let ((m org-open-link-marker))
10578 (catch 'exit
10579 (while (apply 're-search-forward args)
10580 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10581 (goto-char (match-end group))
10582 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10583 (> (match-beginning 0) (marker-position m))
10584 (< (match-end 0) (marker-position m)))
10585 (save-match-data
10586 (or (not (org-in-regexp
10587 org-bracket-link-analytic-regexp 1))
10588 (not (match-end 4)) ; no description
10589 (and (<= (match-beginning 4) (point))
10590 (>= (match-end 4) (point))))))
10591 (throw 'exit (point))))))))
10593 (defun org-get-buffer-for-internal-link (buffer)
10594 "Return a buffer to be used for displaying the link target of internal links."
10595 (cond
10596 ((not org-display-internal-link-with-indirect-buffer)
10597 buffer)
10598 ((string-match "(Clone)$" (buffer-name buffer))
10599 (message "Buffer is already a clone, not making another one")
10600 ;; we also do not modify visibility in this case
10601 buffer)
10602 (t ; make a new indirect buffer for displaying the link
10603 (let* ((bn (buffer-name buffer))
10604 (ibn (concat bn "(Clone)"))
10605 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10606 (with-current-buffer ib (org-overview))
10607 ib))))
10609 (defun org-do-occur (regexp &optional cleanup)
10610 "Call the Emacs command `occur'.
10611 If CLEANUP is non-nil, remove the printout of the regular expression
10612 in the *Occur* buffer. This is useful if the regex is long and not useful
10613 to read."
10614 (occur regexp)
10615 (when cleanup
10616 (let ((cwin (selected-window)) win beg end)
10617 (when (setq win (get-buffer-window "*Occur*"))
10618 (select-window win))
10619 (goto-char (point-min))
10620 (when (re-search-forward "match[a-z]+" nil t)
10621 (setq beg (match-end 0))
10622 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10623 (setq end (1- (match-beginning 0)))))
10624 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10625 (goto-char (point-min))
10626 (select-window cwin))))
10628 ;;; The mark ring for links jumps
10630 (defvar org-mark-ring nil
10631 "Mark ring for positions before jumps in Org-mode.")
10632 (defvar org-mark-ring-last-goto nil
10633 "Last position in the mark ring used to go back.")
10634 ;; Fill and close the ring
10635 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10636 (loop for i from 1 to org-mark-ring-length do
10637 (push (make-marker) org-mark-ring))
10638 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10639 org-mark-ring)
10641 (defun org-mark-ring-push (&optional pos buffer)
10642 "Put the current position or POS into the mark ring and rotate it."
10643 (interactive)
10644 (setq pos (or pos (point)))
10645 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10646 (move-marker (car org-mark-ring)
10647 (or pos (point))
10648 (or buffer (current-buffer)))
10649 (message "%s"
10650 (substitute-command-keys
10651 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10653 (defun org-mark-ring-goto (&optional n)
10654 "Jump to the previous position in the mark ring.
10655 With prefix arg N, jump back that many stored positions. When
10656 called several times in succession, walk through the entire ring.
10657 Org-mode commands jumping to a different position in the current file,
10658 or to another Org-mode file, automatically push the old position
10659 onto the ring."
10660 (interactive "p")
10661 (let (p m)
10662 (if (eq last-command this-command)
10663 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10664 (setq p org-mark-ring))
10665 (setq org-mark-ring-last-goto p)
10666 (setq m (car p))
10667 (org-pop-to-buffer-same-window (marker-buffer m))
10668 (goto-char m)
10669 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10671 (defun org-remove-angle-brackets (s)
10672 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10673 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10675 (defun org-add-angle-brackets (s)
10676 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10677 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10679 (defun org-remove-double-quotes (s)
10680 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10681 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10684 ;;; Following specific links
10686 (defun org-follow-timestamp-link ()
10687 "Open an agenda view for the time-stamp date/range at point."
10688 (cond
10689 ((org-at-date-range-p t)
10690 (let ((org-agenda-start-on-weekday)
10691 (t1 (match-string 1))
10692 (t2 (match-string 2)) tt1 tt2)
10693 (setq tt1 (time-to-days (org-time-string-to-time t1))
10694 tt2 (time-to-days (org-time-string-to-time t2)))
10695 (let ((org-agenda-buffer-tmp-name
10696 (format "*Org Agenda(a:%s)"
10697 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10698 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10699 ((org-at-timestamp-p t)
10700 (let ((org-agenda-buffer-tmp-name
10701 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10702 (org-agenda-list nil (time-to-days (org-time-string-to-time
10703 (substring (match-string 1) 0 10)))
10704 1)))
10705 (t (error "This should not happen"))))
10708 ;;; Following file links
10709 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10710 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10711 (declare-function mailcap-mime-info
10712 "mailcap" (string &optional request no-decode))
10713 (defvar org-wait nil)
10714 (defun org-open-file (path &optional in-emacs line search)
10715 "Open the file at PATH.
10716 First, this expands any special file name abbreviations. Then the
10717 configuration variable `org-file-apps' is checked if it contains an
10718 entry for this file type, and if yes, the corresponding command is launched.
10720 If no application is found, Emacs simply visits the file.
10722 With optional prefix argument IN-EMACS, Emacs will visit the file.
10723 With a double \\[universal-argument] \\[universal-argument] \
10724 prefix arg, Org tries to avoid opening in Emacs
10725 and to use an external application to visit the file.
10727 Optional LINE specifies a line to go to, optional SEARCH a string
10728 to search for. If LINE or SEARCH is given, the file will be
10729 opened in Emacs, unless an entry from org-file-apps that makes
10730 use of groups in a regexp matches.
10732 If you want to change the way frames are used when following a
10733 link, please customize `org-link-frame-setup'.
10735 If the file does not exist, an error is thrown."
10736 (let* ((file (if (equal path "")
10737 buffer-file-name
10738 (substitute-in-file-name (expand-file-name path))))
10739 (file-apps (append org-file-apps (org-default-apps)))
10740 (apps (org-remove-if
10741 'org-file-apps-entry-match-against-dlink-p file-apps))
10742 (apps-dlink (org-remove-if-not
10743 'org-file-apps-entry-match-against-dlink-p file-apps))
10744 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10745 (dirp (if remp nil (file-directory-p file)))
10746 (file (if (and dirp org-open-directory-means-index-dot-org)
10747 (concat (file-name-as-directory file) "index.org")
10748 file))
10749 (a-m-a-p (assq 'auto-mode apps))
10750 (dfile (downcase file))
10751 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10752 (link (cond ((and (eq line nil)
10753 (eq search nil))
10754 file)
10755 (line
10756 (concat file "::" (number-to-string line)))
10757 (search
10758 (concat file "::" search))))
10759 (dlink (downcase link))
10760 (old-buffer (current-buffer))
10761 (old-pos (point))
10762 (old-mode major-mode)
10763 ext cmd link-match-data)
10764 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10765 (setq ext (match-string 1 dfile))
10766 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10767 (setq ext (match-string 1 dfile))))
10768 (cond
10769 ((member in-emacs '((16) system))
10770 (setq cmd (cdr (assoc 'system apps))))
10771 (in-emacs (setq cmd 'emacs))
10773 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10774 (and dirp (cdr (assoc 'directory apps)))
10775 ; first, try matching against apps-dlink
10776 ; if we get a match here, store the match data for later
10777 (let ((match (assoc-default dlink apps-dlink
10778 'string-match)))
10779 (if match
10780 (progn (setq link-match-data (match-data))
10781 match)
10782 (progn (setq in-emacs (or in-emacs line search))
10783 nil))) ; if we have no match in apps-dlink,
10784 ; always open the file in emacs if line or search
10785 ; is given (for backwards compatibility)
10786 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10787 'string-match)
10788 (cdr (assoc ext apps))
10789 (cdr (assoc t apps))))))
10790 (when (eq cmd 'system)
10791 (setq cmd (cdr (assoc 'system apps))))
10792 (when (eq cmd 'default)
10793 (setq cmd (cdr (assoc t apps))))
10794 (when (eq cmd 'mailcap)
10795 (require 'mailcap)
10796 (mailcap-parse-mailcaps)
10797 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10798 (command (mailcap-mime-info mime-type)))
10799 (if (stringp command)
10800 (setq cmd command)
10801 (setq cmd 'emacs))))
10802 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10803 (not (file-exists-p file))
10804 (not org-open-non-existing-files))
10805 (error "No such file: %s" file))
10806 (cond
10807 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10808 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10809 (while (string-match "['\"]%s['\"]" cmd)
10810 (setq cmd (replace-match "%s" t t cmd)))
10811 (while (string-match "%s" cmd)
10812 (setq cmd (replace-match
10813 (save-match-data
10814 (shell-quote-argument
10815 (convert-standard-filename file)))
10816 t t cmd)))
10818 ;; Replace "%1", "%2" etc. in command with group matches from regex
10819 (save-match-data
10820 (let ((match-index 1)
10821 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10822 (set-match-data link-match-data)
10823 (while (<= match-index number-of-groups)
10824 (let ((regex (concat "%" (number-to-string match-index)))
10825 (replace-with (match-string match-index dlink)))
10826 (while (string-match regex cmd)
10827 (setq cmd (replace-match replace-with t t cmd))))
10828 (setq match-index (+ match-index 1)))))
10830 (save-window-excursion
10831 (message "Running %s...done" cmd)
10832 (start-process-shell-command cmd nil cmd)
10833 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10834 ((or (stringp cmd)
10835 (eq cmd 'emacs))
10836 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10837 (widen)
10838 (if line (org-goto-line line)
10839 (if search (org-link-search search))))
10840 ((consp cmd)
10841 (let ((file (convert-standard-filename file)))
10842 (save-match-data
10843 (set-match-data link-match-data)
10844 (eval cmd))))
10845 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10846 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10847 (or (not (equal old-buffer (current-buffer)))
10848 (not (equal old-pos (point))))
10849 (org-mark-ring-push old-pos old-buffer))))
10851 (defun org-file-apps-entry-match-against-dlink-p (entry)
10852 "This function returns non-nil if `entry' uses a regular
10853 expression which should be matched against the whole link by
10854 org-open-file.
10856 It assumes that is the case when the entry uses a regular
10857 expression which has at least one grouping construct and the
10858 action is either a lisp form or a command string containing
10859 '%1', i.e. using at least one subexpression match as a
10860 parameter."
10861 (let ((selector (car entry))
10862 (action (cdr entry)))
10863 (if (stringp selector)
10864 (and (> (regexp-opt-depth selector) 0)
10865 (or (and (stringp action)
10866 (string-match "%[0-9]" action))
10867 (consp action)))
10868 nil)))
10870 (defun org-default-apps ()
10871 "Return the default applications for this operating system."
10872 (cond
10873 ((eq system-type 'darwin)
10874 org-file-apps-defaults-macosx)
10875 ((eq system-type 'windows-nt)
10876 org-file-apps-defaults-windowsnt)
10877 (t org-file-apps-defaults-gnu)))
10879 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10880 "Convert extensions to regular expressions in the cars of LIST.
10881 Also, weed out any non-string entries, because the return value is used
10882 only for regexp matching.
10883 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10884 point to the symbol `emacs', indicating that the file should
10885 be opened in Emacs."
10886 (append
10887 (delq nil
10888 (mapcar (lambda (x)
10889 (if (not (stringp (car x)))
10891 (if (string-match "\\W" (car x))
10893 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10894 list))
10895 (if add-auto-mode
10896 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10898 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10899 (defun org-file-remote-p (file)
10900 "Test whether FILE specifies a location on a remote system.
10901 Return non-nil if the location is indeed remote.
10903 For example, the filename \"/user@host:/foo\" specifies a location
10904 on the system \"/user@host:\"."
10905 (cond ((fboundp 'file-remote-p)
10906 (file-remote-p file))
10907 ((fboundp 'tramp-handle-file-remote-p)
10908 (tramp-handle-file-remote-p file))
10909 ((and (boundp 'ange-ftp-name-format)
10910 (string-match (car ange-ftp-name-format) file))
10911 t)))
10914 ;;;; Refiling
10916 (defun org-get-org-file ()
10917 "Read a filename, with default directory `org-directory'."
10918 (let ((default (or org-default-notes-file remember-data-file)))
10919 (read-file-name (format "File name [%s]: " default)
10920 (file-name-as-directory org-directory)
10921 default)))
10923 (defun org-notes-order-reversed-p ()
10924 "Check if the current file should receive notes in reversed order."
10925 (cond
10926 ((not org-reverse-note-order) nil)
10927 ((eq t org-reverse-note-order) t)
10928 ((not (listp org-reverse-note-order)) nil)
10929 (t (catch 'exit
10930 (let ((all org-reverse-note-order)
10931 entry)
10932 (while (setq entry (pop all))
10933 (if (string-match (car entry) buffer-file-name)
10934 (throw 'exit (cdr entry))))
10935 nil)))))
10937 (defvar org-refile-target-table nil
10938 "The list of refile targets, created by `org-refile'.")
10940 (defvar org-agenda-new-buffers nil
10941 "Buffers created to visit agenda files.")
10943 (defvar org-refile-cache nil
10944 "Cache for refile targets.")
10946 (defvar org-refile-markers nil
10947 "All the markers used for caching refile locations.")
10949 (defun org-refile-marker (pos)
10950 "Get a new refile marker, but only if caching is in use."
10951 (if (not org-refile-use-cache)
10953 (let ((m (make-marker)))
10954 (move-marker m pos)
10955 (push m org-refile-markers)
10956 m)))
10958 (defun org-refile-cache-clear ()
10959 "Clear the refile cache and disable all the markers."
10960 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10961 (setq org-refile-markers nil)
10962 (setq org-refile-cache nil)
10963 (message "Refile cache has been cleared"))
10965 (defun org-refile-cache-check-set (set)
10966 "Check if all the markers in the cache still have live buffers."
10967 (let (marker)
10968 (catch 'exit
10969 (while (and set (setq marker (nth 3 (pop set))))
10970 ;; if org-refile-use-outline-path is 'file, marker may be nil
10971 (when (and marker (null (marker-buffer marker)))
10972 (message "not found") (sit-for 3)
10973 (throw 'exit nil)))
10974 t)))
10976 (defun org-refile-cache-put (set &rest identifiers)
10977 "Push the refile targets SET into the cache, under IDENTIFIERS."
10978 (let* ((key (sha1 (prin1-to-string identifiers)))
10979 (entry (assoc key org-refile-cache)))
10980 (if entry
10981 (setcdr entry set)
10982 (push (cons key set) org-refile-cache))))
10984 (defun org-refile-cache-get (&rest identifiers)
10985 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10986 (cond
10987 ((not org-refile-cache) nil)
10988 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10990 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10991 org-refile-cache))))
10992 (and set (org-refile-cache-check-set set) set)))))
10994 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10995 "Produce a table with refile targets."
10996 (let ((case-fold-search nil)
10997 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10998 (entries (or org-refile-targets '((nil . (:level . 1)))))
10999 targets tgs txt re files f desc descre fast-path-p level pos0)
11000 (message "Getting targets...")
11001 (with-current-buffer (or default-buffer (current-buffer))
11002 (while (setq entry (pop entries))
11003 (setq files (car entry) desc (cdr entry))
11004 (setq fast-path-p nil)
11005 (cond
11006 ((null files) (setq files (list (current-buffer))))
11007 ((eq files 'org-agenda-files)
11008 (setq files (org-agenda-files 'unrestricted)))
11009 ((and (symbolp files) (fboundp files))
11010 (setq files (funcall files)))
11011 ((and (symbolp files) (boundp files))
11012 (setq files (symbol-value files))))
11013 (if (stringp files) (setq files (list files)))
11014 (cond
11015 ((eq (car desc) :tag)
11016 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11017 ((eq (car desc) :todo)
11018 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11019 ((eq (car desc) :regexp)
11020 (setq descre (cdr desc)))
11021 ((eq (car desc) :level)
11022 (setq descre (concat "^\\*\\{" (number-to-string
11023 (if org-odd-levels-only
11024 (1- (* 2 (cdr desc)))
11025 (cdr desc)))
11026 "\\}[ \t]")))
11027 ((eq (car desc) :maxlevel)
11028 (setq fast-path-p t)
11029 (setq descre (concat "^\\*\\{1," (number-to-string
11030 (if org-odd-levels-only
11031 (1- (* 2 (cdr desc)))
11032 (cdr desc)))
11033 "\\}[ \t]")))
11034 (t (error "Bad refiling target description %s" desc)))
11035 (while (setq f (pop files))
11036 (with-current-buffer
11037 (if (bufferp f) f (org-get-agenda-file-buffer f))
11039 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11040 (progn
11041 (if (bufferp f) (setq f (buffer-file-name
11042 (buffer-base-buffer f))))
11043 (setq f (and f (expand-file-name f)))
11044 (if (eq org-refile-use-outline-path 'file)
11045 (push (list (file-name-nondirectory f) f nil nil) tgs))
11046 (save-excursion
11047 (save-restriction
11048 (widen)
11049 (goto-char (point-min))
11050 (while (re-search-forward descre nil t)
11051 (goto-char (setq pos0 (point-at-bol)))
11052 (catch 'next
11053 (when org-refile-target-verify-function
11054 (save-match-data
11055 (or (funcall org-refile-target-verify-function)
11056 (throw 'next t))))
11057 (when (and (looking-at org-complex-heading-regexp)
11058 (not (member (match-string 4) excluded-entries))
11059 (match-string 4))
11060 (setq level (org-reduced-level
11061 (- (match-end 1) (match-beginning 1)))
11062 txt (org-link-display-format (match-string 4))
11063 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11064 re (format org-complex-heading-regexp-format
11065 (regexp-quote (match-string 4))))
11066 (when org-refile-use-outline-path
11067 (setq txt (mapconcat
11068 'org-protect-slash
11069 (append
11070 (if (eq org-refile-use-outline-path
11071 'file)
11072 (list (file-name-nondirectory
11073 (buffer-file-name
11074 (buffer-base-buffer))))
11075 (if (eq org-refile-use-outline-path
11076 'full-file-path)
11077 (list (buffer-file-name
11078 (buffer-base-buffer)))))
11079 (org-get-outline-path fast-path-p
11080 level txt)
11081 (list txt))
11082 "/")))
11083 (push (list txt f re (org-refile-marker (point)))
11084 tgs)))
11085 (when (= (point) pos0)
11086 ;; verification function has not moved point
11087 (goto-char (point-at-eol))))))))
11088 (when org-refile-use-cache
11089 (org-refile-cache-put tgs (buffer-file-name) descre))
11090 (setq targets (append tgs targets))
11091 ))))
11092 (message "Getting targets...done")
11093 (nreverse targets)))
11095 (defun org-protect-slash (s)
11096 (while (string-match "/" s)
11097 (setq s (replace-match "\\" t t s)))
11100 (defvar org-olpa (make-vector 20 nil))
11102 (defun org-get-outline-path (&optional fastp level heading)
11103 "Return the outline path to the current entry, as a list.
11105 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11106 routine which makes outline path derivations for an entire file,
11107 avoiding backtracing. Refile target collection makes use of that."
11108 (if fastp
11109 (progn
11110 (if (> level 19)
11111 (error "Outline path failure, more than 19 levels"))
11112 (loop for i from level upto 19 do
11113 (aset org-olpa i nil))
11114 (prog1
11115 (delq nil (append org-olpa nil))
11116 (aset org-olpa level heading)))
11117 (let (rtn case-fold-search)
11118 (save-excursion
11119 (save-restriction
11120 (widen)
11121 (while (org-up-heading-safe)
11122 (when (looking-at org-complex-heading-regexp)
11123 (push (org-match-string-no-properties 4) rtn)))
11124 rtn)))))
11126 (defun org-format-outline-path (path &optional width prefix separator)
11127 "Format the outline path PATH for display.
11128 WIDTH is the maximum number of characters that is available.
11129 PREFIX is a prefix to be included in the returned string,
11130 such as the file name.
11131 SEPARATOR is inserted between the different parts of the path,
11132 the default is \"/\"."
11133 (setq width (or width 79))
11134 (if prefix (setq width (- width (length prefix))))
11135 (if (not path)
11136 (or prefix "")
11137 (let* ((nsteps (length path))
11138 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11139 (maxwidth (if (<= total-width width)
11140 10000 ;; everything fits
11141 ;; we need to shorten the level headings
11142 (/ (- width nsteps) nsteps)))
11143 (org-odd-levels-only nil)
11144 (n 0)
11145 (total (1+ (length prefix))))
11146 (setq maxwidth (max maxwidth 10))
11147 (concat prefix
11148 (if prefix (or separator "/"))
11149 (mapconcat
11150 (lambda (h)
11151 (setq n (1+ n))
11152 (if (and (= n nsteps) (< maxwidth 10000))
11153 (setq maxwidth (- total-width total)))
11154 (if (< (length h) maxwidth)
11155 (progn (setq total (+ total (length h) 1)) h)
11156 (setq h (substring h 0 (- maxwidth 2))
11157 total (+ total maxwidth 1))
11158 (if (string-match "[ \t]+\\'" h)
11159 (setq h (substring h 0 (match-beginning 0))))
11160 (setq h (concat h "..")))
11161 (org-add-props h nil 'face
11162 (nth (% (1- n) org-n-level-faces)
11163 org-level-faces))
11165 path (or separator "/"))))))
11167 (defun org-display-outline-path (&optional file current separator just-return-string)
11168 "Display the current outline path in the echo area.
11170 If FILE is non-nil, prepend the output with the file name.
11171 If CURRENT is non-nil, append the current heading to the output.
11172 SEPARATOR is passed through to `org-format-outline-path'. It separates
11173 the different parts of the path and defaults to \"/\".
11174 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11175 (interactive "P")
11176 (let* (case-fold-search
11177 message-log-max ; Don't populate the *Messages* buffer
11178 (bfn (buffer-file-name (buffer-base-buffer)))
11179 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11180 res)
11181 (if current (setq path (append path
11182 (save-excursion
11183 (org-back-to-heading t)
11184 (if (looking-at org-complex-heading-regexp)
11185 (list (match-string 4)))))))
11186 (setq res
11187 (org-format-outline-path
11188 path
11189 (1- (frame-width))
11190 (and file bfn (concat (file-name-nondirectory bfn) separator))
11191 separator))
11192 (if just-return-string
11193 (org-no-properties res)
11194 (message "%s" res))))
11196 (defvar org-refile-history nil
11197 "History for refiling operations.")
11199 (defvar org-after-refile-insert-hook nil
11200 "Hook run after `org-refile' has inserted its stuff at the new location.
11201 Note that this is still *before* the stuff will be removed from
11202 the *old* location.")
11204 (defvar org-capture-last-stored-marker)
11205 (defvar org-refile-keep nil
11206 "Non-nil means `org-refile' will copy instead of refile.")
11208 (defun org-copy ()
11209 "Like `org-refile', but copy."
11210 (interactive)
11211 (let ((org-refile-keep t))
11212 (funcall 'org-refile nil nil nil "Copy")))
11214 (defun org-refile (&optional goto default-buffer rfloc msg)
11215 "Move the entry or entries at point to another heading.
11216 The list of target headings is compiled using the information in
11217 `org-refile-targets', which see.
11219 At the target location, the entry is filed as a subitem of the target
11220 heading. Depending on `org-reverse-note-order', the new subitem will
11221 either be the first or the last subitem.
11223 If there is an active region, all entries in that region will be moved.
11224 However, the region must fulfill the requirement that the first heading
11225 is the first one sets the top-level of the moved text - at most siblings
11226 below it are allowed.
11228 With prefix arg GOTO, the command will only visit the target location
11229 and not actually move anything.
11231 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11232 go to the location where the last refiling operation has put the subtree.
11233 With a prefix argument of `2', refile to the running clock.
11235 RFLOC can be a refile location obtained in a different way.
11237 MSG is a string to replace \"Refile\" in the default prompt with
11238 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11240 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11242 If you are using target caching (see `org-refile-use-cache'),
11243 you have to clear the target cache in order to find new targets.
11244 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11245 prefix argument (`C-u C-u C-u C-c C-w')."
11247 (interactive "P")
11248 (if (member goto '(0 (64)))
11249 (org-refile-cache-clear)
11250 (let* ((actionmsg (or msg "Refile"))
11251 (cbuf (current-buffer))
11252 (regionp (org-region-active-p))
11253 (region-start (and regionp (region-beginning)))
11254 (region-end (and regionp (region-end)))
11255 (region-length (and regionp (- region-end region-start)))
11256 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11257 pos it nbuf file re level reversed)
11258 (setq last-command nil)
11259 (when regionp
11260 (goto-char region-start)
11261 (or (bolp) (goto-char (point-at-bol)))
11262 (setq region-start (point))
11263 (unless (or (org-kill-is-subtree-p
11264 (buffer-substring region-start region-end))
11265 (prog1 org-refile-active-region-within-subtree
11266 (org-toggle-heading)))
11267 (error "The region is not a (sequence of) subtree(s)")))
11268 (if (equal goto '(16))
11269 (org-refile-goto-last-stored)
11270 (when (or
11271 (and (equal goto 2)
11272 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11273 (prog1
11274 (setq it (list (or org-clock-heading "running clock")
11275 (buffer-file-name
11276 (marker-buffer org-clock-hd-marker))
11278 (marker-position org-clock-hd-marker)))
11279 (setq goto nil)))
11280 (setq it (or rfloc
11281 (let (heading-text)
11282 (save-excursion
11283 (unless goto
11284 (org-back-to-heading t)
11285 (setq heading-text
11286 (nth 4 (org-heading-components))))
11288 (org-refile-get-location
11289 (cond (goto "Goto")
11290 (regionp (concat actionmsg " region to"))
11291 (t (concat actionmsg " subtree \""
11292 heading-text "\" to")))
11293 default-buffer
11294 (and (not (equal '(4) goto))
11295 org-refile-allow-creating-parent-nodes)
11296 goto))))))
11297 (setq file (nth 1 it)
11298 re (nth 2 it)
11299 pos (nth 3 it))
11300 (if (and (not goto)
11302 (equal (buffer-file-name) file)
11303 (if regionp
11304 (and (>= pos region-start)
11305 (<= pos region-end))
11306 (and (>= pos (point))
11307 (< pos (save-excursion
11308 (org-end-of-subtree t t))))))
11309 (error "Cannot refile to position inside the tree or region"))
11311 (setq nbuf (or (find-buffer-visiting file)
11312 (find-file-noselect file)))
11313 (if goto
11314 (progn
11315 (org-pop-to-buffer-same-window nbuf)
11316 (goto-char pos)
11317 (org-show-context 'org-goto))
11318 (if regionp
11319 (progn
11320 (org-kill-new (buffer-substring region-start region-end))
11321 (org-save-markers-in-region region-start region-end))
11322 (org-copy-subtree 1 nil t))
11323 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11324 (find-file-noselect file)))
11325 (setq reversed (org-notes-order-reversed-p))
11326 (save-excursion
11327 (save-restriction
11328 (widen)
11329 (if pos
11330 (progn
11331 (goto-char pos)
11332 (looking-at org-outline-regexp)
11333 (setq level (org-get-valid-level (funcall outline-level) 1))
11334 (goto-char
11335 (if reversed
11336 (or (outline-next-heading) (point-max))
11337 (or (save-excursion (org-get-next-sibling))
11338 (org-end-of-subtree t t)
11339 (point-max)))))
11340 (setq level 1)
11341 (if (not reversed)
11342 (goto-char (point-max))
11343 (goto-char (point-min))
11344 (or (outline-next-heading) (goto-char (point-max)))))
11345 (if (not (bolp)) (newline))
11346 (org-paste-subtree level)
11347 (when org-log-refile
11348 (org-add-log-setup 'refile nil nil 'findpos
11349 org-log-refile)
11350 (unless (eq org-log-refile 'note)
11351 (save-excursion (org-add-log-note))))
11352 (and org-auto-align-tags
11353 (let ((org-loop-over-headlines-in-active-region nil))
11354 (org-set-tags nil t)))
11355 (with-demoted-errors
11356 (bookmark-set "org-refile-last-stored"))
11357 ;; If we are refiling for capture, make sure that the
11358 ;; last-capture pointers point here
11359 (when (org-bound-and-true-p org-refile-for-capture)
11360 (with-demoted-errors
11361 (bookmark-set "org-capture-last-stored-marker"))
11362 (move-marker org-capture-last-stored-marker (point)))
11363 (if (fboundp 'deactivate-mark) (deactivate-mark))
11364 (run-hooks 'org-after-refile-insert-hook))))
11365 (unless org-refile-keep
11366 (if regionp
11367 (delete-region (point) (+ (point) region-length))
11368 (org-cut-subtree)))
11369 (when (featurep 'org-inlinetask)
11370 (org-inlinetask-remove-END-maybe))
11371 (setq org-markers-to-move nil)
11372 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11374 (defun org-refile-goto-last-stored ()
11375 "Go to the location where the last refile was stored."
11376 (interactive)
11377 (bookmark-jump "org-refile-last-stored")
11378 (message "This is the location of the last refile"))
11380 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11381 no-exclude)
11382 "Prompt the user for a refile location, using PROMPT.
11383 PROMPT should not be suffixed with a colon and a space, because
11384 this function appends the default value from
11385 `org-refile-history' automatically, if that is not empty.
11386 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11387 this is used for the GOTO interface."
11388 (let ((org-refile-targets org-refile-targets)
11389 (org-refile-use-outline-path org-refile-use-outline-path)
11390 excluded-entries)
11391 (when (and (derived-mode-p 'org-mode)
11392 (not org-refile-use-cache)
11393 (not no-exclude))
11394 (org-map-tree
11395 (lambda()
11396 (setq excluded-entries
11397 (append excluded-entries (list (org-get-heading t t)))))))
11398 (setq org-refile-target-table
11399 (org-refile-get-targets default-buffer excluded-entries)))
11400 (unless org-refile-target-table
11401 (error "No refile targets"))
11402 (let* ((cbuf (current-buffer))
11403 (partial-completion-mode nil)
11404 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11405 (cfunc (if (and org-refile-use-outline-path
11406 org-outline-path-complete-in-steps)
11407 'org-olpath-completing-read
11408 'org-icompleting-read))
11409 (extra (if org-refile-use-outline-path "/" ""))
11410 (cbnex (concat (buffer-name) extra))
11411 (filename (and cfn (expand-file-name cfn)))
11412 (tbl (mapcar
11413 (lambda (x)
11414 (if (and (not (member org-refile-use-outline-path
11415 '(file full-file-path)))
11416 (not (equal filename (nth 1 x))))
11417 (cons (concat (car x) extra " ("
11418 (file-name-nondirectory (nth 1 x)) ")")
11419 (cdr x))
11420 (cons (concat (car x) extra) (cdr x))))
11421 org-refile-target-table))
11422 (completion-ignore-case t)
11423 cdef
11424 (prompt (concat prompt
11425 (or (and (car org-refile-history)
11426 (concat " (default " (car org-refile-history) ")"))
11427 (and (assoc cbnex tbl) (setq cdef cbnex)
11428 (concat " (default " cbnex ")"))) ": "))
11429 pa answ parent-target child parent old-hist)
11430 (setq old-hist org-refile-history)
11431 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11432 nil 'org-refile-history (or cdef (car org-refile-history))))
11433 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11434 (org-refile-check-position pa)
11435 (if pa
11436 (progn
11437 (when (or (not org-refile-history)
11438 (not (eq old-hist org-refile-history))
11439 (not (equal (car pa) (car org-refile-history))))
11440 (setq org-refile-history
11441 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11442 org-refile-history
11443 (cdr org-refile-history))))
11444 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11445 (pop org-refile-history)))
11447 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11448 (progn
11449 (setq parent (match-string 1 answ)
11450 child (match-string 2 answ))
11451 (setq parent-target (or (assoc parent tbl)
11452 (assoc (concat parent "/") tbl)))
11453 (when (and parent-target
11454 (or (eq new-nodes t)
11455 (and (eq new-nodes 'confirm)
11456 (y-or-n-p (format "Create new node \"%s\"? "
11457 child)))))
11458 (org-refile-new-child parent-target child)))
11459 (error "Invalid target location")))))
11461 (declare-function org-string-nw-p "org-macs" (s))
11462 (defun org-refile-check-position (refile-pointer)
11463 "Check if the refile pointer matches the headline to which it points."
11464 (let* ((file (nth 1 refile-pointer))
11465 (re (nth 2 refile-pointer))
11466 (pos (nth 3 refile-pointer))
11467 buffer)
11468 (if (and (not (markerp pos)) (not file))
11469 (error "Please save the buffer to a file before refiling")
11470 (when (org-string-nw-p re)
11471 (setq buffer (if (markerp pos)
11472 (marker-buffer pos)
11473 (or (find-buffer-visiting file)
11474 (find-file-noselect file))))
11475 (with-current-buffer buffer
11476 (save-excursion
11477 (save-restriction
11478 (widen)
11479 (goto-char pos)
11480 (beginning-of-line 1)
11481 (unless (org-looking-at-p re)
11482 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11484 (defun org-refile-new-child (parent-target child)
11485 "Use refile target PARENT-TARGET to add new CHILD below it."
11486 (unless parent-target
11487 (error "Cannot find parent for new node"))
11488 (let ((file (nth 1 parent-target))
11489 (pos (nth 3 parent-target))
11490 level)
11491 (with-current-buffer (or (find-buffer-visiting file)
11492 (find-file-noselect file))
11493 (save-excursion
11494 (save-restriction
11495 (widen)
11496 (if pos
11497 (goto-char pos)
11498 (goto-char (point-max))
11499 (if (not (bolp)) (newline)))
11500 (when (looking-at org-outline-regexp)
11501 (setq level (funcall outline-level))
11502 (org-end-of-subtree t t))
11503 (org-back-over-empty-lines)
11504 (insert "\n" (make-string
11505 (if pos (org-get-valid-level level 1) 1) ?*)
11506 " " child "\n")
11507 (beginning-of-line 0)
11508 (list (concat (car parent-target) "/" child) file "" (point)))))))
11510 (defun org-olpath-completing-read (prompt collection &rest args)
11511 "Read an outline path like a file name."
11512 (let ((thetable collection)
11513 (org-completion-use-ido nil) ; does not work with ido.
11514 (org-completion-use-iswitchb nil)) ; or iswitchb
11515 (apply
11516 'org-icompleting-read prompt
11517 (lambda (string predicate &optional flag)
11518 (let (rtn r f (l (length string)))
11519 (cond
11520 ((eq flag nil)
11521 ;; try completion
11522 (try-completion string thetable))
11523 ((eq flag t)
11524 ;; all-completions
11525 (setq rtn (all-completions string thetable predicate))
11526 (mapcar
11527 (lambda (x)
11528 (setq r (substring x l))
11529 (if (string-match " ([^)]*)$" x)
11530 (setq f (match-string 0 x))
11531 (setq f ""))
11532 (if (string-match "/" r)
11533 (concat string (substring r 0 (match-end 0)) f)
11535 rtn))
11536 ((eq flag 'lambda)
11537 ;; exact match?
11538 (assoc string thetable)))))
11539 args)))
11541 ;;;; Dynamic blocks
11543 (defun org-find-dblock (name)
11544 "Find the first dynamic block with name NAME in the buffer.
11545 If not found, stay at current position and return nil."
11546 (let ((case-fold-search t) pos)
11547 (save-excursion
11548 (goto-char (point-min))
11549 (setq pos (and (re-search-forward
11550 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11551 (match-beginning 0))))
11552 (if pos (goto-char pos))
11553 pos))
11555 (defconst org-dblock-start-re
11556 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11557 "Matches the start line of a dynamic block, with parameters.")
11559 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11560 "Matches the end of a dynamic block.")
11562 (defun org-create-dblock (plist)
11563 "Create a dynamic block section, with parameters taken from PLIST.
11564 PLIST must contain a :name entry which is used as name of the block."
11565 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11566 (end-of-line 1)
11567 (newline))
11568 (let ((col (current-column))
11569 (name (plist-get plist :name)))
11570 (insert "#+BEGIN: " name)
11571 (while plist
11572 (if (eq (car plist) :name)
11573 (setq plist (cddr plist))
11574 (insert " " (prin1-to-string (pop plist)))))
11575 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11576 (beginning-of-line -2)))
11578 (defun org-prepare-dblock ()
11579 "Prepare dynamic block for refresh.
11580 This empties the block, puts the cursor at the insert position and returns
11581 the property list including an extra property :name with the block name."
11582 (unless (looking-at org-dblock-start-re)
11583 (error "Not at a dynamic block"))
11584 (let* ((begdel (1+ (match-end 0)))
11585 (name (org-no-properties (match-string 1)))
11586 (params (append (list :name name)
11587 (read (concat "(" (match-string 3) ")")))))
11588 (save-excursion
11589 (beginning-of-line 1)
11590 (skip-chars-forward " \t")
11591 (setq params (plist-put params :indentation-column (current-column))))
11592 (unless (re-search-forward org-dblock-end-re nil t)
11593 (error "Dynamic block not terminated"))
11594 (setq params
11595 (append params
11596 (list :content (buffer-substring
11597 begdel (match-beginning 0)))))
11598 (delete-region begdel (match-beginning 0))
11599 (goto-char begdel)
11600 (open-line 1)
11601 params))
11603 (defun org-map-dblocks (&optional command)
11604 "Apply COMMAND to all dynamic blocks in the current buffer.
11605 If COMMAND is not given, use `org-update-dblock'."
11606 (let ((cmd (or command 'org-update-dblock)))
11607 (save-excursion
11608 (goto-char (point-min))
11609 (while (re-search-forward org-dblock-start-re nil t)
11610 (goto-char (match-beginning 0))
11611 (save-excursion
11612 (condition-case nil
11613 (funcall cmd)
11614 (error (message "Error during update of dynamic block"))))
11615 (unless (re-search-forward org-dblock-end-re nil t)
11616 (error "Dynamic block not terminated"))))))
11618 (defun org-dblock-update (&optional arg)
11619 "User command for updating dynamic blocks.
11620 Update the dynamic block at point. With prefix ARG, update all dynamic
11621 blocks in the buffer."
11622 (interactive "P")
11623 (if arg
11624 (org-update-all-dblocks)
11625 (or (looking-at org-dblock-start-re)
11626 (org-beginning-of-dblock))
11627 (org-update-dblock)))
11629 (defun org-update-dblock ()
11630 "Update the dynamic block at point.
11631 This means to empty the block, parse for parameters and then call
11632 the correct writing function."
11633 (interactive)
11634 (save-window-excursion
11635 (let* ((pos (point))
11636 (line (org-current-line))
11637 (params (org-prepare-dblock))
11638 (name (plist-get params :name))
11639 (indent (plist-get params :indentation-column))
11640 (cmd (intern (concat "org-dblock-write:" name))))
11641 (message "Updating dynamic block `%s' at line %d..." name line)
11642 (funcall cmd params)
11643 (message "Updating dynamic block `%s' at line %d...done" name line)
11644 (goto-char pos)
11645 (when (and indent (> indent 0))
11646 (setq indent (make-string indent ?\ ))
11647 (save-excursion
11648 (org-beginning-of-dblock)
11649 (forward-line 1)
11650 (while (not (looking-at org-dblock-end-re))
11651 (insert indent)
11652 (beginning-of-line 2))
11653 (when (looking-at org-dblock-end-re)
11654 (and (looking-at "[ \t]+")
11655 (replace-match ""))
11656 (insert indent)))))))
11658 (defun org-beginning-of-dblock ()
11659 "Find the beginning of the dynamic block at point.
11660 Error if there is no such block at point."
11661 (let ((pos (point))
11662 beg)
11663 (end-of-line 1)
11664 (if (and (re-search-backward org-dblock-start-re nil t)
11665 (setq beg (match-beginning 0))
11666 (re-search-forward org-dblock-end-re nil t)
11667 (> (match-end 0) pos))
11668 (goto-char beg)
11669 (goto-char pos)
11670 (error "Not in a dynamic block"))))
11672 (defun org-update-all-dblocks ()
11673 "Update all dynamic blocks in the buffer.
11674 This function can be used in a hook."
11675 (interactive)
11676 (when (derived-mode-p 'org-mode)
11677 (org-map-dblocks 'org-update-dblock)))
11680 ;;;; Completion
11682 (defun org-get-export-keywords ()
11683 "Return a list of all currently understood export keywords.
11684 Export keywords include options, block names, attributes and
11685 keywords relative to each registered export back-end."
11686 (delq nil
11687 (let (keywords)
11688 (mapc
11689 (lambda (back-end)
11690 (let ((props (cdr back-end)))
11691 ;; Back-end name (for keywords, like #+LATEX:)
11692 (push (upcase (symbol-name (car back-end))) keywords)
11693 ;; Back-end options.
11694 (mapc (lambda (option) (push (cadr option) keywords))
11695 (plist-get (cdr back-end) :options-alist))))
11696 (org-bound-and-true-p org-export-registered-backends))
11697 keywords)))
11699 (defconst org-options-keywords
11700 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11701 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11702 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11703 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11704 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "INFOJS_OPT:"))
11706 (defcustom org-structure-template-alist
11707 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11708 "<src lang=\"?\">\n\n</src>")
11709 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11710 "<example>\n?\n</example>")
11711 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11712 "<quote>\n?\n</quote>")
11713 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11714 "<verse>\n?\n</verse>")
11715 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11716 "<verbatim>\n?\n</verbatim>")
11717 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11718 "<center>\n?\n</center>")
11719 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11720 "<literal style=\"latex\">\n?\n</literal>")
11721 ("L" "#+LaTeX: "
11722 "<literal style=\"latex\">?</literal>")
11723 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11724 "<literal style=\"html\">\n?\n</literal>")
11725 ("H" "#+HTML: "
11726 "<literal style=\"html\">?</literal>")
11727 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11728 ("A" "#+ASCII: ")
11729 ("i" "#+INDEX: ?"
11730 "#+INDEX: ?")
11731 ("I" "#+INCLUDE: %file ?"
11732 "<include file=%file markup=\"?\">"))
11733 "Structure completion elements.
11734 This is a list of abbreviation keys and values. The value gets inserted
11735 if you type `<' followed by the key and then press the completion key,
11736 usually `M-TAB'. %file will be replaced by a file name after prompting
11737 for the file using completion. The cursor will be placed at the position
11738 of the `?` in the template.
11739 There are two templates for each key, the first uses the original Org syntax,
11740 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11741 the default when the /org-mtags.el/ module has been loaded. See also the
11742 variable `org-mtags-prefer-muse-templates'."
11743 :group 'org-completion
11744 :type '(repeat
11745 (string :tag "Key")
11746 (string :tag "Template")
11747 (string :tag "Muse Template")))
11749 (defun org-try-structure-completion ()
11750 "Try to complete a structure template before point.
11751 This looks for strings like \"<e\" on an otherwise empty line and
11752 expands them."
11753 (let ((l (buffer-substring (point-at-bol) (point)))
11755 (when (and (looking-at "[ \t]*$")
11756 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11757 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11758 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11759 (match-beginning 1)) a)
11760 t)))
11762 (defun org-complete-expand-structure-template (start cell)
11763 "Expand a structure template."
11764 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11765 (rpl (nth (if musep 2 1) cell))
11766 (ind ""))
11767 (delete-region start (point))
11768 (when (string-match "\\`#\\+" rpl)
11769 (cond
11770 ((bolp))
11771 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11772 (setq ind (buffer-substring (point-at-bol) (point))))
11773 (t (newline))))
11774 (setq start (point))
11775 (if (string-match "%file" rpl)
11776 (setq rpl (replace-match
11777 (concat
11778 "\""
11779 (save-match-data
11780 (abbreviate-file-name (read-file-name "Include file: ")))
11781 "\"")
11782 t t rpl)))
11783 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11784 (concat "\n" ind)))
11785 (insert rpl)
11786 (if (re-search-backward "\\?" start t) (delete-char 1))))
11788 ;;;; TODO, DEADLINE, Comments
11790 (defun org-toggle-comment ()
11791 "Change the COMMENT state of an entry."
11792 (interactive)
11793 (save-excursion
11794 (org-back-to-heading)
11795 (let (case-fold-search)
11796 (cond
11797 ((looking-at (format org-heading-keyword-regexp-format
11798 org-comment-string))
11799 (goto-char (match-end 1))
11800 (looking-at (concat " +" org-comment-string))
11801 (replace-match "" t t)
11802 (when (eolp) (insert " ")))
11803 ((looking-at org-outline-regexp)
11804 (goto-char (match-end 0))
11805 (insert org-comment-string " "))))))
11807 (defvar org-last-todo-state-is-todo nil
11808 "This is non-nil when the last TODO state change led to a TODO state.
11809 If the last change removed the TODO tag or switched to DONE, then
11810 this is nil.")
11812 (defvar org-setting-tags nil) ; dynamically skipped
11814 (defvar org-todo-setup-filter-hook nil
11815 "Hook for functions that pre-filter todo specs.
11816 Each function takes a todo spec and returns either nil or the spec
11817 transformed into canonical form." )
11819 (defvar org-todo-get-default-hook nil
11820 "Hook for functions that get a default item for todo.
11821 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11822 nil or a string to be used for the todo mark." )
11824 (defvar org-agenda-headline-snapshot-before-repeat)
11826 (defun org-current-effective-time ()
11827 "Return current time adjusted for `org-extend-today-until' variable."
11828 (let* ((ct (org-current-time))
11829 (dct (decode-time ct))
11830 (ct1
11831 (cond
11832 (org-use-last-clock-out-time-as-effective-time
11833 (or (org-clock-get-last-clock-out-time) ct))
11834 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11835 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11836 (t ct))))
11837 ct1))
11839 (defun org-todo-yesterday (&optional arg)
11840 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11841 (interactive "P")
11842 (if (eq major-mode 'org-agenda-mode)
11843 (apply 'org-agenda-todo-yesterday arg)
11844 (let* ((hour (third (decode-time
11845 (org-current-time))))
11846 (org-extend-today-until (1+ hour)))
11847 (org-todo arg))))
11849 (defvar org-block-entry-blocking ""
11850 "First entry preventing the TODO state change.")
11852 (defun org-todo (&optional arg)
11853 "Change the TODO state of an item.
11854 The state of an item is given by a keyword at the start of the heading,
11855 like
11856 *** TODO Write paper
11857 *** DONE Call mom
11859 The different keywords are specified in the variable `org-todo-keywords'.
11860 By default the available states are \"TODO\" and \"DONE\".
11861 So for this example: when the item starts with TODO, it is changed to DONE.
11862 When it starts with DONE, the DONE is removed. And when neither TODO nor
11863 DONE are present, add TODO at the beginning of the heading.
11865 With \\[universal-argument] prefix arg, use completion to determine the new \
11866 state.
11867 With numeric prefix arg, switch to that state.
11868 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11869 keywords (nextset).
11870 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11871 With a numeric prefix arg of 0, inhibit note taking for the change.
11873 For calling through lisp, arg is also interpreted in the following way:
11874 'none -> empty state
11875 \"\"(empty string) -> switch to empty state
11876 'done -> switch to DONE
11877 'nextset -> switch to the next set of keywords
11878 'previousset -> switch to the previous set of keywords
11879 \"WAITING\" -> switch to the specified keyword, but only if it
11880 really is a member of `org-todo-keywords'."
11881 (interactive "P")
11882 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11883 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11884 'region-start-level 'region))
11885 org-loop-over-headlines-in-active-region)
11886 (org-map-entries
11887 `(org-todo ,arg)
11888 org-loop-over-headlines-in-active-region
11889 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11890 (if (equal arg '(16)) (setq arg 'nextset))
11891 (let ((org-blocker-hook org-blocker-hook)
11892 commentp
11893 case-fold-search)
11894 (when (equal arg '(64))
11895 (setq arg nil org-blocker-hook nil))
11896 (when (and org-blocker-hook
11897 (or org-inhibit-blocking
11898 (org-entry-get nil "NOBLOCKING")))
11899 (setq org-blocker-hook nil))
11900 (save-excursion
11901 (catch 'exit
11902 (org-back-to-heading t)
11903 (when (looking-at (concat "^\\*+ " org-comment-string))
11904 (org-toggle-comment)
11905 (setq commentp t))
11906 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11907 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11908 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11909 (let* ((match-data (match-data))
11910 (startpos (point-at-bol))
11911 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11912 (org-log-done org-log-done)
11913 (org-log-repeat org-log-repeat)
11914 (org-todo-log-states org-todo-log-states)
11915 (org-inhibit-logging
11916 (if (equal arg 0)
11917 (progn (setq arg nil) 'note) org-inhibit-logging))
11918 (this (match-string 1))
11919 (hl-pos (match-beginning 0))
11920 (head (org-get-todo-sequence-head this))
11921 (ass (assoc head org-todo-kwd-alist))
11922 (interpret (nth 1 ass))
11923 (done-word (nth 3 ass))
11924 (final-done-word (nth 4 ass))
11925 (org-last-state (or this ""))
11926 (completion-ignore-case t)
11927 (member (member this org-todo-keywords-1))
11928 (tail (cdr member))
11929 (org-state (cond
11930 ((and org-todo-key-trigger
11931 (or (and (equal arg '(4))
11932 (eq org-use-fast-todo-selection 'prefix))
11933 (and (not arg) org-use-fast-todo-selection
11934 (not (eq org-use-fast-todo-selection
11935 'prefix)))))
11936 ;; Use fast selection
11937 (org-fast-todo-selection))
11938 ((and (equal arg '(4))
11939 (or (not org-use-fast-todo-selection)
11940 (not org-todo-key-trigger)))
11941 ;; Read a state with completion
11942 (org-icompleting-read
11943 "State: " (mapcar (lambda(x) (list x))
11944 org-todo-keywords-1)
11945 nil t))
11946 ((eq arg 'right)
11947 (if this
11948 (if tail (car tail) nil)
11949 (car org-todo-keywords-1)))
11950 ((eq arg 'left)
11951 (if (equal member org-todo-keywords-1)
11953 (if this
11954 (nth (- (length org-todo-keywords-1)
11955 (length tail) 2)
11956 org-todo-keywords-1)
11957 (org-last org-todo-keywords-1))))
11958 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11959 (setq arg nil))) ; hack to fall back to cycling
11960 (arg
11961 ;; user or caller requests a specific state
11962 (cond
11963 ((equal arg "") nil)
11964 ((eq arg 'none) nil)
11965 ((eq arg 'done) (or done-word (car org-done-keywords)))
11966 ((eq arg 'nextset)
11967 (or (car (cdr (member head org-todo-heads)))
11968 (car org-todo-heads)))
11969 ((eq arg 'previousset)
11970 (let ((org-todo-heads (reverse org-todo-heads)))
11971 (or (car (cdr (member head org-todo-heads)))
11972 (car org-todo-heads))))
11973 ((car (member arg org-todo-keywords-1)))
11974 ((stringp arg)
11975 (error "State `%s' not valid in this file" arg))
11976 ((nth (1- (prefix-numeric-value arg))
11977 org-todo-keywords-1))))
11978 ((null member) (or head (car org-todo-keywords-1)))
11979 ((equal this final-done-word) nil) ;; -> make empty
11980 ((null tail) nil) ;; -> first entry
11981 ((memq interpret '(type priority))
11982 (if (eq this-command last-command)
11983 (car tail)
11984 (if (> (length tail) 0)
11985 (or done-word (car org-done-keywords))
11986 nil)))
11988 (car tail))))
11989 (org-state (or
11990 (run-hook-with-args-until-success
11991 'org-todo-get-default-hook org-state org-last-state)
11992 org-state))
11993 (next (if org-state (concat " " org-state " ") " "))
11994 (change-plist (list :type 'todo-state-change :from this :to org-state
11995 :position startpos))
11996 dolog now-done-p)
11997 (when org-blocker-hook
11998 (setq org-last-todo-state-is-todo
11999 (not (member this org-done-keywords)))
12000 (unless (save-excursion
12001 (save-match-data
12002 (org-with-wide-buffer
12003 (run-hook-with-args-until-failure
12004 'org-blocker-hook change-plist))))
12005 (if (org-called-interactively-p 'interactive)
12006 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12007 this org-state org-block-entry-blocking)
12008 ;; fail silently
12009 (message "TODO state change from %s to %s blocked (by \"%s\")"
12010 this org-state org-block-entry-blocking)
12011 (throw 'exit nil))))
12012 (store-match-data match-data)
12013 (replace-match next t t)
12014 (unless (pos-visible-in-window-p hl-pos)
12015 (message "TODO state changed to %s" (org-trim next)))
12016 (unless head
12017 (setq head (org-get-todo-sequence-head org-state)
12018 ass (assoc head org-todo-kwd-alist)
12019 interpret (nth 1 ass)
12020 done-word (nth 3 ass)
12021 final-done-word (nth 4 ass)))
12022 (when (memq arg '(nextset previousset))
12023 (message "Keyword-Set %d/%d: %s"
12024 (- (length org-todo-sets) -1
12025 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12026 (length org-todo-sets)
12027 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12028 (setq org-last-todo-state-is-todo
12029 (not (member org-state org-done-keywords)))
12030 (setq now-done-p (and (member org-state org-done-keywords)
12031 (not (member this org-done-keywords))))
12032 (and logging (org-local-logging logging))
12033 (when (and (or org-todo-log-states org-log-done)
12034 (not (eq org-inhibit-logging t))
12035 (not (memq arg '(nextset previousset))))
12036 ;; we need to look at recording a time and note
12037 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12038 (nth 2 (assoc this org-todo-log-states))))
12039 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12040 (setq dolog 'time))
12041 (when (and org-state
12042 (member org-state org-not-done-keywords)
12043 (not (member this org-not-done-keywords)))
12044 ;; This is now a todo state and was not one before
12045 ;; If there was a CLOSED time stamp, get rid of it.
12046 (org-add-planning-info nil nil 'closed))
12047 (when (and now-done-p org-log-done)
12048 ;; It is now done, and it was not done before
12049 (org-add-planning-info 'closed (org-current-effective-time))
12050 (if (and (not dolog) (eq 'note org-log-done))
12051 (org-add-log-setup 'done org-state this 'findpos 'note)))
12052 (when (and org-state dolog)
12053 ;; This is a non-nil state, and we need to log it
12054 (org-add-log-setup 'state org-state this 'findpos dolog)))
12055 ;; Fixup tag positioning
12056 (org-todo-trigger-tag-changes org-state)
12057 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12058 (when org-provide-todo-statistics
12059 (org-update-parent-todo-statistics))
12060 (run-hooks 'org-after-todo-state-change-hook)
12061 (if (and arg (not (member org-state org-done-keywords)))
12062 (setq head (org-get-todo-sequence-head org-state)))
12063 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12064 ;; Do we need to trigger a repeat?
12065 (when now-done-p
12066 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12067 ;; This is for the agenda, take a snapshot of the headline.
12068 (save-match-data
12069 (setq org-agenda-headline-snapshot-before-repeat
12070 (org-get-heading))))
12071 (org-auto-repeat-maybe org-state))
12072 ;; Fixup cursor location if close to the keyword
12073 (if (and (outline-on-heading-p)
12074 (not (bolp))
12075 (save-excursion (beginning-of-line 1)
12076 (looking-at org-todo-line-regexp))
12077 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12078 (progn
12079 (goto-char (or (match-end 2) (match-end 1)))
12080 (and (looking-at " ") (just-one-space))))
12081 (when org-trigger-hook
12082 (save-excursion
12083 (run-hook-with-args 'org-trigger-hook change-plist)))
12084 (when commentp (org-toggle-comment))))))))
12086 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12087 "Block turning an entry into a TODO, using the hierarchy.
12088 This checks whether the current task should be blocked from state
12089 changes. Such blocking occurs when:
12091 1. The task has children which are not all in a completed state.
12093 2. A task has a parent with the property :ORDERED:, and there
12094 are siblings prior to the current task with incomplete
12095 status.
12097 3. The parent of the task is blocked because it has siblings that should
12098 be done first, or is child of a block grandparent TODO entry."
12100 (if (not org-enforce-todo-dependencies)
12101 t ; if locally turned off don't block
12102 (catch 'dont-block
12103 ;; If this is not a todo state change, or if this entry is already DONE,
12104 ;; do not block
12105 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12106 (member (plist-get change-plist :from)
12107 (cons 'done org-done-keywords))
12108 (member (plist-get change-plist :to)
12109 (cons 'todo org-not-done-keywords))
12110 (not (plist-get change-plist :to)))
12111 (throw 'dont-block t))
12112 ;; If this task has children, and any are undone, it's blocked
12113 (save-excursion
12114 (org-back-to-heading t)
12115 (let ((this-level (funcall outline-level)))
12116 (outline-next-heading)
12117 (let ((child-level (funcall outline-level)))
12118 (while (and (not (eobp))
12119 (> child-level this-level))
12120 ;; this todo has children, check whether they are all
12121 ;; completed
12122 (if (and (not (org-entry-is-done-p))
12123 (org-entry-is-todo-p))
12124 (progn (setq org-block-entry-blocking (org-get-heading))
12125 (throw 'dont-block nil)))
12126 (outline-next-heading)
12127 (setq child-level (funcall outline-level))))))
12128 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12129 ;; any previous siblings are undone, it's blocked
12130 (save-excursion
12131 (org-back-to-heading t)
12132 (let* ((pos (point))
12133 (parent-pos (and (org-up-heading-safe) (point))))
12134 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12135 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12136 (forward-line 1)
12137 (re-search-forward org-not-done-heading-regexp pos t))
12138 (setq org-block-entry-blocking (match-string 0))
12139 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12140 ;; Search further up the hierarchy, to see if an ancestor is blocked
12141 (while t
12142 (goto-char parent-pos)
12143 (if (not (looking-at org-not-done-heading-regexp))
12144 (throw 'dont-block t)) ; do not block, parent is not a TODO
12145 (setq pos (point))
12146 (setq parent-pos (and (org-up-heading-safe) (point)))
12147 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12148 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12149 (forward-line 1)
12150 (re-search-forward org-not-done-heading-regexp pos t)
12151 (setq org-block-entry-blocking (org-get-heading)))
12152 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12154 (defcustom org-track-ordered-property-with-tag nil
12155 "Should the ORDERED property also be shown as a tag?
12156 The ORDERED property decides if an entry should require subtasks to be
12157 completed in sequence. Since a property is not very visible, setting
12158 this option means that toggling the ORDERED property with the command
12159 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12160 not relevant for the behavior, but it makes things more visible.
12162 Note that toggling the tag with tags commands will not change the property
12163 and therefore not influence behavior!
12165 This can be t, meaning the tag ORDERED should be used, It can also be a
12166 string to select a different tag for this task."
12167 :group 'org-todo
12168 :type '(choice
12169 (const :tag "No tracking" nil)
12170 (const :tag "Track with ORDERED tag" t)
12171 (string :tag "Use other tag")))
12173 (defun org-toggle-ordered-property ()
12174 "Toggle the ORDERED property of the current entry.
12175 For better visibility, you can track the value of this property with a tag.
12176 See variable `org-track-ordered-property-with-tag'."
12177 (interactive)
12178 (let* ((t1 org-track-ordered-property-with-tag)
12179 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12180 (save-excursion
12181 (org-back-to-heading)
12182 (if (org-entry-get nil "ORDERED")
12183 (progn
12184 (org-delete-property "ORDERED" "PROPERTIES")
12185 (and tag (org-toggle-tag tag 'off))
12186 (message "Subtasks can be completed in arbitrary order"))
12187 (org-entry-put nil "ORDERED" "t")
12188 (and tag (org-toggle-tag tag 'on))
12189 (message "Subtasks must be completed in sequence")))))
12191 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12192 (defun org-block-todo-from-checkboxes (change-plist)
12193 "Block turning an entry into a TODO, using checkboxes.
12194 This checks whether the current task should be blocked from state
12195 changes because there are unchecked boxes in this entry."
12196 (if (not org-enforce-todo-checkbox-dependencies)
12197 t ; if locally turned off don't block
12198 (catch 'dont-block
12199 ;; If this is not a todo state change, or if this entry is already DONE,
12200 ;; do not block
12201 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12202 (member (plist-get change-plist :from)
12203 (cons 'done org-done-keywords))
12204 (member (plist-get change-plist :to)
12205 (cons 'todo org-not-done-keywords))
12206 (not (plist-get change-plist :to)))
12207 (throw 'dont-block t))
12208 ;; If this task has checkboxes that are not checked, it's blocked
12209 (save-excursion
12210 (org-back-to-heading t)
12211 (let ((beg (point)) end)
12212 (outline-next-heading)
12213 (setq end (point))
12214 (goto-char beg)
12215 (if (org-list-search-forward
12216 (concat (org-item-beginning-re)
12217 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12218 "\\[[- ]\\]")
12219 end t)
12220 (progn
12221 (if (boundp 'org-blocked-by-checkboxes)
12222 (setq org-blocked-by-checkboxes t))
12223 (throw 'dont-block nil)))))
12224 t))) ; do not block
12226 (defun org-entry-blocked-p ()
12227 "Is the current entry blocked?"
12228 (org-with-silent-modifications
12229 (if (org-entry-get nil "NOBLOCKING")
12230 nil ;; Never block this entry
12231 (not (run-hook-with-args-until-failure
12232 'org-blocker-hook
12233 (list :type 'todo-state-change
12234 :position (point)
12235 :from 'todo
12236 :to 'done))))))
12238 (defun org-update-statistics-cookies (all)
12239 "Update the statistics cookie, either from TODO or from checkboxes.
12240 This should be called with the cursor in a line with a statistics cookie."
12241 (interactive "P")
12242 (if all
12243 (progn
12244 (org-update-checkbox-count 'all)
12245 (org-map-entries 'org-update-parent-todo-statistics))
12246 (if (not (org-at-heading-p))
12247 (org-update-checkbox-count)
12248 (let ((pos (point-marker))
12249 end l1 l2)
12250 (ignore-errors (org-back-to-heading t))
12251 (if (not (org-at-heading-p))
12252 (org-update-checkbox-count)
12253 (setq l1 (org-outline-level))
12254 (setq end (save-excursion
12255 (outline-next-heading)
12256 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12257 (point)))
12258 (if (and (save-excursion
12259 (re-search-forward
12260 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12261 (not (save-excursion (re-search-forward
12262 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12263 (org-update-checkbox-count)
12264 (if (and l2 (> l2 l1))
12265 (progn
12266 (goto-char end)
12267 (org-update-parent-todo-statistics))
12268 (goto-char pos)
12269 (beginning-of-line 1)
12270 (while (re-search-forward
12271 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12272 (point-at-eol) t)
12273 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12274 (goto-char pos)
12275 (move-marker pos nil)))))
12277 (defvar org-entry-property-inherited-from) ;; defined below
12278 (defun org-update-parent-todo-statistics ()
12279 "Update any statistics cookie in the parent of the current headline.
12280 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12281 the entire subtree and this will travel up the hierarchy and update
12282 statistics everywhere."
12283 (let* ((prop (save-excursion (org-up-heading-safe)
12284 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12285 (recursive (or (not org-hierarchical-todo-statistics)
12286 (and prop (string-match "\\<recursive\\>" prop))))
12287 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12289 (first t)
12290 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12291 level ltoggle l1 new ndel
12292 (cnt-all 0) (cnt-done 0) is-percent kwd
12293 checkbox-beg ov ovs ove cookie-present)
12294 (catch 'exit
12295 (save-excursion
12296 (beginning-of-line 1)
12297 (setq ltoggle (funcall outline-level))
12298 ;; Three situations are to consider:
12300 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12301 ;; to the top-level ancestor on the headline;
12303 ;; 2. If parent has "recursive" property, repeat up to the
12304 ;; headline setting that property, taking inheritance into
12305 ;; account;
12307 ;; 3. Else, move up to direct parent and proceed only once.
12308 (while (and (setq level (org-up-heading-safe))
12309 (or recursive first)
12310 (>= (point) lim))
12311 (setq first nil cookie-present nil)
12312 (unless (and level
12313 (not (string-match
12314 "\\<checkbox\\>"
12315 (downcase (or (org-entry-get nil "COOKIE_DATA")
12316 "")))))
12317 (throw 'exit nil))
12318 (while (re-search-forward box-re (point-at-eol) t)
12319 (setq cnt-all 0 cnt-done 0 cookie-present t)
12320 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12321 (save-match-data
12322 (unless (outline-next-heading) (throw 'exit nil))
12323 (while (and (looking-at org-complex-heading-regexp)
12324 (> (setq l1 (length (match-string 1))) level))
12325 (setq kwd (and (or recursive (= l1 ltoggle))
12326 (match-string 2)))
12327 (if (or (eq org-provide-todo-statistics 'all-headlines)
12328 (and (listp org-provide-todo-statistics)
12329 (or (member kwd org-provide-todo-statistics)
12330 (member kwd org-done-keywords))))
12331 (setq cnt-all (1+ cnt-all))
12332 (if (eq org-provide-todo-statistics t)
12333 (and kwd (setq cnt-all (1+ cnt-all)))))
12334 (and (member kwd org-done-keywords)
12335 (setq cnt-done (1+ cnt-done)))
12336 (outline-next-heading)))
12337 (setq new
12338 (if is-percent
12339 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12340 (format "[%d/%d]" cnt-done cnt-all))
12341 ndel (- (match-end 0) checkbox-beg))
12342 ;; handle overlays when updating cookie from column view
12343 (when (setq ov (car (overlays-at checkbox-beg)))
12344 (setq ovs (overlay-start ov) ove (overlay-end ov))
12345 (delete-overlay ov))
12346 (goto-char checkbox-beg)
12347 (insert new)
12348 (delete-region (point) (+ (point) ndel))
12349 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12350 (when ov (move-overlay ov ovs ove)))
12351 (when cookie-present
12352 (run-hook-with-args 'org-after-todo-statistics-hook
12353 cnt-done (- cnt-all cnt-done))))))
12354 (run-hooks 'org-todo-statistics-hook)))
12356 (defvar org-after-todo-statistics-hook nil
12357 "Hook that is called after a TODO statistics cookie has been updated.
12358 Each function is called with two arguments: the number of not-done entries
12359 and the number of done entries.
12361 For example, the following function, when added to this hook, will switch
12362 an entry to DONE when all children are done, and back to TODO when new
12363 entries are set to a TODO status. Note that this hook is only called
12364 when there is a statistics cookie in the headline!
12366 (defun org-summary-todo (n-done n-not-done)
12367 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12368 (let (org-log-done org-log-states) ; turn off logging
12369 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12372 (defvar org-todo-statistics-hook nil
12373 "Hook that is run whenever Org thinks TODO statistics should be updated.
12374 This hook runs even if there is no statistics cookie present, in which case
12375 `org-after-todo-statistics-hook' would not run.")
12377 (defun org-todo-trigger-tag-changes (state)
12378 "Apply the changes defined in `org-todo-state-tags-triggers'."
12379 (let ((l org-todo-state-tags-triggers)
12380 changes)
12381 (when (or (not state) (equal state ""))
12382 (setq changes (append changes (cdr (assoc "" l)))))
12383 (when (and (stringp state) (> (length state) 0))
12384 (setq changes (append changes (cdr (assoc state l)))))
12385 (when (member state org-not-done-keywords)
12386 (setq changes (append changes (cdr (assoc 'todo l)))))
12387 (when (member state org-done-keywords)
12388 (setq changes (append changes (cdr (assoc 'done l)))))
12389 (dolist (c changes)
12390 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12392 (defun org-local-logging (value)
12393 "Get logging settings from a property VALUE."
12394 (let* (words w a)
12395 ;; directly set the variables, they are already local.
12396 (setq org-log-done nil
12397 org-log-repeat nil
12398 org-todo-log-states nil)
12399 (setq words (org-split-string value))
12400 (while (setq w (pop words))
12401 (cond
12402 ((setq a (assoc w org-startup-options))
12403 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12404 (set (nth 1 a) (nth 2 a))))
12405 ((setq a (org-extract-log-state-settings w))
12406 (and (member (car a) org-todo-keywords-1)
12407 (push a org-todo-log-states)))))))
12409 (defun org-get-todo-sequence-head (kwd)
12410 "Return the head of the TODO sequence to which KWD belongs.
12411 If KWD is not set, check if there is a text property remembering the
12412 right sequence."
12413 (let (p)
12414 (cond
12415 ((not kwd)
12416 (or (get-text-property (point-at-bol) 'org-todo-head)
12417 (progn
12418 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12419 nil (point-at-eol)))
12420 (get-text-property p 'org-todo-head))))
12421 ((not (member kwd org-todo-keywords-1))
12422 (car org-todo-keywords-1))
12423 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12425 (defun org-fast-todo-selection ()
12426 "Fast TODO keyword selection with single keys.
12427 Returns the new TODO keyword, or nil if no state change should occur."
12428 (let* ((fulltable org-todo-key-alist)
12429 (done-keywords org-done-keywords) ;; needed for the faces.
12430 (maxlen (apply 'max (mapcar
12431 (lambda (x)
12432 (if (stringp (car x)) (string-width (car x)) 0))
12433 fulltable)))
12434 (expert nil)
12435 (fwidth (+ maxlen 3 1 3))
12436 (ncol (/ (- (window-width) 4) fwidth))
12437 tg cnt e c tbl
12438 groups ingroup)
12439 (save-excursion
12440 (save-window-excursion
12441 (if expert
12442 (set-buffer (get-buffer-create " *Org todo*"))
12443 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12444 (erase-buffer)
12445 (org-set-local 'org-done-keywords done-keywords)
12446 (setq tbl fulltable cnt 0)
12447 (while (setq e (pop tbl))
12448 (cond
12449 ((equal e '(:startgroup))
12450 (push '() groups) (setq ingroup t)
12451 (when (not (= cnt 0))
12452 (setq cnt 0)
12453 (insert "\n"))
12454 (insert "{ "))
12455 ((equal e '(:endgroup))
12456 (setq ingroup nil cnt 0)
12457 (insert "}\n"))
12458 ((equal e '(:newline))
12459 (when (not (= cnt 0))
12460 (setq cnt 0)
12461 (insert "\n")
12462 (setq e (car tbl))
12463 (while (equal (car tbl) '(:newline))
12464 (insert "\n")
12465 (setq tbl (cdr tbl)))))
12467 (setq tg (car e) c (cdr e))
12468 (if ingroup (push tg (car groups)))
12469 (setq tg (org-add-props tg nil 'face
12470 (org-get-todo-face tg)))
12471 (if (and (= cnt 0) (not ingroup)) (insert " "))
12472 (insert "[" c "] " tg (make-string
12473 (- fwidth 4 (length tg)) ?\ ))
12474 (when (= (setq cnt (1+ cnt)) ncol)
12475 (insert "\n")
12476 (if ingroup (insert " "))
12477 (setq cnt 0)))))
12478 (insert "\n")
12479 (goto-char (point-min))
12480 (if (not expert) (org-fit-window-to-buffer))
12481 (message "[a-z..]:Set [SPC]:clear")
12482 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12483 (cond
12484 ((or (= c ?\C-g)
12485 (and (= c ?q) (not (rassoc c fulltable))))
12486 (setq quit-flag t))
12487 ((= c ?\ ) nil)
12488 ((setq e (rassoc c fulltable) tg (car e))
12490 (t (setq quit-flag t)))))))
12492 (defun org-entry-is-todo-p ()
12493 (member (org-get-todo-state) org-not-done-keywords))
12495 (defun org-entry-is-done-p ()
12496 (member (org-get-todo-state) org-done-keywords))
12498 (defun org-get-todo-state ()
12499 (save-excursion
12500 (org-back-to-heading t)
12501 (and (looking-at org-todo-line-regexp)
12502 (match-end 2)
12503 (match-string 2))))
12505 (defun org-at-date-range-p (&optional inactive-ok)
12506 "Is the cursor inside a date range?"
12507 (interactive)
12508 (save-excursion
12509 (catch 'exit
12510 (let ((pos (point)))
12511 (skip-chars-backward "^[<\r\n")
12512 (skip-chars-backward "<[")
12513 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12514 (>= (match-end 0) pos)
12515 (throw 'exit t))
12516 (skip-chars-backward "^<[\r\n")
12517 (skip-chars-backward "<[")
12518 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12519 (>= (match-end 0) pos)
12520 (throw 'exit t)))
12521 nil)))
12523 (defun org-get-repeat (&optional tagline)
12524 "Check if there is a deadline/schedule with repeater in this entry."
12525 (save-match-data
12526 (save-excursion
12527 (org-back-to-heading t)
12528 (and (re-search-forward (if tagline
12529 (concat tagline "\\s-*" org-repeat-re)
12530 org-repeat-re)
12531 (org-entry-end-position) t)
12532 (match-string-no-properties 1)))))
12534 (defvar org-last-changed-timestamp)
12535 (defvar org-last-inserted-timestamp)
12536 (defvar org-log-post-message)
12537 (defvar org-log-note-purpose)
12538 (defvar org-log-note-how)
12539 (defvar org-log-note-extra)
12540 (defun org-auto-repeat-maybe (done-word)
12541 "Check if the current headline contains a repeated deadline/schedule.
12542 If yes, set TODO state back to what it was and change the base date
12543 of repeating deadline/scheduled time stamps to new date.
12544 This function is run automatically after each state change to a DONE state."
12545 ;; last-state is dynamically scoped into this function
12546 (let* ((repeat (org-get-repeat))
12547 (aa (assoc org-last-state org-todo-kwd-alist))
12548 (interpret (nth 1 aa))
12549 (head (nth 2 aa))
12550 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12551 (msg "Entry repeats: ")
12552 (org-log-done nil)
12553 (org-todo-log-states nil)
12554 re type n what ts time to-state)
12555 (when repeat
12556 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12557 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12558 org-todo-repeat-to-state))
12559 (unless (and to-state (member to-state org-todo-keywords-1))
12560 (setq to-state (if (eq interpret 'type) org-last-state head)))
12561 (org-todo to-state)
12562 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12563 (org-entry-put nil "LAST_REPEAT" (format-time-string
12564 (org-time-stamp-format t t))))
12565 (when org-log-repeat
12566 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12567 (memq 'org-add-log-note post-command-hook))
12568 ;; OK, we are already setup for some record
12569 (if (eq org-log-repeat 'note)
12570 ;; make sure we take a note, not only a time stamp
12571 (setq org-log-note-how 'note))
12572 ;; Set up for taking a record
12573 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12574 org-last-state
12575 'findpos org-log-repeat)))
12576 (org-back-to-heading t)
12577 (org-add-planning-info nil nil 'closed)
12578 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12579 org-deadline-time-regexp "\\)\\|\\("
12580 org-ts-regexp "\\)"))
12581 (while (re-search-forward
12582 re (save-excursion (outline-next-heading) (point)) t)
12583 (setq type (if (match-end 1) org-scheduled-string
12584 (if (match-end 3) org-deadline-string "Plain:"))
12585 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12586 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12587 (setq n (string-to-number (match-string 2 ts))
12588 what (match-string 3 ts))
12589 (if (equal what "w") (setq n (* n 7) what "d"))
12590 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12591 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12592 ;; Preparation, see if we need to modify the start date for the change
12593 (when (match-end 1)
12594 (setq time (save-match-data (org-time-string-to-time ts)))
12595 (cond
12596 ((equal (match-string 1 ts) ".")
12597 ;; Shift starting date to today
12598 (org-timestamp-change
12599 (- (org-today) (time-to-days time))
12600 'day))
12601 ((equal (match-string 1 ts) "+")
12602 (let ((nshiftmax 10) (nshift 0))
12603 (while (or (= nshift 0)
12604 (<= (time-to-days time)
12605 (time-to-days (current-time))))
12606 (when (= (incf nshift) nshiftmax)
12607 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12608 (error "Abort")))
12609 (org-timestamp-change n (cdr (assoc what whata)))
12610 (org-at-timestamp-p t)
12611 (setq ts (match-string 1))
12612 (setq time (save-match-data (org-time-string-to-time ts)))))
12613 (org-timestamp-change (- n) (cdr (assoc what whata)))
12614 ;; rematch, so that we have everything in place for the real shift
12615 (org-at-timestamp-p t)
12616 (setq ts (match-string 1))
12617 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12618 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12619 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12620 (setq org-log-post-message msg)
12621 (message "%s" msg))))
12623 (defun org-show-todo-tree (arg)
12624 "Make a compact tree which shows all headlines marked with TODO.
12625 The tree will show the lines where the regexp matches, and all higher
12626 headlines above the match.
12627 With a \\[universal-argument] prefix, prompt for a regexp to match.
12628 With a numeric prefix N, construct a sparse tree for the Nth element
12629 of `org-todo-keywords-1'."
12630 (interactive "P")
12631 (let ((case-fold-search nil)
12632 (kwd-re
12633 (cond ((null arg) org-not-done-regexp)
12634 ((equal arg '(4))
12635 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12636 (mapcar 'list org-todo-keywords-1))))
12637 (concat "\\("
12638 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12639 "\\)\\>")))
12640 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12641 (regexp-quote (nth (1- (prefix-numeric-value arg))
12642 org-todo-keywords-1)))
12643 (t (error "Invalid prefix argument: %s" arg)))))
12644 (message "%d TODO entries found"
12645 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12647 (defun org-deadline (arg &optional time)
12648 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12649 With one universal prefix argument, remove any deadline from the item.
12650 With two universal prefix arguments, prompt for a warning delay.
12651 With argument TIME, set the deadline at the corresponding date. TIME
12652 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12653 (interactive "P")
12654 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12655 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12656 'region-start-level 'region))
12657 org-loop-over-headlines-in-active-region)
12658 (org-map-entries
12659 `(org-deadline ',arg ,time)
12660 org-loop-over-headlines-in-active-region
12661 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12662 (let* ((old-date (org-entry-get nil "DEADLINE"))
12663 (old-date-time (if old-date (org-time-string-to-time old-date)))
12664 (repeater (and old-date
12665 (string-match
12666 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12667 old-date)
12668 (match-string 1 old-date))))
12669 (cond
12670 ((equal arg '(4))
12671 (when (and old-date org-log-redeadline)
12672 (org-add-log-setup 'deldeadline nil old-date 'findpos
12673 org-log-redeadline))
12674 (org-remove-timestamp-with-keyword org-deadline-string)
12675 (message "Item no longer has a deadline."))
12676 ((equal arg '(16))
12677 (save-excursion
12678 (if (re-search-forward
12679 org-deadline-time-regexp
12680 (save-excursion (outline-next-heading) (point)) t)
12681 (let* ((rpl0 (match-string 1))
12682 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12683 (replace-match
12684 (concat org-deadline-string
12685 " <" rpl
12686 (format " -%dd"
12687 (abs
12688 (- (time-to-days
12689 (save-match-data
12690 (org-read-date nil t nil "Warn starting from" old-date-time)))
12691 (time-to-days old-date-time))))
12692 ">") t t))
12693 (user-error "No deadline information to update"))))
12695 (org-add-planning-info 'deadline time 'closed)
12696 (when (and old-date org-log-redeadline
12697 (not (equal old-date
12698 (substring org-last-inserted-timestamp 1 -1))))
12699 (org-add-log-setup 'redeadline nil old-date 'findpos
12700 org-log-redeadline))
12701 (when repeater
12702 (save-excursion
12703 (org-back-to-heading t)
12704 (when (re-search-forward (concat org-deadline-string " "
12705 org-last-inserted-timestamp)
12706 (save-excursion
12707 (outline-next-heading) (point)) t)
12708 (goto-char (1- (match-end 0)))
12709 (insert " " repeater)
12710 (setq org-last-inserted-timestamp
12711 (concat (substring org-last-inserted-timestamp 0 -1)
12712 " " repeater
12713 (substring org-last-inserted-timestamp -1))))))
12714 (message "Deadline on %s" org-last-inserted-timestamp))))))
12716 (defun org-schedule (arg &optional time)
12717 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12718 With one universal prefix argument, remove any scheduling date from the item.
12719 With two universal prefix arguments, prompt for a delay cookie.
12720 With argument TIME, scheduled at the corresponding date. TIME can
12721 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12722 (interactive "P")
12723 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12724 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12725 'region-start-level 'region))
12726 org-loop-over-headlines-in-active-region)
12727 (org-map-entries
12728 `(org-schedule ',arg ,time)
12729 org-loop-over-headlines-in-active-region
12730 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12731 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12732 (old-date-time (if old-date (org-time-string-to-time old-date)))
12733 (repeater (and old-date
12734 (string-match
12735 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12736 old-date)
12737 (match-string 1 old-date))))
12738 (cond
12739 ((equal arg '(4))
12740 (progn
12741 (when (and old-date org-log-reschedule)
12742 (org-add-log-setup 'delschedule nil old-date 'findpos
12743 org-log-reschedule))
12744 (org-remove-timestamp-with-keyword org-scheduled-string)
12745 (message "Item is no longer scheduled.")))
12746 ((equal arg '(16))
12747 (save-excursion
12748 (if (re-search-forward
12749 org-scheduled-time-regexp
12750 (save-excursion (outline-next-heading) (point)) t)
12751 (let* ((rpl0 (match-string 1))
12752 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12753 (replace-match
12754 (concat org-scheduled-string
12755 " <" rpl
12756 (format " -%dd"
12757 (abs
12758 (- (time-to-days
12759 (save-match-data
12760 (org-read-date nil t nil "Delay until" old-date-time)))
12761 (time-to-days old-date-time))))
12762 ">") t t))
12763 (user-error "No scheduled information to update"))))
12765 (org-add-planning-info 'scheduled time 'closed)
12766 (when (and old-date org-log-reschedule
12767 (not (equal old-date
12768 (substring org-last-inserted-timestamp 1 -1))))
12769 (org-add-log-setup 'reschedule nil old-date 'findpos
12770 org-log-reschedule))
12771 (when repeater
12772 (save-excursion
12773 (org-back-to-heading t)
12774 (when (re-search-forward (concat org-scheduled-string " "
12775 org-last-inserted-timestamp)
12776 (save-excursion
12777 (outline-next-heading) (point)) t)
12778 (goto-char (1- (match-end 0)))
12779 (insert " " repeater)
12780 (setq org-last-inserted-timestamp
12781 (concat (substring org-last-inserted-timestamp 0 -1)
12782 " " repeater
12783 (substring org-last-inserted-timestamp -1))))))
12784 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12786 (defun org-get-scheduled-time (pom &optional inherit)
12787 "Get the scheduled time as a time tuple, of a format suitable
12788 for calling org-schedule with, or if there is no scheduling,
12789 returns nil."
12790 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12791 (when time
12792 (apply 'encode-time (org-parse-time-string time)))))
12794 (defun org-get-deadline-time (pom &optional inherit)
12795 "Get the deadline as a time tuple, of a format suitable for
12796 calling org-deadline with, or if there is no scheduling, returns
12797 nil."
12798 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12799 (when time
12800 (apply 'encode-time (org-parse-time-string time)))))
12802 (defun org-remove-timestamp-with-keyword (keyword)
12803 "Remove all time stamps with KEYWORD in the current entry."
12804 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12805 beg)
12806 (save-excursion
12807 (org-back-to-heading t)
12808 (setq beg (point))
12809 (outline-next-heading)
12810 (while (re-search-backward re beg t)
12811 (replace-match "")
12812 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12813 (equal (char-before) ?\ ))
12814 (backward-delete-char 1)
12815 (if (string-match "^[ \t]*$" (buffer-substring
12816 (point-at-bol) (point-at-eol)))
12817 (delete-region (point-at-bol)
12818 (min (point-max) (1+ (point-at-eol))))))))))
12820 (defun org-add-planning-info (what &optional time &rest remove)
12821 "Insert new timestamp with keyword in the line directly after the headline.
12822 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12823 If non is given, the user is prompted for a date.
12824 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12825 be removed."
12826 (interactive)
12827 (let (org-time-was-given org-end-time-was-given ts
12828 end default-time default-input)
12830 (catch 'exit
12831 (when (and (memq what '(scheduled deadline))
12832 (or (not time)
12833 (and (stringp time)
12834 (string-match "^[-+]+[0-9]" time))))
12835 ;; Try to get a default date/time from existing timestamp
12836 (save-excursion
12837 (org-back-to-heading t)
12838 (setq end (save-excursion (outline-next-heading) (point)))
12839 (when (re-search-forward (if (eq what 'scheduled)
12840 org-scheduled-time-regexp
12841 org-deadline-time-regexp)
12842 end t)
12843 (setq ts (match-string 1)
12844 default-time
12845 (apply 'encode-time (org-parse-time-string ts))
12846 default-input (and ts (org-get-compact-tod ts))))))
12847 (when what
12848 (setq time
12849 (if (stringp time)
12850 ;; This is a string (relative or absolute), set proper date
12851 (apply 'encode-time
12852 (org-read-date-analyze
12853 time default-time (decode-time default-time)))
12854 ;; If necessary, get the time from the user
12855 (or time (org-read-date nil 'to-time nil nil
12856 default-time default-input)))))
12858 (when (and org-insert-labeled-timestamps-at-point
12859 (member what '(scheduled deadline)))
12860 (insert
12861 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12862 (org-insert-time-stamp time org-time-was-given
12863 nil nil nil (list org-end-time-was-given))
12864 (setq what nil))
12865 (save-excursion
12866 (save-restriction
12867 (let (col list elt ts buffer-invisibility-spec)
12868 (org-back-to-heading t)
12869 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12870 (goto-char (match-end 1))
12871 (setq col (current-column))
12872 (goto-char (match-end 0))
12873 (if (eobp) (insert "\n") (forward-char 1))
12874 (when (and (not what)
12875 (not (looking-at
12876 (concat "[ \t]*"
12877 org-keyword-time-not-clock-regexp))))
12878 ;; Nothing to add, nothing to remove...... :-)
12879 (throw 'exit nil))
12880 (if (and (not (looking-at org-outline-regexp))
12881 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12882 "[^\r\n]*"))
12883 (not (equal (match-string 1) org-clock-string)))
12884 (narrow-to-region (match-beginning 0) (match-end 0))
12885 (insert-before-markers "\n")
12886 (backward-char 1)
12887 (narrow-to-region (point) (point))
12888 (and org-adapt-indentation (org-indent-to-column col)))
12889 ;; Check if we have to remove something.
12890 (setq list (cons what remove))
12891 (while list
12892 (setq elt (pop list))
12893 (when (or (and (eq elt 'scheduled)
12894 (re-search-forward org-scheduled-time-regexp nil t))
12895 (and (eq elt 'deadline)
12896 (re-search-forward org-deadline-time-regexp nil t))
12897 (and (eq elt 'closed)
12898 (re-search-forward org-closed-time-regexp nil t)))
12899 (replace-match "")
12900 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12901 (and (looking-at "[ \t]+") (replace-match ""))
12902 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12903 (when what
12904 (insert
12905 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12906 (cond ((eq what 'scheduled) org-scheduled-string)
12907 ((eq what 'deadline) org-deadline-string)
12908 ((eq what 'closed) org-closed-string))
12909 " ")
12910 (setq ts (org-insert-time-stamp
12911 time
12912 (or org-time-was-given
12913 (and (eq what 'closed) org-log-done-with-time))
12914 (eq what 'closed)
12915 nil nil (list org-end-time-was-given)))
12916 (insert
12917 (if (not (or (bolp) (eq (char-before) ?\ )
12918 (memq (char-after) '(32 10))
12919 (eobp))) " " ""))
12920 (end-of-line 1))
12921 (goto-char (point-min))
12922 (widen)
12923 (if (and (looking-at "[ \t]*\n")
12924 (equal (char-before) ?\n))
12925 (delete-region (1- (point)) (point-at-eol)))
12926 ts))))))
12928 (defvar org-log-note-marker (make-marker))
12929 (defvar org-log-note-purpose nil)
12930 (defvar org-log-note-state nil)
12931 (defvar org-log-note-previous-state nil)
12932 (defvar org-log-note-how nil)
12933 (defvar org-log-note-extra nil)
12934 (defvar org-log-note-window-configuration nil)
12935 (defvar org-log-note-return-to (make-marker))
12936 (defvar org-log-note-effective-time nil
12937 "Remembered current time so that dynamically scoped
12938 `org-extend-today-until' affects tha timestamps in state change
12939 log")
12941 (defvar org-log-post-message nil
12942 "Message to be displayed after a log note has been stored.
12943 The auto-repeater uses this.")
12945 (defun org-add-note ()
12946 "Add a note to the current entry.
12947 This is done in the same way as adding a state change note."
12948 (interactive)
12949 (org-add-log-setup 'note nil nil 'findpos nil))
12951 (defvar org-property-end-re)
12952 (defun org-add-log-setup (&optional purpose state prev-state
12953 findpos how extra)
12954 "Set up the post command hook to take a note.
12955 If this is about to TODO state change, the new state is expected in STATE.
12956 When FINDPOS is non-nil, find the correct position for the note in
12957 the current entry. If not, assume that it can be inserted at point.
12958 HOW is an indicator what kind of note should be created.
12959 EXTRA is additional text that will be inserted into the notes buffer."
12960 (let* ((org-log-into-drawer (org-log-into-drawer))
12961 (drawer (cond ((stringp org-log-into-drawer)
12962 org-log-into-drawer)
12963 (org-log-into-drawer "LOGBOOK"))))
12964 (save-restriction
12965 (save-excursion
12966 (when findpos
12967 (org-back-to-heading t)
12968 (narrow-to-region (point) (save-excursion
12969 (outline-next-heading) (point)))
12970 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12971 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12972 "[^\r\n]*\\)?"))
12973 (goto-char (match-end 0))
12974 (cond
12975 (drawer
12976 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12977 nil t)
12978 (progn
12979 (goto-char (match-end 0))
12980 (or org-log-states-order-reversed
12981 (and (re-search-forward org-property-end-re nil t)
12982 (goto-char (1- (match-beginning 0))))))
12983 (insert "\n:" drawer ":\n:END:")
12984 (beginning-of-line 0)
12985 (org-indent-line)
12986 (beginning-of-line 2)
12987 (org-indent-line)
12988 (end-of-line 0)))
12989 ((and org-log-state-notes-insert-after-drawers
12990 (save-excursion
12991 (forward-line) (looking-at org-drawer-regexp)))
12992 (forward-line)
12993 (while (looking-at org-drawer-regexp)
12994 (goto-char (match-end 0))
12995 (re-search-forward org-property-end-re (point-max) t)
12996 (forward-line))
12997 (forward-line -1)))
12998 (unless org-log-states-order-reversed
12999 (and (= (char-after) ?\n) (forward-char 1))
13000 (org-skip-over-state-notes)
13001 (skip-chars-backward " \t\n\r")))
13002 (move-marker org-log-note-marker (point))
13003 (setq org-log-note-purpose purpose
13004 org-log-note-state state
13005 org-log-note-previous-state prev-state
13006 org-log-note-how how
13007 org-log-note-extra extra
13008 org-log-note-effective-time (org-current-effective-time))
13009 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13011 (defun org-skip-over-state-notes ()
13012 "Skip past the list of State notes in an entry."
13013 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13014 (when (ignore-errors (goto-char (org-in-item-p)))
13015 (let* ((struct (org-list-struct))
13016 (prevs (org-list-prevs-alist struct)))
13017 (while (looking-at "[ \t]*- State")
13018 (goto-char (or (org-list-get-next-item (point) struct prevs)
13019 (org-list-get-item-end (point) struct)))))))
13021 (defun org-add-log-note (&optional purpose)
13022 "Pop up a window for taking a note, and add this note later at point."
13023 (remove-hook 'post-command-hook 'org-add-log-note)
13024 (setq org-log-note-window-configuration (current-window-configuration))
13025 (delete-other-windows)
13026 (move-marker org-log-note-return-to (point))
13027 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13028 (goto-char org-log-note-marker)
13029 (org-switch-to-buffer-other-window "*Org Note*")
13030 (erase-buffer)
13031 (if (memq org-log-note-how '(time state))
13032 (let (current-prefix-arg) (org-store-log-note))
13033 (let ((org-inhibit-startup t)) (org-mode))
13034 (insert (format "# Insert note for %s.
13035 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13036 (cond
13037 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13038 ((eq org-log-note-purpose 'done) "closed todo item")
13039 ((eq org-log-note-purpose 'state)
13040 (format "state change from \"%s\" to \"%s\""
13041 (or org-log-note-previous-state "")
13042 (or org-log-note-state "")))
13043 ((eq org-log-note-purpose 'reschedule)
13044 "rescheduling")
13045 ((eq org-log-note-purpose 'delschedule)
13046 "no longer scheduled")
13047 ((eq org-log-note-purpose 'redeadline)
13048 "changing deadline")
13049 ((eq org-log-note-purpose 'deldeadline)
13050 "removing deadline")
13051 ((eq org-log-note-purpose 'refile)
13052 "refiling")
13053 ((eq org-log-note-purpose 'note)
13054 "this entry")
13055 (t (error "This should not happen")))))
13056 (if org-log-note-extra (insert org-log-note-extra))
13057 (org-set-local 'org-finish-function 'org-store-log-note)
13058 (run-hooks 'org-log-buffer-setup-hook)))
13060 (defvar org-note-abort nil) ; dynamically scoped
13061 (defun org-store-log-note ()
13062 "Finish taking a log note, and insert it to where it belongs."
13063 (let ((txt (buffer-string)))
13064 (kill-buffer (current-buffer))
13065 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13066 lines ind bul)
13067 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13068 (setq txt (replace-match "" t t txt)))
13069 (if (string-match "\\s-+\\'" txt)
13070 (setq txt (replace-match "" t t txt)))
13071 (setq lines (org-split-string txt "\n"))
13072 (when (and note (string-match "\\S-" note))
13073 (setq note
13074 (org-replace-escapes
13075 note
13076 (list (cons "%u" (user-login-name))
13077 (cons "%U" user-full-name)
13078 (cons "%t" (format-time-string
13079 (org-time-stamp-format 'long 'inactive)
13080 org-log-note-effective-time))
13081 (cons "%T" (format-time-string
13082 (org-time-stamp-format 'long nil)
13083 org-log-note-effective-time))
13084 (cons "%d" (format-time-string
13085 (org-time-stamp-format nil 'inactive)
13086 org-log-note-effective-time))
13087 (cons "%D" (format-time-string
13088 (org-time-stamp-format nil nil)
13089 org-log-note-effective-time))
13090 (cons "%s" (if org-log-note-state
13091 (concat "\"" org-log-note-state "\"")
13092 ""))
13093 (cons "%S" (if org-log-note-previous-state
13094 (concat "\"" org-log-note-previous-state "\"")
13095 "\"\"")))))
13096 (if lines (setq note (concat note " \\\\")))
13097 (push note lines))
13098 (when (or current-prefix-arg org-note-abort)
13099 (when org-log-into-drawer
13100 (org-remove-empty-drawer-at
13101 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13102 org-log-note-marker))
13103 (setq lines nil))
13104 (when lines
13105 (with-current-buffer (marker-buffer org-log-note-marker)
13106 (save-excursion
13107 (goto-char org-log-note-marker)
13108 (move-marker org-log-note-marker nil)
13109 (end-of-line 1)
13110 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13111 (setq ind (save-excursion
13112 (if (ignore-errors (goto-char (org-in-item-p)))
13113 (let ((struct (org-list-struct)))
13114 (org-list-get-ind
13115 (org-list-get-top-point struct) struct))
13116 (skip-chars-backward " \r\t\n")
13117 (cond
13118 ((and (org-at-heading-p)
13119 org-adapt-indentation)
13120 (1+ (org-current-level)))
13121 ((org-at-heading-p) 0)
13122 (t (org-get-indentation))))))
13123 (setq bul (org-list-bullet-string "-"))
13124 (org-indent-line-to ind)
13125 (insert bul (pop lines))
13126 (let ((ind-body (+ (length bul) ind)))
13127 (while lines
13128 (insert "\n")
13129 (org-indent-line-to ind-body)
13130 (insert (pop lines))))
13131 (message "Note stored")
13132 (org-back-to-heading t)
13133 (org-cycle-hide-drawers 'children))))))
13134 (set-window-configuration org-log-note-window-configuration)
13135 (with-current-buffer (marker-buffer org-log-note-return-to)
13136 (goto-char org-log-note-return-to))
13137 (move-marker org-log-note-return-to nil)
13138 (and org-log-post-message (message "%s" org-log-post-message)))
13140 (defun org-remove-empty-drawer-at (drawer pos)
13141 "Remove an empty drawer DRAWER at position POS.
13142 POS may also be a marker."
13143 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13144 (save-excursion
13145 (save-restriction
13146 (widen)
13147 (goto-char pos)
13148 (if (org-in-regexp
13149 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13150 (replace-match ""))))))
13152 (defvar org-ts-type nil)
13153 (defun org-sparse-tree (&optional arg type)
13154 "Create a sparse tree, prompt for the details.
13155 This command can create sparse trees. You first need to select the type
13156 of match used to create the tree:
13158 t Show all TODO entries.
13159 T Show entries with a specific TODO keyword.
13160 m Show entries selected by a tags/property match.
13161 p Enter a property name and its value (both with completion on existing
13162 names/values) and show entries with that property.
13163 r Show entries matching a regular expression (`/' can be used as well).
13164 b Show deadlines and scheduled items before a date.
13165 a Show deadlines and scheduled items after a date.
13166 d Show deadlines due within `org-deadline-warning-days'.
13167 D Show deadlines and scheduled items between a date range."
13168 (interactive "P")
13169 (let (ans kwd value ts-type)
13170 (setq type (or type org-sparse-tree-default-date-type))
13171 (setq org-ts-type type)
13172 (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"
13173 (cond ((eq type 'all) "all timestamps")
13174 ((eq type 'scheduled) "only scheduled")
13175 ((eq type 'deadline) "only deadline")
13176 ((eq type 'active) "only active timestamps")
13177 ((eq type 'inactive) "only inactive timestamps")
13178 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13179 (t "scheduled/deadline")))
13180 (setq ans (read-char-exclusive))
13181 (cond
13182 ((equal ans ?c)
13183 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13184 ((equal ans ?d)
13185 (call-interactively 'org-check-deadlines))
13186 ((equal ans ?b)
13187 (call-interactively 'org-check-before-date))
13188 ((equal ans ?a)
13189 (call-interactively 'org-check-after-date))
13190 ((equal ans ?D)
13191 (call-interactively 'org-check-dates-range))
13192 ((equal ans ?t)
13193 (call-interactively 'org-show-todo-tree))
13194 ((equal ans ?T)
13195 (org-show-todo-tree '(4)))
13196 ((member ans '(?T ?m))
13197 (call-interactively 'org-match-sparse-tree))
13198 ((member ans '(?p ?P))
13199 (setq kwd (org-icompleting-read "Property: "
13200 (mapcar 'list (org-buffer-property-keys))))
13201 (setq value (org-icompleting-read "Value: "
13202 (mapcar 'list (org-property-values kwd))))
13203 (unless (string-match "\\`{.*}\\'" value)
13204 (setq value (concat "\"" value "\"")))
13205 (org-match-sparse-tree arg (concat kwd "=" value)))
13206 ((member ans '(?r ?R ?/))
13207 (call-interactively 'org-occur))
13208 (t (error "No such sparse tree command \"%c\"" ans)))))
13210 (defvar org-occur-highlights nil
13211 "List of overlays used for occur matches.")
13212 (make-variable-buffer-local 'org-occur-highlights)
13213 (defvar org-occur-parameters nil
13214 "Parameters of the active org-occur calls.
13215 This is a list, each call to org-occur pushes as cons cell,
13216 containing the regular expression and the callback, onto the list.
13217 The list can contain several entries if `org-occur' has been called
13218 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13219 will only contain one set of parameters. When the highlights are
13220 removed (for example with `C-c C-c', or with the next edit (depending
13221 on `org-remove-highlights-with-change'), this variable is emptied
13222 as well.")
13223 (make-variable-buffer-local 'org-occur-parameters)
13225 (defun org-occur (regexp &optional keep-previous callback)
13226 "Make a compact tree which shows all matches of REGEXP.
13227 The tree will show the lines where the regexp matches, and all higher
13228 headlines above the match. It will also show the heading after the match,
13229 to make sure editing the matching entry is easy.
13230 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13231 call to `org-occur' will be kept, to allow stacking of calls to this
13232 command.
13233 If CALLBACK is non-nil, it is a function which is called to confirm
13234 that the match should indeed be shown."
13235 (interactive "sRegexp: \nP")
13236 (when (equal regexp "")
13237 (error "Regexp cannot be empty"))
13238 (unless keep-previous
13239 (org-remove-occur-highlights nil nil t))
13240 (push (cons regexp callback) org-occur-parameters)
13241 (let ((cnt 0))
13242 (save-excursion
13243 (goto-char (point-min))
13244 (if (or (not keep-previous) ; do not want to keep
13245 (not org-occur-highlights)) ; no previous matches
13246 ;; hide everything
13247 (org-overview))
13248 (while (re-search-forward regexp nil t)
13249 (when (or (not callback)
13250 (save-match-data (funcall callback)))
13251 (setq cnt (1+ cnt))
13252 (when org-highlight-sparse-tree-matches
13253 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13254 (org-show-context 'occur-tree))))
13255 (when org-remove-highlights-with-change
13256 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13257 nil 'local))
13258 (unless org-sparse-tree-open-archived-trees
13259 (org-hide-archived-subtrees (point-min) (point-max)))
13260 (run-hooks 'org-occur-hook)
13261 (if (org-called-interactively-p 'interactive)
13262 (message "%d match(es) for regexp %s" cnt regexp))
13263 cnt))
13265 (defun org-occur-next-match (&optional n reset)
13266 "Function for `next-error-function' to find sparse tree matches.
13267 N is the number of matches to move, when negative move backwards.
13268 RESET is entirely ignored - this function always goes back to the
13269 starting point when no match is found."
13270 (let* ((limit (if (< n 0) (point-min) (point-max)))
13271 (search-func (if (< n 0)
13272 'previous-single-char-property-change
13273 'next-single-char-property-change))
13274 (n (abs n))
13275 (pos (point))
13277 (catch 'exit
13278 (while (setq p1 (funcall search-func (point) 'org-type))
13279 (when (equal p1 limit)
13280 (goto-char pos)
13281 (error "No more matches"))
13282 (when (equal (get-char-property p1 'org-type) 'org-occur)
13283 (setq n (1- n))
13284 (when (= n 0)
13285 (goto-char p1)
13286 (throw 'exit (point))))
13287 (goto-char p1))
13288 (goto-char p1)
13289 (error "No more matches"))))
13291 (defun org-show-context (&optional key)
13292 "Make sure point and context are visible.
13293 How much context is shown depends upon the variables
13294 `org-show-hierarchy-above', `org-show-following-heading',
13295 `org-show-entry-below' and `org-show-siblings'."
13296 (let ((heading-p (org-at-heading-p t))
13297 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13298 (following-p (org-get-alist-option org-show-following-heading key))
13299 (entry-p (org-get-alist-option org-show-entry-below key))
13300 (siblings-p (org-get-alist-option org-show-siblings key)))
13301 ;; Show heading or entry text
13302 (if (and heading-p (not entry-p))
13303 (org-flag-heading nil) ; only show the heading
13304 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13305 (org-show-hidden-entry))) ; show entire entry
13306 (when following-p
13307 ;; Show next sibling, or heading below text
13308 (save-excursion
13309 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13310 (org-flag-heading nil))))
13311 (when siblings-p (org-show-siblings))
13312 (when hierarchy-p
13313 ;; show all higher headings, possibly with siblings
13314 (save-excursion
13315 (while (and (condition-case nil
13316 (progn (org-up-heading-all 1) t)
13317 (error nil))
13318 (not (bobp)))
13319 (org-flag-heading nil)
13320 (when siblings-p (org-show-siblings)))))
13321 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13323 (defvar org-reveal-start-hook nil
13324 "Hook run before revealing a location.")
13326 (defun org-reveal (&optional siblings)
13327 "Show current entry, hierarchy above it, and the following headline.
13328 This can be used to show a consistent set of context around locations
13329 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13330 not t for the search context.
13332 With optional argument SIBLINGS, on each level of the hierarchy all
13333 siblings are shown. This repairs the tree structure to what it would
13334 look like when opened with hierarchical calls to `org-cycle'.
13335 With double optional argument \\[universal-argument] \\[universal-argument], \
13336 go to the parent and show the
13337 entire tree."
13338 (interactive "P")
13339 (run-hooks 'org-reveal-start-hook)
13340 (let ((org-show-hierarchy-above t)
13341 (org-show-following-heading t)
13342 (org-show-siblings (if siblings t org-show-siblings)))
13343 (org-show-context nil))
13344 (when (equal siblings '(16))
13345 (save-excursion
13346 (when (org-up-heading-safe)
13347 (org-show-subtree)
13348 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13350 (defun org-highlight-new-match (beg end)
13351 "Highlight from BEG to END and mark the highlight is an occur headline."
13352 (let ((ov (make-overlay beg end)))
13353 (overlay-put ov 'face 'secondary-selection)
13354 (overlay-put ov 'org-type 'org-occur)
13355 (push ov org-occur-highlights)))
13357 (defun org-remove-occur-highlights (&optional beg end noremove)
13358 "Remove the occur highlights from the buffer.
13359 BEG and END are ignored. If NOREMOVE is nil, remove this function
13360 from the `before-change-functions' in the current buffer."
13361 (interactive)
13362 (unless org-inhibit-highlight-removal
13363 (mapc 'delete-overlay org-occur-highlights)
13364 (setq org-occur-highlights nil)
13365 (setq org-occur-parameters nil)
13366 (unless noremove
13367 (remove-hook 'before-change-functions
13368 'org-remove-occur-highlights 'local))))
13370 ;;;; Priorities
13372 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13373 "Regular expression matching the priority indicator.")
13375 (defvar org-remove-priority-next-time nil)
13377 (defun org-priority-up ()
13378 "Increase the priority of the current item."
13379 (interactive)
13380 (org-priority 'up))
13382 (defun org-priority-down ()
13383 "Decrease the priority of the current item."
13384 (interactive)
13385 (org-priority 'down))
13387 (defun org-priority (&optional action show)
13388 "Change the priority of an item.
13389 ACTION can be `set', `up', `down', or a character."
13390 (interactive "P")
13391 (if (equal action '(4))
13392 (org-show-priority)
13393 (unless org-enable-priority-commands
13394 (error "Priority commands are disabled"))
13395 (setq action (or action 'set))
13396 (let (current new news have remove)
13397 (save-excursion
13398 (org-back-to-heading t)
13399 (if (looking-at org-priority-regexp)
13400 (setq current (string-to-char (match-string 2))
13401 have t))
13402 (cond
13403 ((eq action 'remove)
13404 (setq remove t new ?\ ))
13405 ((or (eq action 'set)
13406 (if (featurep 'xemacs) (characterp action) (integerp action)))
13407 (if (not (eq action 'set))
13408 (setq new action)
13409 (message "Priority %c-%c, SPC to remove: "
13410 org-highest-priority org-lowest-priority)
13411 (save-match-data
13412 (setq new (read-char-exclusive))))
13413 (if (and (= (upcase org-highest-priority) org-highest-priority)
13414 (= (upcase org-lowest-priority) org-lowest-priority))
13415 (setq new (upcase new)))
13416 (cond ((equal new ?\ ) (setq remove t))
13417 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13418 (error "Priority must be between `%c' and `%c'"
13419 org-highest-priority org-lowest-priority))))
13420 ((eq action 'up)
13421 (setq new (if have
13422 (1- current) ; normal cycling
13423 ;; last priority was empty
13424 (if (eq last-command this-command)
13425 org-lowest-priority ; wrap around empty to lowest
13426 ;; default
13427 (if org-priority-start-cycle-with-default
13428 org-default-priority
13429 (1- org-default-priority))))))
13430 ((eq action 'down)
13431 (setq new (if have
13432 (1+ current) ; normal cycling
13433 ;; last priority was empty
13434 (if (eq last-command this-command)
13435 org-highest-priority ; wrap around empty to highest
13436 ;; default
13437 (if org-priority-start-cycle-with-default
13438 org-default-priority
13439 (1+ org-default-priority))))))
13440 (t (error "Invalid action")))
13441 (if (or (< (upcase new) org-highest-priority)
13442 (> (upcase new) org-lowest-priority))
13443 (if (and (memq action '(up down))
13444 (not have) (not (eq last-command this-command)))
13445 ;; `new' is from default priority
13446 (error
13447 "The default can not be set, see `org-default-priority' why")
13448 ;; normal cycling: `new' is beyond highest/lowest priority
13449 ;; and is wrapped around to the empty priority
13450 (setq remove t)))
13451 (setq news (format "%c" new))
13452 (if have
13453 (if remove
13454 (replace-match "" t t nil 1)
13455 (replace-match news t t nil 2))
13456 (if remove
13457 (error "No priority cookie found in line")
13458 (let ((case-fold-search nil))
13459 (looking-at org-todo-line-regexp))
13460 (if (match-end 2)
13461 (progn
13462 (goto-char (match-end 2))
13463 (insert " [#" news "]"))
13464 (goto-char (match-beginning 3))
13465 (insert "[#" news "] "))))
13466 (org-preserve-lc (org-set-tags nil 'align)))
13467 (if remove
13468 (message "Priority removed")
13469 (message "Priority of current item set to %s" news)))))
13471 (defun org-show-priority ()
13472 "Show the priority of the current item.
13473 This priority is composed of the main priority given with the [#A] cookies,
13474 and by additional input from the age of a schedules or deadline entry."
13475 (interactive)
13476 (let ((pri (if (eq major-mode 'org-agenda-mode)
13477 (org-get-at-bol 'priority)
13478 (save-excursion
13479 (save-match-data
13480 (beginning-of-line)
13481 (and (looking-at org-heading-regexp)
13482 (org-get-priority (match-string 0))))))))
13483 (message "Priority is %d" (if pri pri -1000))))
13485 (defun org-get-priority (s)
13486 "Find priority cookie and return priority."
13487 (save-match-data
13488 (if (functionp org-get-priority-function)
13489 (funcall org-get-priority-function)
13490 (if (not (string-match org-priority-regexp s))
13491 (* 1000 (- org-lowest-priority org-default-priority))
13492 (* 1000 (- org-lowest-priority
13493 (string-to-char (match-string 2 s))))))))
13495 ;;;; Tags
13497 (defvar org-agenda-archives-mode)
13498 (defvar org-map-continue-from nil
13499 "Position from where mapping should continue.
13500 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13502 (defvar org-scanner-tags nil
13503 "The current tag list while the tags scanner is running.")
13504 (defvar org-trust-scanner-tags nil
13505 "Should `org-get-tags-at' use the tags for the scanner.
13506 This is for internal dynamical scoping only.
13507 When this is non-nil, the function `org-get-tags-at' will return the value
13508 of `org-scanner-tags' instead of building the list by itself. This
13509 can lead to large speed-ups when the tags scanner is used in a file with
13510 many entries, and when the list of tags is retrieved, for example to
13511 obtain a list of properties. Building the tags list for each entry in such
13512 a file becomes an N^2 operation - but with this variable set, it scales
13513 as N.")
13515 (defun org-scan-tags (action matcher todo-only &optional start-level)
13516 "Sca headline tags with inheritance and produce output ACTION.
13518 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13519 or `agenda' to produce an entry list for an agenda view. It can also be
13520 a Lisp form or a function that should be called at each matched headline, in
13521 this case the return value is a list of all return values from these calls.
13523 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13524 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13525 only lines with a not-done TODO keyword are included in the output.
13526 This should be the same variable that was scoped into
13527 and set by `org-make-tags-matcher' when it constructed MATCHER.
13529 START-LEVEL can be a string with asterisks, reducing the scope to
13530 headlines matching this string."
13531 (require 'org-agenda)
13532 (let* ((re (concat "^"
13533 (if start-level
13534 ;; Get the correct level to match
13535 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13536 org-outline-regexp)
13537 " *\\(\\<\\("
13538 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13539 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13540 (props (list 'face 'default
13541 'done-face 'org-agenda-done
13542 'undone-face 'default
13543 'mouse-face 'highlight
13544 'org-not-done-regexp org-not-done-regexp
13545 'org-todo-regexp org-todo-regexp
13546 'org-complex-heading-regexp org-complex-heading-regexp
13547 'help-echo
13548 (format "mouse-2 or RET jump to org file %s"
13549 (abbreviate-file-name
13550 (or (buffer-file-name (buffer-base-buffer))
13551 (buffer-name (buffer-base-buffer)))))))
13552 (case-fold-search nil)
13553 (org-map-continue-from nil)
13554 lspos tags tags-list
13555 (tags-alist (list (cons 0 org-file-tags)))
13556 (llast 0) rtn rtn1 level category i txt
13557 todo marker entry priority)
13558 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13559 (setq action (list 'lambda nil action)))
13560 (save-excursion
13561 (goto-char (point-min))
13562 (when (eq action 'sparse-tree)
13563 (org-overview)
13564 (org-remove-occur-highlights))
13565 (while (re-search-forward re nil t)
13566 (setq org-map-continue-from nil)
13567 (catch :skip
13568 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13569 tags (if (match-end 4) (org-match-string-no-properties 4)))
13570 (goto-char (setq lspos (match-beginning 0)))
13571 (setq level (org-reduced-level (org-outline-level))
13572 category (org-get-category))
13573 (setq i llast llast level)
13574 ;; remove tag lists from same and sublevels
13575 (while (>= i level)
13576 (when (setq entry (assoc i tags-alist))
13577 (setq tags-alist (delete entry tags-alist)))
13578 (setq i (1- i)))
13579 ;; add the next tags
13580 (when tags
13581 (setq tags (org-split-string tags ":")
13582 tags-alist
13583 (cons (cons level tags) tags-alist)))
13584 ;; compile tags for current headline
13585 (setq tags-list
13586 (if org-use-tag-inheritance
13587 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13588 tags)
13589 org-scanner-tags tags-list)
13590 (when org-use-tag-inheritance
13591 (setcdr (car tags-alist)
13592 (mapcar (lambda (x)
13593 (setq x (copy-sequence x))
13594 (org-add-prop-inherited x))
13595 (cdar tags-alist))))
13596 (when (and tags org-use-tag-inheritance
13597 (or (not (eq t org-use-tag-inheritance))
13598 org-tags-exclude-from-inheritance))
13599 ;; selective inheritance, remove uninherited ones
13600 (setcdr (car tags-alist)
13601 (org-remove-uninherited-tags (cdar tags-alist))))
13602 (when (and
13604 ;; eval matcher only when the todo condition is OK
13605 (and (or (not todo-only) (member todo org-not-done-keywords))
13606 (let ((case-fold-search t) (org-trust-scanner-tags t))
13607 (eval matcher)))
13609 ;; Call the skipper, but return t if it does not skip,
13610 ;; so that the `and' form continues evaluating
13611 (progn
13612 (unless (eq action 'sparse-tree) (org-agenda-skip))
13615 ;; Check if timestamps are deselecting this entry
13616 (or (not todo-only)
13617 (and (member todo org-not-done-keywords)
13618 (or (not org-agenda-tags-todo-honor-ignore-options)
13619 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13621 ;; select this headline
13622 (cond
13623 ((eq action 'sparse-tree)
13624 (and org-highlight-sparse-tree-matches
13625 (org-get-heading) (match-end 0)
13626 (org-highlight-new-match
13627 (match-beginning 1) (match-end 1)))
13628 (org-show-context 'tags-tree))
13629 ((eq action 'agenda)
13630 (setq txt (org-agenda-format-item
13632 (concat
13633 (if (eq org-tags-match-list-sublevels 'indented)
13634 (make-string (1- level) ?.) "")
13635 (org-get-heading))
13636 level category
13637 tags-list)
13638 priority (org-get-priority txt))
13639 (goto-char lspos)
13640 (setq marker (org-agenda-new-marker))
13641 (org-add-props txt props
13642 'org-marker marker 'org-hd-marker marker 'org-category category
13643 'todo-state todo
13644 'priority priority 'type "tagsmatch")
13645 (push txt rtn))
13646 ((functionp action)
13647 (setq org-map-continue-from nil)
13648 (save-excursion
13649 (setq rtn1 (funcall action))
13650 (push rtn1 rtn)))
13651 (t (error "Invalid action")))
13653 ;; if we are to skip sublevels, jump to end of subtree
13654 (unless org-tags-match-list-sublevels
13655 (org-end-of-subtree t)
13656 (backward-char 1))))
13657 ;; Get the correct position from where to continue
13658 (if org-map-continue-from
13659 (goto-char org-map-continue-from)
13660 (and (= (point) lspos) (end-of-line 1)))))
13661 (when (and (eq action 'sparse-tree)
13662 (not org-sparse-tree-open-archived-trees))
13663 (org-hide-archived-subtrees (point-min) (point-max)))
13664 (nreverse rtn)))
13666 (defun org-remove-uninherited-tags (tags)
13667 "Remove all tags that are not inherited from the list TAGS."
13668 (cond
13669 ((eq org-use-tag-inheritance t)
13670 (if org-tags-exclude-from-inheritance
13671 (org-delete-all org-tags-exclude-from-inheritance tags)
13672 tags))
13673 ((not org-use-tag-inheritance) nil)
13674 ((stringp org-use-tag-inheritance)
13675 (delq nil (mapcar
13676 (lambda (x)
13677 (if (and (string-match org-use-tag-inheritance x)
13678 (not (member x org-tags-exclude-from-inheritance)))
13679 x nil))
13680 tags)))
13681 ((listp org-use-tag-inheritance)
13682 (delq nil (mapcar
13683 (lambda (x)
13684 (if (member x org-use-tag-inheritance) x nil))
13685 tags)))))
13687 (defun org-match-sparse-tree (&optional todo-only match)
13688 "Create a sparse tree according to tags string MATCH.
13689 MATCH can contain positive and negative selection of tags, like
13690 \"+WORK+URGENT-WITHBOSS\".
13691 If optional argument TODO-ONLY is non-nil, only select lines that are
13692 also TODO lines."
13693 (interactive "P")
13694 (org-agenda-prepare-buffers (list (current-buffer)))
13695 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13697 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13699 (defvar org-cached-props nil)
13700 (defun org-cached-entry-get (pom property)
13701 (if (or (eq t org-use-property-inheritance)
13702 (and (stringp org-use-property-inheritance)
13703 (string-match org-use-property-inheritance property))
13704 (and (listp org-use-property-inheritance)
13705 (member property org-use-property-inheritance)))
13706 ;; Caching is not possible, check it directly
13707 (org-entry-get pom property 'inherit)
13708 ;; Get all properties, so that we can do complicated checks easily
13709 (cdr (assoc property (or org-cached-props
13710 (setq org-cached-props
13711 (org-entry-properties pom)))))))
13713 (defun org-global-tags-completion-table (&optional files)
13714 "Return the list of all tags in all agenda buffer/files.
13715 Optional FILES argument is a list of files which can be used
13716 instead of the agenda files."
13717 (save-excursion
13718 (org-uniquify
13719 (delq nil
13720 (apply 'append
13721 (mapcar
13722 (lambda (file)
13723 (set-buffer (find-file-noselect file))
13724 (append (org-get-buffer-tags)
13725 (mapcar (lambda (x) (if (stringp (car-safe x))
13726 (list (car-safe x)) nil))
13727 org-tag-alist)))
13728 (if (and files (car files))
13729 files
13730 (org-agenda-files))))))))
13732 (defun org-make-tags-matcher (match)
13733 "Create the TAGS/TODO matcher form for the selection string MATCH.
13735 The variable `todo-only' is scoped dynamically into this function.
13736 It will be set to t if the matcher restricts matching to TODO entries,
13737 otherwise will not be touched.
13739 Returns a cons of the selection string MATCH and the constructed
13740 lisp form implementing the matcher. The matcher is to be evaluated
13741 at an Org entry, with point on the headline, and returns t if the
13742 entry matches the selection string MATCH. The returned lisp form
13743 references two variables with information about the entry, which
13744 must be bound around the form's evaluation: todo, the TODO keyword
13745 at the entry (or nil of none); and tags-list, the list of all tags
13746 at the entry including inherited ones. Additionally, the category
13747 of the entry (if any) must be specified as the text property
13748 'org-category on the headline.
13750 See also `org-scan-tags'.
13752 (declare (special todo-only))
13753 (unless (boundp 'todo-only)
13754 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13755 (unless match
13756 ;; Get a new match request, with completion
13757 (let ((org-last-tags-completion-table
13758 (org-global-tags-completion-table)))
13759 (setq match (org-completing-read-no-i
13760 "Match: " 'org-tags-completion-function nil nil nil
13761 'org-tags-history))))
13763 ;; Parse the string and create a lisp form
13764 (let ((match0 match)
13765 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13766 minus tag mm
13767 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13768 orterms term orlist re-p str-p level-p level-op time-p
13769 prop-p pn pv po gv rest)
13770 (if (string-match "/+" match)
13771 ;; match contains also a todo-matching request
13772 (progn
13773 (setq tagsmatch (substring match 0 (match-beginning 0))
13774 todomatch (substring match (match-end 0)))
13775 (if (string-match "^!" todomatch)
13776 (setq todo-only t todomatch (substring todomatch 1)))
13777 (if (string-match "^\\s-*$" todomatch)
13778 (setq todomatch nil)))
13779 ;; only matching tags
13780 (setq tagsmatch match todomatch nil))
13782 ;; Make the tags matcher
13783 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13784 (setq tagsmatcher t)
13785 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13786 (while (setq term (pop orterms))
13787 (while (and (equal (substring term -1) "\\") orterms)
13788 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13789 (while (string-match re term)
13790 (setq rest (substring term (match-end 0))
13791 minus (and (match-end 1)
13792 (equal (match-string 1 term) "-"))
13793 tag (save-match-data (replace-regexp-in-string
13794 "\\\\-" "-"
13795 (match-string 2 term)))
13796 re-p (equal (string-to-char tag) ?{)
13797 level-p (match-end 4)
13798 prop-p (match-end 5)
13799 mm (cond
13800 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13801 (level-p
13802 (setq level-op (org-op-to-function (match-string 3 term)))
13803 `(,level-op level ,(string-to-number
13804 (match-string 4 term))))
13805 (prop-p
13806 (setq pn (match-string 5 term)
13807 po (match-string 6 term)
13808 pv (match-string 7 term)
13809 re-p (equal (string-to-char pv) ?{)
13810 str-p (equal (string-to-char pv) ?\")
13811 time-p (save-match-data
13812 (string-match "^\"[[<].*[]>]\"$" pv))
13813 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13814 (if time-p (setq pv (org-matcher-time pv)))
13815 (setq po (org-op-to-function po (if time-p 'time str-p)))
13816 (cond
13817 ((equal pn "CATEGORY")
13818 (setq gv '(get-text-property (point) 'org-category)))
13819 ((equal pn "TODO")
13820 (setq gv 'todo))
13822 (setq gv `(org-cached-entry-get nil ,pn))))
13823 (if re-p
13824 (if (eq po 'org<>)
13825 `(not (string-match ,pv (or ,gv "")))
13826 `(string-match ,pv (or ,gv "")))
13827 (if str-p
13828 `(,po (or ,gv "") ,pv)
13829 `(,po (string-to-number (or ,gv ""))
13830 ,(string-to-number pv) ))))
13831 (t `(member ,tag tags-list)))
13832 mm (if minus (list 'not mm) mm)
13833 term rest)
13834 (push mm tagsmatcher))
13835 (push (if (> (length tagsmatcher) 1)
13836 (cons 'and tagsmatcher)
13837 (car tagsmatcher))
13838 orlist)
13839 (setq tagsmatcher nil))
13840 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13841 (setq tagsmatcher
13842 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13843 ;; Make the todo matcher
13844 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13845 (setq todomatcher t)
13846 (setq orterms (org-split-string todomatch "|") orlist nil)
13847 (while (setq term (pop orterms))
13848 (while (string-match re term)
13849 (setq minus (and (match-end 1)
13850 (equal (match-string 1 term) "-"))
13851 kwd (match-string 2 term)
13852 re-p (equal (string-to-char kwd) ?{)
13853 term (substring term (match-end 0))
13854 mm (if re-p
13855 `(string-match ,(substring kwd 1 -1) todo)
13856 (list 'equal 'todo kwd))
13857 mm (if minus (list 'not mm) mm))
13858 (push mm todomatcher))
13859 (push (if (> (length todomatcher) 1)
13860 (cons 'and todomatcher)
13861 (car todomatcher))
13862 orlist)
13863 (setq todomatcher nil))
13864 (setq todomatcher (if (> (length orlist) 1)
13865 (cons 'or orlist) (car orlist))))
13867 ;; Return the string and lisp forms of the matcher
13868 (setq matcher (if todomatcher
13869 (list 'and tagsmatcher todomatcher)
13870 tagsmatcher))
13871 (when todo-only
13872 (setq matcher (list 'and '(member todo org-not-done-keywords)
13873 matcher)))
13874 (cons match0 matcher)))
13876 (defun org-op-to-function (op &optional stringp)
13877 "Turn an operator into the appropriate function."
13878 (setq op
13879 (cond
13880 ((equal op "<" ) '(< string< org-time<))
13881 ((equal op ">" ) '(> org-string> org-time>))
13882 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13883 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13884 ((member op '("=" "==")) '(= string= org-time=))
13885 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13886 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13888 (defun org<> (a b) (not (= a b)))
13889 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13890 (defun org-string>= (a b) (not (string< a b)))
13891 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13892 (defun org-string<> (a b) (not (string= a b)))
13893 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13894 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13895 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13896 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13897 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13898 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13899 (defun org-2ft (s)
13900 "Convert S to a floating point time.
13901 If S is already a number, just return it. If it is a string, parse
13902 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13903 (cond
13904 ((numberp s) s)
13905 ((stringp s)
13906 (condition-case nil
13907 (float-time (apply 'encode-time (org-parse-time-string s)))
13908 (error 0.)))
13909 (t 0.)))
13911 (defun org-time-today ()
13912 "Time in seconds today at 0:00.
13913 Returns the float number of seconds since the beginning of the
13914 epoch to the beginning of today (00:00)."
13915 (float-time (apply 'encode-time
13916 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13918 (defun org-matcher-time (s)
13919 "Interpret a time comparison value."
13920 (save-match-data
13921 (cond
13922 ((string= s "<now>") (float-time))
13923 ((string= s "<today>") (org-time-today))
13924 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13925 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13926 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13927 (+ (org-time-today)
13928 (* (string-to-number (match-string 1 s))
13929 (cdr (assoc (match-string 2 s)
13930 '(("d" . 86400.0) ("w" . 604800.0)
13931 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13932 (t (org-2ft s)))))
13934 (defun org-match-any-p (re list)
13935 "Does re match any element of list?"
13936 (setq list (mapcar (lambda (x) (string-match re x)) list))
13937 (delq nil list))
13939 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13940 (defvar org-tags-overlay (make-overlay 1 1))
13941 (org-detach-overlay org-tags-overlay)
13943 (defun org-get-local-tags-at (&optional pos)
13944 "Get a list of tags defined in the current headline."
13945 (org-get-tags-at pos 'local))
13947 (defun org-get-local-tags ()
13948 "Get a list of tags defined in the current headline."
13949 (org-get-tags-at nil 'local))
13951 (defun org-get-tags-at (&optional pos local)
13952 "Get a list of all headline tags applicable at POS.
13953 POS defaults to point. If tags are inherited, the list contains
13954 the targets in the same sequence as the headlines appear, i.e.
13955 the tags of the current headline come last.
13956 When LOCAL is non-nil, only return tags from the current headline,
13957 ignore inherited ones."
13958 (interactive)
13959 (if (and org-trust-scanner-tags
13960 (or (not pos) (equal pos (point)))
13961 (not local))
13962 org-scanner-tags
13963 (let (tags ltags lastpos parent)
13964 (save-excursion
13965 (save-restriction
13966 (widen)
13967 (goto-char (or pos (point)))
13968 (save-match-data
13969 (catch 'done
13970 (condition-case nil
13971 (progn
13972 (org-back-to-heading t)
13973 (while (not (equal lastpos (point)))
13974 (setq lastpos (point))
13975 (when (looking-at
13976 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13977 (setq ltags (org-split-string
13978 (org-match-string-no-properties 1) ":"))
13979 (when parent
13980 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13981 (setq tags (append
13982 (if parent
13983 (org-remove-uninherited-tags ltags)
13984 ltags)
13985 tags)))
13986 (or org-use-tag-inheritance (throw 'done t))
13987 (if local (throw 'done t))
13988 (or (org-up-heading-safe) (error nil))
13989 (setq parent t)))
13990 (error nil)))))
13991 (if local
13992 tags
13993 (reverse (delete-dups
13994 (reverse (append
13995 (org-remove-uninherited-tags
13996 org-file-tags) tags)))))))))
13998 (defun org-add-prop-inherited (s)
13999 (add-text-properties 0 (length s) '(inherited t) s)
14002 (defun org-toggle-tag (tag &optional onoff)
14003 "Toggle the tag TAG for the current line.
14004 If ONOFF is `on' or `off', don't toggle but set to this state."
14005 (let (res current)
14006 (save-excursion
14007 (org-back-to-heading t)
14008 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14009 (point-at-eol) t)
14010 (progn
14011 (setq current (match-string 1))
14012 (replace-match ""))
14013 (setq current ""))
14014 (setq current (nreverse (org-split-string current ":")))
14015 (cond
14016 ((eq onoff 'on)
14017 (setq res t)
14018 (or (member tag current) (push tag current)))
14019 ((eq onoff 'off)
14020 (or (not (member tag current)) (setq current (delete tag current))))
14021 (t (if (member tag current)
14022 (setq current (delete tag current))
14023 (setq res t)
14024 (push tag current))))
14025 (end-of-line 1)
14026 (if current
14027 (progn
14028 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14029 (org-set-tags nil t))
14030 (delete-horizontal-space))
14031 (run-hooks 'org-after-tags-change-hook))
14032 res))
14034 (defun org-align-tags-here (to-col)
14035 ;; Assumes that this is a headline
14036 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14037 (beginning-of-line 1)
14038 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14039 (< pos (match-beginning 2)))
14040 (progn
14041 (setq tags-l (- (match-end 2) (match-beginning 2)))
14042 (goto-char (match-beginning 1))
14043 (insert " ")
14044 (delete-region (point) (1+ (match-beginning 2)))
14045 (setq ncol (max (current-column)
14046 (1+ col)
14047 (if (> to-col 0)
14048 to-col
14049 (- (abs to-col) tags-l))))
14050 (setq p (point))
14051 (insert (make-string (- ncol (current-column)) ?\ ))
14052 (setq ncol (current-column))
14053 (when indent-tabs-mode (tabify p (point-at-eol)))
14054 (org-move-to-column (min ncol col) t))
14055 (goto-char pos))))
14057 (defun org-set-tags-command (&optional arg just-align)
14058 "Call the set-tags command for the current entry."
14059 (interactive "P")
14060 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14061 (org-set-tags arg just-align)
14062 (save-excursion
14063 (unless (and (org-region-active-p)
14064 org-loop-over-headlines-in-active-region)
14065 (org-back-to-heading t))
14066 (org-set-tags arg just-align))))
14068 (defun org-set-tags-to (data)
14069 "Set the tags of the current entry to DATA, replacing the current tags.
14070 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14071 If DATA is nil or the empty string, any tags will be removed."
14072 (interactive "sTags: ")
14073 (setq data
14074 (cond
14075 ((eq data nil) "")
14076 ((equal data "") "")
14077 ((stringp data)
14078 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14079 ":"))
14080 ((listp data)
14081 (concat ":" (mapconcat 'identity data ":") ":"))))
14082 (when data
14083 (save-excursion
14084 (org-back-to-heading t)
14085 (when (looking-at org-complex-heading-regexp)
14086 (if (match-end 5)
14087 (progn
14088 (goto-char (match-beginning 5))
14089 (insert data)
14090 (delete-region (point) (point-at-eol))
14091 (org-set-tags nil 'align))
14092 (goto-char (point-at-eol))
14093 (insert " " data)
14094 (org-set-tags nil 'align)))
14095 (beginning-of-line 1)
14096 (if (looking-at ".*?\\([ \t]+\\)$")
14097 (delete-region (match-beginning 1) (match-end 1))))))
14099 (defun org-align-all-tags ()
14100 "Align the tags i all headings."
14101 (interactive)
14102 (save-excursion
14103 (or (ignore-errors (org-back-to-heading t))
14104 (outline-next-heading))
14105 (if (org-at-heading-p)
14106 (org-set-tags t)
14107 (message "No headings"))))
14109 (defvar org-indent-indentation-per-level)
14110 (defun org-set-tags (&optional arg just-align)
14111 "Set the tags for the current headline.
14112 With prefix ARG, realign all tags in headings in the current buffer."
14113 (interactive "P")
14114 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14115 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14116 'region-start-level 'region))
14117 org-loop-over-headlines-in-active-region)
14118 (org-map-entries
14119 ;; We don't use ARG and JUST-ALIGN here these args are not
14120 ;; useful when looping over headlines
14121 `(org-set-tags)
14122 org-loop-over-headlines-in-active-region
14123 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14124 (let* ((re org-outline-regexp-bol)
14125 (current (unless arg (org-get-tags-string)))
14126 (col (current-column))
14127 (org-setting-tags t)
14128 table current-tags inherited-tags ; computed below when needed
14129 tags p0 c0 c1 rpl di tc level)
14130 (if arg
14131 (save-excursion
14132 (goto-char (point-min))
14133 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14134 (while (re-search-forward re nil t)
14135 (org-set-tags nil t)
14136 (end-of-line 1)))
14137 (message "All tags realigned to column %d" org-tags-column))
14138 (if just-align
14139 (setq tags current)
14140 ;; Get a new set of tags from the user
14141 (save-excursion
14142 (setq table (append org-tag-persistent-alist
14143 (or org-tag-alist (org-get-buffer-tags))
14144 (and
14145 org-complete-tags-always-offer-all-agenda-tags
14146 (org-global-tags-completion-table
14147 (org-agenda-files))))
14148 org-last-tags-completion-table table
14149 current-tags (org-split-string current ":")
14150 inherited-tags (nreverse
14151 (nthcdr (length current-tags)
14152 (nreverse (org-get-tags-at))))
14153 tags
14154 (if (or (eq t org-use-fast-tag-selection)
14155 (and org-use-fast-tag-selection
14156 (delq nil (mapcar 'cdr table))))
14157 (org-fast-tag-selection
14158 current-tags inherited-tags table
14159 (if org-fast-tag-selection-include-todo
14160 org-todo-key-alist))
14161 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14162 (org-trim
14163 (org-icompleting-read "Tags: "
14164 'org-tags-completion-function
14165 nil nil current 'org-tags-history))))))
14166 (while (string-match "[-+&]+" tags)
14167 ;; No boolean logic, just a list
14168 (setq tags (replace-match ":" t t tags))))
14170 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14172 (if org-tags-sort-function
14173 (setq tags (mapconcat 'identity
14174 (sort (org-split-string
14175 tags (org-re "[^[:alnum:]_@#%]+"))
14176 org-tags-sort-function) ":")))
14178 (if (string-match "\\`[\t ]*\\'" tags)
14179 (setq tags "")
14180 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14181 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14183 ;; Insert new tags at the correct column
14184 (beginning-of-line 1)
14185 (setq level (or (and (looking-at org-outline-regexp)
14186 (- (match-end 0) (point) 1))
14188 (cond
14189 ((and (equal current "") (equal tags "")))
14190 ((re-search-forward
14191 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14192 (point-at-eol) t)
14193 (if (equal tags "")
14194 (setq rpl "")
14195 (goto-char (match-beginning 0))
14196 (setq c0 (current-column)
14197 ;; compute offset for the case of org-indent-mode active
14198 di (if org-indent-mode
14199 (* (1- org-indent-indentation-per-level) (1- level))
14201 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14202 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14203 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14204 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14205 (replace-match rpl t t)
14206 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14207 tags)
14208 (t (error "Tags alignment failed")))
14209 (org-move-to-column col)
14210 (unless just-align
14211 (run-hooks 'org-after-tags-change-hook))))))
14213 (defun org-change-tag-in-region (beg end tag off)
14214 "Add or remove TAG for each entry in the region.
14215 This works in the agenda, and also in an org-mode buffer."
14216 (interactive
14217 (list (region-beginning) (region-end)
14218 (let ((org-last-tags-completion-table
14219 (if (derived-mode-p 'org-mode)
14220 (org-get-buffer-tags)
14221 (org-global-tags-completion-table))))
14222 (org-icompleting-read
14223 "Tag: " 'org-tags-completion-function nil nil nil
14224 'org-tags-history))
14225 (progn
14226 (message "[s]et or [r]emove? ")
14227 (equal (read-char-exclusive) ?r))))
14228 (if (fboundp 'deactivate-mark) (deactivate-mark))
14229 (let ((agendap (equal major-mode 'org-agenda-mode))
14230 l1 l2 m buf pos newhead (cnt 0))
14231 (goto-char end)
14232 (setq l2 (1- (org-current-line)))
14233 (goto-char beg)
14234 (setq l1 (org-current-line))
14235 (loop for l from l1 to l2 do
14236 (org-goto-line l)
14237 (setq m (get-text-property (point) 'org-hd-marker))
14238 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14239 (and agendap m))
14240 (setq buf (if agendap (marker-buffer m) (current-buffer))
14241 pos (if agendap m (point)))
14242 (with-current-buffer buf
14243 (save-excursion
14244 (save-restriction
14245 (goto-char pos)
14246 (setq cnt (1+ cnt))
14247 (org-toggle-tag tag (if off 'off 'on))
14248 (setq newhead (org-get-heading)))))
14249 (and agendap (org-agenda-change-all-lines newhead m))))
14250 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14252 (defun org-tags-completion-function (string predicate &optional flag)
14253 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14254 (confirm (lambda (x) (stringp (car x)))))
14255 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14256 (setq s1 (match-string 1 string)
14257 s2 (match-string 2 string))
14258 (setq s1 "" s2 string))
14259 (cond
14260 ((eq flag nil)
14261 ;; try completion
14262 (setq rtn (try-completion s2 ctable confirm))
14263 (if (stringp rtn)
14264 (setq rtn
14265 (concat s1 s2 (substring rtn (length s2))
14266 (if (and org-add-colon-after-tag-completion
14267 (assoc rtn ctable))
14268 ":" ""))))
14269 rtn)
14270 ((eq flag t)
14271 ;; all-completions
14272 (all-completions s2 ctable confirm)
14274 ((eq flag 'lambda)
14275 ;; exact match?
14276 (assoc s2 ctable)))
14279 (defun org-fast-tag-insert (kwd tags face &optional end)
14280 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14281 (insert (format "%-12s" (concat kwd ":"))
14282 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14283 (or end "")))
14285 (defun org-fast-tag-show-exit (flag)
14286 (save-excursion
14287 (org-goto-line 3)
14288 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14289 (replace-match ""))
14290 (when flag
14291 (end-of-line 1)
14292 (org-move-to-column (- (window-width) 19) t)
14293 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14295 (defun org-set-current-tags-overlay (current prefix)
14296 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14297 (if (featurep 'xemacs)
14298 (org-overlay-display org-tags-overlay (concat prefix s)
14299 'secondary-selection)
14300 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14301 (org-overlay-display org-tags-overlay (concat prefix s)))))
14303 (defvar org-last-tag-selection-key nil)
14304 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14305 "Fast tag selection with single keys.
14306 CURRENT is the current list of tags in the headline, INHERITED is the
14307 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14308 possibly with grouping information. TODO-TABLE is a similar table with
14309 TODO keywords, should these have keys assigned to them.
14310 If the keys are nil, a-z are automatically assigned.
14311 Returns the new tags string, or nil to not change the current settings."
14312 (let* ((fulltable (append table todo-table))
14313 (maxlen (apply 'max (mapcar
14314 (lambda (x)
14315 (if (stringp (car x)) (string-width (car x)) 0))
14316 fulltable)))
14317 (buf (current-buffer))
14318 (expert (eq org-fast-tag-selection-single-key 'expert))
14319 (buffer-tags nil)
14320 (fwidth (+ maxlen 3 1 3))
14321 (ncol (/ (- (window-width) 4) fwidth))
14322 (i-face 'org-done)
14323 (c-face 'org-todo)
14324 tg cnt e c char c1 c2 ntable tbl rtn
14325 ov-start ov-end ov-prefix
14326 (exit-after-next org-fast-tag-selection-single-key)
14327 (done-keywords org-done-keywords)
14328 groups ingroup)
14329 (save-excursion
14330 (beginning-of-line 1)
14331 (if (looking-at
14332 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14333 (setq ov-start (match-beginning 1)
14334 ov-end (match-end 1)
14335 ov-prefix "")
14336 (setq ov-start (1- (point-at-eol))
14337 ov-end (1+ ov-start))
14338 (skip-chars-forward "^\n\r")
14339 (setq ov-prefix
14340 (concat
14341 (buffer-substring (1- (point)) (point))
14342 (if (> (current-column) org-tags-column)
14344 (make-string (- org-tags-column (current-column)) ?\ ))))))
14345 (move-overlay org-tags-overlay ov-start ov-end)
14346 (save-window-excursion
14347 (if expert
14348 (set-buffer (get-buffer-create " *Org tags*"))
14349 (delete-other-windows)
14350 (split-window-vertically)
14351 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14352 (erase-buffer)
14353 (org-set-local 'org-done-keywords done-keywords)
14354 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14355 (org-fast-tag-insert "Current" current c-face "\n\n")
14356 (org-fast-tag-show-exit exit-after-next)
14357 (org-set-current-tags-overlay current ov-prefix)
14358 (setq tbl fulltable char ?a cnt 0)
14359 (while (setq e (pop tbl))
14360 (cond
14361 ((equal (car e) :startgroup)
14362 (push '() groups) (setq ingroup t)
14363 (when (not (= cnt 0))
14364 (setq cnt 0)
14365 (insert "\n"))
14366 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14367 ((equal (car e) :endgroup)
14368 (setq ingroup nil cnt 0)
14369 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14370 ((equal e '(:newline))
14371 (when (not (= cnt 0))
14372 (setq cnt 0)
14373 (insert "\n")
14374 (setq e (car tbl))
14375 (while (equal (car tbl) '(:newline))
14376 (insert "\n")
14377 (setq tbl (cdr tbl)))))
14379 (setq tg (copy-sequence (car e)) c2 nil)
14380 (if (cdr e)
14381 (setq c (cdr e))
14382 ;; automatically assign a character.
14383 (setq c1 (string-to-char
14384 (downcase (substring
14385 tg (if (= (string-to-char tg) ?@) 1 0)))))
14386 (if (or (rassoc c1 ntable) (rassoc c1 table))
14387 (while (or (rassoc char ntable) (rassoc char table))
14388 (setq char (1+ char)))
14389 (setq c2 c1))
14390 (setq c (or c2 char)))
14391 (if ingroup (push tg (car groups)))
14392 (setq tg (org-add-props tg nil 'face
14393 (cond
14394 ((not (assoc tg table))
14395 (org-get-todo-face tg))
14396 ((member tg current) c-face)
14397 ((member tg inherited) i-face))))
14398 (if (and (= cnt 0) (not ingroup)) (insert " "))
14399 (insert "[" c "] " tg (make-string
14400 (- fwidth 4 (length tg)) ?\ ))
14401 (push (cons tg c) ntable)
14402 (when (= (setq cnt (1+ cnt)) ncol)
14403 (insert "\n")
14404 (if ingroup (insert " "))
14405 (setq cnt 0)))))
14406 (setq ntable (nreverse ntable))
14407 (insert "\n")
14408 (goto-char (point-min))
14409 (if (not expert) (org-fit-window-to-buffer))
14410 (setq rtn
14411 (catch 'exit
14412 (while t
14413 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14414 (if (not groups) "no " "")
14415 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14416 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14417 (setq org-last-tag-selection-key c)
14418 (cond
14419 ((= c ?\r) (throw 'exit t))
14420 ((= c ?!)
14421 (setq groups (not groups))
14422 (goto-char (point-min))
14423 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14424 ((= c ?\C-c)
14425 (if (not expert)
14426 (org-fast-tag-show-exit
14427 (setq exit-after-next (not exit-after-next)))
14428 (setq expert nil)
14429 (delete-other-windows)
14430 (set-window-buffer (split-window-vertically) " *Org tags*")
14431 (org-switch-to-buffer-other-window " *Org tags*")
14432 (org-fit-window-to-buffer)))
14433 ((or (= c ?\C-g)
14434 (and (= c ?q) (not (rassoc c ntable))))
14435 (org-detach-overlay org-tags-overlay)
14436 (setq quit-flag t))
14437 ((= c ?\ )
14438 (setq current nil)
14439 (if exit-after-next (setq exit-after-next 'now)))
14440 ((= c ?\t)
14441 (condition-case nil
14442 (setq tg (org-icompleting-read
14443 "Tag: "
14444 (or buffer-tags
14445 (with-current-buffer buf
14446 (org-get-buffer-tags)))))
14447 (quit (setq tg "")))
14448 (when (string-match "\\S-" tg)
14449 (add-to-list 'buffer-tags (list tg))
14450 (if (member tg current)
14451 (setq current (delete tg current))
14452 (push tg current)))
14453 (if exit-after-next (setq exit-after-next 'now)))
14454 ((setq e (rassoc c todo-table) tg (car e))
14455 (with-current-buffer buf
14456 (save-excursion (org-todo tg)))
14457 (if exit-after-next (setq exit-after-next 'now)))
14458 ((setq e (rassoc c ntable) tg (car e))
14459 (if (member tg current)
14460 (setq current (delete tg current))
14461 (loop for g in groups do
14462 (if (member tg g)
14463 (mapc (lambda (x)
14464 (setq current (delete x current)))
14465 g)))
14466 (push tg current))
14467 (if exit-after-next (setq exit-after-next 'now))))
14469 ;; Create a sorted list
14470 (setq current
14471 (sort current
14472 (lambda (a b)
14473 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14474 (if (eq exit-after-next 'now) (throw 'exit t))
14475 (goto-char (point-min))
14476 (beginning-of-line 2)
14477 (delete-region (point) (point-at-eol))
14478 (org-fast-tag-insert "Current" current c-face)
14479 (org-set-current-tags-overlay current ov-prefix)
14480 (while (re-search-forward
14481 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14482 (setq tg (match-string 1))
14483 (add-text-properties
14484 (match-beginning 1) (match-end 1)
14485 (list 'face
14486 (cond
14487 ((member tg current) c-face)
14488 ((member tg inherited) i-face)
14489 (t (get-text-property (match-beginning 1) 'face))))))
14490 (goto-char (point-min)))))
14491 (org-detach-overlay org-tags-overlay)
14492 (if rtn
14493 (mapconcat 'identity current ":")
14494 nil))))
14496 (defun org-get-tags-string ()
14497 "Get the TAGS string in the current headline."
14498 (unless (org-at-heading-p t)
14499 (error "Not on a heading"))
14500 (save-excursion
14501 (beginning-of-line 1)
14502 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14503 (org-match-string-no-properties 1)
14504 "")))
14506 (defun org-get-tags ()
14507 "Get the list of tags specified in the current headline."
14508 (org-split-string (org-get-tags-string) ":"))
14510 (defun org-get-buffer-tags ()
14511 "Get a table of all tags used in the buffer, for completion."
14512 (let (tags)
14513 (save-excursion
14514 (goto-char (point-min))
14515 (while (re-search-forward
14516 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14517 (when (equal (char-after (point-at-bol 0)) ?*)
14518 (mapc (lambda (x) (add-to-list 'tags x))
14519 (org-split-string (org-match-string-no-properties 1) ":")))))
14520 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14521 (mapcar 'list tags)))
14523 ;;;; The mapping API
14525 (defun org-map-entries (func &optional match scope &rest skip)
14526 "Call FUNC at each headline selected by MATCH in SCOPE.
14528 FUNC is a function or a lisp form. The function will be called without
14529 arguments, with the cursor positioned at the beginning of the headline.
14530 The return values of all calls to the function will be collected and
14531 returned as a list.
14533 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14534 does not need to preserve point. After evaluation, the cursor will be
14535 moved to the end of the line (presumably of the headline of the
14536 processed entry) and search continues from there. Under some
14537 circumstances, this may not produce the wanted results. For example,
14538 if you have removed (e.g. archived) the current (sub)tree it could
14539 mean that the next entry will be skipped entirely. In such cases, you
14540 can specify the position from where search should continue by making
14541 FUNC set the variable `org-map-continue-from' to the desired buffer
14542 position.
14544 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14545 Only headlines that are matched by this query will be considered during
14546 the iteration. When MATCH is nil or t, all headlines will be
14547 visited by the iteration.
14549 SCOPE determines the scope of this command. It can be any of:
14551 nil The current buffer, respecting the restriction if any
14552 tree The subtree started with the entry at point
14553 region The entries within the active region, if any
14554 region-start-level
14555 The entries within the active region, but only those at
14556 the same level than the first one.
14557 file The current buffer, without restriction
14558 file-with-archives
14559 The current buffer, and any archives associated with it
14560 agenda All agenda files
14561 agenda-with-archives
14562 All agenda files with any archive files associated with them
14563 \(file1 file2 ...)
14564 If this is a list, all files in the list will be scanned
14566 The remaining args are treated as settings for the skipping facilities of
14567 the scanner. The following items can be given here:
14569 archive skip trees with the archive tag
14570 comment skip trees with the COMMENT keyword
14571 function or Emacs Lisp form:
14572 will be used as value for `org-agenda-skip-function', so
14573 whenever the function returns a position, FUNC will not be
14574 called for that entry and search will continue from the
14575 position returned
14577 If your function needs to retrieve the tags including inherited tags
14578 at the *current* entry, you can use the value of the variable
14579 `org-scanner-tags' which will be much faster than getting the value
14580 with `org-get-tags-at'. If your function gets properties with
14581 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14582 to t around the call to `org-entry-properties' to get the same speedup.
14583 Note that if your function moves around to retrieve tags and properties at
14584 a *different* entry, you cannot use these techniques."
14585 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14586 (not (org-region-active-p)))
14587 (let* ((org-agenda-archives-mode nil) ; just to make sure
14588 (org-agenda-skip-archived-trees (memq 'archive skip))
14589 (org-agenda-skip-comment-trees (memq 'comment skip))
14590 (org-agenda-skip-function
14591 (car (org-delete-all '(comment archive) skip)))
14592 (org-tags-match-list-sublevels t)
14593 (start-level (eq scope 'region-start-level))
14594 matcher file res
14595 org-todo-keywords-for-agenda
14596 org-done-keywords-for-agenda
14597 org-todo-keyword-alist-for-agenda
14598 org-drawers-for-agenda
14599 org-tag-alist-for-agenda
14600 todo-only)
14602 (cond
14603 ((eq match t) (setq matcher t))
14604 ((eq match nil) (setq matcher t))
14605 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14607 (save-excursion
14608 (save-restriction
14609 (cond ((eq scope 'tree)
14610 (org-back-to-heading t)
14611 (org-narrow-to-subtree)
14612 (setq scope nil))
14613 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14614 (org-region-active-p))
14615 ;; If needed, set start-level to a string like "2"
14616 (when start-level
14617 (save-excursion
14618 (goto-char (region-beginning))
14619 (unless (org-at-heading-p) (outline-next-heading))
14620 (setq start-level (org-current-level))))
14621 (narrow-to-region (region-beginning)
14622 (save-excursion
14623 (goto-char (region-end))
14624 (unless (and (bolp) (org-at-heading-p))
14625 (outline-next-heading))
14626 (point)))
14627 (setq scope nil)))
14629 (if (not scope)
14630 (progn
14631 (org-agenda-prepare-buffers
14632 (list (buffer-file-name (current-buffer))))
14633 (setq res (org-scan-tags func matcher todo-only start-level)))
14634 ;; Get the right scope
14635 (cond
14636 ((and scope (listp scope) (symbolp (car scope)))
14637 (setq scope (eval scope)))
14638 ((eq scope 'agenda)
14639 (setq scope (org-agenda-files t)))
14640 ((eq scope 'agenda-with-archives)
14641 (setq scope (org-agenda-files t))
14642 (setq scope (org-add-archive-files scope)))
14643 ((eq scope 'file)
14644 (setq scope (list (buffer-file-name))))
14645 ((eq scope 'file-with-archives)
14646 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14647 (org-agenda-prepare-buffers scope)
14648 (while (setq file (pop scope))
14649 (with-current-buffer (org-find-base-buffer-visiting file)
14650 (save-excursion
14651 (save-restriction
14652 (widen)
14653 (goto-char (point-min))
14654 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14655 res)))
14657 ;;;; Properties
14659 ;;; Setting and retrieving properties
14661 (defconst org-special-properties
14662 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14663 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14664 "The special properties valid in Org-mode.
14666 These are properties that are not defined in the property drawer,
14667 but in some other way.")
14669 (defconst org-default-properties
14670 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14671 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14672 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14673 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14674 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14675 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14676 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14677 "Some properties that are used by Org-mode for various purposes.
14678 Being in this list makes sure that they are offered for completion.")
14680 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14681 "Regular expression matching the first line of a property drawer.")
14683 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14684 "Regular expression matching the last line of a property drawer.")
14686 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14687 "Regular expression matching the first line of a property drawer.")
14689 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14690 "Regular expression matching the first line of a property drawer.")
14692 (defconst org-property-drawer-re
14693 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14694 org-property-end-re "\\)\n?")
14695 "Matches an entire property drawer.")
14697 (defconst org-clock-drawer-re
14698 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14699 org-property-end-re "\\)\n?")
14700 "Matches an entire clock drawer.")
14702 (defsubst org-re-property (property)
14703 "Return a regexp matching a PROPERTY line.
14704 Match group 1 will be set to the value."
14705 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14707 (defsubst org-re-property-keyword (property)
14708 "Return a regexp matching a PROPERTY line, possibly with no
14709 value for the property."
14710 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14712 (defun org-property-action ()
14713 "Do an action on properties."
14714 (interactive)
14715 (let (c)
14716 (org-at-property-p)
14717 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14718 (setq c (read-char-exclusive))
14719 (cond
14720 ((equal c ?s)
14721 (call-interactively 'org-set-property))
14722 ((equal c ?d)
14723 (call-interactively 'org-delete-property))
14724 ((equal c ?D)
14725 (call-interactively 'org-delete-property-globally))
14726 ((equal c ?c)
14727 (call-interactively 'org-compute-property-at-point))
14728 (t (error "No such property action %c" c)))))
14730 (defun org-inc-effort ()
14731 "Increment the value of the effort property in the current entry."
14732 (interactive)
14733 (org-set-effort nil t))
14735 (defvar org-clock-effort) ;; Defined in org-clock.el
14736 (defvar org-clock-current-task) ;; Defined in org-clock.el
14737 (defun org-set-effort (&optional value increment)
14738 "Set the effort property of the current entry.
14739 With numerical prefix arg, use the nth allowed value, 0 stands for the
14740 10th allowed value.
14742 When INCREMENT is non-nil, set the property to the next allowed value."
14743 (interactive "P")
14744 (if (equal value 0) (setq value 10))
14745 (let* ((completion-ignore-case t)
14746 (prop org-effort-property)
14747 (cur (org-entry-get nil prop))
14748 (allowed (org-property-get-allowed-values nil prop 'table))
14749 (existing (mapcar 'list (org-property-values prop)))
14750 (heading (nth 4 (org-heading-components)))
14752 (val (cond
14753 ((stringp value) value)
14754 ((and allowed (integerp value))
14755 (or (car (nth (1- value) allowed))
14756 (car (org-last allowed))))
14757 ((and allowed increment)
14758 (or (caadr (member (list cur) allowed))
14759 (error "Allowed effort values are not set")))
14760 (allowed
14761 (message "Select 1-9,0, [RET%s]: %s"
14762 (if cur (concat "=" cur) "")
14763 (mapconcat 'car allowed " "))
14764 (setq rpl (read-char-exclusive))
14765 (if (equal rpl ?\r)
14767 (setq rpl (- rpl ?0))
14768 (if (equal rpl 0) (setq rpl 10))
14769 (if (and (> rpl 0) (<= rpl (length allowed)))
14770 (car (nth (1- rpl) allowed))
14771 (org-completing-read "Effort: " allowed nil))))
14773 (let (org-completion-use-ido org-completion-use-iswitchb)
14774 (org-completing-read
14775 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14776 (concat "[" cur "]") "")
14777 ": ")
14778 existing nil nil "" nil cur))))))
14779 (unless (equal (org-entry-get nil prop) val)
14780 (org-entry-put nil prop val))
14781 (save-excursion
14782 (org-back-to-heading t)
14783 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14784 (when (string= heading org-clock-current-task)
14785 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
14786 (org-clock-update-mode-line))
14787 (message "%s is now %s" prop val)))
14789 (defun org-at-property-p ()
14790 "Is cursor inside a property drawer?"
14791 (save-excursion
14792 (beginning-of-line 1)
14793 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14794 (save-match-data ;; Used by calling procedures
14795 (let ((p (point))
14796 (range (unless (org-before-first-heading-p)
14797 (org-get-property-block))))
14798 (and range (<= (car range) p) (< p (cdr range))))))))
14800 (defun org-get-property-block (&optional beg end force)
14801 "Return the (beg . end) range of the body of the property drawer.
14802 BEG and END are the beginning and end of the current subtree, or of
14803 the part before the first headline. If they are not given, they will
14804 be found. If the drawer does not exist and FORCE is non-nil, create
14805 the drawer."
14806 (catch 'exit
14807 (save-excursion
14808 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14809 (progn (org-back-to-heading t) (point))))
14810 (end (or end (and (not (outline-next-heading)) (point-max))
14811 (point))))
14812 (goto-char beg)
14813 (if (re-search-forward org-property-start-re end t)
14814 (setq beg (1+ (match-end 0)))
14815 (if force
14816 (save-excursion
14817 (org-insert-property-drawer)
14818 (setq end (progn (outline-next-heading) (point))))
14819 (throw 'exit nil))
14820 (goto-char beg)
14821 (if (re-search-forward org-property-start-re end t)
14822 (setq beg (1+ (match-end 0)))))
14823 (if (re-search-forward org-property-end-re end t)
14824 (setq end (match-beginning 0))
14825 (or force (throw 'exit nil))
14826 (goto-char beg)
14827 (setq end beg)
14828 (org-indent-line)
14829 (insert ":END:\n"))
14830 (cons beg end)))))
14832 (defun org-entry-properties (&optional pom which specific)
14833 "Get all properties of the entry at point-or-marker POM.
14834 This includes the TODO keyword, the tags, time strings for deadline,
14835 scheduled, and clocking, and any additional properties defined in the
14836 entry. The return value is an alist, keys may occur multiple times
14837 if the property key was used several times.
14838 POM may also be nil, in which case the current entry is used.
14839 If WHICH is nil or `all', get all properties. If WHICH is
14840 `special' or `standard', only get that subclass. If WHICH
14841 is a string only get exactly this property. SPECIFIC can be a string, the
14842 specific property we are interested in. Specifying it can speed
14843 things up because then unnecessary parsing is avoided."
14844 (setq which (or which 'all))
14845 (org-with-point-at pom
14846 (let ((clockstr (substring org-clock-string 0 -1))
14847 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14848 (case-fold-search nil)
14849 beg end range props sum-props key key1 value string clocksum clocksumt)
14850 (save-excursion
14851 (when (condition-case nil
14852 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14853 (error nil))
14854 (setq beg (point))
14855 (setq sum-props (get-text-property (point) 'org-summaries))
14856 (setq clocksum (get-text-property (point) :org-clock-minutes)
14857 clocksumt (get-text-property (point) :org-clock-minutes-today))
14858 (outline-next-heading)
14859 (setq end (point))
14860 (when (memq which '(all special))
14861 ;; Get the special properties, like TODO and tags
14862 (goto-char beg)
14863 (when (and (or (not specific) (string= specific "TODO"))
14864 (looking-at org-todo-line-regexp) (match-end 2))
14865 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14866 (when (and (or (not specific) (string= specific "PRIORITY"))
14867 (looking-at org-priority-regexp))
14868 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14869 (when (or (not specific) (string= specific "FILE"))
14870 (push (cons "FILE" buffer-file-name) props))
14871 (when (and (or (not specific) (string= specific "TAGS"))
14872 (setq value (org-get-tags-string))
14873 (string-match "\\S-" value))
14874 (push (cons "TAGS" value) props))
14875 (when (and (or (not specific) (string= specific "ALLTAGS"))
14876 (setq value (org-get-tags-at)))
14877 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14878 ":"))
14879 props))
14880 (when (or (not specific) (string= specific "BLOCKED"))
14881 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14882 (when (or (not specific)
14883 (member specific
14884 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14885 "TIMESTAMP" "TIMESTAMP_IA")))
14886 (catch 'match
14887 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14888 (setq key (if (match-end 1)
14889 (substring (org-match-string-no-properties 1)
14890 0 -1))
14891 string (if (equal key clockstr)
14892 (org-trim
14893 (buffer-substring-no-properties
14894 (match-beginning 3) (goto-char
14895 (point-at-eol))))
14896 (substring (org-match-string-no-properties 3)
14897 1 -1)))
14898 ;; Get the correct property name from the key. This is
14899 ;; necessary if the user has configured time keywords.
14900 (setq key1 (concat key ":"))
14901 (cond
14902 ((not key)
14903 (setq key
14904 (if (= (char-after (match-beginning 3)) ?\[)
14905 "TIMESTAMP_IA" "TIMESTAMP")))
14906 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14907 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14908 ((equal key1 org-closed-string) (setq key "CLOSED"))
14909 ((equal key1 org-clock-string) (setq key "CLOCK")))
14910 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14911 (progn
14912 (push (cons key string) props)
14913 ;; no need to search further if match is found
14914 (throw 'match t))
14915 (when (or (equal key "CLOCK") (not (assoc key props)))
14916 (push (cons key string) props)))))))
14918 (when (memq which '(all standard))
14919 ;; Get the standard properties, like :PROP: ...
14920 (setq range (org-get-property-block beg end))
14921 (when range
14922 (goto-char (car range))
14923 (while (re-search-forward
14924 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14925 (cdr range) t)
14926 (setq key (org-match-string-no-properties 1)
14927 value (org-trim (or (org-match-string-no-properties 2) "")))
14928 (unless (member key excluded)
14929 (push (cons key (or value "")) props)))))
14930 (if clocksum
14931 (push (cons "CLOCKSUM"
14932 (org-columns-number-to-string (/ (float clocksum) 60.)
14933 'add_times))
14934 props))
14935 (if clocksumt
14936 (push (cons "CLOCKSUM_T"
14937 (org-columns-number-to-string (/ (float clocksumt) 60.)
14938 'add_times))
14939 props))
14940 (unless (assoc "CATEGORY" props)
14941 (push (cons "CATEGORY" (org-get-category)) props))
14942 (append sum-props (nreverse props)))))))
14944 (defun org-entry-get (pom property &optional inherit literal-nil)
14945 "Get value of PROPERTY for entry or content at point-or-marker POM.
14946 If INHERIT is non-nil and the entry does not have the property,
14947 then also check higher levels of the hierarchy.
14948 If INHERIT is the symbol `selective', use inheritance only if the setting
14949 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14950 If the property is present but empty, the return value is the empty string.
14951 If the property is not present at all, nil is returned.
14953 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14954 do not interpret it as the list atom nil. This is used for inheritance
14955 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14956 (org-with-point-at pom
14957 (if (and inherit (if (eq inherit 'selective)
14958 (org-property-inherit-p property)
14960 (org-entry-get-with-inheritance property literal-nil)
14961 (if (member property org-special-properties)
14962 ;; We need a special property. Use `org-entry-properties' to
14963 ;; retrieve it, but specify the wanted property
14964 (cdr (assoc property (org-entry-properties nil 'special property)))
14965 (let ((range (org-get-property-block)))
14966 (when (and range (not (eq (car range) (cdr range))))
14967 (let* ((props (list (or (assoc property org-file-properties)
14968 (assoc property org-global-properties)
14969 (assoc property org-global-properties-fixed))))
14970 (ap (lambda (key)
14971 (when (re-search-forward
14972 (org-re-property key) (cdr range) t)
14973 (setq props
14974 (org-update-property-plist
14976 (if (match-end 1)
14977 (org-match-string-no-properties 1) "")
14978 props)))))
14979 val)
14980 (goto-char (car range))
14981 (funcall ap property)
14982 (goto-char (car range))
14983 (while (funcall ap (concat property "+")))
14984 (setq val (cdr (assoc property props)))
14985 (when val (if literal-nil val (org-not-nil val))))))))))
14987 (defun org-property-or-variable-value (var &optional inherit)
14988 "Check if there is a property fixing the value of VAR.
14989 If yes, return this value. If not, return the current value of the variable."
14990 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14991 (if (and prop (stringp prop) (string-match "\\S-" prop))
14992 (read prop)
14993 (symbol-value var))))
14995 (defun org-entry-delete (pom property &optional delete-empty-drawer)
14996 "Delete the property PROPERTY from entry at point-or-marker POM.
14997 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
14998 an empty drawer to delete."
14999 (org-with-point-at pom
15000 (if (member property org-special-properties)
15001 nil ; cannot delete these properties.
15002 (let ((range (org-get-property-block)))
15003 (if (and range
15004 (goto-char (car range))
15005 (re-search-forward
15006 (org-re-property property)
15007 (cdr range) t))
15008 (progn
15009 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15010 (and delete-empty-drawer
15011 (org-remove-empty-drawer-at
15012 delete-empty-drawer (car range)))
15014 nil)))))
15016 ;; Multi-values properties are properties that contain multiple values
15017 ;; These values are assumed to be single words, separated by whitespace.
15018 (defun org-entry-add-to-multivalued-property (pom property value)
15019 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15020 (let* ((old (org-entry-get pom property))
15021 (values (and old (org-split-string old "[ \t]"))))
15022 (setq value (org-entry-protect-space value))
15023 (unless (member value values)
15024 (setq values (cons value values))
15025 (org-entry-put pom property
15026 (mapconcat 'identity values " ")))))
15028 (defun org-entry-remove-from-multivalued-property (pom property value)
15029 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15030 (let* ((old (org-entry-get pom property))
15031 (values (and old (org-split-string old "[ \t]"))))
15032 (setq value (org-entry-protect-space value))
15033 (when (member value values)
15034 (setq values (delete value values))
15035 (org-entry-put pom property
15036 (mapconcat 'identity values " ")))))
15038 (defun org-entry-member-in-multivalued-property (pom property value)
15039 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15040 (let* ((old (org-entry-get pom property))
15041 (values (and old (org-split-string old "[ \t]"))))
15042 (setq value (org-entry-protect-space value))
15043 (member value values)))
15045 (defun org-entry-get-multivalued-property (pom property)
15046 "Return a list of values in a multivalued property."
15047 (let* ((value (org-entry-get pom property))
15048 (values (and value (org-split-string value "[ \t]"))))
15049 (mapcar 'org-entry-restore-space values)))
15051 (defun org-entry-put-multivalued-property (pom property &rest values)
15052 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15053 VALUES should be a list of strings. Spaces will be protected."
15054 (org-entry-put pom property
15055 (mapconcat 'org-entry-protect-space values " "))
15056 (let* ((value (org-entry-get pom property))
15057 (values (and value (org-split-string value "[ \t]"))))
15058 (mapcar 'org-entry-restore-space values)))
15060 (defun org-entry-protect-space (s)
15061 "Protect spaces and newline in string S."
15062 (while (string-match " " s)
15063 (setq s (replace-match "%20" t t s)))
15064 (while (string-match "\n" s)
15065 (setq s (replace-match "%0A" t t s)))
15068 (defun org-entry-restore-space (s)
15069 "Restore spaces and newline in string S."
15070 (while (string-match "%20" s)
15071 (setq s (replace-match " " t t s)))
15072 (while (string-match "%0A" s)
15073 (setq s (replace-match "\n" t t s)))
15076 (defvar org-entry-property-inherited-from (make-marker)
15077 "Marker pointing to the entry from where a property was inherited.
15078 Each call to `org-entry-get-with-inheritance' will set this marker to the
15079 location of the entry where the inheritance search matched. If there was
15080 no match, the marker will point nowhere.
15081 Note that also `org-entry-get' calls this function, if the INHERIT flag
15082 is set.")
15084 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15085 "Get PROPERTY of entry or content at point, search higher levels if needed.
15086 The search will stop at the first ancestor which has the property defined.
15087 If the value found is \"nil\", return nil to show that the property
15088 should be considered as undefined (this is the meaning of nil here).
15089 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15090 (move-marker org-entry-property-inherited-from nil)
15091 (let (tmp)
15092 (save-excursion
15093 (save-restriction
15094 (widen)
15095 (catch 'ex
15096 (while t
15097 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15098 (or (ignore-errors (org-back-to-heading t))
15099 (goto-char (point-min)))
15100 (move-marker org-entry-property-inherited-from (point))
15101 (throw 'ex tmp))
15102 (or (ignore-errors (org-up-heading-safe))
15103 (throw 'ex nil))))))
15104 (setq tmp (or tmp
15105 (cdr (assoc property org-file-properties))
15106 (cdr (assoc property org-global-properties))
15107 (cdr (assoc property org-global-properties-fixed))))
15108 (if literal-nil tmp (org-not-nil tmp))))
15110 (defvar org-property-changed-functions nil
15111 "Hook called when the value of a property has changed.
15112 Each hook function should accept two arguments, the name of the property
15113 and the new value.")
15115 (defun org-entry-put (pom property value)
15116 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15117 (org-with-point-at pom
15118 (org-back-to-heading t)
15119 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15120 range)
15121 (cond
15122 ((equal property "TODO")
15123 (when (and (stringp value) (string-match "\\S-" value)
15124 (not (member value org-todo-keywords-1)))
15125 (error "\"%s\" is not a valid TODO state" value))
15126 (if (or (not value)
15127 (not (string-match "\\S-" value)))
15128 (setq value 'none))
15129 (org-todo value)
15130 (org-set-tags nil 'align))
15131 ((equal property "PRIORITY")
15132 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15133 (string-to-char value) ?\ ))
15134 (org-set-tags nil 'align))
15135 ((equal property "CLOCKSUM")
15136 (if (not (re-search-forward
15137 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15138 (error "Cannot find a clock log")
15139 (goto-char (- (match-end 1) 2))
15140 (cond
15141 ((eq value 'earlier) (org-timestamp-down))
15142 ((eq value 'later) (org-timestamp-up)))
15143 (org-clock-sum-current-item)))
15144 ((equal property "SCHEDULED")
15145 (if (re-search-forward org-scheduled-time-regexp end t)
15146 (cond
15147 ((eq value 'earlier) (org-timestamp-change -1 'day))
15148 ((eq value 'later) (org-timestamp-change 1 'day))
15149 (t (call-interactively 'org-schedule)))
15150 (call-interactively 'org-schedule)))
15151 ((equal property "DEADLINE")
15152 (if (re-search-forward org-deadline-time-regexp end t)
15153 (cond
15154 ((eq value 'earlier) (org-timestamp-change -1 'day))
15155 ((eq value 'later) (org-timestamp-change 1 'day))
15156 (t (call-interactively 'org-deadline)))
15157 (call-interactively 'org-deadline)))
15158 ((member property org-special-properties)
15159 (error "The %s property can not yet be set with `org-entry-put'"
15160 property))
15161 (t ; a non-special property
15162 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15163 (setq range (org-get-property-block beg end 'force))
15164 (goto-char (car range))
15165 (if (re-search-forward
15166 (org-re-property-keyword property) (cdr range) t)
15167 (progn
15168 (delete-region (match-beginning 0) (match-end 0))
15169 (goto-char (match-beginning 0)))
15170 (goto-char (cdr range))
15171 (insert "\n")
15172 (backward-char 1)
15173 (org-indent-line))
15174 (insert ":" property ":")
15175 (and value (insert " " value))
15176 (org-indent-line)))))
15177 (run-hook-with-args 'org-property-changed-functions property value)))
15179 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15180 "Get all property keys in the current buffer.
15181 With INCLUDE-SPECIALS, also list the special properties that reflect things
15182 like tags and TODO state.
15183 With INCLUDE-DEFAULTS, also include properties that has special meaning
15184 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15185 and others.
15186 With INCLUDE-COLUMNS, also include property names given in COLUMN
15187 formats in the current buffer."
15188 (let (rtn range cfmt s p)
15189 (save-excursion
15190 (save-restriction
15191 (widen)
15192 (goto-char (point-min))
15193 (while (re-search-forward org-property-start-re nil t)
15194 (setq range (org-get-property-block))
15195 (goto-char (car range))
15196 (while (re-search-forward
15197 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15198 (cdr range) t)
15199 (add-to-list 'rtn (org-match-string-no-properties 1)))
15200 (outline-next-heading))))
15202 (when include-specials
15203 (setq rtn (append org-special-properties rtn)))
15205 (when include-defaults
15206 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15207 (add-to-list 'rtn org-effort-property))
15209 (when include-columns
15210 (save-excursion
15211 (save-restriction
15212 (widen)
15213 (goto-char (point-min))
15214 (while (re-search-forward
15215 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15216 nil t)
15217 (setq cfmt (match-string 2) s 0)
15218 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15219 cfmt s)
15220 (setq s (match-end 0)
15221 p (match-string 1 cfmt))
15222 (unless (or (equal p "ITEM")
15223 (member p org-special-properties))
15224 (add-to-list 'rtn (match-string 1 cfmt))))))))
15226 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15228 (defun org-property-values (key)
15229 "Return a list of all values of property KEY in the current buffer."
15230 (save-excursion
15231 (save-restriction
15232 (widen)
15233 (goto-char (point-min))
15234 (let ((re (org-re-property key))
15235 values)
15236 (while (re-search-forward re nil t)
15237 (add-to-list 'values (org-trim (match-string 1))))
15238 (delete "" values)))))
15240 (defun org-insert-property-drawer ()
15241 "Insert a property drawer into the current entry."
15242 (org-back-to-heading t)
15243 (looking-at org-outline-regexp)
15244 (let ((indent (if org-adapt-indentation
15245 (- (match-end 0) (match-beginning 0))
15247 (beg (point))
15248 (re (concat "^[ \t]*" org-keyword-time-regexp))
15249 end hiddenp)
15250 (outline-next-heading)
15251 (setq end (point))
15252 (goto-char beg)
15253 (while (re-search-forward re end t))
15254 (setq hiddenp (outline-invisible-p))
15255 (end-of-line 1)
15256 (and (equal (char-after) ?\n) (forward-char 1))
15257 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15258 (if (member (match-string 1) '("CLOCK:" ":END:"))
15259 ;; just skip this line
15260 (beginning-of-line 2)
15261 ;; Drawer start, find the end
15262 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15263 (beginning-of-line 1)))
15264 (org-skip-over-state-notes)
15265 (skip-chars-backward " \t\n\r")
15266 (if (eq (char-before) ?*) (forward-char 1))
15267 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15268 (beginning-of-line 0)
15269 (org-indent-to-column indent)
15270 (beginning-of-line 2)
15271 (org-indent-to-column indent)
15272 (beginning-of-line 0)
15273 (if hiddenp
15274 (save-excursion
15275 (org-back-to-heading t)
15276 (hide-entry))
15277 (org-flag-drawer t))))
15279 (defun org-insert-drawer (&optional arg drawer)
15280 "Insert a drawer at point.
15282 Optional argument DRAWER, when non-nil, is a string representing
15283 drawer's name. Otherwise, the user is prompted for a name.
15285 If a region is active, insert the drawer around that region
15286 instead.
15288 Point is left between drawer's boundaries."
15289 (interactive "P")
15290 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15291 "LOGBOOK"))
15292 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15293 ;; internally by Org. They are meant to be inserted
15294 ;; automatically.
15295 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15296 ;; Remove system drawers from list. Note: For some reason,
15297 ;; `org-completing-read' ignores the predicate while
15298 ;; `completing-read' handles it fine.
15299 (drawer (if arg "PROPERTIES"
15300 (or drawer
15301 (completing-read
15302 "Drawer: " org-drawers
15303 (lambda (d) (not (member d system-drawers))))))))
15304 (cond
15305 ;; With C-u, fall back on `org-insert-property-drawer'
15306 (arg (org-insert-property-drawer))
15307 ;; With an active region, insert a drawer at point.
15308 ((not (org-region-active-p))
15309 (progn
15310 (unless (bolp) (insert "\n"))
15311 (insert (format ":%s:\n\n:END:\n" drawer))
15312 (forward-line -2)))
15313 ;; Otherwise, insert the drawer at point
15315 (let ((rbeg (region-beginning))
15316 (rend (copy-marker (region-end))))
15317 (unwind-protect
15318 (progn
15319 (goto-char rbeg)
15320 (beginning-of-line)
15321 (when (save-excursion
15322 (re-search-forward org-outline-regexp-bol rend t))
15323 (error "Drawers cannot contain headlines"))
15324 ;; Position point at the beginning of the first
15325 ;; non-blank line in region. Insert drawer's opening
15326 ;; there, then indent it.
15327 (org-skip-whitespace)
15328 (beginning-of-line)
15329 (insert ":" drawer ":\n")
15330 (forward-line -1)
15331 (indent-for-tab-command)
15332 ;; Move point to the beginning of the first blank line
15333 ;; after the last non-blank line in region. Insert
15334 ;; drawer's closing, then indent it.
15335 (goto-char rend)
15336 (skip-chars-backward " \r\t\n")
15337 (insert "\n:END:")
15338 (deactivate-mark t)
15339 (indent-for-tab-command)
15340 (unless (eolp) (insert "\n")))
15341 ;; Clear marker, whatever the outcome of insertion is.
15342 (set-marker rend nil)))))))
15344 (defvar org-property-set-functions-alist nil
15345 "Property set function alist.
15346 Each entry should have the following format:
15348 (PROPERTY . READ-FUNCTION)
15350 The read function will be called with the same argument as
15351 `org-completing-read'.")
15353 (defun org-set-property-function (property)
15354 "Get the function that should be used to set PROPERTY.
15355 This is computed according to `org-property-set-functions-alist'."
15356 (or (cdr (assoc property org-property-set-functions-alist))
15357 'org-completing-read))
15359 (defun org-read-property-value (property)
15360 "Read PROPERTY value from user."
15361 (let* ((completion-ignore-case t)
15362 (allowed (org-property-get-allowed-values nil property 'table))
15363 (cur (org-entry-get nil property))
15364 (prompt (concat property " value"
15365 (if (and cur (string-match "\\S-" cur))
15366 (concat " [" cur "]") "") ": "))
15367 (set-function (org-set-property-function property))
15368 (val (if allowed
15369 (funcall set-function prompt allowed nil
15370 (not (get-text-property 0 'org-unrestricted
15371 (caar allowed))))
15372 (let (org-completion-use-ido org-completion-use-iswitchb)
15373 (funcall set-function prompt
15374 (mapcar 'list (org-property-values property))
15375 nil nil "" nil cur)))))
15376 (if (equal val "")
15378 val)))
15380 (defvar org-last-set-property nil)
15381 (defvar org-last-set-property-value nil)
15382 (defun org-read-property-name ()
15383 "Read a property name."
15384 (let* ((completion-ignore-case t)
15385 (keys (org-buffer-property-keys nil t t))
15386 (default-prop (or (save-excursion
15387 (save-match-data
15388 (beginning-of-line)
15389 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15390 (null (string= (match-string 1) "END"))
15391 (match-string 1))))
15392 org-last-set-property))
15393 (property (org-icompleting-read
15394 (concat "Property"
15395 (if default-prop (concat " [" default-prop "]") "")
15396 ": ")
15397 (mapcar 'list keys)
15398 nil nil nil nil
15399 default-prop)))
15400 (if (member property keys)
15401 property
15402 (or (cdr (assoc (downcase property)
15403 (mapcar (lambda (x) (cons (downcase x) x))
15404 keys)))
15405 property))))
15407 (defun org-set-property-and-value (use-last)
15408 "Allow to set [PROPERTY]: [value] direction from prompt.
15409 When use-default, don't even ask, just use the last
15410 \"[PROPERTY]: [value]\" string from the history."
15411 (interactive "P")
15412 (let* ((completion-ignore-case t)
15413 (pv (or (and use-last org-last-set-property-value)
15414 (org-completing-read
15415 "Enter a \"[Property]: [value]\" pair: "
15416 nil nil nil nil nil
15417 org-last-set-property-value)))
15418 prop val)
15419 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15420 (setq prop (match-string 1 pv)
15421 val (match-string 2 pv))
15422 (org-set-property prop val))))
15424 (defun org-set-property (property value)
15425 "In the current entry, set PROPERTY to VALUE.
15426 When called interactively, this will prompt for a property name, offering
15427 completion on existing and default properties. And then it will prompt
15428 for a value, offering completion either on allowed values (via an inherited
15429 xxx_ALL property) or on existing values in other instances of this property
15430 in the current file."
15431 (interactive (list nil nil))
15432 (let* ((property (or property (org-read-property-name)))
15433 (value (or value (org-read-property-value property)))
15434 (fn (cdr (assoc property org-properties-postprocess-alist))))
15435 (setq org-last-set-property property)
15436 (setq org-last-set-property-value (concat property ": " value))
15437 ;; Possibly postprocess the inserted value:
15438 (when fn (setq value (funcall fn value)))
15439 (unless (equal (org-entry-get nil property) value)
15440 (org-entry-put nil property value))))
15442 (defun org-delete-property (property &optional delete-empty-drawer)
15443 "In the current entry, delete PROPERTY.
15444 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15445 an empty drawer to delete."
15446 (interactive
15447 (let* ((completion-ignore-case t)
15448 (prop (org-icompleting-read "Property: "
15449 (org-entry-properties nil 'standard))))
15450 (list prop)))
15451 (message "Property %s %s" property
15452 (if (org-entry-delete nil property delete-empty-drawer)
15453 "deleted"
15454 "was not present in the entry")))
15456 (defun org-delete-property-globally (property)
15457 "Remove PROPERTY globally, from all entries."
15458 (interactive
15459 (let* ((completion-ignore-case t)
15460 (prop (org-icompleting-read
15461 "Globally remove property: "
15462 (mapcar 'list (org-buffer-property-keys)))))
15463 (list prop)))
15464 (save-excursion
15465 (save-restriction
15466 (widen)
15467 (goto-char (point-min))
15468 (let ((cnt 0))
15469 (while (re-search-forward
15470 (org-re-property property)
15471 nil t)
15472 (setq cnt (1+ cnt))
15473 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15474 (message "Property \"%s\" removed from %d entries" property cnt)))))
15476 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15478 (defun org-compute-property-at-point ()
15479 "Compute the property at point.
15480 This looks for an enclosing column format, extracts the operator and
15481 then applies it to the property in the column format's scope."
15482 (interactive)
15483 (unless (org-at-property-p)
15484 (error "Not at a property"))
15485 (let ((prop (org-match-string-no-properties 2)))
15486 (org-columns-get-format-and-top-level)
15487 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15488 (error "No operator defined for property %s" prop))
15489 (org-columns-compute prop)))
15491 (defvar org-property-allowed-value-functions nil
15492 "Hook for functions supplying allowed values for a specific property.
15493 The functions must take a single argument, the name of the property, and
15494 return a flat list of allowed values. If \":ETC\" is one of
15495 the values, this means that these values are intended as defaults for
15496 completion, but that other values should be allowed too.
15497 The functions must return nil if they are not responsible for this
15498 property.")
15500 (defun org-property-get-allowed-values (pom property &optional table)
15501 "Get allowed values for the property PROPERTY.
15502 When TABLE is non-nil, return an alist that can directly be used for
15503 completion."
15504 (let (vals)
15505 (cond
15506 ((equal property "TODO")
15507 (setq vals (org-with-point-at pom
15508 (append org-todo-keywords-1 '("")))))
15509 ((equal property "PRIORITY")
15510 (let ((n org-lowest-priority))
15511 (while (>= n org-highest-priority)
15512 (push (char-to-string n) vals)
15513 (setq n (1- n)))))
15514 ((member property org-special-properties))
15515 ((setq vals (run-hook-with-args-until-success
15516 'org-property-allowed-value-functions property)))
15518 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15519 (when (and vals (string-match "\\S-" vals))
15520 (setq vals (car (read-from-string (concat "(" vals ")"))))
15521 (setq vals (mapcar (lambda (x)
15522 (cond ((stringp x) x)
15523 ((numberp x) (number-to-string x))
15524 ((symbolp x) (symbol-name x))
15525 (t "???")))
15526 vals)))))
15527 (when (member ":ETC" vals)
15528 (setq vals (remove ":ETC" vals))
15529 (org-add-props (car vals) '(org-unrestricted t)))
15530 (if table (mapcar 'list vals) vals)))
15532 (defun org-property-previous-allowed-value (&optional previous)
15533 "Switch to the next allowed value for this property."
15534 (interactive)
15535 (org-property-next-allowed-value t))
15537 (defun org-property-next-allowed-value (&optional previous)
15538 "Switch to the next allowed value for this property."
15539 (interactive)
15540 (unless (org-at-property-p)
15541 (error "Not at a property"))
15542 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15543 (key (match-string 2))
15544 (value (match-string 3))
15545 (allowed (or (org-property-get-allowed-values (point) key)
15546 (and (member value '("[ ]" "[-]" "[X]"))
15547 '("[ ]" "[X]"))))
15548 (heading (save-match-data (nth 4 (org-heading-components))))
15549 nval)
15550 (unless allowed
15551 (error "Allowed values for this property have not been defined"))
15552 (if previous (setq allowed (reverse allowed)))
15553 (if (member value allowed)
15554 (setq nval (car (cdr (member value allowed)))))
15555 (setq nval (or nval (car allowed)))
15556 (if (equal nval value)
15557 (error "Only one allowed value for this property"))
15558 (org-at-property-p)
15559 (replace-match (concat " :" key ": " nval) t t)
15560 (org-indent-line)
15561 (beginning-of-line 1)
15562 (skip-chars-forward " \t")
15563 (when (equal prop org-effort-property)
15564 (save-excursion
15565 (org-back-to-heading t)
15566 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15567 (when (string= org-clock-current-task heading)
15568 (setq org-clock-effort nval)
15569 (org-clock-update-mode-line)))
15570 (run-hook-with-args 'org-property-changed-functions key nval)))
15572 (defun org-find-olp (path &optional this-buffer)
15573 "Return a marker pointing to the entry at outline path OLP.
15574 If anything goes wrong, throw an error.
15575 You can wrap this call to catch the error like this:
15577 (condition-case msg
15578 (org-mobile-locate-entry (match-string 4))
15579 (error (nth 1 msg)))
15581 The return value will then be either a string with the error message,
15582 or a marker if everything is OK.
15584 If THIS-BUFFER is set, the outline path does not contain a file,
15585 only headings."
15586 (let* ((file (if this-buffer buffer-file-name (pop path)))
15587 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15588 (level 1)
15589 (lmin 1)
15590 (lmax 1)
15591 limit re end found pos heading cnt flevel)
15592 (unless buffer (error "File not found :%s" file))
15593 (with-current-buffer buffer
15594 (save-excursion
15595 (save-restriction
15596 (widen)
15597 (setq limit (point-max))
15598 (goto-char (point-min))
15599 (while (setq heading (pop path))
15600 (setq re (format org-complex-heading-regexp-format
15601 (regexp-quote heading)))
15602 (setq cnt 0 pos (point))
15603 (while (re-search-forward re end t)
15604 (setq level (- (match-end 1) (match-beginning 1)))
15605 (if (and (>= level lmin) (<= level lmax))
15606 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15607 (when (= cnt 0) (error "Heading not found on level %d: %s"
15608 lmax heading))
15609 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15610 lmax heading))
15611 (goto-char found)
15612 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15613 (setq end (save-excursion (org-end-of-subtree t t))))
15614 (when (org-at-heading-p)
15615 (point-marker)))))))
15617 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15618 "Find node HEADING in BUFFER.
15619 Return a marker to the heading if it was found, or nil if not.
15620 If POS-ONLY is set, return just the position instead of a marker.
15622 The heading text must match exact, but it may have a TODO keyword,
15623 a priority cookie and tags in the standard locations."
15624 (with-current-buffer (or buffer (current-buffer))
15625 (save-excursion
15626 (save-restriction
15627 (widen)
15628 (goto-char (point-min))
15629 (let (case-fold-search)
15630 (if (re-search-forward
15631 (format org-complex-heading-regexp-format
15632 (regexp-quote heading)) nil t)
15633 (if pos-only
15634 (match-beginning 0)
15635 (move-marker (make-marker) (match-beginning 0)))))))))
15637 (defun org-find-exact-heading-in-directory (heading &optional dir)
15638 "Find Org node headline HEADING in all .org files in directory DIR.
15639 When the target headline is found, return a marker to this location."
15640 (let ((files (directory-files (or dir default-directory)
15641 nil "\\`[^.#].*\\.org\\'"))
15642 file visiting m buffer)
15643 (catch 'found
15644 (while (setq file (pop files))
15645 (message "trying %s" file)
15646 (setq visiting (org-find-base-buffer-visiting file))
15647 (setq buffer (or visiting (find-file-noselect file)))
15648 (setq m (org-find-exact-headline-in-buffer
15649 heading buffer))
15650 (when (and (not m) (not visiting)) (kill-buffer buffer))
15651 (and m (throw 'found m))))))
15653 (defun org-find-entry-with-id (ident)
15654 "Locate the entry that contains the ID property with exact value IDENT.
15655 IDENT can be a string, a symbol or a number, this function will search for
15656 the string representation of it.
15657 Return the position where this entry starts, or nil if there is no such entry."
15658 (interactive "sID: ")
15659 (let ((id (cond
15660 ((stringp ident) ident)
15661 ((symbol-name ident) (symbol-name ident))
15662 ((numberp ident) (number-to-string ident))
15663 (t (error "IDENT %s must be a string, symbol or number" ident))))
15664 (case-fold-search nil))
15665 (save-excursion
15666 (save-restriction
15667 (widen)
15668 (goto-char (point-min))
15669 (when (re-search-forward
15670 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15671 nil t)
15672 (org-back-to-heading t)
15673 (point))))))
15675 ;;;; Timestamps
15677 (defvar org-last-changed-timestamp nil)
15678 (defvar org-last-inserted-timestamp nil
15679 "The last time stamp inserted with `org-insert-time-stamp'.")
15680 (defvar org-time-was-given) ; dynamically scoped parameter
15681 (defvar org-end-time-was-given) ; dynamically scoped parameter
15682 (defvar org-ts-what) ; dynamically scoped parameter
15684 (defun org-time-stamp (arg &optional inactive)
15685 "Prompt for a date/time and insert a time stamp.
15686 If the user specifies a time like HH:MM or if this command is
15687 called with at least one prefix argument, the time stamp contains
15688 the date and the time. Otherwise, only the date is be included.
15690 All parts of a date not specified by the user is filled in from
15691 the current date/time. So if you just press return without
15692 typing anything, the time stamp will represent the current
15693 date/time.
15695 If there is already a timestamp at the cursor, it will be
15696 modified.
15698 With two universal prefix arguments, insert an active timestamp
15699 with the current time without prompting the user."
15700 (interactive "P")
15701 (let* ((ts nil)
15702 (default-time
15703 ;; Default time is either today, or, when entering a range,
15704 ;; the range start.
15705 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15706 (save-excursion
15707 (re-search-backward
15708 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15709 (- (point) 20) t)))
15710 (apply 'encode-time (org-parse-time-string (match-string 1)))
15711 (current-time)))
15712 (default-input (and ts (org-get-compact-tod ts)))
15713 (repeater (save-excursion
15714 (save-match-data
15715 (beginning-of-line)
15716 (when (re-search-forward
15717 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15718 (save-excursion (progn (end-of-line) (point))) t)
15719 (match-string 0)))))
15720 org-time-was-given org-end-time-was-given time)
15721 (cond
15722 ((and (org-at-timestamp-p t)
15723 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15724 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15725 (insert "--")
15726 (setq time (let ((this-command this-command))
15727 (org-read-date arg 'totime nil nil
15728 default-time default-input inactive)))
15729 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15730 ((org-at-timestamp-p t)
15731 (setq time (let ((this-command this-command))
15732 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15733 (when (org-at-timestamp-p t) ; just to get the match data
15734 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15735 (replace-match "")
15736 (setq org-last-changed-timestamp
15737 (org-insert-time-stamp
15738 time (or org-time-was-given arg)
15739 inactive nil nil (list org-end-time-was-given)))
15740 (when repeater (goto-char (1- (point))) (insert " " repeater)
15741 (setq org-last-changed-timestamp
15742 (concat (substring org-last-inserted-timestamp 0 -1)
15743 " " repeater ">"))))
15744 (message "Timestamp updated"))
15745 ((equal arg '(16))
15746 (org-insert-time-stamp (current-time) t))
15748 (setq time (let ((this-command this-command))
15749 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15750 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15751 nil nil (list org-end-time-was-given))))))
15753 ;; FIXME: can we use this for something else, like computing time differences?
15754 (defun org-get-compact-tod (s)
15755 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15756 (let* ((t1 (match-string 1 s))
15757 (h1 (string-to-number (match-string 2 s)))
15758 (m1 (string-to-number (match-string 3 s)))
15759 (t2 (and (match-end 4) (match-string 5 s)))
15760 (h2 (and t2 (string-to-number (match-string 6 s))))
15761 (m2 (and t2 (string-to-number (match-string 7 s))))
15762 dh dm)
15763 (if (not t2)
15765 (setq dh (- h2 h1) dm (- m2 m1))
15766 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15767 (concat t1 "+" (number-to-string dh)
15768 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15770 (defun org-time-stamp-inactive (&optional arg)
15771 "Insert an inactive time stamp.
15772 An inactive time stamp is enclosed in square brackets instead of angle
15773 brackets. It is inactive in the sense that it does not trigger agenda entries,
15774 does not link to the calendar and cannot be changed with the S-cursor keys.
15775 So these are more for recording a certain time/date."
15776 (interactive "P")
15777 (org-time-stamp arg 'inactive))
15779 (defvar org-date-ovl (make-overlay 1 1))
15780 (overlay-put org-date-ovl 'face 'org-date-selected)
15781 (org-detach-overlay org-date-ovl)
15783 (defvar org-ans1) ; dynamically scoped parameter
15784 (defvar org-ans2) ; dynamically scoped parameter
15786 (defvar org-plain-time-of-day-regexp) ; defined below
15788 (defvar org-overriding-default-time nil) ; dynamically scoped
15789 (defvar org-read-date-overlay nil)
15790 (defvar org-dcst nil) ; dynamically scoped
15791 (defvar org-read-date-history nil)
15792 (defvar org-read-date-final-answer nil)
15793 (defvar org-read-date-analyze-futurep nil)
15794 (defvar org-read-date-analyze-forced-year nil)
15795 (defvar org-read-date-inactive)
15797 (defvar org-read-date-minibuffer-local-map
15798 (let ((map (make-sparse-keymap)))
15799 (set-keymap-parent map minibuffer-local-map)
15800 (org-defkey map (kbd ".")
15801 (lambda () (interactive)
15802 (org-eval-in-calendar '(calendar-goto-today))))
15803 (org-defkey map [(meta shift left)]
15804 (lambda () (interactive)
15805 (org-eval-in-calendar '(calendar-backward-month 1))))
15806 (org-defkey map [(meta shift right)]
15807 (lambda () (interactive)
15808 (org-eval-in-calendar '(calendar-forward-month 1))))
15809 (org-defkey map [(meta shift up)]
15810 (lambda () (interactive)
15811 (org-eval-in-calendar '(calendar-backward-year 1))))
15812 (org-defkey map [(meta shift down)]
15813 (lambda () (interactive)
15814 (org-eval-in-calendar '(calendar-forward-year 1))))
15815 (org-defkey map [?\e (shift left)]
15816 (lambda () (interactive)
15817 (org-eval-in-calendar '(calendar-backward-month 1))))
15818 (org-defkey map [?\e (shift right)]
15819 (lambda () (interactive)
15820 (org-eval-in-calendar '(calendar-forward-month 1))))
15821 (org-defkey map [?\e (shift up)]
15822 (lambda () (interactive)
15823 (org-eval-in-calendar '(calendar-backward-year 1))))
15824 (org-defkey map [?\e (shift down)]
15825 (lambda () (interactive)
15826 (org-eval-in-calendar '(calendar-forward-year 1))))
15827 (org-defkey map [(shift up)]
15828 (lambda () (interactive)
15829 (org-eval-in-calendar '(calendar-backward-week 1))))
15830 (org-defkey map [(shift down)]
15831 (lambda () (interactive)
15832 (org-eval-in-calendar '(calendar-forward-week 1))))
15833 (org-defkey map [(shift left)]
15834 (lambda () (interactive)
15835 (org-eval-in-calendar '(calendar-backward-day 1))))
15836 (org-defkey map [(shift right)]
15837 (lambda () (interactive)
15838 (org-eval-in-calendar '(calendar-forward-day 1))))
15839 (org-defkey map "!"
15840 (lambda () (interactive)
15841 (org-eval-in-calendar '(diary-view-entries))
15842 (message "")))
15843 (org-defkey map ">"
15844 (lambda () (interactive)
15845 (org-eval-in-calendar '(scroll-calendar-left 1))))
15846 (org-defkey map "<"
15847 (lambda () (interactive)
15848 (org-eval-in-calendar '(scroll-calendar-right 1))))
15849 (org-defkey map "\C-v"
15850 (lambda () (interactive)
15851 (org-eval-in-calendar
15852 '(calendar-scroll-left-three-months 1))))
15853 (org-defkey map "\M-v"
15854 (lambda () (interactive)
15855 (org-eval-in-calendar
15856 '(calendar-scroll-right-three-months 1))))
15857 map)
15858 "Keymap for minibuffer commands when using `org-read-date'.")
15860 (defun org-read-date (&optional org-with-time to-time from-string prompt
15861 default-time default-input inactive)
15862 "Read a date, possibly a time, and make things smooth for the user.
15863 The prompt will suggest to enter an ISO date, but you can also enter anything
15864 which will at least partially be understood by `parse-time-string'.
15865 Unrecognized parts of the date will default to the current day, month, year,
15866 hour and minute. If this command is called to replace a timestamp at point,
15867 or to enter the second timestamp of a range, the default time is taken
15868 from the existing stamp. Furthermore, the command prefers the future,
15869 so if you are giving a date where the year is not given, and the day-month
15870 combination is already past in the current year, it will assume you
15871 mean next year. For details, see the manual. A few examples:
15873 3-2-5 --> 2003-02-05
15874 feb 15 --> currentyear-02-15
15875 2/15 --> currentyear-02-15
15876 sep 12 9 --> 2009-09-12
15877 12:45 --> today 12:45
15878 22 sept 0:34 --> currentyear-09-22 0:34
15879 12 --> currentyear-currentmonth-12
15880 Fri --> nearest Friday (today or later)
15881 etc.
15883 Furthermore you can specify a relative date by giving, as the *first* thing
15884 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15885 change in days weeks, months, years.
15886 With a single plus or minus, the date is relative to today. With a double
15887 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15888 +4d --> four days from today
15889 +4 --> same as above
15890 +2w --> two weeks from today
15891 ++5 --> five days from default date
15893 The function understands only English month and weekday abbreviations.
15895 While prompting, a calendar is popped up - you can also select the
15896 date with the mouse (button 1). The calendar shows a period of three
15897 months. To scroll it to other months, use the keys `>' and `<'.
15898 If you don't like the calendar, turn it off with
15899 \(setq org-read-date-popup-calendar nil)
15901 With optional argument TO-TIME, the date will immediately be converted
15902 to an internal time.
15903 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15904 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15905 still enter a time, and this function will inform the calling routine
15906 about this change. The calling routine may then choose to change the
15907 format used to insert the time stamp into the buffer to include the time.
15908 With optional argument FROM-STRING, read from this string instead from
15909 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15910 the time/date that is used for everything that is not specified by the
15911 user."
15912 (require 'parse-time)
15913 (let* ((org-time-stamp-rounding-minutes
15914 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15915 (org-dcst org-display-custom-times)
15916 (ct (org-current-time))
15917 (org-def (or org-overriding-default-time default-time ct))
15918 (org-defdecode (decode-time org-def))
15919 (dummy (progn
15920 (when (< (nth 2 org-defdecode) org-extend-today-until)
15921 (setcar (nthcdr 2 org-defdecode) -1)
15922 (setcar (nthcdr 1 org-defdecode) 59)
15923 (setq org-def (apply 'encode-time org-defdecode)
15924 org-defdecode (decode-time org-def)))))
15925 (mouse-autoselect-window nil) ; Don't let the mouse jump
15926 (calendar-frame-setup nil)
15927 (calendar-setup nil)
15928 (calendar-move-hook nil)
15929 (calendar-view-diary-initially-flag nil)
15930 (calendar-view-holidays-initially-flag nil)
15931 (timestr (format-time-string
15932 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15933 (prompt (concat (if prompt (concat prompt " ") "")
15934 (format "Date+time [%s]: " timestr)))
15935 ans (org-ans0 "") org-ans1 org-ans2 final)
15937 (cond
15938 (from-string (setq ans from-string))
15939 (org-read-date-popup-calendar
15940 (save-excursion
15941 (save-window-excursion
15942 (calendar)
15943 (org-eval-in-calendar '(setq cursor-type nil) t)
15944 (unwind-protect
15945 (progn
15946 (calendar-forward-day (- (time-to-days org-def)
15947 (calendar-absolute-from-gregorian
15948 (calendar-current-date))))
15949 (org-eval-in-calendar nil t)
15950 (let* ((old-map (current-local-map))
15951 (map (copy-keymap calendar-mode-map))
15952 (minibuffer-local-map
15953 (copy-keymap org-read-date-minibuffer-local-map)))
15954 (org-defkey map (kbd "RET") 'org-calendar-select)
15955 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15956 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15957 (unwind-protect
15958 (progn
15959 (use-local-map map)
15960 (setq org-read-date-inactive inactive)
15961 (add-hook 'post-command-hook 'org-read-date-display)
15962 (setq org-ans0 (read-string prompt default-input
15963 'org-read-date-history nil))
15964 ;; org-ans0: from prompt
15965 ;; org-ans1: from mouse click
15966 ;; org-ans2: from calendar motion
15967 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15968 (remove-hook 'post-command-hook 'org-read-date-display)
15969 (use-local-map old-map)
15970 (when org-read-date-overlay
15971 (delete-overlay org-read-date-overlay)
15972 (setq org-read-date-overlay nil)))))
15973 (bury-buffer "*Calendar*")))))
15975 (t ; Naked prompt only
15976 (unwind-protect
15977 (setq ans (read-string prompt default-input
15978 'org-read-date-history timestr))
15979 (when org-read-date-overlay
15980 (delete-overlay org-read-date-overlay)
15981 (setq org-read-date-overlay nil)))))
15983 (setq final (org-read-date-analyze ans org-def org-defdecode))
15985 (when org-read-date-analyze-forced-year
15986 (message "Year was forced into %s"
15987 (if org-read-date-force-compatible-dates
15988 "compatible range (1970-2037)"
15989 "range representable on this machine"))
15990 (ding))
15992 ;; One round trip to get rid of 34th of August and stuff like that....
15993 (setq final (decode-time (apply 'encode-time final)))
15995 (setq org-read-date-final-answer ans)
15997 (if to-time
15998 (apply 'encode-time final)
15999 (if (and (boundp 'org-time-was-given) org-time-was-given)
16000 (format "%04d-%02d-%02d %02d:%02d"
16001 (nth 5 final) (nth 4 final) (nth 3 final)
16002 (nth 2 final) (nth 1 final))
16003 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16005 (defvar org-def)
16006 (defvar org-defdecode)
16007 (defvar org-with-time)
16008 (defun org-read-date-display ()
16009 "Display the current date prompt interpretation in the minibuffer."
16010 (when org-read-date-display-live
16011 (when org-read-date-overlay
16012 (delete-overlay org-read-date-overlay))
16013 (when (minibufferp (current-buffer))
16014 (save-excursion
16015 (end-of-line 1)
16016 (while (not (equal (buffer-substring
16017 (max (point-min) (- (point) 4)) (point))
16018 " "))
16019 (insert " ")))
16020 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16021 " " (or org-ans1 org-ans2)))
16022 (org-end-time-was-given nil)
16023 (f (org-read-date-analyze ans org-def org-defdecode))
16024 (fmts (if org-dcst
16025 org-time-stamp-custom-formats
16026 org-time-stamp-formats))
16027 (fmt (if (or org-with-time
16028 (and (boundp 'org-time-was-given) org-time-was-given))
16029 (cdr fmts)
16030 (car fmts)))
16031 (txt (format-time-string fmt (apply 'encode-time f)))
16032 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16033 (txt (concat "=> " txt)))
16034 (when (and org-end-time-was-given
16035 (string-match org-plain-time-of-day-regexp txt))
16036 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16037 org-end-time-was-given
16038 (substring txt (match-end 0)))))
16039 (when org-read-date-analyze-futurep
16040 (setq txt (concat txt " (=>F)")))
16041 (setq org-read-date-overlay
16042 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16043 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16045 (defun org-read-date-analyze (ans org-def org-defdecode)
16046 "Analyze the combined answer of the date prompt."
16047 ;; FIXME: cleanup and comment
16048 (let ((nowdecode (decode-time (current-time)))
16049 delta deltan deltaw deltadef year month day
16050 hour minute second wday pm h2 m2 tl wday1
16051 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16052 (setq org-read-date-analyze-futurep nil
16053 org-read-date-analyze-forced-year nil)
16054 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16055 (setq ans "+0"))
16057 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16058 (setq ans (replace-match "" t t ans)
16059 deltan (car delta)
16060 deltaw (nth 1 delta)
16061 deltadef (nth 2 delta)))
16063 ;; Check if there is an iso week date in there. If yes, store the
16064 ;; info and postpone interpreting it until the rest of the parsing
16065 ;; is done.
16066 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16067 (setq iso-year (if (match-end 1)
16068 (org-small-year-to-year
16069 (string-to-number (match-string 1 ans))))
16070 iso-weekday (if (match-end 3)
16071 (string-to-number (match-string 3 ans)))
16072 iso-week (string-to-number (match-string 2 ans)))
16073 (setq ans (replace-match "" t t ans)))
16075 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16076 (when (string-match
16077 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16078 (setq year (if (match-end 2)
16079 (string-to-number (match-string 2 ans))
16080 (progn (setq kill-year t)
16081 (string-to-number (format-time-string "%Y"))))
16082 month (string-to-number (match-string 3 ans))
16083 day (string-to-number (match-string 4 ans)))
16084 (if (< year 100) (setq year (+ 2000 year)))
16085 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16086 t nil ans)))
16088 ;; Help matching dotted european dates
16089 (when (string-match
16090 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16091 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16092 (setq kill-year t)
16093 (string-to-number (format-time-string "%Y")))
16094 day (string-to-number (match-string 1 ans))
16095 month (string-to-number (match-string 2 ans))
16096 ans (replace-match (format "%04d-%02d-%02d" year month day)
16097 t nil ans)))
16099 ;; Help matching american dates, like 5/30 or 5/30/7
16100 (when (string-match
16101 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16102 (setq year (if (match-end 4)
16103 (string-to-number (match-string 4 ans))
16104 (progn (setq kill-year t)
16105 (string-to-number (format-time-string "%Y"))))
16106 month (string-to-number (match-string 1 ans))
16107 day (string-to-number (match-string 2 ans)))
16108 (if (< year 100) (setq year (+ 2000 year)))
16109 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16110 t nil ans)))
16111 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16112 ;; If there is a time with am/pm, and *no* time without it, we convert
16113 ;; so that matching will be successful.
16114 (loop for i from 1 to 2 do ; twice, for end time as well
16115 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16116 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16117 (setq hour (string-to-number (match-string 1 ans))
16118 minute (if (match-end 3)
16119 (string-to-number (match-string 3 ans))
16121 pm (equal ?p
16122 (string-to-char (downcase (match-string 4 ans)))))
16123 (if (and (= hour 12) (not pm))
16124 (setq hour 0)
16125 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16126 (setq ans (replace-match (format "%02d:%02d" hour minute)
16127 t t ans))))
16129 ;; Check if a time range is given as a duration
16130 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16131 (setq hour (string-to-number (match-string 1 ans))
16132 h2 (+ hour (string-to-number (match-string 3 ans)))
16133 minute (string-to-number (match-string 2 ans))
16134 m2 (+ minute (if (match-end 5) (string-to-number
16135 (match-string 5 ans))0)))
16136 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16137 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16138 t t ans)))
16140 ;; Check if there is a time range
16141 (when (boundp 'org-end-time-was-given)
16142 (setq org-time-was-given nil)
16143 (when (and (string-match org-plain-time-of-day-regexp ans)
16144 (match-end 8))
16145 (setq org-end-time-was-given (match-string 8 ans))
16146 (setq ans (concat (substring ans 0 (match-beginning 7))
16147 (substring ans (match-end 7))))))
16149 (setq tl (parse-time-string ans)
16150 day (or (nth 3 tl) (nth 3 org-defdecode))
16151 month (or (nth 4 tl)
16152 (if (and org-read-date-prefer-future
16153 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16154 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16155 (nth 4 org-defdecode)))
16156 year (or (and (not kill-year) (nth 5 tl))
16157 (if (and org-read-date-prefer-future
16158 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16159 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16160 (nth 5 org-defdecode)))
16161 hour (or (nth 2 tl) (nth 2 org-defdecode))
16162 minute (or (nth 1 tl) (nth 1 org-defdecode))
16163 second (or (nth 0 tl) 0)
16164 wday (nth 6 tl))
16166 (when (and (eq org-read-date-prefer-future 'time)
16167 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16168 (equal day (nth 3 nowdecode))
16169 (equal month (nth 4 nowdecode))
16170 (equal year (nth 5 nowdecode))
16171 (nth 2 tl)
16172 (or (< (nth 2 tl) (nth 2 nowdecode))
16173 (and (= (nth 2 tl) (nth 2 nowdecode))
16174 (nth 1 tl)
16175 (< (nth 1 tl) (nth 1 nowdecode)))))
16176 (setq day (1+ day)
16177 futurep t))
16179 ;; Special date definitions below
16180 (cond
16181 (iso-week
16182 ;; There was an iso week
16183 (require 'cal-iso)
16184 (setq futurep nil)
16185 (setq year (or iso-year year)
16186 day (or iso-weekday wday 1)
16187 wday nil ; to make sure that the trigger below does not match
16188 iso-date (calendar-gregorian-from-absolute
16189 (calendar-absolute-from-iso
16190 (list iso-week day year))))
16191 ; FIXME: Should we also push ISO weeks into the future?
16192 ; (when (and org-read-date-prefer-future
16193 ; (not iso-year)
16194 ; (< (calendar-absolute-from-gregorian iso-date)
16195 ; (time-to-days (current-time))))
16196 ; (setq year (1+ year)
16197 ; iso-date (calendar-gregorian-from-absolute
16198 ; (calendar-absolute-from-iso
16199 ; (list iso-week day year)))))
16200 (setq month (car iso-date)
16201 year (nth 2 iso-date)
16202 day (nth 1 iso-date)))
16203 (deltan
16204 (setq futurep nil)
16205 (unless deltadef
16206 (let ((now (decode-time (current-time))))
16207 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16208 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16209 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16210 ((equal deltaw "m") (setq month (+ month deltan)))
16211 ((equal deltaw "y") (setq year (+ year deltan)))))
16212 ((and wday (not (nth 3 tl)))
16213 ;; Weekday was given, but no day, so pick that day in the week
16214 ;; on or after the derived date.
16215 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16216 (unless (equal wday wday1)
16217 (setq day (+ day (% (- wday wday1 -7) 7))))))
16218 (if (and (boundp 'org-time-was-given)
16219 (nth 2 tl))
16220 (setq org-time-was-given t))
16221 (if (< year 100) (setq year (+ 2000 year)))
16222 ;; Check of the date is representable
16223 (if org-read-date-force-compatible-dates
16224 (progn
16225 (if (< year 1970)
16226 (setq year 1970 org-read-date-analyze-forced-year t))
16227 (if (> year 2037)
16228 (setq year 2037 org-read-date-analyze-forced-year t)))
16229 (condition-case nil
16230 (ignore (encode-time second minute hour day month year))
16231 (error
16232 (setq year (nth 5 org-defdecode))
16233 (setq org-read-date-analyze-forced-year t))))
16234 (setq org-read-date-analyze-futurep futurep)
16235 (list second minute hour day month year)))
16237 (defvar parse-time-weekdays)
16238 (defun org-read-date-get-relative (s today default)
16239 "Check string S for special relative date string.
16240 TODAY and DEFAULT are internal times, for today and for a default.
16241 Return shift list (N what def-flag)
16242 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16243 N is the number of WHATs to shift.
16244 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16245 the DEFAULT date rather than TODAY."
16246 (require 'parse-time)
16247 (when (and
16248 (string-match
16249 (concat
16250 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16251 "\\([0-9]+\\)?"
16252 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16253 "\\([ \t]\\|$\\)") s)
16254 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16255 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16256 (string-to-char (substring (match-string 1 s) -1))
16257 ?+))
16258 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16259 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16260 (what (if (match-end 3) (match-string 3 s) "d"))
16261 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16262 (date (if rel default today))
16263 (wday (nth 6 (decode-time date)))
16264 delta)
16265 (if wday1
16266 (progn
16267 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16268 (if (= dir ?-) (setq delta (- delta 7)))
16269 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16270 (list delta "d" rel))
16271 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16273 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16274 "Turn a user-specified date into the internal representation.
16275 The internal representation needed by the calendar is (month day year).
16276 This is a wrapper to handle the brain-dead convention in calendar that
16277 user function argument order change dependent on argument order."
16278 (if (boundp 'calendar-date-style)
16279 (cond
16280 ((eq calendar-date-style 'american)
16281 (list arg1 arg2 arg3))
16282 ((eq calendar-date-style 'european)
16283 (list arg2 arg1 arg3))
16284 ((eq calendar-date-style 'iso)
16285 (list arg2 arg3 arg1)))
16286 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16287 (if (org-bound-and-true-p european-calendar-style)
16288 (list arg2 arg1 arg3)
16289 (list arg1 arg2 arg3)))))
16291 (defun org-eval-in-calendar (form &optional keepdate)
16292 "Eval FORM in the calendar window and return to current window.
16293 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16294 otherwise stick to the current value of `org-ans2'."
16295 (let ((sf (selected-frame))
16296 (sw (selected-window)))
16297 (select-window (get-buffer-window "*Calendar*" t))
16298 (eval form)
16299 (when (and (not keepdate) (calendar-cursor-to-date))
16300 (let* ((date (calendar-cursor-to-date))
16301 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16302 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16303 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16304 (select-window sw)
16305 (org-select-frame-set-input-focus sf)))
16307 (defun org-calendar-select ()
16308 "Return to `org-read-date' with the date currently selected.
16309 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16310 (interactive)
16311 (when (calendar-cursor-to-date)
16312 (let* ((date (calendar-cursor-to-date))
16313 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16314 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16315 (if (active-minibuffer-window) (exit-minibuffer))))
16317 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16318 "Insert a date stamp for the date given by the internal TIME.
16319 WITH-HM means use the stamp format that includes the time of the day.
16320 INACTIVE means use square brackets instead of angular ones, so that the
16321 stamp will not contribute to the agenda.
16322 PRE and POST are optional strings to be inserted before and after the
16323 stamp.
16324 The command returns the inserted time stamp."
16325 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16326 stamp)
16327 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16328 (insert-before-markers (or pre ""))
16329 (when (listp extra)
16330 (setq extra (car extra))
16331 (if (and (stringp extra)
16332 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16333 (setq extra (format "-%02d:%02d"
16334 (string-to-number (match-string 1 extra))
16335 (string-to-number (match-string 2 extra))))
16336 (setq extra nil)))
16337 (when extra
16338 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16339 (insert-before-markers (setq stamp (format-time-string fmt time)))
16340 (insert-before-markers (or post ""))
16341 (setq org-last-inserted-timestamp stamp)))
16343 (defun org-toggle-time-stamp-overlays ()
16344 "Toggle the use of custom time stamp formats."
16345 (interactive)
16346 (setq org-display-custom-times (not org-display-custom-times))
16347 (unless org-display-custom-times
16348 (let ((p (point-min)) (bmp (buffer-modified-p)))
16349 (while (setq p (next-single-property-change p 'display))
16350 (if (and (get-text-property p 'display)
16351 (eq (get-text-property p 'face) 'org-date))
16352 (remove-text-properties
16353 p (setq p (next-single-property-change p 'display))
16354 '(display t))))
16355 (set-buffer-modified-p bmp)))
16356 (if (featurep 'xemacs)
16357 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16358 (org-restart-font-lock)
16359 (setq org-table-may-need-update t)
16360 (if org-display-custom-times
16361 (message "Time stamps are overlaid with custom format")
16362 (message "Time stamp overlays removed")))
16364 (defun org-display-custom-time (beg end)
16365 "Overlay modified time stamp format over timestamp between BEG and END."
16366 (let* ((ts (buffer-substring beg end))
16367 t1 w1 with-hm tf time str w2 (off 0))
16368 (save-match-data
16369 (setq t1 (org-parse-time-string ts t))
16370 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16371 (setq off (- (match-end 0) (match-beginning 0)))))
16372 (setq end (- end off))
16373 (setq w1 (- end beg)
16374 with-hm (and (nth 1 t1) (nth 2 t1))
16375 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16376 time (org-fix-decoded-time t1)
16377 str (org-add-props
16378 (format-time-string
16379 (substring tf 1 -1) (apply 'encode-time time))
16380 nil 'mouse-face 'highlight)
16381 w2 (length str))
16382 (if (not (= w2 w1))
16383 (add-text-properties (1+ beg) (+ 2 beg)
16384 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16385 (if (featurep 'xemacs)
16386 (progn
16387 (put-text-property beg end 'invisible t)
16388 (put-text-property beg end 'end-glyph (make-glyph str)))
16389 (put-text-property beg end 'display str))))
16391 (defun org-translate-time (string)
16392 "Translate all timestamps in STRING to custom format.
16393 But do this only if the variable `org-display-custom-times' is set."
16394 (when org-display-custom-times
16395 (save-match-data
16396 (let* ((start 0)
16397 (re org-ts-regexp-both)
16398 t1 with-hm inactive tf time str beg end)
16399 (while (setq start (string-match re string start))
16400 (setq beg (match-beginning 0)
16401 end (match-end 0)
16402 t1 (save-match-data
16403 (org-parse-time-string (substring string beg end) t))
16404 with-hm (and (nth 1 t1) (nth 2 t1))
16405 inactive (equal (substring string beg (1+ beg)) "[")
16406 tf (funcall (if with-hm 'cdr 'car)
16407 org-time-stamp-custom-formats)
16408 time (org-fix-decoded-time t1)
16409 str (format-time-string
16410 (concat
16411 (if inactive "[" "<") (substring tf 1 -1)
16412 (if inactive "]" ">"))
16413 (apply 'encode-time time))
16414 string (replace-match str t t string)
16415 start (+ start (length str)))))))
16416 string)
16418 (defun org-fix-decoded-time (time)
16419 "Set 0 instead of nil for the first 6 elements of time.
16420 Don't touch the rest."
16421 (let ((n 0))
16422 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16424 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16426 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16427 "Difference between TIMESTAMP-STRING and now in days.
16428 If SECONDS is non-nil, return the difference in seconds."
16429 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16430 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16431 (funcall fdiff (current-time)))))
16433 (defun org-deadline-close (timestamp-string &optional ndays)
16434 "Is the time in TIMESTAMP-STRING close to the current date?"
16435 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16436 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16437 (not (org-entry-is-done-p))))
16439 (defun org-get-wdays (ts &optional delay zero-delay)
16440 "Get the deadline lead time appropriate for timestring TS.
16441 When DELAY is non-nil, get the delay time for scheduled items
16442 instead of the deadline lead time. When ZERO-DELAY is non-nil
16443 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16444 don't try to find the delay cookie in the scheduled timestamp."
16445 (let ((tv (if delay org-scheduled-delay-days
16446 org-deadline-warning-days)))
16447 (cond
16448 ((or (and delay (< tv 0))
16449 (and delay zero-delay (<= tv 0))
16450 (and (not delay) (<= tv 0)))
16451 ;; Enforce this value no matter what
16452 (- tv))
16453 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16454 ;; lead time is specified.
16455 (floor (* (string-to-number (match-string 1 ts))
16456 (cdr (assoc (match-string 2 ts)
16457 '(("d" . 1) ("w" . 7)
16458 ("m" . 30.4) ("y" . 365.25)
16459 ("h" . 0.041667)))))))
16460 ;; go for the default.
16461 (t tv))))
16463 (defun org-calendar-select-mouse (ev)
16464 "Return to `org-read-date' with the date currently selected.
16465 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16466 (interactive "e")
16467 (mouse-set-point ev)
16468 (when (calendar-cursor-to-date)
16469 (let* ((date (calendar-cursor-to-date))
16470 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16471 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16472 (if (active-minibuffer-window) (exit-minibuffer))))
16474 (defun org-check-deadlines (ndays)
16475 "Check if there are any deadlines due or past due.
16476 A deadline is considered due if it happens within `org-deadline-warning-days'
16477 days from today's date. If the deadline appears in an entry marked DONE,
16478 it is not shown. The prefix arg NDAYS can be used to test that many
16479 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16480 (interactive "P")
16481 (let* ((org-warn-days
16482 (cond
16483 ((equal ndays '(4)) 100000)
16484 (ndays (prefix-numeric-value ndays))
16485 (t (abs org-deadline-warning-days))))
16486 (case-fold-search nil)
16487 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16488 (callback
16489 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16491 (message "%d deadlines past-due or due within %d days"
16492 (org-occur regexp nil callback)
16493 org-warn-days)))
16495 (defsubst org-re-timestamp (type)
16496 "Return a regexp for timestamp TYPE.
16497 Allowed values for TYPE are:
16499 all: all timestamps
16500 active: only active timestamps (<...>)
16501 inactive: only inactive timestamps ([...])
16502 scheduled: only scheduled timestamps
16503 deadline: only deadline timestamps
16505 When TYPE is nil, fall back on returning a regexp that matches
16506 both scheduled and deadline timestamps."
16507 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16508 ((eq type 'active) org-ts-regexp)
16509 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16510 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16511 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16512 ((eq type 'scheduled-or-deadline)
16513 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16515 (defun org-check-before-date (date)
16516 "Check if there are deadlines or scheduled entries before DATE."
16517 (interactive (list (org-read-date)))
16518 (let ((case-fold-search nil)
16519 (regexp (org-re-timestamp org-ts-type))
16520 (callback
16521 (lambda () (time-less-p
16522 (org-time-string-to-time (match-string 1))
16523 (org-time-string-to-time date)))))
16524 (message "%d entries before %s"
16525 (org-occur regexp nil callback) date)))
16527 (defun org-check-after-date (date)
16528 "Check if there are deadlines or scheduled entries after DATE."
16529 (interactive (list (org-read-date)))
16530 (let ((case-fold-search nil)
16531 (regexp (org-re-timestamp org-ts-type))
16532 (callback
16533 (lambda () (not
16534 (time-less-p
16535 (org-time-string-to-time (match-string 1))
16536 (org-time-string-to-time date))))))
16537 (message "%d entries after %s"
16538 (org-occur regexp nil callback) date)))
16540 (defun org-check-dates-range (start-date end-date)
16541 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16542 (interactive (list (org-read-date nil nil nil "Range starts")
16543 (org-read-date nil nil nil "Range end")))
16544 (let ((case-fold-search nil)
16545 (regexp (org-re-timestamp org-ts-type))
16546 (callback
16547 (lambda ()
16548 (let ((match (match-string 1)))
16549 (and
16550 (not (time-less-p
16551 (org-time-string-to-time match)
16552 (org-time-string-to-time start-date)))
16553 (time-less-p
16554 (org-time-string-to-time match)
16555 (org-time-string-to-time end-date)))))))
16556 (message "%d entries between %s and %s"
16557 (org-occur regexp nil callback) start-date end-date)))
16559 (defun org-evaluate-time-range (&optional to-buffer)
16560 "Evaluate a time range by computing the difference between start and end.
16561 Normally the result is just printed in the echo area, but with prefix arg
16562 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16563 If the time range is actually in a table, the result is inserted into the
16564 next column.
16565 For time difference computation, a year is assumed to be exactly 365
16566 days in order to avoid rounding problems."
16567 (interactive "P")
16569 (org-clock-update-time-maybe)
16570 (save-excursion
16571 (unless (org-at-date-range-p t)
16572 (goto-char (point-at-bol))
16573 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16574 (if (not (org-at-date-range-p t))
16575 (error "Not at a time-stamp range, and none found in current line")))
16576 (let* ((ts1 (match-string 1))
16577 (ts2 (match-string 2))
16578 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16579 (match-end (match-end 0))
16580 (time1 (org-time-string-to-time ts1))
16581 (time2 (org-time-string-to-time ts2))
16582 (t1 (org-float-time time1))
16583 (t2 (org-float-time time2))
16584 (diff (abs (- t2 t1)))
16585 (negative (< (- t2 t1) 0))
16586 ;; (ys (floor (* 365 24 60 60)))
16587 (ds (* 24 60 60))
16588 (hs (* 60 60))
16589 (fy "%dy %dd %02d:%02d")
16590 (fy1 "%dy %dd")
16591 (fd "%dd %02d:%02d")
16592 (fd1 "%dd")
16593 (fh "%02d:%02d")
16594 y d h m align)
16595 (if havetime
16596 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16598 d (floor (/ diff ds)) diff (mod diff ds)
16599 h (floor (/ diff hs)) diff (mod diff hs)
16600 m (floor (/ diff 60)))
16601 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16603 d (floor (+ (/ diff ds) 0.5))
16604 h 0 m 0))
16605 (if (not to-buffer)
16606 (message "%s" (org-make-tdiff-string y d h m))
16607 (if (org-at-table-p)
16608 (progn
16609 (goto-char match-end)
16610 (setq align t)
16611 (and (looking-at " *|") (goto-char (match-end 0))))
16612 (goto-char match-end))
16613 (if (looking-at
16614 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16615 (replace-match ""))
16616 (if negative (insert " -"))
16617 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16618 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16619 (insert " " (format fh h m))))
16620 (if align (org-table-align))
16621 (message "Time difference inserted")))))
16623 (defun org-make-tdiff-string (y d h m)
16624 (let ((fmt "")
16625 (l nil))
16626 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16627 l (push y l)))
16628 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16629 l (push d l)))
16630 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16631 l (push h l)))
16632 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16633 l (push m l)))
16634 (apply 'format fmt (nreverse l))))
16636 (defun org-time-string-to-time (s &optional buffer pos)
16637 "Convert a timestamp string into internal time."
16638 (condition-case errdata
16639 (apply 'encode-time (org-parse-time-string s))
16640 (error (error "Bad timestamp `%s'%s\nError was: %s"
16641 s (if (not (and buffer pos))
16643 (format " at %d in buffer `%s'" pos buffer))
16644 (cdr errdata)))))
16646 (defun org-time-string-to-seconds (s)
16647 "Convert a timestamp string to a number of seconds."
16648 (org-float-time (org-time-string-to-time s)))
16650 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16651 "Convert a time stamp to an absolute day number.
16652 If there is a specifier for a cyclic time stamp, get the closest
16653 date to DAYNR.
16654 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16655 The variable date is bound by the calendar when this is called."
16656 (cond
16657 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16658 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16659 daynr
16660 (+ daynr 1000)))
16661 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16662 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16663 (time-to-days (current-time))) (match-string 0 s)
16664 prefer show-all))
16665 (t (time-to-days
16666 (condition-case errdata
16667 (apply 'encode-time (org-parse-time-string s))
16668 (error (error "Bad timestamp `%s'%s\nError was: %s"
16669 s (if (not (and buffer pos))
16671 (format " at %d in buffer `%s'" pos buffer))
16672 (cdr errdata))))))))
16674 (defun org-days-to-iso-week (days)
16675 "Return the iso week number."
16676 (require 'cal-iso)
16677 (car (calendar-iso-from-absolute days)))
16679 (defun org-small-year-to-year (year)
16680 "Convert 2-digit years into 4-digit years.
16681 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16682 The year 2000 cannot be abbreviated. Any year larger than 99
16683 is returned unchanged."
16684 (if (< year 38)
16685 (setq year (+ 2000 year))
16686 (if (< year 100)
16687 (setq year (+ 1900 year))))
16688 year)
16690 (defun org-time-from-absolute (d)
16691 "Return the time corresponding to date D.
16692 D may be an absolute day number, or a calendar-type list (month day year)."
16693 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16694 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16696 (defun org-calendar-holiday ()
16697 "List of holidays, for Diary display in Org-mode."
16698 (require 'holidays)
16699 (let ((hl (funcall
16700 (if (fboundp 'calendar-check-holidays)
16701 'calendar-check-holidays 'check-calendar-holidays) date)))
16702 (if hl (mapconcat 'identity hl "; "))))
16704 (defun org-diary-sexp-entry (sexp entry date)
16705 "Process a SEXP diary ENTRY for DATE."
16706 (require 'diary-lib)
16707 (let ((result (if calendar-debug-sexp
16708 (let ((stack-trace-on-error t))
16709 (eval (car (read-from-string sexp))))
16710 (condition-case nil
16711 (eval (car (read-from-string sexp)))
16712 (error
16713 (beep)
16714 (message "Bad sexp at line %d in %s: %s"
16715 (org-current-line)
16716 (buffer-file-name) sexp)
16717 (sleep-for 2))))))
16718 (cond ((stringp result) (split-string result "; "))
16719 ((and (consp result)
16720 (not (consp (cdr result)))
16721 (stringp (cdr result))) (cdr result))
16722 ((and (consp result)
16723 (stringp (car result))) result)
16724 (result entry))))
16726 (defun org-diary-to-ical-string (frombuf)
16727 "Get iCalendar entries from diary entries in buffer FROMBUF.
16728 This uses the icalendar.el library."
16729 (let* ((tmpdir (if (featurep 'xemacs)
16730 (temp-directory)
16731 temporary-file-directory))
16732 (tmpfile (make-temp-name
16733 (expand-file-name "orgics" tmpdir)))
16734 buf rtn b e)
16735 (with-current-buffer frombuf
16736 (icalendar-export-region (point-min) (point-max) tmpfile)
16737 (setq buf (find-buffer-visiting tmpfile))
16738 (set-buffer buf)
16739 (goto-char (point-min))
16740 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16741 (setq b (match-beginning 0)))
16742 (goto-char (point-max))
16743 (if (re-search-backward "^END:VEVENT" nil t)
16744 (setq e (match-end 0)))
16745 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16746 (kill-buffer buf)
16747 (delete-file tmpfile)
16748 rtn))
16750 (defun org-closest-date (start current change prefer show-all)
16751 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16752 When PREFER is `past', return a date that is either CURRENT or past.
16753 When PREFER is `future', return a date that is either CURRENT or future.
16754 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16755 ;; Make the proper lists from the dates
16756 (catch 'exit
16757 (let ((a1 '(("h" . hour)
16758 ("d" . day)
16759 ("w" . week)
16760 ("m" . month)
16761 ("y" . year)))
16762 (shour (nth 2 (org-parse-time-string start)))
16763 dn dw sday cday n1 n2 n0
16764 d m y y1 y2 date1 date2 nmonths nm ny m2)
16766 (setq start (org-date-to-gregorian start)
16767 current (org-date-to-gregorian
16768 (if show-all
16769 current
16770 (time-to-days (current-time))))
16771 sday (calendar-absolute-from-gregorian start)
16772 cday (calendar-absolute-from-gregorian current))
16774 (if (<= cday sday) (throw 'exit sday))
16776 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16777 (setq dn (string-to-number (match-string 1 change))
16778 dw (cdr (assoc (match-string 2 change) a1)))
16779 (error "Invalid change specifier: %s" change))
16780 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16781 (cond
16782 ((eq dw 'hour)
16783 (let ((missing-hours
16784 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16785 dn)))
16786 (setq n1 (if (zerop missing-hours) cday
16787 (- cday (1+ (floor (/ missing-hours 24)))))
16788 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16789 ((eq dw 'day)
16790 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16791 n2 (+ n1 dn)))
16792 ((eq dw 'year)
16793 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16794 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16795 (setq date1 (list m d y1)
16796 n1 (calendar-absolute-from-gregorian date1)
16797 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16798 n2 (calendar-absolute-from-gregorian date2)))
16799 ((eq dw 'month)
16800 ;; approx number of month between the two dates
16801 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16802 ;; How often does dn fit in there?
16803 (setq d (nth 1 start) m (car start) y (nth 2 start)
16804 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16805 m (+ m nm)
16806 ny (floor (/ m 12))
16807 y (+ y ny)
16808 m (- m (* ny 12)))
16809 (while (> m 12) (setq m (- m 12) y (1+ y)))
16810 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16811 (setq m2 (+ m dn) y2 y)
16812 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16813 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16814 (while (<= n2 cday)
16815 (setq n1 n2 m m2 y y2)
16816 (setq m2 (+ m dn) y2 y)
16817 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16818 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16819 ;; Make sure n1 is the earlier date
16820 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16821 (if show-all
16822 (cond
16823 ((eq prefer 'past) (if (= cday n2) n2 n1))
16824 ((eq prefer 'future) (if (= cday n1) n1 n2))
16825 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16826 (cond
16827 ((eq prefer 'past) (if (= cday n2) n2 n1))
16828 ((eq prefer 'future) (if (= cday n1) n1 n2))
16829 (t (if (= cday n1) n1 n2)))))))
16831 (defun org-date-to-gregorian (date)
16832 "Turn any specification of DATE into a Gregorian date for the calendar."
16833 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16834 ((and (listp date) (= (length date) 3)) date)
16835 ((stringp date)
16836 (setq date (org-parse-time-string date))
16837 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16838 ((listp date)
16839 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16841 (defun org-parse-time-string (s &optional nodefault)
16842 "Parse the standard Org-mode time string.
16843 This should be a lot faster than the normal `parse-time-string'.
16844 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16845 hour and minute fields will be nil if not given."
16846 (cond ((string-match org-ts-regexp0 s)
16847 (list 0
16848 (if (or (match-beginning 8) (not nodefault))
16849 (string-to-number (or (match-string 8 s) "0")))
16850 (if (or (match-beginning 7) (not nodefault))
16851 (string-to-number (or (match-string 7 s) "0")))
16852 (string-to-number (match-string 4 s))
16853 (string-to-number (match-string 3 s))
16854 (string-to-number (match-string 2 s))
16855 nil nil nil))
16856 ((string-match "^<[^>]+>$" s)
16857 (decode-time (seconds-to-time (org-matcher-time s))))
16858 (t (error "Not a standard Org-mode time string: %s" s))))
16860 (defun org-timestamp-up (&optional arg)
16861 "Increase the date item at the cursor by one.
16862 If the cursor is on the year, change the year. If it is on the month,
16863 the day or the time, change that.
16864 With prefix ARG, change by that many units."
16865 (interactive "p")
16866 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16868 (defun org-timestamp-down (&optional arg)
16869 "Decrease the date item at the cursor by one.
16870 If the cursor is on the year, change the year. If it is on the month,
16871 the day or the time, change that.
16872 With prefix ARG, change by that many units."
16873 (interactive "p")
16874 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16876 (defun org-timestamp-up-day (&optional arg)
16877 "Increase the date in the time stamp by one day.
16878 With prefix ARG, change that many days."
16879 (interactive "p")
16880 (if (and (not (org-at-timestamp-p t))
16881 (org-at-heading-p))
16882 (org-todo 'up)
16883 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16885 (defun org-timestamp-down-day (&optional arg)
16886 "Decrease the date in the time stamp by one day.
16887 With prefix ARG, change that many days."
16888 (interactive "p")
16889 (if (and (not (org-at-timestamp-p t))
16890 (org-at-heading-p))
16891 (org-todo 'down)
16892 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16894 (defun org-at-timestamp-p (&optional inactive-ok)
16895 "Determine if the cursor is in or at a timestamp."
16896 (interactive)
16897 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16898 (pos (point))
16899 (ans (or (looking-at tsr)
16900 (save-excursion
16901 (skip-chars-backward "^[<\n\r\t")
16902 (if (> (point) (point-min)) (backward-char 1))
16903 (and (looking-at tsr)
16904 (> (- (match-end 0) pos) -1))))))
16905 (and ans
16906 (boundp 'org-ts-what)
16907 (setq org-ts-what
16908 (cond
16909 ((= pos (match-beginning 0)) 'bracket)
16910 ;; Point is considered to be "on the bracket" whether
16911 ;; it's really on it or right after it.
16912 ((= pos (1- (match-end 0))) 'bracket)
16913 ((= pos (match-end 0)) 'after)
16914 ((org-pos-in-match-range pos 2) 'year)
16915 ((org-pos-in-match-range pos 3) 'month)
16916 ((org-pos-in-match-range pos 7) 'hour)
16917 ((org-pos-in-match-range pos 8) 'minute)
16918 ((or (org-pos-in-match-range pos 4)
16919 (org-pos-in-match-range pos 5)) 'day)
16920 ((and (> pos (or (match-end 8) (match-end 5)))
16921 (< pos (match-end 0)))
16922 (- pos (or (match-end 8) (match-end 5))))
16923 (t 'day))))
16924 ans))
16926 (defun org-toggle-timestamp-type ()
16927 "Toggle the type (<active> or [inactive]) of a time stamp."
16928 (interactive)
16929 (when (org-at-timestamp-p t)
16930 (let ((beg (match-beginning 0)) (end (match-end 0))
16931 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16932 (save-excursion
16933 (goto-char beg)
16934 (while (re-search-forward "[][<>]" end t)
16935 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16936 t t)))
16937 (message "Timestamp is now %sactive"
16938 (if (equal (char-after beg) ?<) "" "in")))))
16940 (defun org-at-clock-log-p nil
16941 "Is the cursor on the clock log line?"
16942 (save-excursion
16943 (move-beginning-of-line 1)
16944 (looking-at "^[ \t]*CLOCK:")))
16946 (defvar org-clock-history) ; defined in org-clock.el
16947 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16948 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16949 "Change the date in the time stamp at point.
16950 The date will be changed by N times WHAT. WHAT can be `day', `month',
16951 `year', `minute', `second'. If WHAT is not given, the cursor position
16952 in the timestamp determines what will be changed.
16953 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
16954 (let ((origin (point)) origin-cat
16955 with-hm inactive
16956 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16957 org-ts-what
16958 extra rem
16959 ts time time0 fixnext clrgx)
16960 (if (not (org-at-timestamp-p t))
16961 (error "Not at a timestamp"))
16962 (if (and (not what) (eq org-ts-what 'bracket))
16963 (org-toggle-timestamp-type)
16964 ;; Point isn't on brackets. Remember the part of the time-stamp
16965 ;; the point was in. Indeed, size of time-stamps may change,
16966 ;; but point must be kept in the same category nonetheless.
16967 (setq origin-cat org-ts-what)
16968 (if (and (not what) (not (eq org-ts-what 'day))
16969 org-display-custom-times
16970 (get-text-property (point) 'display)
16971 (not (get-text-property (1- (point)) 'display)))
16972 (setq org-ts-what 'day))
16973 (setq org-ts-what (or what org-ts-what)
16974 inactive (= (char-after (match-beginning 0)) ?\[)
16975 ts (match-string 0))
16976 (replace-match "")
16977 (when (string-match
16978 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16980 (setq extra (match-string 1 ts))
16981 (if suppress-tmp-delay
16982 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
16983 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16984 (setq with-hm t))
16985 (setq time0 (org-parse-time-string ts))
16986 (when (and updown
16987 (eq org-ts-what 'minute)
16988 (not current-prefix-arg))
16989 ;; This looks like s-up and s-down. Change by one rounding step.
16990 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16991 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16992 (setcar (cdr time0) (+ (nth 1 time0)
16993 (if (> n 0) (- rem) (- dm rem))))))
16994 (setq time
16995 (encode-time (or (car time0) 0)
16996 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16997 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16998 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16999 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17000 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17001 (nthcdr 6 time0)))
17002 (when (and (member org-ts-what '(hour minute))
17003 extra
17004 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17005 (setq extra (org-modify-ts-extra
17006 extra
17007 (if (eq org-ts-what 'hour) 2 5)
17008 n dm)))
17009 (when (integerp org-ts-what)
17010 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17011 (if (eq what 'calendar)
17012 (let ((cal-date (org-get-date-from-calendar)))
17013 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17014 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17015 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17016 (setcar time0 (or (car time0) 0))
17017 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17018 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17019 (setq time (apply 'encode-time time0))))
17020 ;; Insert the new time-stamp, and ensure point stays in the same
17021 ;; category as before (i.e. not after the last position in that
17022 ;; category).
17023 (let ((pos (point)))
17024 ;; Stay before inserted string. `save-excursion' is of no use.
17025 (setq org-last-changed-timestamp
17026 (org-insert-time-stamp time with-hm inactive nil nil extra))
17027 (goto-char pos))
17028 (save-match-data
17029 (looking-at org-ts-regexp3)
17030 (goto-char (cond
17031 ;; `day' category ends before `hour' if any, or at
17032 ;; the end of the day name.
17033 ((eq origin-cat 'day)
17034 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17035 ((eq origin-cat 'hour) (min (match-end 7) origin))
17036 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17037 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17038 ;; `year' and `month' have both fixed size: point
17039 ;; couldn't have moved into another part.
17040 (t origin))))
17041 ;; Update clock if on a CLOCK line.
17042 (org-clock-update-time-maybe)
17043 ;; Maybe adjust the closest clock in `org-clock-history'
17044 (when org-clock-adjust-closest
17045 (if (not (and (org-at-clock-log-p)
17046 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
17047 org-clock-history))))))
17048 (message "No clock to adjust")
17049 (cond ((save-excursion ; fix previous clock?
17050 (re-search-backward org-ts-regexp0 nil t)
17051 (org-looking-back (concat org-clock-string " \\[")))
17052 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17053 ((save-excursion ; fix next clock?
17054 (re-search-backward org-ts-regexp0 nil t)
17055 (looking-at (concat org-ts-regexp0 "\\] =>")))
17056 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17057 (save-window-excursion
17058 ;; Find closest clock to point, adjust the previous/next one in history
17059 (let* ((p (save-excursion (org-back-to-heading t)))
17060 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17061 (clfixnth
17062 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17063 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17064 (if (not clfixpos)
17065 (message "No clock to adjust")
17066 (save-excursion
17067 (org-goto-marker-or-bmk clfixpos)
17068 (org-show-subtree)
17069 (when (re-search-forward clrgx nil t)
17070 (goto-char (match-beginning 1))
17071 (let (org-clock-adjust-closest)
17072 (org-timestamp-change n org-ts-what updown))
17073 (message "Clock adjusted in %s for heading: %s"
17074 (file-name-nondirectory (buffer-file-name))
17075 (org-get-heading t t)))))))))
17076 ;; Try to recenter the calendar window, if any.
17077 (if (and org-calendar-follow-timestamp-change
17078 (get-buffer-window "*Calendar*" t)
17079 (memq org-ts-what '(day month year)))
17080 (org-recenter-calendar (time-to-days time))))))
17082 (defun org-modify-ts-extra (s pos n dm)
17083 "Change the different parts of the lead-time and repeat fields in timestamp."
17084 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17085 ng h m new rem)
17086 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17087 (cond
17088 ((or (org-pos-in-match-range pos 2)
17089 (org-pos-in-match-range pos 3))
17090 (setq m (string-to-number (match-string 3 s))
17091 h (string-to-number (match-string 2 s)))
17092 (if (org-pos-in-match-range pos 2)
17093 (setq h (+ h n))
17094 (setq n (* dm (org-no-warnings (signum n))))
17095 (when (not (= 0 (setq rem (% m dm))))
17096 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17097 (setq m (+ m n)))
17098 (if (< m 0) (setq m (+ m 60) h (1- h)))
17099 (if (> m 59) (setq m (- m 60) h (1+ h)))
17100 (setq h (min 24 (max 0 h)))
17101 (setq ng 1 new (format "-%02d:%02d" h m)))
17102 ((org-pos-in-match-range pos 6)
17103 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17104 ((org-pos-in-match-range pos 5)
17105 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17107 ((org-pos-in-match-range pos 9)
17108 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17109 ((org-pos-in-match-range pos 8)
17110 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17112 (when ng
17113 (setq s (concat
17114 (substring s 0 (match-beginning ng))
17116 (substring s (match-end ng))))))
17119 (defun org-recenter-calendar (date)
17120 "If the calendar is visible, recenter it to DATE."
17121 (let ((cwin (get-buffer-window "*Calendar*" t)))
17122 (when cwin
17123 (let ((calendar-move-hook nil))
17124 (with-selected-window cwin
17125 (calendar-goto-date (if (listp date) date
17126 (calendar-gregorian-from-absolute date))))))))
17128 (defun org-goto-calendar (&optional arg)
17129 "Go to the Emacs calendar at the current date.
17130 If there is a time stamp in the current line, go to that date.
17131 A prefix ARG can be used to force the current date."
17132 (interactive "P")
17133 (let ((tsr org-ts-regexp) diff
17134 (calendar-move-hook nil)
17135 (calendar-view-holidays-initially-flag nil)
17136 (calendar-view-diary-initially-flag nil))
17137 (if (or (org-at-timestamp-p)
17138 (save-excursion
17139 (beginning-of-line 1)
17140 (looking-at (concat ".*" tsr))))
17141 (let ((d1 (time-to-days (current-time)))
17142 (d2 (time-to-days
17143 (org-time-string-to-time (match-string 1)))))
17144 (setq diff (- d2 d1))))
17145 (calendar)
17146 (calendar-goto-today)
17147 (if (and diff (not arg)) (calendar-forward-day diff))))
17149 (defun org-get-date-from-calendar ()
17150 "Return a list (month day year) of date at point in calendar."
17151 (with-current-buffer "*Calendar*"
17152 (save-match-data
17153 (calendar-cursor-to-date))))
17155 (defun org-date-from-calendar ()
17156 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17157 If there is already a time stamp at the cursor position, update it."
17158 (interactive)
17159 (if (org-at-timestamp-p t)
17160 (org-timestamp-change 0 'calendar)
17161 (let ((cal-date (org-get-date-from-calendar)))
17162 (org-insert-time-stamp
17163 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17165 (defcustom org-effort-durations
17166 `(("h" . 60)
17167 ("d" . ,(* 60 8))
17168 ("w" . ,(* 60 8 5))
17169 ("m" . ,(* 60 8 5 4))
17170 ("y" . ,(* 60 8 5 40)))
17171 "Conversion factor to minutes for an effort modifier.
17173 Each entry has the form (MODIFIER . MINUTES).
17175 In an effort string, a number followed by MODIFIER is multiplied
17176 by the specified number of MINUTES to obtain an effort in
17177 minutes.
17179 For example, if the value of this variable is ((\"hours\" . 60)), then an
17180 effort string \"2hours\" is equivalent to 120 minutes."
17181 :group 'org-agenda
17182 :version "24.1"
17183 :type '(alist :key-type (string :tag "Modifier")
17184 :value-type (number :tag "Minutes")))
17186 (defun org-minutes-to-clocksum-string (m)
17187 "Format number of minutes as a clocksum string.
17188 The format is determined by `org-time-clocksum-format',
17189 `org-time-clocksum-use-fractional' and
17190 `org-time-clocksum-fractional-format' and
17191 `org-time-clocksum-use-effort-durations'."
17192 (let ((clocksum "") h d w mo y fmt n)
17193 (setq h (if org-time-clocksum-use-effort-durations
17194 (cdr (assoc "h" org-effort-durations)) 60)
17195 d (if org-time-clocksum-use-effort-durations
17196 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17197 w (if org-time-clocksum-use-effort-durations
17198 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17199 mo (if org-time-clocksum-use-effort-durations
17200 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17201 y (if org-time-clocksum-use-effort-durations
17202 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17203 ;; fractional format
17204 (if org-time-clocksum-use-fractional
17205 (cond
17206 ;; single format string
17207 ((stringp org-time-clocksum-fractional-format)
17208 (format org-time-clocksum-fractional-format (/ m (float h))))
17209 ;; choice of fractional formats for different time units
17210 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17211 (> (/ (truncate m) (* y d h)) 0))
17212 (format fmt (/ m (* y d (float h)))))
17213 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17214 (> (/ (truncate m) (* mo d h)) 0))
17215 (format fmt (/ m (* mo d (float h)))))
17216 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17217 (> (/ (truncate m) (* w d h)) 0))
17218 (format fmt (/ m (* w d (float h)))))
17219 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17220 (> (/ (truncate m) (* d h)) 0))
17221 (format fmt (/ m (* d (float h)))))
17222 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17223 (> (/ (truncate m) h) 0))
17224 (format fmt (/ m (float h))))
17225 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17226 (format fmt m))
17227 ;; fall back to smallest time unit with a format
17228 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17229 (format fmt (/ m (float h))))
17230 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17231 (format fmt (/ m (* d (float h)))))
17232 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17233 (format fmt (/ m (* w d (float h)))))
17234 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17235 (format fmt (/ m (* mo d (float h)))))
17236 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17237 (format fmt (/ m (* y d (float h))))))
17238 ;; standard (non-fractional) format, with single format string
17239 (if (stringp org-time-clocksum-format)
17240 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17241 ;; separate formats components
17242 (and (setq fmt (plist-get org-time-clocksum-format :years))
17243 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17244 (plist-get org-time-clocksum-format :require-years))
17245 (setq clocksum (concat clocksum (format fmt n))
17246 m (- m (* n y d h))))
17247 (and (setq fmt (plist-get org-time-clocksum-format :months))
17248 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17249 (plist-get org-time-clocksum-format :require-months))
17250 (setq clocksum (concat clocksum (format fmt n))
17251 m (- m (* n mo d h))))
17252 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17253 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17254 (plist-get org-time-clocksum-format :require-weeks))
17255 (setq clocksum (concat clocksum (format fmt n))
17256 m (- m (* n w d h))))
17257 (and (setq fmt (plist-get org-time-clocksum-format :days))
17258 (or (> (setq n (/ (truncate m) (* d h))) 0)
17259 (plist-get org-time-clocksum-format :require-days))
17260 (setq clocksum (concat clocksum (format fmt n))
17261 m (- m (* n d h))))
17262 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17263 (or (> (setq n (/ (truncate m) h)) 0)
17264 (plist-get org-time-clocksum-format :require-hours))
17265 (setq clocksum (concat clocksum (format fmt n))
17266 m (- m (* n h))))
17267 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17268 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17269 (setq clocksum (concat clocksum (format fmt m))))
17270 ;; return formatted time duration
17271 clocksum))))
17273 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17274 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17275 "Org mode version 8.0")
17277 (defun org-hours-to-clocksum-string (n)
17278 (org-minutes-to-clocksum-string (* n 60)))
17280 (defun org-hh:mm-string-to-minutes (s)
17281 "Convert a string H:MM to a number of minutes.
17282 If the string is just a number, interpret it as minutes.
17283 In fact, the first hh:mm or number in the string will be taken,
17284 there can be extra stuff in the string.
17285 If no number is found, the return value is 0."
17286 (cond
17287 ((integerp s) s)
17288 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17289 (+ (* (string-to-number (match-string 1 s)) 60)
17290 (string-to-number (match-string 2 s))))
17291 ((string-match "\\([0-9]+\\)" s)
17292 (string-to-number (match-string 1 s)))
17293 (t 0)))
17295 (defcustom org-image-actual-width t
17296 "Should we use the actual width of images when inlining them?
17298 When set to `t', always use the image width.
17300 When set to a number, use imagemagick (when available) to set
17301 the image's width to this value.
17303 When set to a number in a list, try to get the width from the
17304 #+ATTR.* keyword if it matches a width specification like
17305 width=\"[0-9]+\", and fall back on that number if none is found.
17307 When set to nil, try to get the width from an #+ATTR.* keyword
17308 and fall back on the original width if none is found.
17310 This requires Emacs >= 24.1, build with imagemagick support."
17311 :group 'org-appearance
17312 :version "24.4"
17313 :package-version '(Org . "8.0")
17314 :type '(choice
17315 (const :tag "Use the image width" t)
17316 (integer :tag "Use a number of pixels")
17317 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17318 (const :tag "Use #+ATTR* or don't resize" nil)))
17320 (defcustom org-agenda-inhibit-startup nil
17321 "Inhibit startup when preparing agenda buffers.
17322 When this variable is `t' (the default), the initialization of
17323 the Org agenda buffers is inhibited: e.g. the visibility state
17324 is not set, the tables are not re-aligned, etc."
17325 :type 'boolean
17326 :version "24.3"
17327 :group 'org-agenda)
17329 (defun org-duration-string-to-minutes (s &optional output-to-string)
17330 "Convert a duration string S to minutes.
17332 A bare number is interpreted as minutes, modifiers can be set by
17333 customizing `org-effort-durations' (which see).
17335 Entries containing a colon are interpreted as H:MM by
17336 `org-hh:mm-string-to-minutes'."
17337 (let ((result 0)
17338 (re (concat "\\([0-9.]+\\) *\\("
17339 (regexp-opt (mapcar 'car org-effort-durations))
17340 "\\)")))
17341 (while (string-match re s)
17342 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17343 (string-to-number (match-string 1 s))))
17344 (setq s (replace-match "" nil t s)))
17345 (setq result (floor result))
17346 (incf result (org-hh:mm-string-to-minutes s))
17347 (if output-to-string (number-to-string result) result)))
17349 ;;;; Files
17351 (defun org-save-all-org-buffers ()
17352 "Save all Org-mode buffers without user confirmation."
17353 (interactive)
17354 (message "Saving all Org-mode buffers...")
17355 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17356 (when (featurep 'org-id) (org-id-locations-save))
17357 (message "Saving all Org-mode buffers... done"))
17359 (defun org-revert-all-org-buffers ()
17360 "Revert all Org-mode buffers.
17361 Prompt for confirmation when there are unsaved changes.
17362 Be sure you know what you are doing before letting this function
17363 overwrite your changes.
17365 This function is useful in a setup where one tracks org files
17366 with a version control system, to revert on one machine after pulling
17367 changes from another. I believe the procedure must be like this:
17369 1. M-x org-save-all-org-buffers
17370 2. Pull changes from the other machine, resolve conflicts
17371 3. M-x org-revert-all-org-buffers"
17372 (interactive)
17373 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17374 (error "Abort"))
17375 (save-excursion
17376 (save-window-excursion
17377 (mapc
17378 (lambda (b)
17379 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17380 (with-current-buffer b buffer-file-name))
17381 (org-pop-to-buffer-same-window b)
17382 (revert-buffer t 'no-confirm)))
17383 (buffer-list))
17384 (when (and (featurep 'org-id) org-id-track-globally)
17385 (org-id-locations-load)))))
17387 ;;;; Agenda files
17389 ;;;###autoload
17390 (defun org-switchb (&optional arg)
17391 "Switch between Org buffers.
17392 With one prefix argument, restrict available buffers to files.
17393 With two prefix arguments, restrict available buffers to agenda files.
17395 Defaults to `iswitchb' for buffer name completion.
17396 Set `org-completion-use-ido' to make it use ido instead."
17397 (interactive "P")
17398 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17399 ((equal arg '(16)) (org-buffer-list 'agenda))
17400 (t (org-buffer-list))))
17401 (org-completion-use-iswitchb org-completion-use-iswitchb)
17402 (org-completion-use-ido org-completion-use-ido))
17403 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17404 (setq org-completion-use-iswitchb t))
17405 (org-pop-to-buffer-same-window
17406 (org-icompleting-read "Org buffer: "
17407 (mapcar 'list (mapcar 'buffer-name blist))
17408 nil t))))
17410 ;;; Define some older names previously used for this functionality
17411 ;;;###autoload
17412 (defalias 'org-ido-switchb 'org-switchb)
17413 ;;;###autoload
17414 (defalias 'org-iswitchb 'org-switchb)
17416 (defun org-buffer-list (&optional predicate exclude-tmp)
17417 "Return a list of Org buffers.
17418 PREDICATE can be `export', `files' or `agenda'.
17420 export restrict the list to Export buffers.
17421 files restrict the list to buffers visiting Org files.
17422 agenda restrict the list to buffers visiting agenda files.
17424 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17425 (let* ((bfn nil)
17426 (agenda-files (and (eq predicate 'agenda)
17427 (mapcar 'file-truename (org-agenda-files t))))
17428 (filter
17429 (cond
17430 ((eq predicate 'files)
17431 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17432 ((eq predicate 'export)
17433 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17434 ((eq predicate 'agenda)
17435 (lambda (b)
17436 (with-current-buffer b
17437 (and (derived-mode-p 'org-mode)
17438 (setq bfn (buffer-file-name b))
17439 (member (file-truename bfn) agenda-files)))))
17440 (t (lambda (b) (with-current-buffer b
17441 (or (derived-mode-p 'org-mode)
17442 (string-match "\*Org .*Export"
17443 (buffer-name b)))))))))
17444 (delq nil
17445 (mapcar
17446 (lambda(b)
17447 (if (and (funcall filter b)
17448 (or (not exclude-tmp)
17449 (not (string-match "tmp" (buffer-name b)))))
17451 nil))
17452 (buffer-list)))))
17454 (defun org-agenda-files (&optional unrestricted archives)
17455 "Get the list of agenda files.
17456 Optional UNRESTRICTED means return the full list even if a restriction
17457 is currently in place.
17458 When ARCHIVES is t, include all archive files that are really being
17459 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17460 `org-agenda-archives-mode' is t."
17461 (let ((files
17462 (cond
17463 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17464 ((stringp org-agenda-files) (org-read-agenda-file-list))
17465 ((listp org-agenda-files) org-agenda-files)
17466 (t (error "Invalid value of `org-agenda-files'")))))
17467 (setq files (apply 'append
17468 (mapcar (lambda (f)
17469 (if (file-directory-p f)
17470 (directory-files
17471 f t org-agenda-file-regexp)
17472 (list f)))
17473 files)))
17474 (when org-agenda-skip-unavailable-files
17475 (setq files (delq nil
17476 (mapcar (function
17477 (lambda (file)
17478 (and (file-readable-p file) file)))
17479 files))))
17480 (when (or (eq archives t)
17481 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17482 (setq files (org-add-archive-files files)))
17483 files))
17485 (defun org-agenda-file-p (&optional file)
17486 "Return non-nil, if FILE is an agenda file.
17487 If FILE is omitted, use the file associated with the current
17488 buffer."
17489 (member (or file (buffer-file-name))
17490 (org-agenda-files t)))
17492 (defun org-edit-agenda-file-list ()
17493 "Edit the list of agenda files.
17494 Depending on setup, this either uses customize to edit the variable
17495 `org-agenda-files', or it visits the file that is holding the list. In the
17496 latter case, the buffer is set up in a way that saving it automatically kills
17497 the buffer and restores the previous window configuration."
17498 (interactive)
17499 (if (stringp org-agenda-files)
17500 (let ((cw (current-window-configuration)))
17501 (find-file org-agenda-files)
17502 (org-set-local 'org-window-configuration cw)
17503 (org-add-hook 'after-save-hook
17504 (lambda ()
17505 (set-window-configuration
17506 (prog1 org-window-configuration
17507 (kill-buffer (current-buffer))))
17508 (org-install-agenda-files-menu)
17509 (message "New agenda file list installed"))
17510 nil 'local)
17511 (message "%s" (substitute-command-keys
17512 "Edit list and finish with \\[save-buffer]")))
17513 (customize-variable 'org-agenda-files)))
17515 (defun org-store-new-agenda-file-list (list)
17516 "Set new value for the agenda file list and save it correctly."
17517 (if (stringp org-agenda-files)
17518 (let ((fe (org-read-agenda-file-list t)) b u)
17519 (while (setq b (find-buffer-visiting org-agenda-files))
17520 (kill-buffer b))
17521 (with-temp-file org-agenda-files
17522 (insert
17523 (mapconcat
17524 (lambda (f) ;; Keep un-expanded entries.
17525 (if (setq u (assoc f fe))
17526 (cdr u)
17528 list "\n")
17529 "\n")))
17530 (let ((org-mode-hook nil) (org-inhibit-startup t)
17531 (org-insert-mode-line-in-empty-file nil))
17532 (setq org-agenda-files list)
17533 (customize-save-variable 'org-agenda-files org-agenda-files))))
17535 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17536 "Read the list of agenda files from a file.
17537 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17538 filenames, used by `org-store-new-agenda-file-list' to write back
17539 un-expanded file names."
17540 (when (file-directory-p org-agenda-files)
17541 (error "`org-agenda-files' cannot be a single directory"))
17542 (when (stringp org-agenda-files)
17543 (with-temp-buffer
17544 (insert-file-contents org-agenda-files)
17545 (mapcar
17546 (lambda (f)
17547 (let ((e (expand-file-name (substitute-in-file-name f)
17548 org-directory)))
17549 (if pair-with-expansion
17550 (cons e f)
17551 e)))
17552 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17554 ;;;###autoload
17555 (defun org-cycle-agenda-files ()
17556 "Cycle through the files in `org-agenda-files'.
17557 If the current buffer visits an agenda file, find the next one in the list.
17558 If the current buffer does not, find the first agenda file."
17559 (interactive)
17560 (let* ((fs (org-agenda-files t))
17561 (files (append fs (list (car fs))))
17562 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17563 file)
17564 (unless files (error "No agenda files"))
17565 (catch 'exit
17566 (while (setq file (pop files))
17567 (if (equal (file-truename file) tcf)
17568 (when (car files)
17569 (find-file (car files))
17570 (throw 'exit t))))
17571 (find-file (car fs)))
17572 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17574 (defun org-agenda-file-to-front (&optional to-end)
17575 "Move/add the current file to the top of the agenda file list.
17576 If the file is not present in the list, it is added to the front. If it is
17577 present, it is moved there. With optional argument TO-END, add/move to the
17578 end of the list."
17579 (interactive "P")
17580 (let ((org-agenda-skip-unavailable-files nil)
17581 (file-alist (mapcar (lambda (x)
17582 (cons (file-truename x) x))
17583 (org-agenda-files t)))
17584 (ctf (file-truename
17585 (or buffer-file-name
17586 (error "Please save the current buffer to a file"))))
17587 x had)
17588 (setq x (assoc ctf file-alist) had x)
17590 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17591 (if to-end
17592 (setq file-alist (append (delq x file-alist) (list x)))
17593 (setq file-alist (cons x (delq x file-alist))))
17594 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17595 (org-install-agenda-files-menu)
17596 (message "File %s to %s of agenda file list"
17597 (if had "moved" "added") (if to-end "end" "front"))))
17599 (defun org-remove-file (&optional file)
17600 "Remove current file from the list of files in variable `org-agenda-files'.
17601 These are the files which are being checked for agenda entries.
17602 Optional argument FILE means use this file instead of the current."
17603 (interactive)
17604 (let* ((org-agenda-skip-unavailable-files nil)
17605 (file (or file buffer-file-name
17606 (error "Current buffer does not visit a file")))
17607 (true-file (file-truename file))
17608 (afile (abbreviate-file-name file))
17609 (files (delq nil (mapcar
17610 (lambda (x)
17611 (if (equal true-file
17612 (file-truename x))
17613 nil x))
17614 (org-agenda-files t)))))
17615 (if (not (= (length files) (length (org-agenda-files t))))
17616 (progn
17617 (org-store-new-agenda-file-list files)
17618 (org-install-agenda-files-menu)
17619 (message "Removed file: %s" afile))
17620 (message "File was not in list: %s (not removed)" afile))))
17622 (defun org-file-menu-entry (file)
17623 (vector file (list 'find-file file) t))
17625 (defun org-check-agenda-file (file)
17626 "Make sure FILE exists. If not, ask user what to do."
17627 (when (not (file-exists-p file))
17628 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17629 (abbreviate-file-name file))
17630 (let ((r (downcase (read-char-exclusive))))
17631 (cond
17632 ((equal r ?r)
17633 (org-remove-file file)
17634 (throw 'nextfile t))
17635 (t (error "Abort"))))))
17637 (defun org-get-agenda-file-buffer (file)
17638 "Get a buffer visiting FILE. If the buffer needs to be created, add
17639 it to the list of buffers which might be released later."
17640 (let ((buf (org-find-base-buffer-visiting file)))
17641 (if buf
17642 buf ; just return it
17643 ;; Make a new buffer and remember it
17644 (setq buf (find-file-noselect file))
17645 (if buf (push buf org-agenda-new-buffers))
17646 buf)))
17648 (defun org-release-buffers (blist)
17649 "Release all buffers in list, asking the user for confirmation when needed.
17650 When a buffer is unmodified, it is just killed. When modified, it is saved
17651 \(if the user agrees) and then killed."
17652 (let (buf file)
17653 (while (setq buf (pop blist))
17654 (setq file (buffer-file-name buf))
17655 (when (and (buffer-modified-p buf)
17656 file
17657 (y-or-n-p (format "Save file %s? " file)))
17658 (with-current-buffer buf (save-buffer)))
17659 (kill-buffer buf))))
17661 (defun org-agenda-prepare-buffers (files)
17662 "Create buffers for all agenda files, protect archived trees and comments."
17663 (interactive)
17664 (let ((pa '(:org-archived t))
17665 (pc '(:org-comment t))
17666 (pall '(:org-archived t :org-comment t))
17667 (inhibit-read-only t)
17668 (org-inhibit-startup org-agenda-inhibit-startup)
17669 (rea (concat ":" org-archive-tag ":"))
17670 file re)
17671 (save-excursion
17672 (save-restriction
17673 (while (setq file (pop files))
17674 (catch 'nextfile
17675 (if (bufferp file)
17676 (set-buffer file)
17677 (org-check-agenda-file file)
17678 (set-buffer (org-get-agenda-file-buffer file)))
17679 (widen)
17680 (org-refresh-category-properties)
17681 (org-refresh-properties org-effort-property 'org-effort)
17682 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17683 (setq org-todo-keywords-for-agenda
17684 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17685 (setq org-done-keywords-for-agenda
17686 (append org-done-keywords-for-agenda org-done-keywords))
17687 (setq org-todo-keyword-alist-for-agenda
17688 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17689 (setq org-drawers-for-agenda
17690 (append org-drawers-for-agenda org-drawers))
17691 (setq org-tag-alist-for-agenda
17692 (append org-tag-alist-for-agenda org-tag-alist))
17693 (org-with-silent-modifications
17694 (save-excursion
17695 (remove-text-properties (point-min) (point-max) pall)
17696 (when org-agenda-skip-archived-trees
17697 (goto-char (point-min))
17698 (while (re-search-forward rea nil t)
17699 (if (org-at-heading-p t)
17700 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17701 (goto-char (point-min))
17702 (setq re (format org-heading-keyword-regexp-format
17703 org-comment-string))
17704 (while (re-search-forward re nil t)
17705 (add-text-properties
17706 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17707 (setq org-todo-keywords-for-agenda
17708 (org-uniquify org-todo-keywords-for-agenda))
17709 (setq org-todo-keyword-alist-for-agenda
17710 (org-uniquify org-todo-keyword-alist-for-agenda)
17711 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17714 ;;;; CDLaTeX minor mode
17716 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17717 "Keymap for the minor `org-cdlatex-mode'.")
17719 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17720 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17721 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17722 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17723 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17725 (defvar org-cdlatex-texmathp-advice-is-done nil
17726 "Flag remembering if we have applied the advice to texmathp already.")
17728 (define-minor-mode org-cdlatex-mode
17729 "Toggle the minor `org-cdlatex-mode'.
17730 This mode supports entering LaTeX environment and math in LaTeX fragments
17731 in Org-mode.
17732 \\{org-cdlatex-mode-map}"
17733 nil " OCDL" nil
17734 (when org-cdlatex-mode
17735 (require 'cdlatex)
17736 (run-hooks 'cdlatex-mode-hook)
17737 (cdlatex-compute-tables))
17738 (unless org-cdlatex-texmathp-advice-is-done
17739 (setq org-cdlatex-texmathp-advice-is-done t)
17740 (defadvice texmathp (around org-math-always-on activate)
17741 "Always return t in org-mode buffers.
17742 This is because we want to insert math symbols without dollars even outside
17743 the LaTeX math segments. If Orgmode thinks that point is actually inside
17744 an embedded LaTeX fragment, let texmathp do its job.
17745 \\[org-cdlatex-mode-map]"
17746 (interactive)
17747 (let (p)
17748 (cond
17749 ((not (derived-mode-p 'org-mode)) ad-do-it)
17750 ((eq this-command 'cdlatex-math-symbol)
17751 (setq ad-return-value t
17752 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17754 (let ((p (org-inside-LaTeX-fragment-p)))
17755 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17756 (setq ad-return-value t
17757 texmathp-why '("Org-mode embedded math" . 0))
17758 (if p ad-do-it)))))))))
17760 (defun turn-on-org-cdlatex ()
17761 "Unconditionally turn on `org-cdlatex-mode'."
17762 (org-cdlatex-mode 1))
17764 (defun org-try-cdlatex-tab ()
17765 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17766 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17767 - inside a LaTeX fragment, or
17768 - after the first word in a line, where an abbreviation expansion could
17769 insert a LaTeX environment."
17770 (when org-cdlatex-mode
17771 (cond
17772 ;; Before any word on the line: No expansion possible.
17773 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17774 ;; Just after first word on the line: Expand it. Make sure it
17775 ;; cannot happen on headlines, though.
17776 ((save-excursion
17777 (skip-chars-backward "a-zA-Z0-9*")
17778 (skip-chars-backward " \t")
17779 (and (bolp) (not (org-at-heading-p))))
17780 (cdlatex-tab) t)
17781 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17783 (defun org-cdlatex-underscore-caret (&optional arg)
17784 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17785 Revert to the normal definition outside of these fragments."
17786 (interactive "P")
17787 (if (org-inside-LaTeX-fragment-p)
17788 (call-interactively 'cdlatex-sub-superscript)
17789 (let (org-cdlatex-mode)
17790 (call-interactively (key-binding (vector last-input-event))))))
17792 (defun org-cdlatex-math-modify (&optional arg)
17793 "Execute `cdlatex-math-modify' in LaTeX fragments.
17794 Revert to the normal definition outside of these fragments."
17795 (interactive "P")
17796 (if (org-inside-LaTeX-fragment-p)
17797 (call-interactively 'cdlatex-math-modify)
17798 (let (org-cdlatex-mode)
17799 (call-interactively (key-binding (vector last-input-event))))))
17803 ;;;; LaTeX fragments
17805 (defvar org-latex-regexps
17806 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17807 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17808 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17809 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17810 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17811 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17812 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17813 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17814 "Regular expressions for matching embedded LaTeX.")
17816 (defun org-inside-LaTeX-fragment-p ()
17817 "Test if point is inside a LaTeX fragment.
17818 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17819 sequence appearing also before point.
17820 Even though the matchers for math are configurable, this function assumes
17821 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17822 delimiters are skipped when they have been removed by customization.
17823 The return value is nil, or a cons cell with the delimiter and the
17824 position of this delimiter.
17826 This function does a reasonably good job, but can locally be fooled by
17827 for example currency specifications. For example it will assume being in
17828 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17829 fragments that are properly closed, but during editing, we have to live
17830 with the uncertainty caused by missing closing delimiters. This function
17831 looks only before point, not after."
17832 (catch 'exit
17833 (let ((pos (point))
17834 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17835 (lim (progn
17836 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17837 (point)))
17838 dd-on str (start 0) m re)
17839 (goto-char pos)
17840 (when dodollar
17841 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17842 re (nth 1 (assoc "$" org-latex-regexps)))
17843 (while (string-match re str start)
17844 (cond
17845 ((= (match-end 0) (length str))
17846 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17847 ((= (match-end 0) (- (length str) 5))
17848 (throw 'exit nil))
17849 (t (setq start (match-end 0))))))
17850 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17851 (goto-char pos)
17852 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17853 (and (match-beginning 2) (throw 'exit nil))
17854 ;; count $$
17855 (while (re-search-backward "\\$\\$" lim t)
17856 (setq dd-on (not dd-on)))
17857 (goto-char pos)
17858 (if dd-on (cons "$$" m))))))
17860 (defun org-inside-latex-macro-p ()
17861 "Is point inside a LaTeX macro or its arguments?"
17862 (save-match-data
17863 (org-in-regexp
17864 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17866 (defvar org-latex-fragment-image-overlays nil
17867 "List of overlays carrying the images of latex fragments.")
17868 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17870 (defun org-remove-latex-fragment-image-overlays ()
17871 "Remove all overlays with LaTeX fragment images in current buffer."
17872 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17873 (setq org-latex-fragment-image-overlays nil))
17875 (defun org-preview-latex-fragment (&optional subtree)
17876 "Preview the LaTeX fragment at point, or all locally or globally.
17877 If the cursor is in a LaTeX fragment, create the image and overlay
17878 it over the source code. If there is no fragment at point, display
17879 all fragments in the current text, from one headline to the next. With
17880 prefix SUBTREE, display all fragments in the current subtree. With a
17881 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17882 the cursor is before the first headline,
17883 display all fragments in the buffer.
17884 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17885 (interactive "P")
17886 (unless buffer-file-name
17887 (error "Can't preview LaTeX fragment in a non-file buffer"))
17888 (org-remove-latex-fragment-image-overlays)
17889 (save-excursion
17890 (save-restriction
17891 (let (beg end at msg)
17892 (cond
17893 ((or (equal subtree '(16))
17894 (not (save-excursion
17895 (re-search-backward org-outline-regexp-bol nil t))))
17896 (setq beg (point-min) end (point-max)
17897 msg "Creating images for buffer...%s"))
17898 ((equal subtree '(4))
17899 (org-back-to-heading)
17900 (setq beg (point) end (org-end-of-subtree t)
17901 msg "Creating images for subtree...%s"))
17903 (if (setq at (org-inside-LaTeX-fragment-p))
17904 (goto-char (max (point-min) (- (cdr at) 2)))
17905 (org-back-to-heading))
17906 (setq beg (point) end (progn (outline-next-heading) (point))
17907 msg (if at "Creating image...%s"
17908 "Creating images for entry...%s"))))
17909 (message msg "")
17910 (narrow-to-region beg end)
17911 (goto-char beg)
17912 (org-format-latex
17913 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17914 (file-name-nondirectory
17915 buffer-file-name)))
17916 default-directory 'overlays msg at 'forbuffer
17917 org-latex-create-formula-image-program)
17918 (message msg "done. Use `C-c C-c' to remove images.")))))
17920 (defun org-format-latex (prefix &optional dir overlays msg at
17921 forbuffer processing-type)
17922 "Replace LaTeX fragments with links to an image, and produce images.
17923 Some of the options can be changed using the variable
17924 `org-format-latex-options'."
17925 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17926 (let* ((prefixnodir (file-name-nondirectory prefix))
17927 (absprefix (expand-file-name prefix dir))
17928 (todir (file-name-directory absprefix))
17929 (opt org-format-latex-options)
17930 (optnew org-format-latex-options)
17931 (matchers (plist-get opt :matchers))
17932 (re-list org-latex-regexps)
17933 (cnt 0) txt hash link beg end re e checkdir
17934 string
17935 m n block-type block linkfile movefile ov)
17936 ;; Check the different regular expressions
17937 (while (setq e (pop re-list))
17938 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17939 block (if block-type "\n\n" ""))
17940 (when (member m matchers)
17941 (goto-char (point-min))
17942 (while (re-search-forward re nil t)
17943 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17944 (or (not overlays)
17945 (not (eq (get-char-property (match-beginning n)
17946 'org-overlay-type)
17947 'org-latex-overlay))))
17948 (cond
17949 ((eq processing-type 'verbatim))
17950 ((eq processing-type 'mathjax)
17951 ;; Prepare for MathJax processing.
17952 (setq string (match-string n))
17953 (when (member m '("$" "$1"))
17954 (save-excursion
17955 (delete-region (match-beginning n) (match-end n))
17956 (goto-char (match-beginning n))
17957 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17958 ((or (eq processing-type 'dvipng)
17959 (eq processing-type 'imagemagick))
17960 ;; Process to an image.
17961 (setq txt (match-string n)
17962 beg (match-beginning n) end (match-end n)
17963 cnt (1+ cnt))
17964 (let ((face (face-at-point))
17965 (fg (plist-get opt :foreground))
17966 (bg (plist-get opt :background))
17967 ;; Ensure full list is printed.
17968 print-length print-level)
17969 (when forbuffer
17970 ;; Get the colors from the face at point.
17971 (goto-char beg)
17972 (when (eq fg 'auto)
17973 (setq fg (face-attribute face :foreground nil 'default)))
17974 (when (eq bg 'auto)
17975 (setq bg (face-attribute face :background nil 'default)))
17976 (setq optnew (copy-sequence opt))
17977 (plist-put optnew :foreground fg)
17978 (plist-put optnew :background bg))
17979 (setq hash (sha1 (prin1-to-string
17980 (list org-format-latex-header
17981 org-latex-default-packages-alist
17982 org-latex-packages-alist
17983 org-format-latex-options
17984 forbuffer txt fg bg)))
17985 linkfile (format "%s_%s.png" prefix hash)
17986 movefile (format "%s_%s.png" absprefix hash)))
17987 (setq link (concat block "[[file:" linkfile "]]" block))
17988 (if msg (message msg cnt))
17989 (goto-char beg)
17990 (unless checkdir ; Ensure the directory exists.
17991 (setq checkdir t)
17992 (or (file-directory-p todir) (make-directory todir t)))
17993 (unless (file-exists-p movefile)
17994 (org-create-formula-image
17995 txt movefile optnew forbuffer processing-type))
17996 (if overlays
17997 (progn
17998 (mapc (lambda (o)
17999 (if (eq (overlay-get o 'org-overlay-type)
18000 'org-latex-overlay)
18001 (delete-overlay o)))
18002 (overlays-in beg end))
18003 (setq ov (make-overlay beg end))
18004 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18005 (if (featurep 'xemacs)
18006 (progn
18007 (overlay-put ov 'invisible t)
18008 (overlay-put
18009 ov 'end-glyph
18010 (make-glyph (vector 'png :file movefile))))
18011 (overlay-put
18012 ov 'display
18013 (list 'image :type 'png :file movefile :ascent 'center)))
18014 (push ov org-latex-fragment-image-overlays)
18015 (goto-char end))
18016 (delete-region beg end)
18017 (insert (org-add-props link
18018 (list 'org-latex-src
18019 (replace-regexp-in-string
18020 "\"" "" txt)
18021 'org-latex-src-embed-type
18022 (if block-type 'paragraph 'character))))))
18023 ((eq processing-type 'mathml)
18024 ;; Process to MathML
18025 (unless (save-match-data (org-format-latex-mathml-available-p))
18026 (error "LaTeX to MathML converter not configured"))
18027 (setq txt (match-string n)
18028 beg (match-beginning n) end (match-end n)
18029 cnt (1+ cnt))
18030 (if msg (message msg cnt))
18031 (goto-char beg)
18032 (delete-region beg end)
18033 (insert (org-format-latex-as-mathml
18034 txt block-type prefix dir)))
18036 (error "Unknown conversion type %s for latex fragments"
18037 processing-type)))))))))
18039 (defun org-create-math-formula (latex-frag &optional mathml-file)
18040 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18041 Use `org-latex-to-mathml-convert-command'. If the conversion is
18042 sucessful, return the portion between \"<math...> </math>\"
18043 elements otherwise return nil. When MATHML-FILE is specified,
18044 write the results in to that file. When invoked as an
18045 interactive command, prompt for LATEX-FRAG, with initial value
18046 set to the current active region and echo the results for user
18047 inspection."
18048 (interactive (list (let ((frag (when (org-region-active-p)
18049 (buffer-substring-no-properties
18050 (region-beginning) (region-end)))))
18051 (read-string "LaTeX Fragment: " frag nil frag))))
18052 (unless latex-frag (error "Invalid latex-frag"))
18053 (let* ((tmp-in-file (file-relative-name
18054 (make-temp-name (expand-file-name "ltxmathml-in"))))
18055 (ignore (write-region latex-frag nil tmp-in-file))
18056 (tmp-out-file (file-relative-name
18057 (make-temp-name (expand-file-name "ltxmathml-out"))))
18058 (cmd (format-spec
18059 org-latex-to-mathml-convert-command
18060 `((?j . ,(shell-quote-argument
18061 (expand-file-name org-latex-to-mathml-jar-file)))
18062 (?I . ,(shell-quote-argument tmp-in-file))
18063 (?o . ,(shell-quote-argument tmp-out-file)))))
18064 mathml shell-command-output)
18065 (when (org-called-interactively-p 'any)
18066 (unless (org-format-latex-mathml-available-p)
18067 (error "LaTeX to MathML converter not configured")))
18068 (message "Running %s" cmd)
18069 (setq shell-command-output (shell-command-to-string cmd))
18070 (setq mathml
18071 (when (file-readable-p tmp-out-file)
18072 (with-current-buffer (find-file-noselect tmp-out-file t)
18073 (goto-char (point-min))
18074 (when (re-search-forward
18075 (concat
18076 (regexp-quote
18077 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18078 "\\(.\\|\n\\)*"
18079 (regexp-quote "</math>")) nil t)
18080 (prog1 (match-string 0) (kill-buffer))))))
18081 (cond
18082 (mathml
18083 (setq mathml
18084 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18085 (when mathml-file
18086 (write-region mathml nil mathml-file))
18087 (when (org-called-interactively-p 'any)
18088 (message mathml)))
18089 ((message "LaTeX to MathML conversion failed")
18090 (message shell-command-output)))
18091 (delete-file tmp-in-file)
18092 (when (file-exists-p tmp-out-file)
18093 (delete-file tmp-out-file))
18094 mathml))
18096 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18097 prefix &optional dir)
18098 "Use `org-create-math-formula' but check local cache first."
18099 (let* ((absprefix (expand-file-name prefix dir))
18100 (print-length nil) (print-level nil)
18101 (formula-id (concat
18102 "formula-"
18103 (sha1
18104 (prin1-to-string
18105 (list latex-frag
18106 org-latex-to-mathml-convert-command)))))
18107 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18108 (formula-cache-dir (file-name-directory formula-cache)))
18110 (unless (file-directory-p formula-cache-dir)
18111 (make-directory formula-cache-dir t))
18113 (unless (file-exists-p formula-cache)
18114 (org-create-math-formula latex-frag formula-cache))
18116 (if (file-exists-p formula-cache)
18117 ;; Successful conversion. Return the link to MathML file.
18118 (org-add-props
18119 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18120 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18121 'org-latex-src-embed-type (if latex-frag-type
18122 'paragraph 'character)))
18123 ;; Failed conversion. Return the LaTeX fragment verbatim
18124 latex-frag)))
18126 (defun org-create-formula-image (string tofile options buffer &optional type)
18127 "Create an image from LaTeX source using dvipng or convert.
18128 This function calls either `org-create-formula-image-with-dvipng'
18129 or `org-create-formula-image-with-imagemagick' depending on the
18130 value of `org-latex-create-formula-image-program' or on the value
18131 of the optional TYPE variable.
18133 Note: ultimately these two function should be combined as they
18134 share a good deal of logic."
18135 (org-check-external-command
18136 "latex" "needed to convert LaTeX fragments to images")
18137 (funcall
18138 (case (or type org-latex-create-formula-image-program)
18139 ('dvipng
18140 (org-check-external-command
18141 "dvipng" "needed to convert LaTeX fragments to images")
18142 #'org-create-formula-image-with-dvipng)
18143 ('imagemagick
18144 (org-check-external-command
18145 "convert" "you need to install imagemagick")
18146 #'org-create-formula-image-with-imagemagick)
18147 (t (error
18148 "invalid value of `org-latex-create-formula-image-program'")))
18149 string tofile options buffer))
18151 (declare-function org-export--get-global-options "ox" (&optional backend))
18152 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18153 (defun org-create-formula--latex-header ()
18154 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18155 (org-latex-guess-inputenc
18156 (org-splice-latex-header
18157 org-format-latex-header
18158 org-latex-default-packages-alist
18159 org-latex-packages-alist t
18160 (plist-get
18161 (org-combine-plists
18162 (org-export--get-global-options 'latex)
18163 (org-export--get-inbuffer-options 'latex))
18164 :latex-header))))
18166 ;; This function borrows from Ganesh Swami's latex2png.el
18167 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18168 "This calls dvipng."
18169 (require 'ox-latex)
18170 (let* ((tmpdir (if (featurep 'xemacs)
18171 (temp-directory)
18172 temporary-file-directory))
18173 (texfilebase (make-temp-name
18174 (expand-file-name "orgtex" tmpdir)))
18175 (texfile (concat texfilebase ".tex"))
18176 (dvifile (concat texfilebase ".dvi"))
18177 (pngfile (concat texfilebase ".png"))
18178 (fnh (if (featurep 'xemacs)
18179 (font-height (face-font 'default))
18180 (face-attribute 'default :height nil)))
18181 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18182 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18183 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18184 "Black"))
18185 (bg (or (plist-get options (if buffer :background :html-background))
18186 "Transparent")))
18187 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18188 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18189 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18190 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18191 (let ((latex-header (org-create-formula--latex-header)))
18192 (with-temp-file texfile
18193 (insert latex-header)
18194 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18195 (let ((dir default-directory))
18196 (condition-case nil
18197 (progn
18198 (cd tmpdir)
18199 (call-process "latex" nil nil nil texfile))
18200 (error nil))
18201 (cd dir))
18202 (if (not (file-exists-p dvifile))
18203 (progn (message "Failed to create dvi file from %s" texfile) nil)
18204 (condition-case nil
18205 (if (featurep 'xemacs)
18206 (call-process "dvipng" nil nil nil
18207 "-fg" fg "-bg" bg
18208 "-T" "tight"
18209 "-o" pngfile
18210 dvifile)
18211 (call-process "dvipng" nil nil nil
18212 "-fg" fg "-bg" bg
18213 "-D" dpi
18214 ;;"-x" scale "-y" scale
18215 "-T" "tight"
18216 "-o" pngfile
18217 dvifile))
18218 (error nil))
18219 (if (not (file-exists-p pngfile))
18220 (if org-format-latex-signal-error
18221 (error "Failed to create png file from %s" texfile)
18222 (message "Failed to create png file from %s" texfile)
18223 nil)
18224 ;; Use the requested file name and clean up
18225 (copy-file pngfile tofile 'replace)
18226 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18227 (if (file-exists-p (concat texfilebase e))
18228 (delete-file (concat texfilebase e))))
18229 pngfile))))
18231 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18232 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18233 "This calls convert, which is included into imagemagick."
18234 (require 'ox-latex)
18235 (let* ((tmpdir (if (featurep 'xemacs)
18236 (temp-directory)
18237 temporary-file-directory))
18238 (texfilebase (make-temp-name
18239 (expand-file-name "orgtex" tmpdir)))
18240 (texfile (concat texfilebase ".tex"))
18241 (pdffile (concat texfilebase ".pdf"))
18242 (pngfile (concat texfilebase ".png"))
18243 (fnh (if (featurep 'xemacs)
18244 (font-height (face-font 'default))
18245 (face-attribute 'default :height nil)))
18246 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18247 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18248 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18249 "black"))
18250 (bg (or (plist-get options (if buffer :background :html-background))
18251 "white")))
18252 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18253 (setq fg (org-latex-color-format fg)))
18254 (if (eq bg 'default) (setq bg (org-latex-color :background))
18255 (setq bg (org-latex-color-format
18256 (if (string= bg "Transparent") "white" bg))))
18257 (let ((latex-header (org-create-formula--latex-header)))
18258 (with-temp-file texfile
18259 (insert latex-header)
18260 (insert "\n\\begin{document}\n"
18261 "\\definecolor{fg}{rgb}{" fg "}\n"
18262 "\\definecolor{bg}{rgb}{" bg "}\n"
18263 "\n\\pagecolor{bg}\n"
18264 "\n{\\color{fg}\n"
18265 string
18266 "\n}\n"
18267 "\n\\end{document}\n")))
18268 (org-latex-compile texfile t)
18269 (if (not (file-exists-p pdffile))
18270 (progn (message "Failed to create pdf file from %s" texfile) nil)
18271 (condition-case nil
18272 (if (featurep 'xemacs)
18273 (call-process "convert" nil nil nil
18274 "-density" "96"
18275 "-trim"
18276 "-antialias"
18277 pdffile
18278 "-quality" "100"
18279 ;; "-sharpen" "0x1.0"
18280 pngfile)
18281 (call-process "convert" nil nil nil
18282 "-density" dpi
18283 "-trim"
18284 "-antialias"
18285 pdffile
18286 "-quality" "100"
18287 ;; "-sharpen" "0x1.0"
18288 pngfile))
18289 (error nil))
18290 (if (not (file-exists-p pngfile))
18291 (if org-format-latex-signal-error
18292 (error "Failed to create png file from %s" texfile)
18293 (message "Failed to create png file from %s" texfile)
18294 nil)
18295 ;; Use the requested file name and clean up
18296 (copy-file pngfile tofile 'replace)
18297 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18298 (if (file-exists-p (concat texfilebase e))
18299 (delete-file (concat texfilebase e))))
18300 pngfile))))
18302 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18303 "Fill a LaTeX header template TPL.
18304 In the template, the following place holders will be recognized:
18306 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18307 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18308 [PACKAGES] \\usepackage statements for PKG
18309 [NO-PACKAGES] do not include PKG
18310 [EXTRA] the string EXTRA
18311 [NO-EXTRA] do not include EXTRA
18313 For backward compatibility, if both the positive and the negative place
18314 holder is missing, the positive one (without the \"NO-\") will be
18315 assumed to be present at the end of the template.
18316 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18317 EXTRA is a string.
18318 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18319 (let (rpl (end ""))
18320 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18321 (setq rpl (if (or (match-end 1) (not def-pkg))
18322 "" (org-latex-packages-to-string def-pkg snippets-p t))
18323 tpl (replace-match rpl t t tpl))
18324 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18326 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18327 (setq rpl (if (or (match-end 1) (not pkg))
18328 "" (org-latex-packages-to-string pkg snippets-p t))
18329 tpl (replace-match rpl t t tpl))
18330 (if pkg (setq end
18331 (concat end "\n"
18332 (org-latex-packages-to-string pkg snippets-p)))))
18334 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18335 (setq rpl (if (or (match-end 1) (not extra))
18336 "" (concat extra "\n"))
18337 tpl (replace-match rpl t t tpl))
18338 (if (and extra (string-match "\\S-" extra))
18339 (setq end (concat end "\n" extra))))
18341 (if (string-match "\\S-" end)
18342 (concat tpl "\n" end)
18343 tpl)))
18345 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18346 "Turn an alist of packages into a string with the \\usepackage macros."
18347 (setq pkg (mapconcat (lambda(p)
18348 (cond
18349 ((stringp p) p)
18350 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18351 (format "%% Package %s omitted" (cadr p)))
18352 ((equal "" (car p))
18353 (format "\\usepackage{%s}" (cadr p)))
18355 (format "\\usepackage[%s]{%s}"
18356 (car p) (cadr p)))))
18358 "\n"))
18359 (if newline (concat pkg "\n") pkg))
18361 (defun org-dvipng-color (attr)
18362 "Return a RGB color specification for dvipng."
18363 (apply 'format "rgb %s %s %s"
18364 (mapcar 'org-normalize-color
18365 (if (featurep 'xemacs)
18366 (color-rgb-components
18367 (face-property 'default
18368 (cond ((eq attr :foreground) 'foreground)
18369 ((eq attr :background) 'background))))
18370 (color-values (face-attribute 'default attr nil))))))
18372 (defun org-dvipng-color-format (color-name)
18373 "Convert COLOR-NAME to a RGB color value for dvipng."
18374 (apply 'format "rgb %s %s %s"
18375 (mapcar 'org-normalize-color
18376 (color-values color-name))))
18378 (defun org-latex-color (attr)
18379 "Return a RGB color for the LaTeX color package."
18380 (apply 'format "%s,%s,%s"
18381 (mapcar 'org-normalize-color
18382 (if (featurep 'xemacs)
18383 (color-rgb-components
18384 (face-property 'default
18385 (cond ((eq attr :foreground) 'foreground)
18386 ((eq attr :background) 'background))))
18387 (color-values (face-attribute 'default attr nil))))))
18389 (defun org-latex-color-format (color-name)
18390 "Convert COLOR-NAME to a RGB color value."
18391 (apply 'format "%s,%s,%s"
18392 (mapcar 'org-normalize-color
18393 (color-values color-name))))
18395 (defun org-normalize-color (value)
18396 "Return string to be used as color value for an RGB component."
18397 (format "%g" (/ value 65535.0)))
18401 ;; Image display
18403 (defvar org-inline-image-overlays nil)
18404 (make-variable-buffer-local 'org-inline-image-overlays)
18406 (defun org-toggle-inline-images (&optional include-linked)
18407 "Toggle the display of inline images.
18408 INCLUDE-LINKED is passed to `org-display-inline-images'."
18409 (interactive "P")
18410 (if org-inline-image-overlays
18411 (progn
18412 (org-remove-inline-images)
18413 (message "Inline image display turned off"))
18414 (org-display-inline-images include-linked)
18415 (if (and (org-called-interactively-p)
18416 org-inline-image-overlays)
18417 (message "%d images displayed inline"
18418 (length org-inline-image-overlays))
18419 (message "No images to display inline"))))
18421 (defun org-redisplay-inline-images ()
18422 "Refresh the display of inline images."
18423 (interactive)
18424 (if (not org-inline-image-overlays)
18425 (org-toggle-inline-images)
18426 (org-toggle-inline-images)
18427 (org-toggle-inline-images)))
18429 (defun org-display-inline-images (&optional include-linked refresh beg end)
18430 "Display inline images.
18431 Normally only links without a description part are inlined, because this
18432 is how it will work for export. When INCLUDE-LINKED is set, also links
18433 with a description part will be inlined. This can be nice for a quick
18434 look at those images, but it does not reflect what exported files will look
18435 like.
18436 When REFRESH is set, refresh existing images between BEG and END.
18437 This will create new image displays only if necessary.
18438 BEG and END default to the buffer boundaries."
18439 (interactive "P")
18440 (unless refresh
18441 (org-remove-inline-images)
18442 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18443 (save-excursion
18444 (save-restriction
18445 (widen)
18446 (setq beg (or beg (point-min)) end (or end (point-max)))
18447 (goto-char beg)
18448 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18449 (substring (org-image-file-name-regexp) 0 -2)
18450 "\\)\\]" (if include-linked "" "\\]")))
18451 old file ov img type attrwidth width)
18452 (while (re-search-forward re end t)
18453 (setq old (get-char-property-and-overlay (match-beginning 1)
18454 'org-image-overlay)
18455 file (expand-file-name
18456 (concat (or (match-string 3) "") (match-string 4))))
18457 (when (image-type-available-p 'imagemagick)
18458 (setq attrwidth (if (or (listp org-image-actual-width)
18459 (null org-image-actual-width))
18460 (save-excursion
18461 (save-match-data
18462 (when (re-search-backward
18463 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18464 (save-excursion
18465 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18466 (string-to-number (match-string 1))))))
18467 width (cond ((eq org-image-actual-width t) nil)
18468 ((null org-image-actual-width) attrwidth)
18469 ((numberp org-image-actual-width)
18470 org-image-actual-width)
18471 ((listp org-image-actual-width)
18472 (or attrwidth (car org-image-actual-width))))
18473 type (if width 'imagemagick)))
18474 (when (file-exists-p file)
18475 (if (and (car-safe old) refresh)
18476 (image-refresh (overlay-get (cdr old) 'display))
18477 (setq img (save-match-data (create-image file type nil :width width)))
18478 (when img
18479 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18480 (overlay-put ov 'display img)
18481 (overlay-put ov 'face 'default)
18482 (overlay-put ov 'org-image-overlay t)
18483 (overlay-put ov 'modification-hooks
18484 (list 'org-display-inline-remove-overlay))
18485 (push ov org-inline-image-overlays)))))))))
18487 (define-obsolete-function-alias
18488 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18490 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18491 "Remove inline-display overlay if a corresponding region is modified."
18492 (let ((inhibit-modification-hooks t))
18493 (when (and ov after)
18494 (delete ov org-inline-image-overlays)
18495 (delete-overlay ov))))
18497 (defun org-remove-inline-images ()
18498 "Remove inline display of images."
18499 (interactive)
18500 (mapc 'delete-overlay org-inline-image-overlays)
18501 (setq org-inline-image-overlays nil))
18503 ;;;; Key bindings
18505 ;; Outline functions from `outline-mode-prefix-map'
18506 ;; that can be remapped in Org:
18507 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18508 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18509 (define-key org-mode-map [remap outline-forward-same-level]
18510 'org-forward-heading-same-level)
18511 (define-key org-mode-map [remap outline-backward-same-level]
18512 'org-backward-heading-same-level)
18513 (define-key org-mode-map [remap show-branches]
18514 'org-kill-note-or-show-branches)
18515 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18516 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18517 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18519 ;; Outline functions from `outline-mode-prefix-map' that can not
18520 ;; be remapped in Org:
18522 ;; - the column "key binding" shows whether the Outline function is still
18523 ;; available in Org mode on the same key that it has been bound to in
18524 ;; Outline mode:
18525 ;; - "overridden": key used for a different functionality in Org mode
18526 ;; - else: key still bound to the same Outline function in Org mode
18528 ;; | Outline function | key binding | Org replacement |
18529 ;; |------------------------------------+-------------+-----------------------|
18530 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18531 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18532 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18533 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18534 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18535 ;; | `show-entry' | overridden | no replacement |
18536 ;; | `show-children' | `C-c C-i' | visibility cycling |
18537 ;; | `show-branches' | `C-c C-k' | still same function |
18538 ;; | `show-subtree' | overridden | visibility cycling |
18539 ;; | `show-all' | overridden | no replacement |
18540 ;; | `hide-subtree' | overridden | visibility cycling |
18541 ;; | `hide-body' | overridden | no replacement |
18542 ;; | `hide-entry' | overridden | visibility cycling |
18543 ;; | `hide-leaves' | overridden | no replacement |
18544 ;; | `hide-sublevels' | overridden | no replacement |
18545 ;; | `hide-other' | overridden | no replacement |
18547 ;; Make `C-c C-x' a prefix key
18548 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18550 ;; TAB key with modifiers
18551 (org-defkey org-mode-map "\C-i" 'org-cycle)
18552 (org-defkey org-mode-map [(tab)] 'org-cycle)
18553 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18554 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18555 ;; The following line is necessary under Suse GNU/Linux
18556 (unless (featurep 'xemacs)
18557 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18558 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18559 (define-key org-mode-map [backtab] 'org-shifttab)
18561 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18562 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18563 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18565 ;; Cursor keys with modifiers
18566 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18567 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18568 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18569 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18571 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18572 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18573 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18574 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18576 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18577 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18578 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18579 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18581 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18582 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18583 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18584 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18586 ;; Babel keys
18587 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18588 (mapc (lambda (pair)
18589 (define-key org-babel-map (car pair) (cdr pair)))
18590 org-babel-key-bindings)
18592 ;;; Extra keys for tty access.
18593 ;; We only set them when really needed because otherwise the
18594 ;; menus don't show the simple keys
18596 (when (or org-use-extra-keys
18597 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18598 (not window-system))
18599 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18600 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18601 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18602 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18603 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18604 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18605 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18606 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18607 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18608 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18609 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18610 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18611 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18612 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18613 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18614 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18615 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18616 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18617 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18618 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18619 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18620 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18621 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18622 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18623 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18624 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18625 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18626 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18628 ;; All the other keys
18630 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18631 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18632 (if (boundp 'narrow-map)
18633 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18634 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18635 (if (boundp 'narrow-map)
18636 (org-defkey narrow-map "b" 'org-narrow-to-block)
18637 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18638 (if (boundp 'narrow-map)
18639 (org-defkey narrow-map "e" 'org-narrow-to-element)
18640 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18641 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18642 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18643 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18644 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18645 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18646 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18647 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18648 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18649 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18650 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18651 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18652 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18653 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18654 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18655 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18656 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18657 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18658 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18659 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18660 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18661 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18662 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18663 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18664 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18665 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18666 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18667 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18668 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18669 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18670 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18671 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18672 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18673 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18674 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18675 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18676 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18677 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18678 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18679 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18680 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18681 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18682 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18683 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18684 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18685 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18686 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18687 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18688 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18689 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18690 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18691 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18692 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18693 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18694 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18695 (org-defkey org-mode-map "\C-c^" 'org-sort)
18696 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18697 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18698 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18699 (org-defkey org-mode-map "\C-m" 'org-return)
18700 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18701 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18702 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18703 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18704 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18705 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18706 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18707 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18708 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18709 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18710 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18711 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18712 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18713 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18714 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18715 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18716 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18717 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18718 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18719 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18720 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18721 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18722 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18724 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18725 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18726 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18728 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18729 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18730 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18731 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18732 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18733 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18734 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18735 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18736 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18737 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18738 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18739 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18740 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18741 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18742 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18743 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18744 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18745 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18746 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18747 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18748 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18749 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18750 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18752 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18753 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18754 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18755 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18756 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18758 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18760 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18762 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18763 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18765 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18768 (when (featurep 'xemacs)
18769 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18772 (defconst org-speed-commands-default
18774 ("Outline Navigation")
18775 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18776 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18777 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18778 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18779 ("F" . org-next-block)
18780 ("B" . org-previous-block)
18781 ("u" . (org-speed-move-safe 'outline-up-heading))
18782 ("j" . org-goto)
18783 ("g" . (org-refile t))
18784 ("Outline Visibility")
18785 ("c" . org-cycle)
18786 ("C" . org-shifttab)
18787 (" " . org-display-outline-path)
18788 ("=" . org-columns)
18789 ("Outline Structure Editing")
18790 ("U" . org-shiftmetaup)
18791 ("D" . org-shiftmetadown)
18792 ("r" . org-metaright)
18793 ("l" . org-metaleft)
18794 ("R" . org-shiftmetaright)
18795 ("L" . org-shiftmetaleft)
18796 ("i" . (progn (forward-char 1) (call-interactively
18797 'org-insert-heading-respect-content)))
18798 ("^" . org-sort)
18799 ("w" . org-refile)
18800 ("a" . org-archive-subtree-default-with-confirmation)
18801 ("@" . org-mark-subtree)
18802 ("#" . org-toggle-comment)
18803 ("Clock Commands")
18804 ("I" . org-clock-in)
18805 ("O" . org-clock-out)
18806 ("Meta Data Editing")
18807 ("t" . org-todo)
18808 ("," . (org-priority))
18809 ("0" . (org-priority ?\ ))
18810 ("1" . (org-priority ?A))
18811 ("2" . (org-priority ?B))
18812 ("3" . (org-priority ?C))
18813 (":" . org-set-tags-command)
18814 ("e" . org-set-effort)
18815 ("E" . org-inc-effort)
18816 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18817 (org-entry-put (point) "APPT_WARNTIME" m)))
18818 ("Agenda Views etc")
18819 ("v" . org-agenda)
18820 ("/" . org-sparse-tree)
18821 ("Misc")
18822 ("o" . org-open-at-point)
18823 ("?" . org-speed-command-help)
18824 ("<" . (org-agenda-set-restriction-lock 'subtree))
18825 (">" . (org-agenda-remove-restriction-lock))
18827 "The default speed commands.")
18829 (defun org-print-speed-command (e)
18830 (if (> (length (car e)) 1)
18831 (progn
18832 (princ "\n")
18833 (princ (car e))
18834 (princ "\n")
18835 (princ (make-string (length (car e)) ?-))
18836 (princ "\n"))
18837 (princ (car e))
18838 (princ " ")
18839 (if (symbolp (cdr e))
18840 (princ (symbol-name (cdr e)))
18841 (prin1 (cdr e)))
18842 (princ "\n")))
18844 (defun org-speed-command-help ()
18845 "Show the available speed commands."
18846 (interactive)
18847 (if (not org-use-speed-commands)
18848 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18849 (with-output-to-temp-buffer "*Help*"
18850 (princ "User-defined Speed commands\n===========================\n")
18851 (mapc 'org-print-speed-command org-speed-commands-user)
18852 (princ "\n")
18853 (princ "Built-in Speed commands\n=======================\n")
18854 (mapc 'org-print-speed-command org-speed-commands-default))
18855 (with-current-buffer "*Help*"
18856 (setq truncate-lines t))))
18858 (defun org-speed-move-safe (cmd)
18859 "Execute CMD, but make sure that the cursor always ends up in a headline.
18860 If not, return to the original position and throw an error."
18861 (interactive)
18862 (let ((pos (point)))
18863 (call-interactively cmd)
18864 (unless (and (bolp) (org-at-heading-p))
18865 (goto-char pos)
18866 (error "Boundary reached while executing %s" cmd))))
18868 (defvar org-self-insert-command-undo-counter 0)
18870 (defvar org-table-auto-blank-field) ; defined in org-table.el
18871 (defvar org-speed-command nil)
18873 (define-obsolete-function-alias
18874 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18876 (defun org-speed-command-activate (keys)
18877 "Hook for activating single-letter speed commands.
18878 `org-speed-commands-default' specifies a minimal command set.
18879 Use `org-speed-commands-user' for further customization."
18880 (when (or (and (bolp) (looking-at org-outline-regexp))
18881 (and (functionp org-use-speed-commands)
18882 (funcall org-use-speed-commands)))
18883 (cdr (assoc keys (append org-speed-commands-user
18884 org-speed-commands-default)))))
18886 (define-obsolete-function-alias
18887 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18889 (defun org-babel-speed-command-activate (keys)
18890 "Hook for activating single-letter code block commands."
18891 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18892 (cdr (assoc keys org-babel-key-bindings))))
18894 (defcustom org-speed-command-hook
18895 '(org-speed-command-default-hook org-babel-speed-command-hook)
18896 "Hook for activating speed commands at strategic locations.
18897 Hook functions are called in sequence until a valid handler is
18898 found.
18900 Each hook takes a single argument, a user-pressed command key
18901 which is also a `self-insert-command' from the global map.
18903 Within the hook, examine the cursor position and the command key
18904 and return nil or a valid handler as appropriate. Handler could
18905 be one of an interactive command, a function, or a form.
18907 Set `org-use-speed-commands' to non-nil value to enable this
18908 hook. The default setting is `org-speed-command-activate'."
18909 :group 'org-structure
18910 :version "24.1"
18911 :type 'hook)
18913 (defun org-self-insert-command (N)
18914 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18915 If the cursor is in a table looking at whitespace, the whitespace is
18916 overwritten, and the table is not marked as requiring realignment."
18917 (interactive "p")
18918 (org-check-before-invisible-edit 'insert)
18919 (cond
18920 ((and org-use-speed-commands
18921 (setq org-speed-command
18922 (run-hook-with-args-until-success
18923 'org-speed-command-hook (this-command-keys))))
18924 (cond
18925 ((commandp org-speed-command)
18926 (setq this-command org-speed-command)
18927 (call-interactively org-speed-command))
18928 ((functionp org-speed-command)
18929 (funcall org-speed-command))
18930 ((and org-speed-command (listp org-speed-command))
18931 (eval org-speed-command))
18932 (t (let (org-use-speed-commands)
18933 (call-interactively 'org-self-insert-command)))))
18934 ((and
18935 (org-table-p)
18936 (progn
18937 ;; check if we blank the field, and if that triggers align
18938 (and (featurep 'org-table) org-table-auto-blank-field
18939 (member last-command
18940 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18941 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18942 ;; got extra space, this field does not determine column width
18943 (let (org-table-may-need-update) (org-table-blank-field))
18944 ;; no extra space, this field may determine column width
18945 (org-table-blank-field)))
18947 (eq N 1)
18948 (looking-at "[^|\n]* |"))
18949 (let (org-table-may-need-update)
18950 (goto-char (1- (match-end 0)))
18951 (backward-delete-char 1)
18952 (goto-char (match-beginning 0))
18953 (self-insert-command N)))
18955 (setq org-table-may-need-update t)
18956 (self-insert-command N)
18957 (org-fix-tags-on-the-fly)
18958 (if org-self-insert-cluster-for-undo
18959 (if (not (eq last-command 'org-self-insert-command))
18960 (setq org-self-insert-command-undo-counter 1)
18961 (if (>= org-self-insert-command-undo-counter 20)
18962 (setq org-self-insert-command-undo-counter 1)
18963 (and (> org-self-insert-command-undo-counter 0)
18964 buffer-undo-list (listp buffer-undo-list)
18965 (not (cadr buffer-undo-list)) ; remove nil entry
18966 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18967 (setq org-self-insert-command-undo-counter
18968 (1+ org-self-insert-command-undo-counter))))))))
18970 (defun org-check-before-invisible-edit (kind)
18971 "Check is editing if kind KIND would be dangerous with invisible text around.
18972 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18973 ;; First, try to get out of here as quickly as possible, to reduce overhead
18974 (if (and org-catch-invisible-edits
18975 (or (not (boundp 'visible-mode)) (not visible-mode))
18976 (or (get-char-property (point) 'invisible)
18977 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18978 ;; OK, we need to take a closer look
18979 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18980 (invisible-before-point (if (bobp) nil (get-char-property
18981 (1- (point)) 'invisible)))
18982 (border-and-ok-direction
18984 ;; Check if we are acting predictably before invisible text
18985 (and invisible-at-point (not invisible-before-point)
18986 (memq kind '(insert delete-backward)))
18987 ;; Check if we are acting predictably after invisible text
18988 ;; This works not well, and I have turned it off. It seems
18989 ;; better to always show and stop after invisible text.
18990 ;; (and (not invisible-at-point) invisible-before-point
18991 ;; (memq kind '(insert delete)))
18993 (when (or (memq invisible-at-point '(outline org-hide-block t))
18994 (memq invisible-before-point '(outline org-hide-block t)))
18995 (if (eq org-catch-invisible-edits 'error)
18996 (error "Editing in invisible areas is prohibited - make visible first"))
18997 (if (and org-custom-properties-overlays
18998 (y-or-n-p "Display invisible properties in this buffer? "))
18999 (org-toggle-custom-properties-visibility)
19000 ;; Make the area visible
19001 (save-excursion
19002 (if invisible-before-point
19003 (goto-char (previous-single-char-property-change
19004 (point) 'invisible)))
19005 (org-cycle))
19006 (cond
19007 ((eq org-catch-invisible-edits 'show)
19008 ;; That's it, we do the edit after showing
19009 (message
19010 "Unfolding invisible region around point before editing")
19011 (sit-for 1))
19012 ((and (eq org-catch-invisible-edits 'smart)
19013 border-and-ok-direction)
19014 (message "Unfolding invisible region around point before editing"))
19016 ;; Don't do the edit, make the user repeat it in full visibility
19017 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19019 (defun org-fix-tags-on-the-fly ()
19020 (when (and (equal (char-after (point-at-bol)) ?*)
19021 (org-at-heading-p))
19022 (org-align-tags-here org-tags-column)))
19024 (defun org-delete-backward-char (N)
19025 "Like `delete-backward-char', insert whitespace at field end in tables.
19026 When deleting backwards, in tables this function will insert whitespace in
19027 front of the next \"|\" separator, to keep the table aligned. The table will
19028 still be marked for re-alignment if the field did fill the entire column,
19029 because, in this case the deletion might narrow the column."
19030 (interactive "p")
19031 (save-match-data
19032 (org-check-before-invisible-edit 'delete-backward)
19033 (if (and (org-table-p)
19034 (eq N 1)
19035 (string-match "|" (buffer-substring (point-at-bol) (point)))
19036 (looking-at ".*?|"))
19037 (let ((pos (point))
19038 (noalign (looking-at "[^|\n\r]* |"))
19039 (c org-table-may-need-update))
19040 (backward-delete-char N)
19041 (if (not overwrite-mode)
19042 (progn
19043 (skip-chars-forward "^|")
19044 (insert " ")
19045 (goto-char (1- pos))))
19046 ;; noalign: if there were two spaces at the end, this field
19047 ;; does not determine the width of the column.
19048 (if noalign (setq org-table-may-need-update c)))
19049 (backward-delete-char N)
19050 (org-fix-tags-on-the-fly))))
19052 (defun org-delete-char (N)
19053 "Like `delete-char', but insert whitespace at field end in tables.
19054 When deleting characters, in tables this function will insert whitespace in
19055 front of the next \"|\" separator, to keep the table aligned. The table will
19056 still be marked for re-alignment if the field did fill the entire column,
19057 because, in this case the deletion might narrow the column."
19058 (interactive "p")
19059 (save-match-data
19060 (org-check-before-invisible-edit 'delete)
19061 (if (and (org-table-p)
19062 (not (bolp))
19063 (not (= (char-after) ?|))
19064 (eq N 1))
19065 (if (looking-at ".*?|")
19066 (let ((pos (point))
19067 (noalign (looking-at "[^|\n\r]* |"))
19068 (c org-table-may-need-update))
19069 (replace-match (concat
19070 (substring (match-string 0) 1 -1)
19071 " |"))
19072 (goto-char pos)
19073 ;; noalign: if there were two spaces at the end, this field
19074 ;; does not determine the width of the column.
19075 (if noalign (setq org-table-may-need-update c)))
19076 (delete-char N))
19077 (delete-char N)
19078 (org-fix-tags-on-the-fly))))
19080 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19081 (put 'org-self-insert-command 'delete-selection t)
19082 (put 'orgtbl-self-insert-command 'delete-selection t)
19083 (put 'org-delete-char 'delete-selection 'supersede)
19084 (put 'org-delete-backward-char 'delete-selection 'supersede)
19085 (put 'org-yank 'delete-selection 'yank)
19087 ;; Make `flyspell-mode' delay after some commands
19088 (put 'org-self-insert-command 'flyspell-delayed t)
19089 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19090 (put 'org-delete-char 'flyspell-delayed t)
19091 (put 'org-delete-backward-char 'flyspell-delayed t)
19093 ;; Make pabbrev-mode expand after org-mode commands
19094 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19095 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19097 ;; How to do this: Measure non-white length of current string
19098 ;; If equal to column width, we should realign.
19100 (defun org-remap (map &rest commands)
19101 "In MAP, remap the functions given in COMMANDS.
19102 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19103 (let (new old)
19104 (while commands
19105 (setq old (pop commands) new (pop commands))
19106 (if (fboundp 'command-remapping)
19107 (org-defkey map (vector 'remap old) new)
19108 (substitute-key-definition old new map global-map)))))
19110 (defun org-transpose-words ()
19111 "Transpose words for Org.
19112 This uses the `org-mode-transpose-word-syntax-table' syntax
19113 table, which interprets characters in `org-emphasis-alist' as
19114 word constituants."
19115 (interactive)
19116 (with-syntax-table org-mode-transpose-word-syntax-table
19117 (call-interactively 'transpose-words)))
19118 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19120 (when (eq org-enable-table-editor 'optimized)
19121 ;; If the user wants maximum table support, we need to hijack
19122 ;; some standard editing functions
19123 (org-remap org-mode-map
19124 'self-insert-command 'org-self-insert-command
19125 'delete-char 'org-delete-char
19126 'delete-backward-char 'org-delete-backward-char)
19127 (org-defkey org-mode-map "|" 'org-force-self-insert))
19129 (defvar org-ctrl-c-ctrl-c-hook nil
19130 "Hook for functions attaching themselves to `C-c C-c'.
19132 This can be used to add additional functionality to the C-c C-c
19133 key which executes context-dependent commands. This hook is run
19134 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19135 run after the last test.
19137 Each function will be called with no arguments. The function
19138 must check if the context is appropriate for it to act. If yes,
19139 it should do its thing and then return a non-nil value. If the
19140 context is wrong, just do nothing and return nil.")
19142 (defvar org-ctrl-c-ctrl-c-final-hook nil
19143 "Hook for functions attaching themselves to `C-c C-c'.
19145 This can be used to add additional functionality to the C-c C-c
19146 key which executes context-dependent commands. This hook is run
19147 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19148 before the first test.
19150 Each function will be called with no arguments. The function
19151 must check if the context is appropriate for it to act. If yes,
19152 it should do its thing and then return a non-nil value. If the
19153 context is wrong, just do nothing and return nil.")
19155 (defvar org-tab-first-hook nil
19156 "Hook for functions to attach themselves to TAB.
19157 See `org-ctrl-c-ctrl-c-hook' for more information.
19158 This hook runs as the first action when TAB is pressed, even before
19159 `org-cycle' messes around with the `outline-regexp' to cater for
19160 inline tasks and plain list item folding.
19161 If any function in this hook returns t, any other actions that
19162 would have been caused by TAB (such as table field motion or visibility
19163 cycling) will not occur.")
19165 (defvar org-tab-after-check-for-table-hook nil
19166 "Hook for functions to attach themselves to TAB.
19167 See `org-ctrl-c-ctrl-c-hook' for more information.
19168 This hook runs after it has been established that the cursor is not in a
19169 table, but before checking if the cursor is in a headline or if global cycling
19170 should be done.
19171 If any function in this hook returns t, not other actions like visibility
19172 cycling will be done.")
19174 (defvar org-tab-after-check-for-cycling-hook nil
19175 "Hook for functions to attach themselves to TAB.
19176 See `org-ctrl-c-ctrl-c-hook' for more information.
19177 This hook runs after it has been established that not table field motion and
19178 not visibility should be done because of current context. This is probably
19179 the place where a package like yasnippets can hook in.")
19181 (defvar org-tab-before-tab-emulation-hook nil
19182 "Hook for functions to attach themselves to TAB.
19183 See `org-ctrl-c-ctrl-c-hook' for more information.
19184 This hook runs after every other options for TAB have been exhausted, but
19185 before indentation and \t insertion takes place.")
19187 (defvar org-metaleft-hook nil
19188 "Hook for functions attaching themselves to `M-left'.
19189 See `org-ctrl-c-ctrl-c-hook' for more information.")
19190 (defvar org-metaright-hook nil
19191 "Hook for functions attaching themselves to `M-right'.
19192 See `org-ctrl-c-ctrl-c-hook' for more information.")
19193 (defvar org-metaup-hook nil
19194 "Hook for functions attaching themselves to `M-up'.
19195 See `org-ctrl-c-ctrl-c-hook' for more information.")
19196 (defvar org-metadown-hook nil
19197 "Hook for functions attaching themselves to `M-down'.
19198 See `org-ctrl-c-ctrl-c-hook' for more information.")
19199 (defvar org-shiftmetaleft-hook nil
19200 "Hook for functions attaching themselves to `M-S-left'.
19201 See `org-ctrl-c-ctrl-c-hook' for more information.")
19202 (defvar org-shiftmetaright-hook nil
19203 "Hook for functions attaching themselves to `M-S-right'.
19204 See `org-ctrl-c-ctrl-c-hook' for more information.")
19205 (defvar org-shiftmetaup-hook nil
19206 "Hook for functions attaching themselves to `M-S-up'.
19207 See `org-ctrl-c-ctrl-c-hook' for more information.")
19208 (defvar org-shiftmetadown-hook nil
19209 "Hook for functions attaching themselves to `M-S-down'.
19210 See `org-ctrl-c-ctrl-c-hook' for more information.")
19211 (defvar org-metareturn-hook nil
19212 "Hook for functions attaching themselves to `M-RET'.
19213 See `org-ctrl-c-ctrl-c-hook' for more information.")
19214 (defvar org-shiftup-hook nil
19215 "Hook for functions attaching themselves to `S-up'.
19216 See `org-ctrl-c-ctrl-c-hook' for more information.")
19217 (defvar org-shiftup-final-hook nil
19218 "Hook for functions attaching themselves to `S-up'.
19219 This one runs after all other options except shift-select have been excluded.
19220 See `org-ctrl-c-ctrl-c-hook' for more information.")
19221 (defvar org-shiftdown-hook nil
19222 "Hook for functions attaching themselves to `S-down'.
19223 See `org-ctrl-c-ctrl-c-hook' for more information.")
19224 (defvar org-shiftdown-final-hook nil
19225 "Hook for functions attaching themselves to `S-down'.
19226 This one runs after all other options except shift-select have been excluded.
19227 See `org-ctrl-c-ctrl-c-hook' for more information.")
19228 (defvar org-shiftleft-hook nil
19229 "Hook for functions attaching themselves to `S-left'.
19230 See `org-ctrl-c-ctrl-c-hook' for more information.")
19231 (defvar org-shiftleft-final-hook nil
19232 "Hook for functions attaching themselves to `S-left'.
19233 This one runs after all other options except shift-select have been excluded.
19234 See `org-ctrl-c-ctrl-c-hook' for more information.")
19235 (defvar org-shiftright-hook nil
19236 "Hook for functions attaching themselves to `S-right'.
19237 See `org-ctrl-c-ctrl-c-hook' for more information.")
19238 (defvar org-shiftright-final-hook nil
19239 "Hook for functions attaching themselves to `S-right'.
19240 This one runs after all other options except shift-select have been excluded.
19241 See `org-ctrl-c-ctrl-c-hook' for more information.")
19243 (defun org-modifier-cursor-error ()
19244 "Throw an error, a modified cursor command was applied in wrong context."
19245 (error "This command is active in special context like tables, headlines or items"))
19247 (defun org-shiftselect-error ()
19248 "Throw an error because Shift-Cursor command was applied in wrong context."
19249 (if (and (boundp 'shift-select-mode) shift-select-mode)
19250 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19251 (error "This command works only in special context like headlines or timestamps")))
19253 (defun org-call-for-shift-select (cmd)
19254 (let ((this-command-keys-shift-translated t))
19255 (call-interactively cmd)))
19257 (defun org-shifttab (&optional arg)
19258 "Global visibility cycling or move to previous table field.
19259 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19260 on context.
19261 See the individual commands for more information."
19262 (interactive "P")
19263 (cond
19264 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19265 ((integerp arg)
19266 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19267 (message "Content view to level: %d" arg)
19268 (org-content (prefix-numeric-value arg2))
19269 (setq org-cycle-global-status 'overview)))
19270 (t (call-interactively 'org-global-cycle))))
19272 (defun org-shiftmetaleft ()
19273 "Promote subtree or delete table column.
19274 Calls `org-promote-subtree', `org-outdent-item-tree', or
19275 `org-table-delete-column', depending on context. See the
19276 individual commands for more information."
19277 (interactive)
19278 (cond
19279 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19280 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19281 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19282 ((if (not (org-region-active-p)) (org-at-item-p)
19283 (save-excursion (goto-char (region-beginning))
19284 (org-at-item-p)))
19285 (call-interactively 'org-outdent-item-tree))
19286 (t (org-modifier-cursor-error))))
19288 (defun org-shiftmetaright ()
19289 "Demote subtree or insert table column.
19290 Calls `org-demote-subtree', `org-indent-item-tree', or
19291 `org-table-insert-column', depending on context. See the
19292 individual commands for more information."
19293 (interactive)
19294 (cond
19295 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19296 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19297 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19298 ((if (not (org-region-active-p)) (org-at-item-p)
19299 (save-excursion (goto-char (region-beginning))
19300 (org-at-item-p)))
19301 (call-interactively 'org-indent-item-tree))
19302 (t (org-modifier-cursor-error))))
19304 (defun org-shiftmetaup (&optional arg)
19305 "Move subtree up or kill table row.
19306 Calls `org-move-subtree-up' or `org-table-kill-row' or
19307 `org-move-item-up' or `org-timestamp-up', depending on context.
19308 See the individual commands for more information."
19309 (interactive "P")
19310 (cond
19311 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19312 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19313 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19314 ((org-at-item-p) (call-interactively 'org-move-item-up))
19315 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19316 (call-interactively 'org-timestamp-up)))
19317 (t (call-interactively 'org-drag-line-backward))))
19319 (defun org-shiftmetadown (&optional arg)
19320 "Move subtree down or insert table row.
19321 Calls `org-move-subtree-down' or `org-table-insert-row' or
19322 `org-move-item-down' or `org-timestamp-up', depending on context.
19323 See the individual commands for more information."
19324 (interactive "P")
19325 (cond
19326 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19327 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19328 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19329 ((org-at-item-p) (call-interactively 'org-move-item-down))
19330 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19331 (call-interactively 'org-timestamp-down)))
19332 (t (call-interactively 'org-drag-line-forward))))
19334 (defsubst org-hidden-tree-error ()
19335 (error
19336 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19338 (defun org-metaleft (&optional arg)
19339 "Promote heading or move table column to left.
19340 Calls `org-do-promote' or `org-table-move-column', depending on context.
19341 With no specific context, calls the Emacs default `backward-word'.
19342 See the individual commands for more information."
19343 (interactive "P")
19344 (cond
19345 ((run-hook-with-args-until-success 'org-metaleft-hook))
19346 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19347 ((org-with-limited-levels
19348 (or (org-at-heading-p)
19349 (and (org-region-active-p)
19350 (save-excursion
19351 (goto-char (region-beginning))
19352 (org-at-heading-p)))))
19353 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19354 (call-interactively 'org-do-promote))
19355 ;; At an inline task.
19356 ((org-at-heading-p)
19357 (call-interactively 'org-inlinetask-promote))
19358 ((or (org-at-item-p)
19359 (and (org-region-active-p)
19360 (save-excursion
19361 (goto-char (region-beginning))
19362 (org-at-item-p))))
19363 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19364 (call-interactively 'org-outdent-item))
19365 (t (call-interactively 'backward-word))))
19367 (defun org-metaright (&optional arg)
19368 "Demote a subtree, a list item or move table column to right.
19369 In front of a drawer or a block keyword, indent it correctly.
19370 With no specific context, calls the Emacs default `forward-word'.
19371 See the individual commands for more information."
19372 (interactive "P")
19373 (cond
19374 ((run-hook-with-args-until-success 'org-metaright-hook))
19375 ((org-at-table-p) (call-interactively 'org-table-move-column))
19376 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19377 ((org-at-block-p) (call-interactively 'org-indent-block))
19378 ((org-with-limited-levels
19379 (or (org-at-heading-p)
19380 (and (org-region-active-p)
19381 (save-excursion
19382 (goto-char (region-beginning))
19383 (org-at-heading-p)))))
19384 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19385 (call-interactively 'org-do-demote))
19386 ;; At an inline task.
19387 ((org-at-heading-p)
19388 (call-interactively 'org-inlinetask-demote))
19389 ((or (org-at-item-p)
19390 (and (org-region-active-p)
19391 (save-excursion
19392 (goto-char (region-beginning))
19393 (org-at-item-p))))
19394 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19395 (call-interactively 'org-indent-item))
19396 (t (call-interactively 'forward-word))))
19398 (defun org-check-for-hidden (what)
19399 "Check if there are hidden headlines/items in the current visual line.
19400 WHAT can be either `headlines' or `items'. If the current line is
19401 an outline or item heading and it has a folded subtree below it,
19402 this function returns t, nil otherwise."
19403 (let ((re (cond
19404 ((eq what 'headlines) org-outline-regexp-bol)
19405 ((eq what 'items) (org-item-beginning-re))
19406 (t (error "This should not happen"))))
19407 beg end)
19408 (save-excursion
19409 (catch 'exit
19410 (unless (org-region-active-p)
19411 (setq beg (point-at-bol))
19412 (beginning-of-line 2)
19413 (while (and (not (eobp)) ;; this is like `next-line'
19414 (get-char-property (1- (point)) 'invisible))
19415 (beginning-of-line 2))
19416 (setq end (point))
19417 (goto-char beg)
19418 (goto-char (point-at-eol))
19419 (setq end (max end (point)))
19420 (while (re-search-forward re end t)
19421 (if (get-char-property (match-beginning 0) 'invisible)
19422 (throw 'exit t))))
19423 nil))))
19425 (defun org-metaup (&optional arg)
19426 "Move subtree up or move table row up.
19427 Calls `org-move-subtree-up' or `org-table-move-row' or
19428 `org-move-item-up', depending on context. See the individual commands
19429 for more information."
19430 (interactive "P")
19431 (cond
19432 ((run-hook-with-args-until-success 'org-metaup-hook))
19433 ((org-region-active-p)
19434 (let* ((a (min (region-beginning) (region-end)))
19435 (b (1- (max (region-beginning) (region-end))))
19436 (c (save-excursion (goto-char a)
19437 (move-beginning-of-line 0)))
19438 (d (save-excursion (goto-char a)
19439 (move-end-of-line 0) (point))))
19440 (transpose-regions a b c d)
19441 (goto-char c)))
19442 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19443 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19444 ((org-at-item-p) (call-interactively 'org-move-item-up))
19445 (t (org-drag-element-backward))))
19447 (defun org-metadown (&optional arg)
19448 "Move subtree down or move table row down.
19449 Calls `org-move-subtree-down' or `org-table-move-row' or
19450 `org-move-item-down', depending on context. See the individual
19451 commands for more information."
19452 (interactive "P")
19453 (cond
19454 ((run-hook-with-args-until-success 'org-metadown-hook))
19455 ((org-region-active-p)
19456 (let* ((a (min (region-beginning) (region-end)))
19457 (b (max (region-beginning) (region-end)))
19458 (c (save-excursion (goto-char b)
19459 (move-beginning-of-line 1)))
19460 (d (save-excursion (goto-char b)
19461 (move-end-of-line 1) (1+ (point)))))
19462 (transpose-regions a b c d)
19463 (goto-char d)))
19464 ((org-at-table-p) (call-interactively 'org-table-move-row))
19465 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19466 ((org-at-item-p) (call-interactively 'org-move-item-down))
19467 (t (org-drag-element-forward))))
19469 (defun org-shiftup (&optional arg)
19470 "Increase item in timestamp or increase priority of current headline.
19471 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19472 depending on context. See the individual commands for more information."
19473 (interactive "P")
19474 (cond
19475 ((run-hook-with-args-until-success 'org-shiftup-hook))
19476 ((and org-support-shift-select (org-region-active-p))
19477 (org-call-for-shift-select 'previous-line))
19478 ((org-at-timestamp-p t)
19479 (call-interactively (if org-edit-timestamp-down-means-later
19480 'org-timestamp-down 'org-timestamp-up)))
19481 ((and (not (eq org-support-shift-select 'always))
19482 org-enable-priority-commands
19483 (org-at-heading-p))
19484 (call-interactively 'org-priority-up))
19485 ((and (not org-support-shift-select) (org-at-item-p))
19486 (call-interactively 'org-previous-item))
19487 ((org-clocktable-try-shift 'up arg))
19488 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19489 (org-support-shift-select
19490 (org-call-for-shift-select 'previous-line))
19491 (t (org-shiftselect-error))))
19493 (defun org-shiftdown (&optional arg)
19494 "Decrease item in timestamp or decrease priority of current headline.
19495 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19496 depending on context. See the individual commands for more information."
19497 (interactive "P")
19498 (cond
19499 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19500 ((and org-support-shift-select (org-region-active-p))
19501 (org-call-for-shift-select 'next-line))
19502 ((org-at-timestamp-p t)
19503 (call-interactively (if org-edit-timestamp-down-means-later
19504 'org-timestamp-up 'org-timestamp-down)))
19505 ((and (not (eq org-support-shift-select 'always))
19506 org-enable-priority-commands
19507 (org-at-heading-p))
19508 (call-interactively 'org-priority-down))
19509 ((and (not org-support-shift-select) (org-at-item-p))
19510 (call-interactively 'org-next-item))
19511 ((org-clocktable-try-shift 'down arg))
19512 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19513 (org-support-shift-select
19514 (org-call-for-shift-select 'next-line))
19515 (t (org-shiftselect-error))))
19517 (defun org-shiftright (&optional arg)
19518 "Cycle the thing at point or in the current line, depending on context.
19519 Depending on context, this does one of the following:
19521 - switch a timestamp at point one day into the future
19522 - on a headline, switch to the next TODO keyword.
19523 - on an item, switch entire list to the next bullet type
19524 - on a property line, switch to the next allowed value
19525 - on a clocktable definition line, move time block into the future"
19526 (interactive "P")
19527 (cond
19528 ((run-hook-with-args-until-success 'org-shiftright-hook))
19529 ((and org-support-shift-select (org-region-active-p))
19530 (org-call-for-shift-select 'forward-char))
19531 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19532 ((and (not (eq org-support-shift-select 'always))
19533 (org-at-heading-p))
19534 (let ((org-inhibit-logging
19535 (not org-treat-S-cursor-todo-selection-as-state-change))
19536 (org-inhibit-blocking
19537 (not org-treat-S-cursor-todo-selection-as-state-change)))
19538 (org-call-with-arg 'org-todo 'right)))
19539 ((or (and org-support-shift-select
19540 (not (eq org-support-shift-select 'always))
19541 (org-at-item-bullet-p))
19542 (and (not org-support-shift-select) (org-at-item-p)))
19543 (org-call-with-arg 'org-cycle-list-bullet nil))
19544 ((and (not (eq org-support-shift-select 'always))
19545 (org-at-property-p))
19546 (call-interactively 'org-property-next-allowed-value))
19547 ((org-clocktable-try-shift 'right arg))
19548 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19549 (org-support-shift-select
19550 (org-call-for-shift-select 'forward-char))
19551 (t (org-shiftselect-error))))
19553 (defun org-shiftleft (&optional arg)
19554 "Cycle the thing at point or in the current line, depending on context.
19555 Depending on context, this does one of the following:
19557 - switch a timestamp at point one day into the past
19558 - on a headline, switch to the previous TODO keyword.
19559 - on an item, switch entire list to the previous bullet type
19560 - on a property line, switch to the previous allowed value
19561 - on a clocktable definition line, move time block into the past"
19562 (interactive "P")
19563 (cond
19564 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19565 ((and org-support-shift-select (org-region-active-p))
19566 (org-call-for-shift-select 'backward-char))
19567 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19568 ((and (not (eq org-support-shift-select 'always))
19569 (org-at-heading-p))
19570 (let ((org-inhibit-logging
19571 (not org-treat-S-cursor-todo-selection-as-state-change))
19572 (org-inhibit-blocking
19573 (not org-treat-S-cursor-todo-selection-as-state-change)))
19574 (org-call-with-arg 'org-todo 'left)))
19575 ((or (and org-support-shift-select
19576 (not (eq org-support-shift-select 'always))
19577 (org-at-item-bullet-p))
19578 (and (not org-support-shift-select) (org-at-item-p)))
19579 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19580 ((and (not (eq org-support-shift-select 'always))
19581 (org-at-property-p))
19582 (call-interactively 'org-property-previous-allowed-value))
19583 ((org-clocktable-try-shift 'left arg))
19584 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19585 (org-support-shift-select
19586 (org-call-for-shift-select 'backward-char))
19587 (t (org-shiftselect-error))))
19589 (defun org-shiftcontrolright ()
19590 "Switch to next TODO set."
19591 (interactive)
19592 (cond
19593 ((and org-support-shift-select (org-region-active-p))
19594 (org-call-for-shift-select 'forward-word))
19595 ((and (not (eq org-support-shift-select 'always))
19596 (org-at-heading-p))
19597 (org-call-with-arg 'org-todo 'nextset))
19598 (org-support-shift-select
19599 (org-call-for-shift-select 'forward-word))
19600 (t (org-shiftselect-error))))
19602 (defun org-shiftcontrolleft ()
19603 "Switch to previous TODO set."
19604 (interactive)
19605 (cond
19606 ((and org-support-shift-select (org-region-active-p))
19607 (org-call-for-shift-select 'backward-word))
19608 ((and (not (eq org-support-shift-select 'always))
19609 (org-at-heading-p))
19610 (org-call-with-arg 'org-todo 'previousset))
19611 (org-support-shift-select
19612 (org-call-for-shift-select 'backward-word))
19613 (t (org-shiftselect-error))))
19615 (defun org-shiftcontrolup (&optional n)
19616 "Change timestamps synchronously up in CLOCK log lines.
19617 Optional argument N tells to change by that many units."
19618 (interactive "P")
19619 (cond ((and (not org-support-shift-select)
19620 (org-at-clock-log-p)
19621 (org-at-timestamp-p t))
19622 (org-clock-timestamps-up n))
19623 (t (org-shiftselect-error))))
19625 (defun org-shiftcontroldown (&optional n)
19626 "Change timestamps synchronously down in CLOCK log lines.
19627 Optional argument N tells to change by that many units."
19628 (interactive "P")
19629 (cond ((and (not org-support-shift-select)
19630 (org-at-clock-log-p)
19631 (org-at-timestamp-p t))
19632 (org-clock-timestamps-down n))
19633 (t (org-shiftselect-error))))
19635 (defun org-ctrl-c-ret ()
19636 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19637 (interactive)
19638 (cond
19639 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19640 (t (call-interactively 'org-insert-heading))))
19642 (defun org-find-visible ()
19643 (let ((s (point)))
19644 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19645 (get-char-property s 'invisible)))
19647 (defun org-find-invisible ()
19648 (let ((s (point)))
19649 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19650 (not (get-char-property s 'invisible))))
19653 (defun org-copy-visible (beg end)
19654 "Copy the visible parts of the region."
19655 (interactive "r")
19656 (let (snippets s)
19657 (save-excursion
19658 (save-restriction
19659 (narrow-to-region beg end)
19660 (setq s (goto-char (point-min)))
19661 (while (not (= (point) (point-max)))
19662 (goto-char (org-find-invisible))
19663 (push (buffer-substring s (point)) snippets)
19664 (setq s (goto-char (org-find-visible))))))
19665 (kill-new (apply 'concat (nreverse snippets)))))
19667 (defun org-copy-special ()
19668 "Copy region in table or copy current subtree.
19669 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19670 See the individual commands for more information."
19671 (interactive)
19672 (call-interactively
19673 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19675 (defun org-cut-special ()
19676 "Cut region in table or cut current subtree.
19677 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19678 See the individual commands for more information."
19679 (interactive)
19680 (call-interactively
19681 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19683 (defun org-paste-special (arg)
19684 "Paste rectangular region into table, or past subtree relative to level.
19685 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19686 See the individual commands for more information."
19687 (interactive "P")
19688 (if (org-at-table-p)
19689 (org-table-paste-rectangle)
19690 (org-paste-subtree arg)))
19692 (defsubst org-in-fixed-width-region-p ()
19693 "Is point in a fixed-width region?"
19694 (save-match-data
19695 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19697 (defun org-edit-special (&optional arg)
19698 "Call a special editor for the element at point.
19699 When at a table, call the formula editor with `org-table-edit-formulas'.
19700 When in a source code block, call `org-edit-src-code'.
19701 When in a fixed-width region, call `org-edit-fixed-width-region'.
19702 When at an #+INCLUDE keyword, visit the included file.
19703 On a link, call `ffap' to visit the link at point.
19704 Otherwise, return a user error."
19705 (interactive)
19706 (let ((element (org-element-at-point)))
19707 (assert (not buffer-read-only) nil
19708 "Buffer is read-only: %s" (buffer-name))
19709 (case (org-element-type element)
19710 (src-block
19711 (if (not arg) (org-edit-src-code)
19712 (let* ((info (org-babel-get-src-block-info))
19713 (lang (nth 0 info))
19714 (params (nth 2 info))
19715 (session (cdr (assq :session params))))
19716 (if (not session) (org-edit-src-code)
19717 ;; At a src-block with a session and function called with
19718 ;; an ARG: switch to the buffer related to the inferior
19719 ;; process.
19720 (funcall (intern (concat "org-babel-prep-session:" lang))
19721 session params)))))
19722 (keyword
19723 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19724 (find-file
19725 (org-remove-double-quotes
19726 (car (org-split-string (org-element-property :value element)))))
19727 (user-error "No special environment to edit here")))
19728 (table
19729 (if (eq (org-element-property :type element) 'table.el)
19730 (org-edit-src-code)
19731 (call-interactively 'org-table-edit-formulas)))
19732 ;; Only Org tables contain `table-row' type elements.
19733 (table-row (call-interactively 'org-table-edit-formulas))
19734 ((example-block export-block) (org-edit-src-code))
19735 (fixed-width (org-edit-fixed-width-region))
19736 (otherwise
19737 ;; No notable element at point. Though, we may be at a link,
19738 ;; which is an object. Thus, scan deeper.
19739 (if (eq (org-element-type (org-element-context element)) 'link)
19740 (call-interactively 'ffap)
19741 (user-error "No special environment to edit here"))))))
19743 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19744 (defun org-ctrl-c-ctrl-c (&optional arg)
19745 "Set tags in headline, or update according to changed information at point.
19747 This command does many different things, depending on context:
19749 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19750 this is what we do.
19752 - If the cursor is on a statistics cookie, update it.
19754 - If the cursor is in a headline, prompt for tags and insert them
19755 into the current line, aligned to `org-tags-column'. When called
19756 with prefix arg, realign all tags in the current buffer.
19758 - If the cursor is in one of the special #+KEYWORD lines, this
19759 triggers scanning the buffer for these lines and updating the
19760 information.
19762 - If the cursor is inside a table, realign the table. This command
19763 works even if the automatic table editor has been turned off.
19765 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19766 the entire table.
19768 - If the cursor is at a footnote reference or definition, jump to
19769 the corresponding definition or references, respectively.
19771 - If the cursor is a the beginning of a dynamic block, update it.
19773 - If the current buffer is a capture buffer, close note and file it.
19775 - If the cursor is on a <<<target>>>, update radio targets and
19776 corresponding links in this buffer.
19778 - If the cursor is on a numbered item in a plain list, renumber the
19779 ordered list.
19781 - If the cursor is on a checkbox, toggle it.
19783 - If the cursor is on a code block, evaluate it. The variable
19784 `org-confirm-babel-evaluate' can be used to control prompting
19785 before code block evaluation, by default every code block
19786 evaluation requires confirmation. Code block evaluation can be
19787 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19788 (interactive "P")
19789 (cond
19790 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19791 org-occur-highlights
19792 org-latex-fragment-image-overlays)
19793 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19794 (org-remove-occur-highlights)
19795 (org-remove-latex-fragment-image-overlays)
19796 (message "Temporary highlights/overlays removed from current buffer"))
19797 ((and (local-variable-p 'org-finish-function (current-buffer))
19798 (fboundp org-finish-function))
19799 (funcall org-finish-function))
19800 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19802 (let* ((context (org-element-context)) (type (org-element-type context)))
19803 ;; Test if point is within a blank line.
19804 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
19805 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19806 (user-error "C-c C-c can do nothing useful at this location"))
19807 ;; For convenience: at the first line of a paragraph on the
19808 ;; same line as an item, apply function on that item instead.
19809 (when (eq type 'paragraph)
19810 (let ((parent (org-element-property :parent context)))
19811 (when (and (eq (org-element-type parent) 'item)
19812 (= (point-at-bol) (org-element-property :begin parent)))
19813 (setq context parent type 'item))))
19814 ;; Act according to type of element or object at point.
19815 (case type
19816 (clock (org-clock-update-time-maybe))
19817 (dynamic-block
19818 (save-excursion
19819 (goto-char (org-element-property :post-affiliated context))
19820 (org-update-dblock)))
19821 (footnote-definition
19822 (goto-char (org-element-property :post-affiliated context))
19823 (call-interactively 'org-footnote-action))
19824 (footnote-reference (call-interactively 'org-footnote-action))
19825 ((headline inlinetask)
19826 (save-excursion (goto-char (org-element-property :begin context))
19827 (call-interactively 'org-set-tags)))
19828 (item
19829 ;; At an item: a double C-u set checkbox to "[-]"
19830 ;; unconditionally, whereas a single one will toggle its
19831 ;; presence. Without an universal argument, if the item
19832 ;; has a checkbox, toggle it. Otherwise repair the list.
19833 (let* ((box (org-element-property :checkbox context))
19834 (struct (org-element-property :structure context))
19835 (old-struct (copy-tree struct))
19836 (parents (org-list-parents-alist struct))
19837 (prevs (org-list-prevs-alist struct))
19838 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19839 (org-list-set-checkbox
19840 (org-element-property :begin context) struct
19841 (cond ((equal arg '(16)) "[-]")
19842 ((and (not box) (equal arg '(4))) "[ ]")
19843 ((or (not box) (equal arg '(4))) nil)
19844 ((eq box 'on) "[ ]")
19845 (t "[X]")))
19846 ;; Mimic `org-list-write-struct' but with grabbing
19847 ;; a return value from `org-list-struct-fix-box'.
19848 (org-list-struct-fix-ind struct parents 2)
19849 (org-list-struct-fix-item-end struct)
19850 (org-list-struct-fix-bul struct prevs)
19851 (org-list-struct-fix-ind struct parents)
19852 (let ((block-item
19853 (org-list-struct-fix-box struct parents prevs orderedp)))
19854 (if (and box (equal struct old-struct))
19855 (if (equal arg '(16))
19856 (message "Checkboxes already reset")
19857 (user-error "Cannot toggle this checkbox: %s"
19858 (if (eq box 'on)
19859 "all subitems checked"
19860 "unchecked subitems")))
19861 (org-list-struct-apply-struct struct old-struct)
19862 (org-update-checkbox-count-maybe))
19863 (when block-item
19864 (message "Checkboxes were removed due to empty box at line %d"
19865 (org-current-line block-item))))))
19866 (keyword
19867 (let ((org-inhibit-startup-visibility-stuff t)
19868 (org-startup-align-all-tables nil))
19869 (when (boundp 'org-table-coordinate-overlays)
19870 (mapc 'delete-overlay org-table-coordinate-overlays)
19871 (setq org-table-coordinate-overlays nil))
19872 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19873 (message "Local setup has been refreshed"))
19874 (plain-list
19875 ;; At a plain list, with a double C-u argument, set
19876 ;; checkboxes of each item to "[-]", whereas a single one
19877 ;; will toggle their presence according to the state of the
19878 ;; first item in the list. Without an argument, repair the
19879 ;; list.
19880 (let* ((begin (org-element-property :contents-begin context))
19881 (struct (org-element-property :structure context))
19882 (old-struct (copy-tree struct))
19883 (first-box (save-excursion
19884 (goto-char begin)
19885 (looking-at org-list-full-item-re)
19886 (match-string-no-properties 3)))
19887 (new-box (cond ((equal arg '(16)) "[-]")
19888 ((equal arg '(4)) (unless first-box "[ ]"))
19889 ((equal first-box "[X]") "[ ]")
19890 (t "[X]"))))
19891 (cond
19892 (arg
19893 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19894 (org-list-get-all-items
19895 begin struct (org-list-prevs-alist struct))))
19896 ((and first-box (eq (point) begin))
19897 ;; For convenience, when point is at bol on the first
19898 ;; item of the list and no argument is provided, simply
19899 ;; toggle checkbox of that item, if any.
19900 (org-list-set-checkbox begin struct new-box)))
19901 (org-list-write-struct
19902 struct (org-list-parents-alist struct) old-struct)
19903 (org-update-checkbox-count-maybe)
19904 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19905 ((property-drawer node-property)
19906 (call-interactively 'org-property-action))
19907 ((radio-target target)
19908 (call-interactively 'org-update-radio-target-regexp))
19909 (statistics-cookie
19910 (call-interactively 'org-update-statistics-cookies))
19911 ((table table-cell table-row)
19912 ;; At a table, recalculate every field and align it. Also
19913 ;; send the table if necessary. If the table has
19914 ;; a `table.el' type, just give up. At a table row or
19915 ;; cell, maybe recalculate line but always align table.
19916 (if (eq (org-element-property :type context) 'table.el)
19917 (message "Use C-c ' to edit table.el tables")
19918 (let ((org-enable-table-editor t))
19919 (if (or (eq type 'table)
19920 ;; Check if point is at a TBLFM line.
19921 (and (eq type 'table-row)
19922 (= (point) (org-element-property :end context))))
19923 (save-excursion
19924 (goto-char (org-element-property :contents-begin context))
19925 (org-call-with-arg 'org-table-recalculate (or arg t))
19926 (orgtbl-send-table 'maybe))
19927 (org-table-maybe-eval-formula)
19928 (cond (arg (call-interactively 'org-table-recalculate))
19929 ((org-table-maybe-recalculate-line))
19930 (t (org-table-align)))))))
19931 (timestamp (org-timestamp-change 0 'day))
19932 (otherwise
19933 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19934 (user-error
19935 "C-c C-c can do nothing useful at this location")))))))))
19937 (defun org-mode-restart ()
19938 "Restart Org-mode, to scan again for special lines.
19939 Also updates the keyword regular expressions."
19940 (interactive)
19941 (org-mode)
19942 (message "Org-mode restarted"))
19944 (defun org-kill-note-or-show-branches ()
19945 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19946 (interactive)
19947 (if (not org-finish-function)
19948 (progn
19949 (hide-subtree)
19950 (call-interactively 'show-branches))
19951 (let ((org-note-abort t))
19952 (funcall org-finish-function))))
19954 (defun org-return (&optional indent)
19955 "Goto next table row or insert a newline.
19956 Calls `org-table-next-row' or `newline', depending on context.
19957 See the individual commands for more information."
19958 (interactive)
19959 (let (org-ts-what)
19960 (cond
19961 ((or (bobp) (org-in-src-block-p))
19962 (if indent (newline-and-indent) (newline)))
19963 ((org-at-table-p)
19964 (org-table-justify-field-maybe)
19965 (call-interactively 'org-table-next-row))
19966 ;; when `newline-and-indent' is called within a list, make sure
19967 ;; text moved stays inside the item.
19968 ((and (org-in-item-p) indent)
19969 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19970 (progn
19971 (save-match-data (newline))
19972 (org-indent-line-to (length (match-string 0))))
19973 (let ((ind (org-get-indentation)))
19974 (newline)
19975 (if (org-looking-back org-list-end-re)
19976 (org-indent-line)
19977 (org-indent-line-to ind)))))
19978 ((and org-return-follows-link
19979 (org-at-timestamp-p t)
19980 (not (eq org-ts-what 'after)))
19981 (org-follow-timestamp-link))
19982 ((and org-return-follows-link
19983 (let ((tprop (get-text-property (point) 'face)))
19984 (or (eq tprop 'org-link)
19985 (and (listp tprop) (memq 'org-link tprop)))))
19986 (call-interactively 'org-open-at-point))
19987 ((and (org-at-heading-p)
19988 (looking-at
19989 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19990 (org-show-entry)
19991 (end-of-line 1)
19992 (newline))
19993 (t (if indent (newline-and-indent) (newline))))))
19995 (defun org-return-indent ()
19996 "Goto next table row or insert a newline and indent.
19997 Calls `org-table-next-row' or `newline-and-indent', depending on
19998 context. See the individual commands for more information."
19999 (interactive)
20000 (org-return t))
20002 (defun org-ctrl-c-star ()
20003 "Compute table, or change heading status of lines.
20004 Calls `org-table-recalculate' or `org-toggle-heading',
20005 depending on context."
20006 (interactive)
20007 (cond
20008 ((org-at-table-p)
20009 (call-interactively 'org-table-recalculate))
20011 ;; Convert all lines in region to list items
20012 (call-interactively 'org-toggle-heading))))
20014 (defun org-ctrl-c-minus ()
20015 "Insert separator line in table or modify bullet status of line.
20016 Also turns a plain line or a region of lines into list items.
20017 Calls `org-table-insert-hline', `org-toggle-item', or
20018 `org-cycle-list-bullet', depending on context."
20019 (interactive)
20020 (cond
20021 ((org-at-table-p)
20022 (call-interactively 'org-table-insert-hline))
20023 ((org-region-active-p)
20024 (call-interactively 'org-toggle-item))
20025 ((org-in-item-p)
20026 (call-interactively 'org-cycle-list-bullet))
20028 (call-interactively 'org-toggle-item))))
20030 (defun org-toggle-item (arg)
20031 "Convert headings or normal lines to items, items to normal lines.
20032 If there is no active region, only the current line is considered.
20034 If the first non blank line in the region is a headline, convert
20035 all headlines to items, shifting text accordingly.
20037 If it is an item, convert all items to normal lines.
20039 If it is normal text, change region into a list of items.
20040 With a prefix argument ARG, change the region in a single item."
20041 (interactive "P")
20042 (let ((shift-text
20043 (function
20044 ;; Shift text in current section to IND, from point to END.
20045 ;; The function leaves point to END line.
20046 (lambda (ind end)
20047 (let ((min-i 1000) (end (copy-marker end)))
20048 ;; First determine the minimum indentation (MIN-I) of
20049 ;; the text.
20050 (save-excursion
20051 (catch 'exit
20052 (while (< (point) end)
20053 (let ((i (org-get-indentation)))
20054 (cond
20055 ;; Skip blank lines and inline tasks.
20056 ((looking-at "^[ \t]*$"))
20057 ((looking-at org-outline-regexp-bol))
20058 ;; We can't find less than 0 indentation.
20059 ((zerop i) (throw 'exit (setq min-i 0)))
20060 ((< i min-i) (setq min-i i))))
20061 (forward-line))))
20062 ;; Then indent each line so that a line indented to
20063 ;; MIN-I becomes indented to IND. Ignore blank lines
20064 ;; and inline tasks in the process.
20065 (let ((delta (- ind min-i)))
20066 (while (< (point) end)
20067 (unless (or (looking-at "^[ \t]*$")
20068 (looking-at org-outline-regexp-bol))
20069 (org-indent-line-to (+ (org-get-indentation) delta)))
20070 (forward-line)))))))
20071 (skip-blanks
20072 (function
20073 ;; Return beginning of first non-blank line, starting from
20074 ;; line at POS.
20075 (lambda (pos)
20076 (save-excursion
20077 (goto-char pos)
20078 (skip-chars-forward " \r\t\n")
20079 (point-at-bol)))))
20080 beg end)
20081 ;; Determine boundaries of changes.
20082 (if (org-region-active-p)
20083 (setq beg (funcall skip-blanks (region-beginning))
20084 end (copy-marker (region-end)))
20085 (setq beg (funcall skip-blanks (point-at-bol))
20086 end (copy-marker (point-at-eol))))
20087 ;; Depending on the starting line, choose an action on the text
20088 ;; between BEG and END.
20089 (org-with-limited-levels
20090 (save-excursion
20091 (goto-char beg)
20092 (cond
20093 ;; Case 1. Start at an item: de-itemize. Note that it only
20094 ;; happens when a region is active: `org-ctrl-c-minus'
20095 ;; would call `org-cycle-list-bullet' otherwise.
20096 ((org-at-item-p)
20097 (while (< (point) end)
20098 (when (org-at-item-p)
20099 (skip-chars-forward " \t")
20100 (delete-region (point) (match-end 0)))
20101 (forward-line)))
20102 ;; Case 2. Start at an heading: convert to items.
20103 ((org-at-heading-p)
20104 (let* ((bul (org-list-bullet-string "-"))
20105 (bul-len (length bul))
20106 ;; Indentation of the first heading. It should be
20107 ;; relative to the indentation of its parent, if any.
20108 (start-ind (save-excursion
20109 (cond
20110 ((not org-adapt-indentation) 0)
20111 ((not (outline-previous-heading)) 0)
20112 (t (length (match-string 0))))))
20113 ;; Level of first heading. Further headings will be
20114 ;; compared to it to determine hierarchy in the list.
20115 (ref-level (org-reduced-level (org-outline-level))))
20116 (while (< (point) end)
20117 (let* ((level (org-reduced-level (org-outline-level)))
20118 (delta (max 0 (- level ref-level))))
20119 ;; If current headline is less indented than the first
20120 ;; one, set it as reference, in order to preserve
20121 ;; subtrees.
20122 (when (< level ref-level) (setq ref-level level))
20123 (replace-match bul t t)
20124 (org-indent-line-to (+ start-ind (* delta bul-len)))
20125 ;; Ensure all text down to END (or SECTION-END) belongs
20126 ;; to the newly created item.
20127 (let ((section-end (save-excursion
20128 (or (outline-next-heading) (point)))))
20129 (forward-line)
20130 (funcall shift-text
20131 (+ start-ind (* (1+ delta) bul-len))
20132 (min end section-end)))))))
20133 ;; Case 3. Normal line with ARG: make the first line of region
20134 ;; an item, and shift indentation of others lines to
20135 ;; set them as item's body.
20136 (arg (let* ((bul (org-list-bullet-string "-"))
20137 (bul-len (length bul))
20138 (ref-ind (org-get-indentation)))
20139 (skip-chars-forward " \t")
20140 (insert bul)
20141 (forward-line)
20142 (while (< (point) end)
20143 ;; Ensure that lines less indented than first one
20144 ;; still get included in item body.
20145 (funcall shift-text
20146 (+ ref-ind bul-len)
20147 (min end (save-excursion (or (outline-next-heading)
20148 (point)))))
20149 (forward-line))))
20150 ;; Case 4. Normal line without ARG: turn each non-item line
20151 ;; into an item.
20153 (while (< (point) end)
20154 (unless (or (org-at-heading-p) (org-at-item-p))
20155 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20156 (replace-match
20157 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20158 (forward-line))))))))
20160 (defun org-toggle-heading (&optional nstars)
20161 "Convert headings to normal text, or items or text to headings.
20162 If there is no active region, only convert the current line.
20164 With a \\[universal-argument] prefix, convert the whole list at
20165 point into heading.
20167 In a region:
20169 - If the first non blank line is a headline, remove the stars
20170 from all headlines in the region.
20172 - If it is a normal line, turn each and every normal line (i.e.,
20173 not an heading or an item) in the region into headings. If you
20174 want to convert only the first line of this region, use one
20175 universal prefix argument.
20177 - If it is a plain list item, turn all plain list items into headings.
20179 When converting a line into a heading, the number of stars is chosen
20180 such that the lines become children of the current entry. However,
20181 when a numeric prefix argument is given, its value determines the
20182 number of stars to add."
20183 (interactive "P")
20184 (let ((skip-blanks
20185 (function
20186 ;; Return beginning of first non-blank line, starting from
20187 ;; line at POS.
20188 (lambda (pos)
20189 (save-excursion
20190 (goto-char pos)
20191 (while (org-at-comment-p) (forward-line))
20192 (skip-chars-forward " \r\t\n")
20193 (point-at-bol)))))
20194 beg end toggled)
20195 ;; Determine boundaries of changes. If a universal prefix has
20196 ;; been given, put the list in a region. If region ends at a bol,
20197 ;; do not consider the last line to be in the region.
20199 (when (and current-prefix-arg (org-at-item-p))
20200 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20201 (org-mark-element))
20203 (if (org-region-active-p)
20204 (setq beg (funcall skip-blanks (region-beginning))
20205 end (copy-marker (save-excursion
20206 (goto-char (region-end))
20207 (if (bolp) (point) (point-at-eol)))))
20208 (setq beg (funcall skip-blanks (point-at-bol))
20209 end (copy-marker (point-at-eol))))
20210 ;; Ensure inline tasks don't count as headings.
20211 (org-with-limited-levels
20212 (save-excursion
20213 (goto-char beg)
20214 (cond
20215 ;; Case 1. Started at an heading: de-star headings.
20216 ((org-at-heading-p)
20217 (while (< (point) end)
20218 (when (org-at-heading-p t)
20219 (looking-at org-outline-regexp) (replace-match "")
20220 (setq toggled t))
20221 (forward-line)))
20222 ;; Case 2. Started at an item: change items into headlines.
20223 ;; One star will be added by `org-list-to-subtree'.
20224 ((org-at-item-p)
20225 (let* ((stars (make-string
20226 ;; subtract the star that will be added again by
20227 ;; `org-list-to-subtree'
20228 (if (numberp nstars) (1- nstars)
20229 (or (org-current-level) 0))
20230 ?*))
20231 (add-stars
20232 (cond (nstars "") ; stars from prefix only
20233 ((equal stars "") "") ; before first heading
20234 (org-odd-levels-only "*") ; inside heading, odd
20235 (t "")))) ; inside heading, oddeven
20236 (while (< (point) end)
20237 (when (org-at-item-p)
20238 ;; Pay attention to cases when region ends before list.
20239 (let* ((struct (org-list-struct))
20240 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20241 (save-restriction
20242 (narrow-to-region (point) list-end)
20243 (insert
20244 (org-list-to-subtree
20245 (org-list-parse-list t)
20246 '(:istart (concat stars add-stars (funcall get-stars depth))
20247 :icount (concat stars add-stars (funcall get-stars depth)))))))
20248 (setq toggled t))
20249 (forward-line))))
20250 ;; Case 3. Started at normal text: make every line an heading,
20251 ;; skipping headlines and items.
20252 (t (let* ((stars
20253 (make-string
20254 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20255 (add-stars
20256 (cond (nstars "") ; stars from prefix only
20257 ((equal stars "") "*") ; before first heading
20258 (org-odd-levels-only "**") ; inside heading, odd
20259 (t "*"))) ; inside heading, oddeven
20260 (rpl (concat stars add-stars " "))
20261 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20262 (while (< (point) (if (equal nstars '(4)) lend end))
20263 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20264 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20265 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20266 (forward-line)))))))
20267 (unless toggled (message "Cannot toggle heading from here"))))
20269 (defun org-meta-return (&optional arg)
20270 "Insert a new heading or wrap a region in a table.
20271 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20272 See the individual commands for more information."
20273 (interactive "P")
20274 (cond
20275 ((run-hook-with-args-until-success 'org-metareturn-hook))
20276 ((or (org-at-drawer-p) (org-at-property-p))
20277 (newline-and-indent))
20278 ((org-at-table-p)
20279 (call-interactively 'org-table-wrap-region))
20280 (t (call-interactively 'org-insert-heading))))
20282 ;;; Menu entries
20284 (defsubst org-in-subtree-not-table-p ()
20285 "Are we in a subtree and not in a table?"
20286 (and (not (org-before-first-heading-p))
20287 (not (org-at-table-p))))
20289 ;; Define the Org-mode menus
20290 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20291 '("Tbl"
20292 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20293 ["Next Field" org-cycle (org-at-table-p)]
20294 ["Previous Field" org-shifttab (org-at-table-p)]
20295 ["Next Row" org-return (org-at-table-p)]
20296 "--"
20297 ["Blank Field" org-table-blank-field (org-at-table-p)]
20298 ["Edit Field" org-table-edit-field (org-at-table-p)]
20299 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20300 "--"
20301 ("Column"
20302 ["Move Column Left" org-metaleft (org-at-table-p)]
20303 ["Move Column Right" org-metaright (org-at-table-p)]
20304 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20305 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20306 ("Row"
20307 ["Move Row Up" org-metaup (org-at-table-p)]
20308 ["Move Row Down" org-metadown (org-at-table-p)]
20309 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20310 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20311 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20312 "--"
20313 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20314 ("Rectangle"
20315 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20316 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20317 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20318 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20319 "--"
20320 ("Calculate"
20321 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20322 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20323 ["Edit Formulas" org-edit-special (org-at-table-p)]
20324 "--"
20325 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20326 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20327 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20328 "--"
20329 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20330 "--"
20331 ["Sum Column/Rectangle" org-table-sum
20332 (or (org-at-table-p) (org-region-active-p))]
20333 ["Which Column?" org-table-current-column (org-at-table-p)])
20334 ["Debug Formulas"
20335 org-table-toggle-formula-debugger
20336 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20337 ["Show Col/Row Numbers"
20338 org-table-toggle-coordinate-overlays
20339 :style toggle
20340 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20341 "--"
20342 ["Create" org-table-create (and (not (org-at-table-p))
20343 org-enable-table-editor)]
20344 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20345 ["Import from File" org-table-import (not (org-at-table-p))]
20346 ["Export to File" org-table-export (org-at-table-p)]
20347 "--"
20348 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20350 (easy-menu-define org-org-menu org-mode-map "Org menu"
20351 '("Org"
20352 ("Show/Hide"
20353 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20354 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20355 ["Sparse Tree..." org-sparse-tree t]
20356 ["Reveal Context" org-reveal t]
20357 ["Show All" show-all t]
20358 "--"
20359 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20360 "--"
20361 ["New Heading" org-insert-heading t]
20362 ("Navigate Headings"
20363 ["Up" outline-up-heading t]
20364 ["Next" outline-next-visible-heading t]
20365 ["Previous" outline-previous-visible-heading t]
20366 ["Next Same Level" outline-forward-same-level t]
20367 ["Previous Same Level" outline-backward-same-level t]
20368 "--"
20369 ["Jump" org-goto t])
20370 ("Edit Structure"
20371 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20372 "--"
20373 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20374 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20375 "--"
20376 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20377 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20378 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20379 "--"
20380 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20381 "--"
20382 ["Copy visible text" org-copy-visible t]
20383 "--"
20384 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20385 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20386 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20387 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20388 "--"
20389 ["Sort Region/Children" org-sort t]
20390 "--"
20391 ["Convert to odd levels" org-convert-to-odd-levels t]
20392 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20393 ("Editing"
20394 ["Emphasis..." org-emphasize t]
20395 ["Edit Source Example" org-edit-special t]
20396 "--"
20397 ["Footnote new/jump" org-footnote-action t]
20398 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20399 ("Archive"
20400 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20401 "--"
20402 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20403 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20404 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20406 "--"
20407 ("Hyperlinks"
20408 ["Store Link (Global)" org-store-link t]
20409 ["Find existing link to here" org-occur-link-in-agenda-files t]
20410 ["Insert Link" org-insert-link t]
20411 ["Follow Link" org-open-at-point t]
20412 "--"
20413 ["Next link" org-next-link t]
20414 ["Previous link" org-previous-link t]
20415 "--"
20416 ["Descriptive Links"
20417 org-toggle-link-display
20418 :style radio
20419 :selected org-descriptive-links
20421 ["Literal Links"
20422 org-toggle-link-display
20423 :style radio
20424 :selected (not org-descriptive-links)])
20425 "--"
20426 ("TODO Lists"
20427 ["TODO/DONE/-" org-todo t]
20428 ("Select keyword"
20429 ["Next keyword" org-shiftright (org-at-heading-p)]
20430 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20431 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20432 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20433 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20434 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20435 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20436 "--"
20437 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20438 :selected org-enforce-todo-dependencies :style toggle :active t]
20439 "Settings for tree at point"
20440 ["Do Children sequentially" org-toggle-ordered-property :style radio
20441 :selected (org-entry-get nil "ORDERED")
20442 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20443 ["Do Children parallel" org-toggle-ordered-property :style radio
20444 :selected (not (org-entry-get nil "ORDERED"))
20445 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20446 "--"
20447 ["Set Priority" org-priority t]
20448 ["Priority Up" org-shiftup t]
20449 ["Priority Down" org-shiftdown t]
20450 "--"
20451 ["Get news from all feeds" org-feed-update-all t]
20452 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20453 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20454 ("TAGS and Properties"
20455 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20456 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20457 "--"
20458 ["Set property" org-set-property (not (org-before-first-heading-p))]
20459 ["Column view of properties" org-columns t]
20460 ["Insert Column View DBlock" org-insert-columns-dblock t])
20461 ("Dates and Scheduling"
20462 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20463 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20464 ("Change Date"
20465 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20466 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20467 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20468 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20469 ["Compute Time Range" org-evaluate-time-range t]
20470 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20471 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20472 "--"
20473 ["Custom time format" org-toggle-time-stamp-overlays
20474 :style radio :selected org-display-custom-times]
20475 "--"
20476 ["Goto Calendar" org-goto-calendar t]
20477 ["Date from Calendar" org-date-from-calendar t]
20478 "--"
20479 ["Start/Restart Timer" org-timer-start t]
20480 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20481 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20482 ["Insert Timer String" org-timer t]
20483 ["Insert Timer Item" org-timer-item t])
20484 ("Logging work"
20485 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20486 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20487 ["Clock out" org-clock-out t]
20488 ["Clock cancel" org-clock-cancel t]
20489 "--"
20490 ["Mark as default task" org-clock-mark-default-task t]
20491 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20492 ["Goto running clock" org-clock-goto t]
20493 "--"
20494 ["Display times" org-clock-display t]
20495 ["Create clock table" org-clock-report t]
20496 "--"
20497 ["Record DONE time"
20498 (progn (setq org-log-done (not org-log-done))
20499 (message "Switching to %s will %s record a timestamp"
20500 (car org-done-keywords)
20501 (if org-log-done "automatically" "not")))
20502 :style toggle :selected org-log-done])
20503 "--"
20504 ["Agenda Command..." org-agenda t]
20505 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20506 ("File List for Agenda")
20507 ("Special views current file"
20508 ["TODO Tree" org-show-todo-tree t]
20509 ["Check Deadlines" org-check-deadlines t]
20510 ["Timeline" org-timeline t]
20511 ["Tags/Property tree" org-match-sparse-tree t])
20512 "--"
20513 ["Export/Publish..." org-export-dispatch t]
20514 ("LaTeX"
20515 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20516 :selected org-cdlatex-mode]
20517 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20518 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20519 ["Modify math symbol" org-cdlatex-math-modify
20520 (org-inside-LaTeX-fragment-p)]
20521 ["Insert citation" org-reftex-citation t]
20522 "--"
20523 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20524 "--"
20525 ("MobileOrg"
20526 ["Push Files and Views" org-mobile-push t]
20527 ["Get Captured and Flagged" org-mobile-pull t]
20528 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20529 "--"
20530 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20531 "--"
20532 ("Documentation"
20533 ["Show Version" org-version t]
20534 ["Info Documentation" org-info t])
20535 ("Customize"
20536 ["Browse Org Group" org-customize t]
20537 "--"
20538 ["Expand This Menu" org-create-customize-menu
20539 (fboundp 'customize-menu-create)])
20540 ["Send bug report" org-submit-bug-report t]
20541 "--"
20542 ("Refresh/Reload"
20543 ["Refresh setup current buffer" org-mode-restart t]
20544 ["Reload Org (after update)" org-reload t]
20545 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20548 (defun org-info (&optional node)
20549 "Read documentation for Org-mode in the info system.
20550 With optional NODE, go directly to that node."
20551 (interactive)
20552 (info (format "(org)%s" (or node ""))))
20554 ;;;###autoload
20555 (defun org-submit-bug-report ()
20556 "Submit a bug report on Org-mode via mail.
20558 Don't hesitate to report any problems or inaccurate documentation.
20560 If you don't have setup sending mail from (X)Emacs, please copy the
20561 output buffer into your mail program, as it gives us important
20562 information about your Org-mode version and configuration."
20563 (interactive)
20564 (require 'reporter)
20565 (org-load-modules-maybe)
20566 (org-require-autoloaded-modules)
20567 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20568 (reporter-submit-bug-report
20569 "emacs-orgmode@gnu.org"
20570 (org-version nil 'full)
20571 (let (list)
20572 (save-window-excursion
20573 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20574 (delete-other-windows)
20575 (erase-buffer)
20576 (insert "You are about to submit a bug report to the Org-mode mailing list.
20578 We would like to add your full Org-mode and Outline configuration to the
20579 bug report. This greatly simplifies the work of the maintainer and
20580 other experts on the mailing list.
20582 HOWEVER, some variables you have customized may contain private
20583 information. The names of customers, colleagues, or friends, might
20584 appear in the form of file names, tags, todo states, or search strings.
20585 If you answer yes to the prompt, you might want to check and remove
20586 such private information before sending the email.")
20587 (add-text-properties (point-min) (point-max) '(face org-warning))
20588 (when (yes-or-no-p "Include your Org-mode configuration ")
20589 (mapatoms
20590 (lambda (v)
20591 (and (boundp v)
20592 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20593 (or (and (symbol-value v)
20594 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20595 (and
20596 (get v 'custom-type) (get v 'standard-value)
20597 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20598 (push v list)))))
20599 (kill-buffer (get-buffer "*Warn about privacy*"))
20600 list))
20601 nil nil
20602 "Remember to cover the basics, that is, what you expected to happen and
20603 what in fact did happen. You don't know how to make a good report? See
20605 http://orgmode.org/manual/Feedback.html#Feedback
20607 Your bug report will be posted to the Org-mode mailing list.
20608 ------------------------------------------------------------------------")
20609 (save-excursion
20610 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20611 (replace-match "\\1Bug: \\3 [\\2]")))))
20614 (defun org-install-agenda-files-menu ()
20615 (let ((bl (buffer-list)))
20616 (save-excursion
20617 (while bl
20618 (set-buffer (pop bl))
20619 (if (derived-mode-p 'org-mode) (setq bl nil)))
20620 (when (derived-mode-p 'org-mode)
20621 (easy-menu-change
20622 '("Org") "File List for Agenda"
20623 (append
20624 (list
20625 ["Edit File List" (org-edit-agenda-file-list) t]
20626 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20627 ["Remove Current File from List" org-remove-file t]
20628 ["Cycle through agenda files" org-cycle-agenda-files t]
20629 ["Occur in all agenda files" org-occur-in-agenda-files t]
20630 "--")
20631 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20633 ;;;; Documentation
20635 (defun org-require-autoloaded-modules ()
20636 (interactive)
20637 (mapc 'require
20638 '(org-agenda org-archive org-attach org-clock org-colview org-id
20639 org-remember org-table org-timer)))
20641 ;;;###autoload
20642 (defun org-reload (&optional uncompiled)
20643 "Reload all org lisp files.
20644 With prefix arg UNCOMPILED, load the uncompiled versions."
20645 (interactive "P")
20646 (require 'loadhist)
20647 (let* ((org-dir (org-find-library-dir "org"))
20648 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20649 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20650 (remove-re (mapconcat 'identity
20651 (mapcar (lambda (f) (concat "^" f "$"))
20652 (list (if (featurep 'xemacs)
20653 "org-colview"
20654 "org-colview-xemacs")
20655 "org" "org-loaddefs" "org-version"))
20656 "\\|"))
20657 (feats (delete-dups
20658 (mapcar 'file-name-sans-extension
20659 (mapcar 'file-name-nondirectory
20660 (delq nil
20661 (mapcar 'feature-file
20662 features))))))
20663 (lfeat (append
20664 (sort
20665 (setq feats
20666 (delq nil (mapcar
20667 (lambda (f)
20668 (if (and (string-match feature-re f)
20669 (not (string-match remove-re f)))
20670 f nil))
20671 feats)))
20672 'string-lessp)
20673 (list "org-version" "org")))
20674 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20675 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20676 load-uncore load-misses)
20677 (setq load-misses
20678 (delq 't
20679 (mapcar (lambda (f)
20680 (or (org-load-noerror-mustsuffix (concat org-dir f))
20681 (and (string= org-dir contrib-dir)
20682 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20683 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20684 (add-to-list 'load-uncore f 'append)
20687 lfeat)))
20688 (if load-uncore
20689 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20690 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20691 (if load-misses
20692 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20693 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20694 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20696 ;;;###autoload
20697 (defun org-customize ()
20698 "Call the customize function with org as argument."
20699 (interactive)
20700 (org-load-modules-maybe)
20701 (org-require-autoloaded-modules)
20702 (customize-browse 'org))
20704 (defun org-create-customize-menu ()
20705 "Create a full customization menu for Org-mode, insert it into the menu."
20706 (interactive)
20707 (org-load-modules-maybe)
20708 (org-require-autoloaded-modules)
20709 (if (fboundp 'customize-menu-create)
20710 (progn
20711 (easy-menu-change
20712 '("Org") "Customize"
20713 `(["Browse Org group" org-customize t]
20714 "--"
20715 ,(customize-menu-create 'org)
20716 ["Set" Custom-set t]
20717 ["Save" Custom-save t]
20718 ["Reset to Current" Custom-reset-current t]
20719 ["Reset to Saved" Custom-reset-saved t]
20720 ["Reset to Standard Settings" Custom-reset-standard t]))
20721 (message "\"Org\"-menu now contains full customization menu"))
20722 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20724 ;;;; Miscellaneous stuff
20726 ;;; Generally useful functions
20728 (defun org-get-at-bol (property)
20729 "Get text property PROPERTY at beginning of line."
20730 (get-text-property (point-at-bol) property))
20732 (defun org-find-text-property-in-string (prop s)
20733 "Return the first non-nil value of property PROP in string S."
20734 (or (get-text-property 0 prop s)
20735 (get-text-property (or (next-single-property-change 0 prop s) 0)
20736 prop s)))
20738 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20739 "Display the given MESSAGE as a warning."
20740 (if (fboundp 'display-warning)
20741 (display-warning 'org message
20742 (if (featurep 'xemacs) 'warning :warning))
20743 (let ((buf (get-buffer-create "*Org warnings*")))
20744 (with-current-buffer buf
20745 (goto-char (point-max))
20746 (insert "Warning (Org): " message)
20747 (unless (bolp)
20748 (newline)))
20749 (display-buffer buf)
20750 (sit-for 0))))
20752 (defun org-eval (form)
20753 "Eval FORM and return result."
20754 (condition-case error
20755 (eval form)
20756 (error (format "%%![Error: %s]" error))))
20758 (defun org-in-clocktable-p ()
20759 "Check if the cursor is in a clocktable."
20760 (let ((pos (point)) start)
20761 (save-excursion
20762 (end-of-line 1)
20763 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20764 (setq start (match-beginning 0))
20765 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20766 (>= (match-end 0) pos)
20767 start))))
20769 (defun org-in-commented-line ()
20770 "Is point in a line starting with `#'?"
20771 (equal (char-after (point-at-bol)) ?#))
20773 (defun org-in-indented-comment-line ()
20774 "Is point in a line starting with `#' after some white space?"
20775 (save-excursion
20776 (save-match-data
20777 (goto-char (point-at-bol))
20778 (looking-at "[ \t]*#"))))
20780 (defun org-in-verbatim-emphasis ()
20781 (save-match-data
20782 (and (org-in-regexp org-emph-re 2)
20783 (>= (point) (match-beginning 3))
20784 (<= (point) (match-end 4))
20785 (member (match-string 3) '("=" "~")))))
20787 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20788 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20789 (if (and marker (marker-buffer marker)
20790 (buffer-live-p (marker-buffer marker)))
20791 (progn
20792 (org-pop-to-buffer-same-window (marker-buffer marker))
20793 (if (or (> marker (point-max)) (< marker (point-min)))
20794 (widen))
20795 (goto-char marker)
20796 (org-show-context 'org-goto))
20797 (if bookmark
20798 (bookmark-jump bookmark)
20799 (error "Cannot find location"))))
20801 (defun org-quote-csv-field (s)
20802 "Quote field for inclusion in CSV material."
20803 (if (string-match "[\",]" s)
20804 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20807 (defun org-force-self-insert (N)
20808 "Needed to enforce self-insert under remapping."
20809 (interactive "p")
20810 (self-insert-command N))
20812 (defun org-string-width (s)
20813 "Compute width of string, ignoring invisible characters.
20814 This ignores character with invisibility property `org-link', and also
20815 characters with property `org-cwidth', because these will become invisible
20816 upon the next fontification round."
20817 (let (b l)
20818 (when (or (eq t buffer-invisibility-spec)
20819 (assq 'org-link buffer-invisibility-spec))
20820 (while (setq b (text-property-any 0 (length s)
20821 'invisible 'org-link s))
20822 (setq s (concat (substring s 0 b)
20823 (substring s (or (next-single-property-change
20824 b 'invisible s) (length s)))))))
20825 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20826 (setq s (concat (substring s 0 b)
20827 (substring s (or (next-single-property-change
20828 b 'org-cwidth s) (length s))))))
20829 (setq l (string-width s) b -1)
20830 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20831 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20834 (defun org-shorten-string (s maxlength)
20835 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20836 If the string is shorter or has length MAXLENGTH, just return the
20837 original string. If it is longer, the functions finds a space in the
20838 string, breaks this string off at that locations and adds three dots
20839 as ellipsis. Including the ellipsis, the string will not be longer
20840 than MAXLENGTH. If finding a good breaking point in the string does
20841 not work, the string is just chopped off in the middle of a word
20842 if necessary."
20843 (if (<= (length s) maxlength)
20845 (let* ((n (max (- maxlength 4) 1))
20846 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20847 (if (string-match re s)
20848 (concat (match-string 1 s) "...")
20849 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20851 (defun org-get-indentation (&optional line)
20852 "Get the indentation of the current line, interpreting tabs.
20853 When LINE is given, assume it represents a line and compute its indentation."
20854 (if line
20855 (if (string-match "^ *" (org-remove-tabs line))
20856 (match-end 0))
20857 (save-excursion
20858 (beginning-of-line 1)
20859 (skip-chars-forward " \t")
20860 (current-column))))
20862 (defun org-get-string-indentation (s)
20863 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20864 (let ((n -1) (i 0) (w tab-width) c)
20865 (catch 'exit
20866 (while (< (setq n (1+ n)) (length s))
20867 (setq c (aref s n))
20868 (cond ((= c ?\ ) (setq i (1+ i)))
20869 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20870 (t (throw 'exit t)))))
20873 (defun org-remove-tabs (s &optional width)
20874 "Replace tabulators in S with spaces.
20875 Assumes that s is a single line, starting in column 0."
20876 (setq width (or width tab-width))
20877 (while (string-match "\t" s)
20878 (setq s (replace-match
20879 (make-string
20880 (- (* width (/ (+ (match-beginning 0) width) width))
20881 (match-beginning 0)) ?\ )
20882 t t s)))
20885 (defun org-fix-indentation (line ind)
20886 "Fix indentation in LINE.
20887 IND is a cons cell with target and minimum indentation.
20888 If the current indentation in LINE is smaller than the minimum,
20889 leave it alone. If it is larger than ind, set it to the target."
20890 (let* ((l (org-remove-tabs line))
20891 (i (org-get-indentation l))
20892 (i1 (car ind)) (i2 (cdr ind)))
20893 (if (>= i i2) (setq l (substring line i2)))
20894 (if (> i1 0)
20895 (concat (make-string i1 ?\ ) l)
20896 l)))
20898 (defun org-remove-indentation (code &optional n)
20899 "Remove the maximum common indentation from the lines in CODE.
20900 N may optionally be the number of spaces to remove."
20901 (with-temp-buffer
20902 (insert code)
20903 (org-do-remove-indentation n)
20904 (buffer-string)))
20906 (defun org-do-remove-indentation (&optional n)
20907 "Remove the maximum common indentation from the buffer."
20908 (untabify (point-min) (point-max))
20909 (let ((min 10000) re)
20910 (if n
20911 (setq min n)
20912 (goto-char (point-min))
20913 (while (re-search-forward "^ *[^ \n]" nil t)
20914 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20915 (unless (or (= min 0) (= min 10000))
20916 (setq re (format "^ \\{%d\\}" min))
20917 (goto-char (point-min))
20918 (while (re-search-forward re nil t)
20919 (replace-match "")
20920 (end-of-line 1))
20921 min)))
20923 (defun org-fill-template (template alist)
20924 "Find each %key of ALIST in TEMPLATE and replace it."
20925 (let ((case-fold-search nil)
20926 entry key value)
20927 (setq alist (sort (copy-sequence alist)
20928 (lambda (a b) (< (length (car a)) (length (car b))))))
20929 (while (setq entry (pop alist))
20930 (setq template
20931 (replace-regexp-in-string
20932 (concat "%" (regexp-quote (car entry)))
20933 (or (cdr entry) "") template t t)))
20934 template))
20936 (defun org-base-buffer (buffer)
20937 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20938 (if (not buffer)
20939 buffer
20940 (or (buffer-base-buffer buffer)
20941 buffer)))
20943 (defun org-trim (s)
20944 "Remove whitespace at beginning and end of string."
20945 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20946 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20949 (defun org-wrap (string &optional width lines)
20950 "Wrap string to either a number of lines, or a width in characters.
20951 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20952 that costs. If there is a word longer than WIDTH, the text is actually
20953 wrapped to the length of that word.
20954 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20955 many lines, whatever width that takes.
20956 The return value is a list of lines, without newlines at the end."
20957 (let* ((words (org-split-string string "[ \t\n]+"))
20958 (maxword (apply 'max (mapcar 'org-string-width words)))
20959 w ll)
20960 (cond (width
20961 (org-do-wrap words (max maxword width)))
20962 (lines
20963 (setq w maxword)
20964 (setq ll (org-do-wrap words maxword))
20965 (if (<= (length ll) lines)
20967 (setq ll words)
20968 (while (> (length ll) lines)
20969 (setq w (1+ w))
20970 (setq ll (org-do-wrap words w)))
20971 ll))
20972 (t (error "Cannot wrap this")))))
20974 (defun org-do-wrap (words width)
20975 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20976 (let (lines line)
20977 (while words
20978 (setq line (pop words))
20979 (while (and words (< (+ (length line) (length (car words))) width))
20980 (setq line (concat line " " (pop words))))
20981 (setq lines (push line lines)))
20982 (nreverse lines)))
20984 (defun org-split-string (string &optional separators)
20985 "Splits STRING into substrings at SEPARATORS.
20986 No empty strings are returned if there are matches at the beginning
20987 and end of string."
20988 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20989 (start 0)
20990 notfirst
20991 (list nil))
20992 (while (and (string-match rexp string
20993 (if (and notfirst
20994 (= start (match-beginning 0))
20995 (< start (length string)))
20996 (1+ start) start))
20997 (< (match-beginning 0) (length string)))
20998 (setq notfirst t)
20999 (or (eq (match-beginning 0) 0)
21000 (and (eq (match-beginning 0) (match-end 0))
21001 (eq (match-beginning 0) start))
21002 (setq list
21003 (cons (substring string start (match-beginning 0))
21004 list)))
21005 (setq start (match-end 0)))
21006 (or (eq start (length string))
21007 (setq list
21008 (cons (substring string start)
21009 list)))
21010 (nreverse list)))
21012 (defun org-quote-vert (s)
21013 "Replace \"|\" with \"\\vert\"."
21014 (while (string-match "|" s)
21015 (setq s (replace-match "\\vert" t t s)))
21018 (defun org-uuidgen-p (s)
21019 "Is S an ID created by UUIDGEN?"
21020 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21022 (defun org-in-src-block-p (&optional inside)
21023 "Whether point is in a code source block.
21024 When INSIDE is non-nil, don't consider we are within a src block
21025 when point is at #+BEGIN_SRC or #+END_SRC."
21026 (let ((case-fold-search t) ov)
21027 (or (and (setq ov (overlays-at (point)))
21028 (memq 'org-block-background
21029 (overlay-properties (car ov))))
21030 (and (not inside)
21031 (save-match-data
21032 (save-excursion
21033 (beginning-of-line)
21034 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21036 (defun org-context ()
21037 "Return a list of contexts of the current cursor position.
21038 If several contexts apply, all are returned.
21039 Each context entry is a list with a symbol naming the context, and
21040 two positions indicating start and end of the context. Possible
21041 contexts are:
21043 :headline anywhere in a headline
21044 :headline-stars on the leading stars in a headline
21045 :todo-keyword on a TODO keyword (including DONE) in a headline
21046 :tags on the TAGS in a headline
21047 :priority on the priority cookie in a headline
21048 :item on the first line of a plain list item
21049 :item-bullet on the bullet/number of a plain list item
21050 :checkbox on the checkbox in a plain list item
21051 :table in an org-mode table
21052 :table-special on a special filed in a table
21053 :table-table in a table.el table
21054 :clocktable in a clocktable
21055 :src-block in a source block
21056 :link on a hyperlink
21057 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21058 :target on a <<target>>
21059 :radio-target on a <<<radio-target>>>
21060 :latex-fragment on a LaTeX fragment
21061 :latex-preview on a LaTeX fragment with overlaid preview image
21063 This function expects the position to be visible because it uses font-lock
21064 faces as a help to recognize the following contexts: :table-special, :link,
21065 and :keyword."
21066 (let* ((f (get-text-property (point) 'face))
21067 (faces (if (listp f) f (list f)))
21068 (case-fold-search t)
21069 (p (point)) clist o)
21070 ;; First the large context
21071 (cond
21072 ((org-at-heading-p t)
21073 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21074 (when (progn
21075 (beginning-of-line 1)
21076 (looking-at org-todo-line-tags-regexp))
21077 (push (org-point-in-group p 1 :headline-stars) clist)
21078 (push (org-point-in-group p 2 :todo-keyword) clist)
21079 (push (org-point-in-group p 4 :tags) clist))
21080 (goto-char p)
21081 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21082 (if (looking-at "\\[#[A-Z0-9]\\]")
21083 (push (org-point-in-group p 0 :priority) clist)))
21085 ((org-at-item-p)
21086 (push (org-point-in-group p 2 :item-bullet) clist)
21087 (push (list :item (point-at-bol)
21088 (save-excursion (org-end-of-item) (point)))
21089 clist)
21090 (and (org-at-item-checkbox-p)
21091 (push (org-point-in-group p 0 :checkbox) clist)))
21093 ((org-at-table-p)
21094 (push (list :table (org-table-begin) (org-table-end)) clist)
21095 (if (memq 'org-formula faces)
21096 (push (list :table-special
21097 (previous-single-property-change p 'face)
21098 (next-single-property-change p 'face)) clist)))
21099 ((org-at-table-p 'any)
21100 (push (list :table-table) clist)))
21101 (goto-char p)
21103 (let ((case-fold-search t))
21104 ;; New the "medium" contexts: clocktables, source blocks
21105 (cond ((org-in-clocktable-p)
21106 (push (list :clocktable
21107 (and (or (looking-at "#\\+BEGIN: clocktable")
21108 (search-backward "#+BEGIN: clocktable" nil t))
21109 (match-beginning 0))
21110 (and (re-search-forward "#\\+END:?" nil t)
21111 (match-end 0))) clist))
21112 ((org-in-src-block-p)
21113 (push (list :src-block
21114 (and (or (looking-at "#\\+BEGIN_SRC")
21115 (search-backward "#+BEGIN_SRC" nil t))
21116 (match-beginning 0))
21117 (and (search-forward "#+END_SRC" nil t)
21118 (match-beginning 0))) clist))))
21119 (goto-char p)
21121 ;; Now the small context
21122 (cond
21123 ((org-at-timestamp-p)
21124 (push (org-point-in-group p 0 :timestamp) clist))
21125 ((memq 'org-link faces)
21126 (push (list :link
21127 (previous-single-property-change p 'face)
21128 (next-single-property-change p 'face)) clist))
21129 ((memq 'org-special-keyword faces)
21130 (push (list :keyword
21131 (previous-single-property-change p 'face)
21132 (next-single-property-change p 'face)) clist))
21133 ((org-at-target-p)
21134 (push (org-point-in-group p 0 :target) clist)
21135 (goto-char (1- (match-beginning 0)))
21136 (if (looking-at org-radio-target-regexp)
21137 (push (org-point-in-group p 0 :radio-target) clist))
21138 (goto-char p))
21139 ((setq o (car (delq nil
21140 (mapcar
21141 (lambda (x)
21142 (if (memq x org-latex-fragment-image-overlays) x))
21143 (overlays-at (point))))))
21144 (push (list :latex-fragment
21145 (overlay-start o) (overlay-end o)) clist)
21146 (push (list :latex-preview
21147 (overlay-start o) (overlay-end o)) clist))
21148 ((org-inside-LaTeX-fragment-p)
21149 ;; FIXME: positions wrong.
21150 (push (list :latex-fragment (point) (point)) clist)))
21152 (setq clist (nreverse (delq nil clist)))
21153 clist))
21155 ;; FIXME: Compare with at-regexp-p Do we need both?
21156 (defun org-in-regexp (re &optional nlines visually)
21157 "Check if point is inside a match of regexp.
21158 Normally only the current line is checked, but you can include NLINES extra
21159 lines both before and after point into the search.
21160 If VISUALLY is set, require that the cursor is not after the match but
21161 really on, so that the block visually is on the match."
21162 (catch 'exit
21163 (let ((pos (point))
21164 (eol (point-at-eol (+ 1 (or nlines 0))))
21165 (inc (if visually 1 0)))
21166 (save-excursion
21167 (beginning-of-line (- 1 (or nlines 0)))
21168 (while (re-search-forward re eol t)
21169 (if (and (<= (match-beginning 0) pos)
21170 (>= (+ inc (match-end 0)) pos))
21171 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21173 (defun org-at-regexp-p (regexp)
21174 "Is point inside a match of REGEXP in the current line?"
21175 (catch 'exit
21176 (save-excursion
21177 (let ((pos (point)) (end (point-at-eol)))
21178 (beginning-of-line 1)
21179 (while (re-search-forward regexp end t)
21180 (if (and (<= (match-beginning 0) pos)
21181 (>= (match-end 0) pos))
21182 (throw 'exit t)))
21183 nil))))
21185 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21186 "Non-nil when point is between matches of START-RE and END-RE.
21188 Also return a non-nil value when point is on one of the matches.
21190 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21191 buffer positions. Default values are the positions of headlines
21192 surrounding the point.
21194 The functions returns a cons cell whose car (resp. cdr) is the
21195 position before START-RE (resp. after END-RE)."
21196 (save-match-data
21197 (let ((pos (point))
21198 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21199 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21200 beg end)
21201 (save-excursion
21202 ;; Point is on a block when on START-RE or if START-RE can be
21203 ;; found before it...
21204 (and (or (org-at-regexp-p start-re)
21205 (re-search-backward start-re limit-up t))
21206 (setq beg (match-beginning 0))
21207 ;; ... and END-RE after it...
21208 (goto-char (match-end 0))
21209 (re-search-forward end-re limit-down t)
21210 (> (setq end (match-end 0)) pos)
21211 ;; ... without another START-RE in-between.
21212 (goto-char (match-beginning 0))
21213 (not (re-search-backward start-re (1+ beg) t))
21214 ;; Return value.
21215 (cons beg end))))))
21217 (defun org-in-block-p (names)
21218 "Non-nil when point belongs to a block whose name belongs to NAMES.
21220 NAMES is a list of strings containing names of blocks.
21222 Return first block name matched, or nil. Beware that in case of
21223 nested blocks, the returned name may not belong to the closest
21224 block from point."
21225 (save-match-data
21226 (catch 'exit
21227 (let ((case-fold-search t)
21228 (lim-up (save-excursion (outline-previous-heading)))
21229 (lim-down (save-excursion (outline-next-heading))))
21230 (mapc (lambda (name)
21231 (let ((n (regexp-quote name)))
21232 (when (org-between-regexps-p
21233 (concat "^[ \t]*#\\+begin_" n)
21234 (concat "^[ \t]*#\\+end_" n)
21235 lim-up lim-down)
21236 (throw 'exit n))))
21237 names))
21238 nil)))
21240 (defun org-occur-in-agenda-files (regexp &optional nlines)
21241 "Call `multi-occur' with buffers for all agenda files."
21242 (interactive "sOrg-files matching: \np")
21243 (let* ((files (org-agenda-files))
21244 (tnames (mapcar 'file-truename files))
21245 (extra org-agenda-text-search-extra-files)
21247 (when (eq (car extra) 'agenda-archives)
21248 (setq extra (cdr extra))
21249 (setq files (org-add-archive-files files)))
21250 (while (setq f (pop extra))
21251 (unless (member (file-truename f) tnames)
21252 (add-to-list 'files f 'append)
21253 (add-to-list 'tnames (file-truename f) 'append)))
21254 (multi-occur
21255 (mapcar (lambda (x)
21256 (with-current-buffer
21257 (or (get-file-buffer x) (find-file-noselect x))
21258 (widen)
21259 (current-buffer)))
21260 files)
21261 regexp)))
21263 (if (boundp 'occur-mode-find-occurrence-hook)
21264 ;; Emacs 23
21265 (add-hook 'occur-mode-find-occurrence-hook
21266 (lambda ()
21267 (when (derived-mode-p 'org-mode)
21268 (org-reveal))))
21269 ;; Emacs 22
21270 (defadvice occur-mode-goto-occurrence
21271 (after org-occur-reveal activate)
21272 (and (derived-mode-p 'org-mode) (org-reveal)))
21273 (defadvice occur-mode-goto-occurrence-other-window
21274 (after org-occur-reveal activate)
21275 (and (derived-mode-p 'org-mode) (org-reveal)))
21276 (defadvice occur-mode-display-occurrence
21277 (after org-occur-reveal activate)
21278 (when (derived-mode-p 'org-mode)
21279 (let ((pos (occur-mode-find-occurrence)))
21280 (with-current-buffer (marker-buffer pos)
21281 (save-excursion
21282 (goto-char pos)
21283 (org-reveal)))))))
21285 (defun org-occur-link-in-agenda-files ()
21286 "Create a link and search for it in the agendas.
21287 The link is not stored in `org-stored-links', it is just created
21288 for the search purpose."
21289 (interactive)
21290 (let ((link (condition-case nil
21291 (org-store-link nil)
21292 (error "Unable to create a link to here"))))
21293 (org-occur-in-agenda-files (regexp-quote link))))
21295 (defun org-reverse-string (string)
21296 "Return the reverse of STRING."
21297 (apply 'string (reverse (string-to-list string))))
21299 (defun org-uniquify (list)
21300 "Remove duplicate elements from LIST."
21301 (let (res)
21302 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21303 res))
21305 (defun org-delete-all (elts list)
21306 "Remove all elements in ELTS from LIST."
21307 (while elts
21308 (setq list (delete (pop elts) list)))
21309 list)
21311 (defun org-count (cl-item cl-seq)
21312 "Count the number of occurrences of ITEM in SEQ.
21313 Taken from `count' in cl-seq.el with all keyword arguments removed."
21314 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21315 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21316 (while (< cl-start cl-end)
21317 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21318 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21319 (setq cl-start (1+ cl-start)))
21320 cl-count))
21322 (defun org-remove-if (predicate seq)
21323 "Remove everything from SEQ that fulfills PREDICATE."
21324 (let (res e)
21325 (while seq
21326 (setq e (pop seq))
21327 (if (not (funcall predicate e)) (push e res)))
21328 (nreverse res)))
21330 (defun org-remove-if-not (predicate seq)
21331 "Remove everything from SEQ that does not fulfill PREDICATE."
21332 (let (res e)
21333 (while seq
21334 (setq e (pop seq))
21335 (if (funcall predicate e) (push e res)))
21336 (nreverse res)))
21338 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21339 "Reduce two-argument FUNCTION across SEQ.
21340 Taken from `reduce' in cl-seq.el with all keyword arguments but
21341 \":initial-value\" removed."
21342 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21343 (cadr (memq :initial-value cl-keys)))
21344 (cl-seq (pop cl-seq))
21345 (t (funcall cl-func)))))
21346 (while cl-seq
21347 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21348 cl-accum))
21350 (defun org-back-over-empty-lines ()
21351 "Move backwards over whitespace, to the beginning of the first empty line.
21352 Returns the number of empty lines passed."
21353 (let ((pos (point)))
21354 (if (cdr (assoc 'heading org-blank-before-new-entry))
21355 (skip-chars-backward " \t\n\r")
21356 (unless (eobp)
21357 (forward-line -1)))
21358 (beginning-of-line 2)
21359 (goto-char (min (point) pos))
21360 (count-lines (point) pos)))
21362 (defun org-skip-whitespace ()
21363 (skip-chars-forward " \t\n\r"))
21365 (defun org-point-in-group (point group &optional context)
21366 "Check if POINT is in match-group GROUP.
21367 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21368 match. If the match group does not exist or point is not inside it,
21369 return nil."
21370 (and (match-beginning group)
21371 (>= point (match-beginning group))
21372 (<= point (match-end group))
21373 (if context
21374 (list context (match-beginning group) (match-end group))
21375 t)))
21377 (defun org-switch-to-buffer-other-window (&rest args)
21378 "Switch to buffer in a second window on the current frame.
21379 In particular, do not allow pop-up frames.
21380 Returns the newly created buffer."
21381 (org-no-popups
21382 (apply 'switch-to-buffer-other-window args)))
21384 (defun org-combine-plists (&rest plists)
21385 "Create a single property list from all plists in PLISTS.
21386 The process starts by copying the first list, and then setting properties
21387 from the other lists. Settings in the last list are the most significant
21388 ones and overrule settings in the other lists."
21389 (let ((rtn (copy-sequence (pop plists)))
21390 p v ls)
21391 (while plists
21392 (setq ls (pop plists))
21393 (while ls
21394 (setq p (pop ls) v (pop ls))
21395 (setq rtn (plist-put rtn p v))))
21396 rtn))
21398 (defun org-replace-escapes (string table)
21399 "Replace %-escapes in STRING with values in TABLE.
21400 TABLE is an association list with keys like \"%a\" and string values.
21401 The sequences in STRING may contain normal field width and padding information,
21402 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21403 so values can contain further %-escapes if they are define later in TABLE."
21404 (let ((tbl (copy-alist table))
21405 (case-fold-search nil)
21406 (pchg 0)
21407 e re rpl)
21408 (while (setq e (pop tbl))
21409 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21410 (when (and (cdr e) (string-match re (cdr e)))
21411 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21412 (safe "SREF"))
21413 (add-text-properties 0 3 (list 'sref sref) safe)
21414 (setcdr e (replace-match safe t t (cdr e)))))
21415 (while (string-match re string)
21416 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21417 (cdr e)))
21418 (setq string (replace-match rpl t t string))))
21419 (while (setq pchg (next-property-change pchg string))
21420 (let ((sref (get-text-property pchg 'sref string)))
21421 (when (and sref (string-match "SREF" string pchg))
21422 (setq string (replace-match sref t t string)))))
21423 string))
21425 (defun org-sublist (list start end)
21426 "Return a section of LIST, from START to END.
21427 Counting starts at 1."
21428 (let (rtn (c start))
21429 (setq list (nthcdr (1- start) list))
21430 (while (and list (<= c end))
21431 (push (pop list) rtn)
21432 (setq c (1+ c)))
21433 (nreverse rtn)))
21435 (defun org-find-base-buffer-visiting (file)
21436 "Like `find-buffer-visiting' but always return the base buffer and
21437 not an indirect buffer."
21438 (let ((buf (or (get-file-buffer file)
21439 (find-buffer-visiting file))))
21440 (if buf
21441 (or (buffer-base-buffer buf) buf)
21442 nil)))
21444 (defun org-image-file-name-regexp (&optional extensions)
21445 "Return regexp matching the file names of images.
21446 If EXTENSIONS is given, only match these."
21447 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21448 (image-file-name-regexp)
21449 (let ((image-file-name-extensions
21450 (or extensions
21451 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21452 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21453 (concat "\\."
21454 (regexp-opt (nconc (mapcar 'upcase
21455 image-file-name-extensions)
21456 image-file-name-extensions)
21458 "\\'"))))
21460 (defun org-file-image-p (file &optional extensions)
21461 "Return non-nil if FILE is an image."
21462 (save-match-data
21463 (string-match (org-image-file-name-regexp extensions) file)))
21465 (defun org-get-cursor-date (&optional with-time)
21466 "Return the date at cursor in as a time.
21467 This works in the calendar and in the agenda, anywhere else it just
21468 returns the current time.
21469 If WITH-TIME is non-nil, returns the time of the event at point (in
21470 the agenda) or the current time of the day."
21471 (let (date day defd tp tm hod mod)
21472 (when with-time
21473 (setq tp (get-text-property (point) 'time))
21474 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21475 (setq hod (string-to-number (match-string 1 tp))
21476 mod (string-to-number (match-string 2 tp))))
21477 (or tp (setq hod (nth 2 (decode-time (current-time)))
21478 mod (nth 1 (decode-time (current-time))))))
21479 (cond
21480 ((eq major-mode 'calendar-mode)
21481 (setq date (calendar-cursor-to-date)
21482 defd (encode-time 0 (or mod 0) (or hod 0)
21483 (nth 1 date) (nth 0 date) (nth 2 date))))
21484 ((eq major-mode 'org-agenda-mode)
21485 (setq day (get-text-property (point) 'day))
21486 (if day
21487 (setq date (calendar-gregorian-from-absolute day)
21488 defd (encode-time 0 (or mod 0) (or hod 0)
21489 (nth 1 date) (nth 0 date) (nth 2 date))))))
21490 (or defd (current-time))))
21492 (defun org-mark-subtree (&optional up)
21493 "Mark the current subtree.
21494 This puts point at the start of the current subtree, and mark at
21495 the end. If a numeric prefix UP is given, move up into the
21496 hierarchy of headlines by UP levels before marking the subtree."
21497 (interactive "P")
21498 (org-with-limited-levels
21499 (cond ((org-at-heading-p) (beginning-of-line))
21500 ((org-before-first-heading-p) (error "Not in a subtree"))
21501 (t (outline-previous-visible-heading 1))))
21502 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21503 (if (org-called-interactively-p 'any)
21504 (call-interactively 'org-mark-element)
21505 (org-mark-element)))
21508 ;;; Indentation
21510 (defun org-indent-line ()
21511 "Indent line depending on context."
21512 (interactive)
21513 (let* ((pos (point))
21514 (itemp (org-at-item-p))
21515 (case-fold-search t)
21516 (org-drawer-regexp (or org-drawer-regexp "\000"))
21517 (inline-task-p (and (featurep 'org-inlinetask)
21518 (org-inlinetask-in-task-p)))
21519 (inline-re (and inline-task-p
21520 (org-inlinetask-outline-regexp)))
21521 column)
21522 (if (and orgstruct-is-++ (eq pos (point)))
21523 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21524 (indent-according-to-mode))
21525 (beginning-of-line 1)
21526 (cond
21527 ;; Headings
21528 ((looking-at org-outline-regexp) (setq column 0))
21529 ;; Footnote definition
21530 ((looking-at org-footnote-definition-re) (setq column 0))
21531 ;; Literal examples
21532 ((looking-at "[ \t]*:\\( \\|$\\)")
21533 (setq column (org-get-indentation))) ; do nothing
21534 ;; Lists
21535 ((ignore-errors (goto-char (org-in-item-p)))
21536 (setq column (if itemp
21537 (org-get-indentation)
21538 (org-list-item-body-column (point))))
21539 (goto-char pos))
21540 ;; Drawers
21541 ((and (looking-at "[ \t]*:END:")
21542 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21543 (save-excursion
21544 (goto-char (1- (match-beginning 1)))
21545 (setq column (current-column))))
21546 ;; Special blocks
21547 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21548 (save-excursion
21549 (re-search-backward
21550 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21551 (setq column (org-get-indentation (match-string 0))))
21552 ((and (not (looking-at "[ \t]*#\\+begin_"))
21553 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21554 (save-excursion
21555 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21556 (setq column
21557 (cond ((equal (downcase (match-string 1)) "src")
21558 ;; src blocks: let `org-edit-src-exit' handle them
21559 (org-get-indentation))
21560 ((equal (downcase (match-string 1)) "example")
21561 (max (org-get-indentation)
21562 (org-get-indentation (match-string 0))))
21564 (org-get-indentation (match-string 0))))))
21565 ;; This line has nothing special, look at the previous relevant
21566 ;; line to compute indentation
21568 (beginning-of-line 0)
21569 (while (and (not (bobp))
21570 (not (looking-at org-table-line-regexp))
21571 (not (looking-at org-drawer-regexp))
21572 ;; When point started in an inline task, do not move
21573 ;; above task starting line.
21574 (not (and inline-task-p (looking-at inline-re)))
21575 ;; Skip drawers, blocks, empty lines, verbatim,
21576 ;; comments, tables, footnotes definitions, lists,
21577 ;; inline tasks.
21578 (or (and (looking-at "[ \t]*:END:")
21579 (re-search-backward org-drawer-regexp nil t))
21580 (and (looking-at "[ \t]*#\\+end_")
21581 (re-search-backward "[ \t]*#\\+begin_"nil t))
21582 (looking-at "[ \t]*[\n:#|]")
21583 (looking-at org-footnote-definition-re)
21584 (and (ignore-errors (goto-char (org-in-item-p)))
21585 (goto-char
21586 (org-list-get-top-point (org-list-struct))))
21587 (and (not inline-task-p)
21588 (featurep 'org-inlinetask)
21589 (org-inlinetask-in-task-p)
21590 (or (org-inlinetask-goto-beginning) t))))
21591 (beginning-of-line 0))
21592 (cond
21593 ;; There was an heading above.
21594 ((looking-at "\\*+[ \t]+")
21595 (if (not org-adapt-indentation)
21596 (setq column 0)
21597 (goto-char (match-end 0))
21598 (setq column (current-column))))
21599 ;; A drawer had started and is unfinished
21600 ((looking-at org-drawer-regexp)
21601 (goto-char (1- (match-beginning 1)))
21602 (setq column (current-column)))
21603 ;; Else, nothing noticeable found: get indentation and go on.
21604 (t (setq column (org-get-indentation))))))
21605 ;; Now apply indentation and move cursor accordingly
21606 (goto-char pos)
21607 (if (<= (current-column) (current-indentation))
21608 (org-indent-line-to column)
21609 (save-excursion (org-indent-line-to column)))
21610 ;; Special polishing for properties, see `org-property-format'
21611 (setq column (current-column))
21612 (beginning-of-line 1)
21613 (if (looking-at
21614 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21615 (replace-match (concat (match-string 1)
21616 (format org-property-format
21617 (match-string 2) (match-string 3)))
21618 t t))
21619 (org-move-to-column column))))
21621 (defun org-indent-drawer ()
21622 "Indent the drawer at point."
21623 (interactive)
21624 (let ((p (point))
21625 (e (and (save-excursion (re-search-forward ":END:" nil t))
21626 (match-end 0)))
21627 (folded
21628 (save-excursion
21629 (end-of-line)
21630 (when (overlays-at (point))
21631 (member 'invisible (overlay-properties
21632 (car (overlays-at (point)))))))))
21633 (when folded (org-cycle))
21634 (indent-for-tab-command)
21635 (while (and (move-beginning-of-line 2) (< (point) e))
21636 (indent-for-tab-command))
21637 (goto-char p)
21638 (when folded (org-cycle)))
21639 (message "Drawer at point indented"))
21641 (defun org-indent-block ()
21642 "Indent the block at point."
21643 (interactive)
21644 (let ((p (point))
21645 (case-fold-search t)
21646 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21647 (match-end 0)))
21648 (folded
21649 (save-excursion
21650 (end-of-line)
21651 (when (overlays-at (point))
21652 (member 'invisible (overlay-properties
21653 (car (overlays-at (point)))))))))
21654 (when folded (org-cycle))
21655 (indent-for-tab-command)
21656 (while (and (move-beginning-of-line 2) (< (point) e))
21657 (indent-for-tab-command))
21658 (goto-char p)
21659 (when folded (org-cycle)))
21660 (message "Block at point indented"))
21662 (defun org-indent-region (start end)
21663 "Indent region."
21664 (interactive "r")
21665 (save-excursion
21666 (let ((line-end (org-current-line end)))
21667 (goto-char start)
21668 (while (< (org-current-line) line-end)
21669 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21670 (t (call-interactively 'org-indent-line)))
21671 (move-beginning-of-line 2)))))
21674 ;;; Filling
21676 ;; We use our own fill-paragraph and auto-fill functions.
21678 ;; `org-fill-paragraph' relies on adaptive filling and context
21679 ;; checking. Appropriate `fill-prefix' is computed with
21680 ;; `org-adaptive-fill-function'.
21682 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21683 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21684 ;; `org-adaptive-fill-function' value. Internally,
21685 ;; `org-comment-line-break-function' breaks the line.
21687 ;; `org-setup-filling' installs filling and auto-filling related
21688 ;; variables during `org-mode' initialization.
21690 (defun org-setup-filling ()
21691 (interactive)
21692 ;; Prevent auto-fill from inserting unwanted new items.
21693 (when (boundp 'fill-nobreak-predicate)
21694 (org-set-local
21695 'fill-nobreak-predicate
21696 (org-uniquify
21697 (append fill-nobreak-predicate
21698 '(org-fill-paragraph-separate-nobreak-p
21699 org-fill-line-break-nobreak-p
21700 org-fill-paragraph-with-timestamp-nobreak-p)))))
21701 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21702 (org-set-local 'auto-fill-inhibit-regexp nil)
21703 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21704 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21705 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21707 (defvar org-element-paragraph-separate) ; org-element.el
21708 (defun org-fill-paragraph-separate-nobreak-p ()
21709 "Non-nil when a line break at point would insert a new item."
21710 (looking-at (substring org-element-paragraph-separate 1)))
21712 (defun org-fill-line-break-nobreak-p ()
21713 "Non-nil when a line break at point would create an Org line break."
21714 (save-excursion
21715 (skip-chars-backward "[ \t]")
21716 (skip-chars-backward "\\\\")
21717 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21719 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21720 "Non-nil when a line break at point would insert a new item."
21721 (and (org-at-timestamp-p t)
21722 (not (looking-at org-ts-regexp-both))))
21724 (declare-function message-in-body-p "message" ())
21725 (defvar orgtbl-line-start-regexp) ; From org-table.el
21726 (defun org-adaptive-fill-function ()
21727 "Compute a fill prefix for the current line.
21728 Return fill prefix, as a string, or nil if current line isn't
21729 meant to be filled."
21730 (let (prefix)
21731 (catch 'exit
21732 (when (derived-mode-p 'message-mode)
21733 (save-excursion
21734 (beginning-of-line)
21735 (cond ((or (not (message-in-body-p))
21736 (looking-at orgtbl-line-start-regexp))
21737 (throw 'exit nil))
21738 ((looking-at message-cite-prefix-regexp)
21739 (throw 'exit (match-string-no-properties 0)))
21740 ((looking-at org-outline-regexp)
21741 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21742 (org-with-wide-buffer
21743 (let* ((p (line-beginning-position))
21744 (element (save-excursion (beginning-of-line)
21745 (org-element-at-point)))
21746 (type (org-element-type element))
21747 (post-affiliated (org-element-property :post-affiliated element)))
21748 (unless (and post-affiliated (< p post-affiliated))
21749 (case type
21750 (comment (looking-at "[ \t]*# ?") (match-string 0))
21751 (footnote-definition "")
21752 ((item plain-list)
21753 (make-string (org-list-item-body-column
21754 (or post-affiliated
21755 (org-element-property :begin element)))
21756 ? ))
21757 (paragraph
21758 ;; Fill prefix is usually the same as the current line,
21759 ;; except if the paragraph is at the beginning of an item.
21760 (let ((parent (org-element-property :parent element)))
21761 (cond ((eq (org-element-type parent) 'item)
21762 (make-string (org-list-item-body-column
21763 (org-element-property :begin parent))
21764 ? ))
21765 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21766 (match-string 0))
21767 (t ""))))
21768 (comment-block
21769 ;; Only fill contents if P is within block boundaries.
21770 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21771 (forward-line)
21772 (point)))
21773 (cend (save-excursion
21774 (goto-char (org-element-property :end element))
21775 (skip-chars-backward " \r\t\n")
21776 (line-beginning-position))))
21777 (when (and (>= p cbeg) (< p cend))
21778 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21779 (match-string 0)
21780 "")))))))))))
21782 (declare-function message-goto-body "message" ())
21783 (defvar message-cite-prefix-regexp) ; From message.el
21784 (defun org-fill-paragraph (&optional justify)
21785 "Fill element at point, when applicable.
21787 This function only applies to comment blocks, comments, example
21788 blocks and paragraphs. Also, as a special case, re-align table
21789 when point is at one.
21791 If JUSTIFY is non-nil (interactively, with prefix argument),
21792 justify as well. If `sentence-end-double-space' is non-nil, then
21793 period followed by one space does not end a sentence, so don't
21794 break a line there. The variable `fill-column' controls the
21795 width for filling.
21797 For convenience, when point is at a plain list, an item or
21798 a footnote definition, try to fill the first paragraph within."
21799 (interactive)
21800 (if (and (derived-mode-p 'message-mode)
21801 (or (not (message-in-body-p))
21802 (save-excursion (move-beginning-of-line 1)
21803 (looking-at message-cite-prefix-regexp))))
21804 ;; First ensure filling is correct in message-mode.
21805 (let ((fill-paragraph-function
21806 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21807 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21808 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21809 (paragraph-separate
21810 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21811 (fill-paragraph nil))
21812 (with-syntax-table org-mode-transpose-word-syntax-table
21813 ;; Move to end of line in order to get the first paragraph
21814 ;; within a plain list or a footnote definition.
21815 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
21816 ;; First check if point is in a blank line at the beginning of
21817 ;; the buffer. In that case, ignore filling.
21818 (case (org-element-type element)
21819 ;; Use major mode filling function is src blocks.
21820 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21821 ;; Align Org tables, leave table.el tables as-is.
21822 (table-row (org-table-align) t)
21823 (table
21824 (when (eq (org-element-property :type element) 'org)
21825 (org-table-align))
21827 (paragraph
21828 ;; Paragraphs may contain `line-break' type objects.
21829 (let ((beg (max (point-min)
21830 (org-element-property :contents-begin element)))
21831 (end (min (point-max)
21832 (org-element-property :contents-end element))))
21833 ;; Do nothing if point is at an affiliated keyword.
21834 (if (< (line-end-position) beg) t
21835 (when (derived-mode-p 'message-mode)
21836 ;; In `message-mode', do not fill following citation
21837 ;; in current paragraph nor text before message body.
21838 (let ((body-start (save-excursion (message-goto-body))))
21839 (when body-start (setq beg (max body-start beg))))
21840 (when (save-excursion
21841 (re-search-forward
21842 (concat "^" message-cite-prefix-regexp) end t))
21843 (setq end (match-beginning 0))))
21844 ;; Fill paragraph, taking line breaks into account.
21845 ;; For that, slice the paragraph using line breaks as
21846 ;; separators, and fill the parts in reverse order to
21847 ;; avoid messing with markers.
21848 (save-excursion
21849 (goto-char end)
21850 (mapc
21851 (lambda (pos)
21852 (fill-region-as-paragraph pos (point) justify)
21853 (goto-char pos))
21854 ;; Find the list of ending positions for line breaks
21855 ;; in the current paragraph. Add paragraph
21856 ;; beginning to include first slice.
21857 (nreverse
21858 (cons beg
21859 (org-element-map
21860 (org-element--parse-objects
21861 beg end nil (org-element-restriction 'paragraph))
21862 'line-break
21863 (lambda (lb) (org-element-property :end lb)))))))
21864 t)))
21865 ;; Contents of `comment-block' type elements should be
21866 ;; filled as plain text, but only if point is within block
21867 ;; markers.
21868 (comment-block
21869 (let* ((case-fold-search t)
21870 (beg (save-excursion
21871 (goto-char (org-element-property :begin element))
21872 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21873 (forward-line)
21874 (point)))
21875 (end (save-excursion
21876 (goto-char (org-element-property :end element))
21877 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21878 (line-beginning-position))))
21879 (when (and (>= (point) beg) (< (point) end))
21880 (fill-region-as-paragraph
21881 (save-excursion
21882 (end-of-line)
21883 (re-search-backward "^[ \t]*$" beg 'move)
21884 (line-beginning-position))
21885 (save-excursion
21886 (beginning-of-line)
21887 (re-search-forward "^[ \t]*$" end 'move)
21888 (line-beginning-position))
21889 justify)))
21891 ;; Fill comments.
21892 (comment (fill-comment-paragraph justify))
21893 ;; Ignore every other element.
21894 (otherwise t))))))
21896 (defun org-auto-fill-function ()
21897 "Auto-fill function."
21898 ;; Check if auto-filling is meaningful.
21899 (let ((fc (current-fill-column)))
21900 (when (and fc (> (current-column) fc))
21901 (let* ((fill-prefix (org-adaptive-fill-function))
21902 ;; Enforce empty fill prefix, if required. Otherwise, it
21903 ;; will be computed again.
21904 (adaptive-fill-mode (not (equal fill-prefix ""))))
21905 (when fill-prefix (do-auto-fill))))))
21907 (defun org-comment-line-break-function (&optional soft)
21908 "Break line at point and indent, continuing comment if within one.
21909 The inserted newline is marked hard if variable
21910 `use-hard-newlines' is true, unless optional argument SOFT is
21911 non-nil."
21912 (if soft (insert-and-inherit ?\n) (newline 1))
21913 (save-excursion (forward-char -1) (delete-horizontal-space))
21914 (delete-horizontal-space)
21915 (indent-to-left-margin)
21916 (insert-before-markers-and-inherit fill-prefix))
21919 ;;; Comments
21921 ;; Org comments syntax is quite complex. It requires the entire line
21922 ;; to be just a comment. Also, even with the right syntax at the
21923 ;; beginning of line, some some elements (i.e. verse-block or
21924 ;; example-block) don't accept comments. Usual Emacs comment commands
21925 ;; cannot cope with those requirements. Therefore, Org replaces them.
21927 ;; Org still relies on `comment-dwim', but cannot trust
21928 ;; `comment-only-p'. So, `comment-region-function' and
21929 ;; `uncomment-region-function' both point
21930 ;; to`org-comment-or-uncomment-region'. Eventually,
21931 ;; `org-insert-comment' takes care of insertion of comments at the
21932 ;; beginning of line.
21934 ;; `org-setup-comments-handling' install comments related variables
21935 ;; during `org-mode' initialization.
21937 (defun org-setup-comments-handling ()
21938 (interactive)
21939 (org-set-local 'comment-use-syntax nil)
21940 (org-set-local 'comment-start "# ")
21941 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21942 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21943 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21944 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21946 (defun org-insert-comment ()
21947 "Insert an empty comment above current line.
21948 If the line is empty, insert comment at its beginning."
21949 (beginning-of-line)
21950 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21951 (org-indent-line)
21952 (insert "# "))
21954 (defvar comment-empty-lines) ; From newcomment.el.
21955 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21956 "Comment or uncomment each non-blank line in the region.
21957 Uncomment each non-blank line between BEG and END if it only
21958 contains commented lines. Otherwise, comment them."
21959 (save-restriction
21960 ;; Restrict region
21961 (narrow-to-region (save-excursion (goto-char beg)
21962 (skip-chars-forward " \r\t\n" end)
21963 (line-beginning-position))
21964 (save-excursion (goto-char end)
21965 (skip-chars-backward " \r\t\n" beg)
21966 (line-end-position)))
21967 (let ((uncommentp
21968 ;; UNCOMMENTP is non-nil when every non blank line between
21969 ;; BEG and END is a comment.
21970 (save-excursion
21971 (goto-char (point-min))
21972 (while (and (not (eobp))
21973 (let ((element (org-element-at-point)))
21974 (and (eq (org-element-type element) 'comment)
21975 (goto-char (min (point-max)
21976 (org-element-property
21977 :end element)))))))
21978 (eobp))))
21979 (if uncommentp
21980 ;; Only blank lines and comments in region: uncomment it.
21981 (save-excursion
21982 (goto-char (point-min))
21983 (while (not (eobp))
21984 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21985 (replace-match "" nil nil nil 1))
21986 (forward-line)))
21987 ;; Comment each line in region.
21988 (let ((min-indent (point-max)))
21989 ;; First find the minimum indentation across all lines.
21990 (save-excursion
21991 (goto-char (point-min))
21992 (while (and (not (eobp)) (not (zerop min-indent)))
21993 (unless (looking-at "[ \t]*$")
21994 (setq min-indent (min min-indent (current-indentation))))
21995 (forward-line)))
21996 ;; Then loop over all lines.
21997 (save-excursion
21998 (goto-char (point-min))
21999 (while (not (eobp))
22000 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22001 (org-move-to-column min-indent t)
22002 (insert comment-start))
22003 (forward-line))))))))
22006 ;;; Planning
22008 ;; This section contains tools to operate on timestamp objects, as
22009 ;; returned by, e.g. `org-element-context'.
22011 (defun org-timestamp-has-time-p (timestamp)
22012 "Non-nil when TIMESTAMP has a time specified."
22013 (org-element-property :hour-start timestamp))
22015 (defun org-timestamp-format (timestamp format &optional end utc)
22016 "Format a TIMESTAMP element into a string.
22018 FORMAT is a format specifier to be passed to
22019 `format-time-string'.
22021 When optional argument END is non-nil, use end of date-range or
22022 time-range, if possible.
22024 When optional argument UTC is non-nil, time will be expressed as
22025 Universal Time."
22026 (format-time-string
22027 format
22028 (apply 'encode-time
22029 (cons 0
22030 (mapcar
22031 (lambda (prop) (or (org-element-property prop timestamp) 0))
22032 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22033 '(:minute-start :hour-start :day-start :month-start
22034 :year-start)))))
22035 utc))
22037 (defun org-timestamp-split-range (timestamp &optional end)
22038 "Extract a timestamp object from a date or time range.
22040 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22041 the end of the range. Otherwise, extract its start.
22043 Return a new timestamp object sharing the same parent as
22044 TIMESTAMP."
22045 (let ((type (org-element-property :type timestamp)))
22046 (if (memq type '(active inactive diary)) timestamp
22047 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22048 ;; Set new type.
22049 (org-element-put-property
22050 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22051 ;; Copy start properties over end properties if END is
22052 ;; non-nil. Otherwise, copy end properties over `start' ones.
22053 (let ((p-alist '((:minute-start . :minute-end)
22054 (:hour-start . :hour-end)
22055 (:day-start . :day-end)
22056 (:month-start . :month-end)
22057 (:year-start . :year-end))))
22058 (dolist (p-cell p-alist)
22059 (org-element-put-property
22060 split-ts
22061 (funcall (if end 'car 'cdr) p-cell)
22062 (org-element-property
22063 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22064 ;; Eventually refresh `:raw-value'.
22065 (org-element-put-property split-ts :raw-value nil)
22066 (org-element-put-property
22067 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22069 (defun org-timestamp-translate (timestamp &optional boundary)
22070 "Apply `org-translate-time' on a TIMESTAMP object.
22071 When optional argument BOUNDARY is non-nil, it is either the
22072 symbol `start' or `end'. In this case, only translate the
22073 starting or ending part of TIMESTAMP if it is a date or time
22074 range. Otherwise, translate both parts."
22075 (if (and (not boundary)
22076 (memq (org-element-property :type timestamp)
22077 '(active-range inactive-range)))
22078 (concat
22079 (org-translate-time
22080 (org-element-property :raw-value
22081 (org-timestamp-split-range timestamp)))
22082 "--"
22083 (org-translate-time
22084 (org-element-property :raw-value
22085 (org-timestamp-split-range timestamp t))))
22086 (org-translate-time
22087 (org-element-property
22088 :raw-value
22089 (if (not boundary) timestamp
22090 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22094 ;;; Other stuff.
22096 (defun org-toggle-fixed-width-section (arg)
22097 "Toggle the fixed-width export.
22098 If there is no active region, the QUOTE keyword at the current headline is
22099 inserted or removed. When present, it causes the text between this headline
22100 and the next to be exported as fixed-width text, and unmodified.
22101 If there is an active region, this command adds or removes a colon as the
22102 first character of this line. If the first character of a line is a colon,
22103 this line is also exported in fixed-width font."
22104 (interactive "P")
22105 (let* ((cc 0)
22106 (regionp (org-region-active-p))
22107 (beg (if regionp (region-beginning) (point)))
22108 (end (if regionp (region-end)))
22109 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22110 (case-fold-search nil)
22111 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22112 off)
22113 (if regionp
22114 (save-excursion
22115 (goto-char beg)
22116 (setq cc (current-column))
22117 (beginning-of-line 1)
22118 (setq off (looking-at re))
22119 (while (> nlines 0)
22120 (setq nlines (1- nlines))
22121 (beginning-of-line 1)
22122 (cond
22123 (arg
22124 (org-move-to-column cc t)
22125 (insert ": \n")
22126 (forward-line -1))
22127 ((and off (looking-at re))
22128 (replace-match "" t t nil 1))
22129 ((not off) (org-move-to-column cc t) (insert ": ")))
22130 (forward-line 1)))
22131 (save-excursion
22132 (org-back-to-heading)
22133 (cond
22134 ((looking-at (format org-heading-keyword-regexp-format
22135 org-quote-string))
22136 (goto-char (match-end 1))
22137 (looking-at (concat " +" org-quote-string))
22138 (replace-match "" t t)
22139 (when (eolp) (insert " ")))
22140 ((looking-at org-outline-regexp)
22141 (goto-char (match-end 0))
22142 (insert org-quote-string " ")))))))
22144 (defun org-reftex-citation ()
22145 "Use reftex-citation to insert a citation into the buffer.
22146 This looks for a line like
22148 #+BIBLIOGRAPHY: foo plain option:-d
22150 and derives from it that foo.bib is the bibliography file relevant
22151 for this document. It then installs the necessary environment for RefTeX
22152 to work in this buffer and calls `reftex-citation' to insert a citation
22153 into the buffer.
22155 Export of such citations to both LaTeX and HTML is handled by the contributed
22156 package org-exp-bibtex by Taru Karttunen."
22157 (interactive)
22158 (let ((reftex-docstruct-symbol 'rds)
22159 (reftex-cite-format "\\cite{%l}")
22160 rds bib)
22161 (save-excursion
22162 (save-restriction
22163 (widen)
22164 (let ((case-fold-search t)
22165 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22166 (if (not (save-excursion
22167 (or (re-search-forward re nil t)
22168 (re-search-backward re nil t))))
22169 (error "No bibliography defined in file")
22170 (setq bib (concat (match-string 1) ".bib")
22171 rds (list (list 'bib bib)))))))
22172 (call-interactively 'reftex-citation)))
22174 ;;;; Functions extending outline functionality
22176 (defun org-beginning-of-line (&optional arg)
22177 "Go to the beginning of the current line. If that is invisible, continue
22178 to a visible line beginning. This makes the function of C-a more intuitive.
22179 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22180 first attempt, and only move to after the tags when the cursor is already
22181 beyond the end of the headline."
22182 (interactive "P")
22183 (let ((pos (point))
22184 (special (if (consp org-special-ctrl-a/e)
22185 (car org-special-ctrl-a/e)
22186 org-special-ctrl-a/e))
22187 refpos)
22188 (if (org-bound-and-true-p visual-line-mode)
22189 (beginning-of-visual-line 1)
22190 (beginning-of-line 1))
22191 (if (and arg (fboundp 'move-beginning-of-line))
22192 (call-interactively 'move-beginning-of-line)
22193 (if (bobp)
22195 (backward-char 1)
22196 (if (org-truely-invisible-p)
22197 (while (and (not (bobp)) (org-truely-invisible-p))
22198 (backward-char 1)
22199 (beginning-of-line 1))
22200 (forward-char 1))))
22201 (when special
22202 (cond
22203 ((and (looking-at org-complex-heading-regexp)
22204 (= (char-after (match-end 1)) ?\ ))
22205 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22206 (point-at-eol)))
22207 (goto-char
22208 (if (eq special t)
22209 (cond ((> pos refpos) refpos)
22210 ((= pos (point)) refpos)
22211 (t (point)))
22212 (cond ((> pos (point)) (point))
22213 ((not (eq last-command this-command)) (point))
22214 (t refpos)))))
22215 ((org-at-item-p)
22216 ;; Being at an item and not looking at an the item means point
22217 ;; was previously moved to beginning of a visual line, which
22218 ;; doesn't contain the item. Therefore, do nothing special,
22219 ;; just stay here.
22220 (when (looking-at org-list-full-item-re)
22221 ;; Set special position at first white space character after
22222 ;; bullet, and check-box, if any.
22223 (let ((after-bullet
22224 (let ((box (match-end 3)))
22225 (if (not box) (match-end 1)
22226 (let ((after (char-after box)))
22227 (if (and after (= after ? )) (1+ box) box))))))
22228 ;; Special case: Move point to special position when
22229 ;; currently after it or at beginning of line.
22230 (if (eq special t)
22231 (when (or (> pos after-bullet) (= (point) pos))
22232 (goto-char after-bullet))
22233 ;; Reversed case: Move point to special position when
22234 ;; point was already at beginning of line and command is
22235 ;; repeated.
22236 (when (and (= (point) pos) (eq last-command this-command))
22237 (goto-char after-bullet))))))))
22238 (org-no-warnings
22239 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22241 (defun org-end-of-line (&optional arg)
22242 "Go to the end of the line.
22243 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22244 tags on the first attempt, and only move to after the tags when
22245 the cursor is already beyond the end of the headline."
22246 (interactive "P")
22247 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22248 org-special-ctrl-a/e))
22249 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22250 'end-of-visual-line)
22251 ((fboundp 'move-end-of-line) 'move-end-of-line)
22252 (t 'end-of-line))))
22253 (if (or (not special) arg) (call-interactively move-fun)
22254 (let* ((element (save-excursion (beginning-of-line)
22255 (org-element-at-point)))
22256 (type (org-element-type element)))
22257 (cond
22258 ((memq type '(headline inlinetask))
22259 (let ((pos (point)))
22260 (beginning-of-line 1)
22261 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22262 (if (eq special t)
22263 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22264 (goto-char (match-beginning 1))
22265 (goto-char (match-end 0)))
22266 (if (or (< pos (match-end 0))
22267 (not (eq this-command last-command)))
22268 (goto-char (match-end 0))
22269 (goto-char (match-beginning 1))))
22270 (call-interactively move-fun))))
22271 ((org-element-property :hiddenp element)
22272 ;; If element is hidden, `move-end-of-line' would put point
22273 ;; after it. Use `end-of-line' to stay on current line.
22274 (call-interactively 'end-of-line))
22275 (t (call-interactively move-fun)))))
22276 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22278 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22279 (define-key org-mode-map "\C-e" 'org-end-of-line)
22281 (defun org-backward-sentence (&optional arg)
22282 "Go to beginning of sentence, or beginning of table field.
22283 This will call `backward-sentence' or `org-table-beginning-of-field',
22284 depending on context."
22285 (interactive "P")
22286 (cond
22287 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22288 (t (call-interactively 'backward-sentence))))
22290 (defun org-forward-sentence (&optional arg)
22291 "Go to end of sentence, or end of table field.
22292 This will call `forward-sentence' or `org-table-end-of-field',
22293 depending on context."
22294 (interactive "P")
22295 (cond
22296 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22297 (t (call-interactively 'forward-sentence))))
22299 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22300 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22302 (defun org-kill-line (&optional arg)
22303 "Kill line, to tags or end of line."
22304 (interactive "P")
22305 (cond
22306 ((or (not org-special-ctrl-k)
22307 (bolp)
22308 (not (org-at-heading-p)))
22309 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22310 org-ctrl-k-protect-subtree)
22311 (if (or (eq org-ctrl-k-protect-subtree 'error)
22312 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22313 (error "C-k aborted - would kill hidden subtree")))
22314 (call-interactively
22315 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22316 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22317 (kill-region (point) (match-beginning 1))
22318 (org-set-tags nil t))
22319 (t (kill-region (point) (point-at-eol)))))
22321 (define-key org-mode-map "\C-k" 'org-kill-line)
22323 (defun org-yank (&optional arg)
22324 "Yank. If the kill is a subtree, treat it specially.
22325 This command will look at the current kill and check if is a single
22326 subtree, or a series of subtrees[1]. If it passes the test, and if the
22327 cursor is at the beginning of a line or after the stars of a currently
22328 empty headline, then the yank is handled specially. How exactly depends
22329 on the value of the following variables, both set by default.
22331 org-yank-folded-subtrees
22332 When set, the subtree(s) will be folded after insertion, but only
22333 if doing so would now swallow text after the yanked text.
22335 org-yank-adjusted-subtrees
22336 When set, the subtree will be promoted or demoted in order to
22337 fit into the local outline tree structure, which means that the level
22338 will be adjusted so that it becomes the smaller one of the two
22339 *visible* surrounding headings.
22341 Any prefix to this command will cause `yank' to be called directly with
22342 no special treatment. In particular, a simple \\[universal-argument] prefix \
22343 will just
22344 plainly yank the text as it is.
22346 \[1] The test checks if the first non-white line is a heading
22347 and if there are no other headings with fewer stars."
22348 (interactive "P")
22349 (org-yank-generic 'yank arg))
22351 (defun org-yank-generic (command arg)
22352 "Perform some yank-like command.
22354 This function implements the behavior described in the `org-yank'
22355 documentation. However, it has been generalized to work for any
22356 interactive command with similar behavior."
22358 ;; pretend to be command COMMAND
22359 (setq this-command command)
22361 (if arg
22362 (call-interactively command)
22364 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22365 (and (org-kill-is-subtree-p)
22366 (or (bolp)
22367 (and (looking-at "[ \t]*$")
22368 (string-match
22369 "\\`\\*+\\'"
22370 (buffer-substring (point-at-bol) (point)))))))
22371 swallowp)
22372 (cond
22373 ((and subtreep org-yank-folded-subtrees)
22374 (let ((beg (point))
22375 end)
22376 (if (and subtreep org-yank-adjusted-subtrees)
22377 (org-paste-subtree nil nil 'for-yank)
22378 (call-interactively command))
22380 (setq end (point))
22381 (goto-char beg)
22382 (when (and (bolp) subtreep
22383 (not (setq swallowp
22384 (org-yank-folding-would-swallow-text beg end))))
22385 (org-with-limited-levels
22386 (or (looking-at org-outline-regexp)
22387 (re-search-forward org-outline-regexp-bol end t))
22388 (while (and (< (point) end) (looking-at org-outline-regexp))
22389 (hide-subtree)
22390 (org-cycle-show-empty-lines 'folded)
22391 (condition-case nil
22392 (outline-forward-same-level 1)
22393 (error (goto-char end))))))
22394 (when swallowp
22395 (message
22396 "Inserted text not folded because that would swallow text"))
22398 (goto-char end)
22399 (skip-chars-forward " \t\n\r")
22400 (beginning-of-line 1)
22401 (push-mark beg 'nomsg)))
22402 ((and subtreep org-yank-adjusted-subtrees)
22403 (let ((beg (point-at-bol)))
22404 (org-paste-subtree nil nil 'for-yank)
22405 (push-mark beg 'nomsg)))
22407 (call-interactively command))))))
22409 (defun org-yank-folding-would-swallow-text (beg end)
22410 "Would hide-subtree at BEG swallow any text after END?"
22411 (let (level)
22412 (org-with-limited-levels
22413 (save-excursion
22414 (goto-char beg)
22415 (when (or (looking-at org-outline-regexp)
22416 (re-search-forward org-outline-regexp-bol end t))
22417 (setq level (org-outline-level)))
22418 (goto-char end)
22419 (skip-chars-forward " \t\r\n\v\f")
22420 (if (or (eobp)
22421 (and (bolp) (looking-at org-outline-regexp)
22422 (<= (org-outline-level) level)))
22423 nil ; Nothing would be swallowed
22424 t))))) ; something would swallow
22426 (define-key org-mode-map "\C-y" 'org-yank)
22428 (defun org-truely-invisible-p ()
22429 "Check if point is at a character currently not visible.
22430 This version does not only check the character property, but also
22431 `visible-mode'."
22432 ;; Early versions of noutline don't have `outline-invisible-p'.
22433 (if (org-bound-and-true-p visible-mode)
22435 (outline-invisible-p)))
22437 (defun org-invisible-p2 ()
22438 "Check if point is at a character currently not visible."
22439 (save-excursion
22440 (if (and (eolp) (not (bobp))) (backward-char 1))
22441 ;; Early versions of noutline don't have `outline-invisible-p'.
22442 (outline-invisible-p)))
22444 (defun org-back-to-heading (&optional invisible-ok)
22445 "Call `outline-back-to-heading', but provide a better error message."
22446 (condition-case nil
22447 (outline-back-to-heading invisible-ok)
22448 (error (error "Before first headline at position %d in buffer %s"
22449 (point) (current-buffer)))))
22451 (defun org-before-first-heading-p ()
22452 "Before first heading?"
22453 (save-excursion
22454 (end-of-line)
22455 (null (re-search-backward org-outline-regexp-bol nil t))))
22457 (defun org-at-heading-p (&optional ignored)
22458 (outline-on-heading-p t))
22459 ;; Compatibility alias with Org versions < 7.8.03
22460 (defalias 'org-on-heading-p 'org-at-heading-p)
22462 (defun org-at-comment-p nil
22463 "Is cursor in a line starting with a # character?"
22464 (save-excursion
22465 (beginning-of-line)
22466 (looking-at "^#")))
22468 (defun org-at-drawer-p nil
22469 "Is cursor at a drawer keyword?"
22470 (save-excursion
22471 (move-beginning-of-line 1)
22472 (looking-at org-drawer-regexp)))
22474 (defun org-at-block-p nil
22475 "Is cursor at a block keyword?"
22476 (save-excursion
22477 (move-beginning-of-line 1)
22478 (looking-at org-block-regexp)))
22480 (defun org-point-at-end-of-empty-headline ()
22481 "If point is at the end of an empty headline, return t, else nil.
22482 If the heading only contains a TODO keyword, it is still still considered
22483 empty."
22484 (and (looking-at "[ \t]*$")
22485 (when org-todo-line-regexp
22486 (save-excursion
22487 (beginning-of-line 1)
22488 (let ((case-fold-search nil))
22489 (looking-at org-todo-line-regexp)
22490 (string= (match-string 3) ""))))))
22492 (defun org-at-heading-or-item-p ()
22493 (or (org-at-heading-p) (org-at-item-p)))
22495 (defun org-at-target-p ()
22496 (or (org-in-regexp org-radio-target-regexp)
22497 (org-in-regexp org-target-regexp)))
22498 ;; Compatibility alias with Org versions < 7.8.03
22499 (defalias 'org-on-target-p 'org-at-target-p)
22501 (defun org-up-heading-all (arg)
22502 "Move to the heading line of which the present line is a subheading.
22503 This function considers both visible and invisible heading lines.
22504 With argument, move up ARG levels."
22505 (if (fboundp 'outline-up-heading-all)
22506 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22507 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22509 (defun org-up-heading-safe ()
22510 "Move to the heading line of which the present line is a subheading.
22511 This version will not throw an error. It will return the level of the
22512 headline found, or nil if no higher level is found.
22514 Also, this function will be a lot faster than `outline-up-heading',
22515 because it relies on stars being the outline starters. This can really
22516 make a significant difference in outlines with very many siblings."
22517 (let (start-level re)
22518 (org-back-to-heading t)
22519 (setq start-level (funcall outline-level))
22520 (if (equal start-level 1)
22522 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22523 (if (re-search-backward re nil t)
22524 (funcall outline-level)))))
22526 (defun org-first-sibling-p ()
22527 "Is this heading the first child of its parents?"
22528 (interactive)
22529 (let ((re org-outline-regexp-bol)
22530 level l)
22531 (unless (org-at-heading-p t)
22532 (error "Not at a heading"))
22533 (setq level (funcall outline-level))
22534 (save-excursion
22535 (if (not (re-search-backward re nil t))
22537 (setq l (funcall outline-level))
22538 (< l level)))))
22540 (defun org-goto-sibling (&optional previous)
22541 "Goto the next sibling, even if it is invisible.
22542 When PREVIOUS is set, go to the previous sibling instead. Returns t
22543 when a sibling was found. When none is found, return nil and don't
22544 move point."
22545 (let ((fun (if previous 're-search-backward 're-search-forward))
22546 (pos (point))
22547 (re org-outline-regexp-bol)
22548 level l)
22549 (when (condition-case nil (org-back-to-heading t) (error nil))
22550 (setq level (funcall outline-level))
22551 (catch 'exit
22552 (or previous (forward-char 1))
22553 (while (funcall fun re nil t)
22554 (setq l (funcall outline-level))
22555 (when (< l level) (goto-char pos) (throw 'exit nil))
22556 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22557 (goto-char pos)
22558 nil))))
22560 (defun org-show-siblings ()
22561 "Show all siblings of the current headline."
22562 (save-excursion
22563 (while (org-goto-sibling) (org-flag-heading nil)))
22564 (save-excursion
22565 (while (org-goto-sibling 'previous)
22566 (org-flag-heading nil))))
22568 (defun org-goto-first-child ()
22569 "Goto the first child, even if it is invisible.
22570 Return t when a child was found. Otherwise don't move point and
22571 return nil."
22572 (let (level (pos (point)) (re org-outline-regexp-bol))
22573 (when (condition-case nil (org-back-to-heading t) (error nil))
22574 (setq level (outline-level))
22575 (forward-char 1)
22576 (if (and (re-search-forward re nil t) (> (outline-level) level))
22577 (progn (goto-char (match-beginning 0)) t)
22578 (goto-char pos) nil))))
22580 (defun org-show-hidden-entry ()
22581 "Show an entry where even the heading is hidden."
22582 (save-excursion
22583 (org-show-entry)))
22585 (defun org-flag-heading (flag &optional entry)
22586 "Flag the current heading. FLAG non-nil means make invisible.
22587 When ENTRY is non-nil, show the entire entry."
22588 (save-excursion
22589 (org-back-to-heading t)
22590 ;; Check if we should show the entire entry
22591 (if entry
22592 (progn
22593 (org-show-entry)
22594 (save-excursion
22595 (and (outline-next-heading)
22596 (org-flag-heading nil))))
22597 (outline-flag-region (max (point-min) (1- (point)))
22598 (save-excursion (outline-end-of-heading) (point))
22599 flag))))
22601 (defun org-get-next-sibling ()
22602 "Move to next heading of the same level, and return point.
22603 If there is no such heading, return nil.
22604 This is like outline-next-sibling, but invisible headings are ok."
22605 (let ((level (funcall outline-level)))
22606 (outline-next-heading)
22607 (while (and (not (eobp)) (> (funcall outline-level) level))
22608 (outline-next-heading))
22609 (if (or (eobp) (< (funcall outline-level) level))
22611 (point))))
22613 (defun org-get-last-sibling ()
22614 "Move to previous heading of the same level, and return point.
22615 If there is no such heading, return nil."
22616 (let ((opoint (point))
22617 (level (funcall outline-level)))
22618 (outline-previous-heading)
22619 (when (and (/= (point) opoint) (outline-on-heading-p t))
22620 (while (and (> (funcall outline-level) level)
22621 (not (bobp)))
22622 (outline-previous-heading))
22623 (if (< (funcall outline-level) level)
22625 (point)))))
22627 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22628 "Goto to the end of a subtree."
22629 ;; This contains an exact copy of the original function, but it uses
22630 ;; `org-back-to-heading', to make it work also in invisible
22631 ;; trees. And is uses an invisible-ok argument.
22632 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22633 ;; Furthermore, when used inside Org, finding the end of a large subtree
22634 ;; with many children and grandchildren etc, this can be much faster
22635 ;; than the outline version.
22636 (org-back-to-heading invisible-ok)
22637 (let ((first t)
22638 (level (funcall outline-level)))
22639 (if (and (derived-mode-p 'org-mode) (< level 1000))
22640 ;; A true heading (not a plain list item), in Org-mode
22641 ;; This means we can easily find the end by looking
22642 ;; only for the right number of stars. Using a regexp to do
22643 ;; this is so much faster than using a Lisp loop.
22644 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22645 (forward-char 1)
22646 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22647 ;; something else, do it the slow way
22648 (while (and (not (eobp))
22649 (or first (> (funcall outline-level) level)))
22650 (setq first nil)
22651 (outline-next-heading)))
22652 (unless to-heading
22653 (if (memq (preceding-char) '(?\n ?\^M))
22654 (progn
22655 ;; Go to end of line before heading
22656 (forward-char -1)
22657 (if (memq (preceding-char) '(?\n ?\^M))
22658 ;; leave blank line before heading
22659 (forward-char -1))))))
22660 (point))
22662 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22663 "Use Org version in org-mode, for dramatic speed-up."
22664 (if (derived-mode-p 'org-mode)
22665 (progn
22666 (org-end-of-subtree nil t)
22667 (unless (eobp) (backward-char 1)))
22668 ad-do-it))
22670 (defun org-end-of-meta-data-and-drawers ()
22671 "Jump to the first text after meta data and drawers in the current entry.
22672 This will move over empty lines, lines with planning time stamps,
22673 clocking lines, and drawers."
22674 (org-back-to-heading t)
22675 (let ((end (save-excursion (outline-next-heading) (point)))
22676 (re (concat "\\(" org-drawer-regexp "\\)"
22677 "\\|" "[ \t]*" org-keyword-time-regexp)))
22678 (forward-line 1)
22679 (while (re-search-forward re end t)
22680 (if (not (match-end 1))
22681 ;; empty or planning line
22682 (forward-line 1)
22683 ;; a drawer, find the end
22684 (re-search-forward "^[ \t]*:END:" end 'move)
22685 (forward-line 1)))
22686 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22687 (point)))
22689 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22690 "Move forward to the ARG'th subheading at same level as this one.
22691 Stop at the first and last subheadings of a superior heading.
22692 Normally this only looks at visible headings, but when INVISIBLE-OK is
22693 non-nil it will also look at invisible ones."
22694 (interactive "p")
22695 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22696 (if (and arg (< arg 0))
22697 (goto-char (point-min))
22698 (outline-next-heading))
22699 (org-at-heading-p)
22700 (let ((level (- (match-end 0) (match-beginning 0) 1))
22701 (f (if (and arg (< arg 0))
22702 're-search-backward
22703 're-search-forward))
22704 (count (if arg (abs arg) 1))
22705 (result (point)))
22706 (forward-char (if (and arg (< arg 0)) -1 1))
22707 (while (and (> count 0)
22708 (funcall f org-outline-regexp-bol nil 'move))
22709 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22710 (cond ((< l level) (setq count 0))
22711 ((and (= l level)
22712 (or invisible-ok
22713 (progn
22714 (goto-char (line-beginning-position))
22715 (not (outline-invisible-p)))))
22716 (setq count (1- count))
22717 (when (eq l level)
22718 (setq result (point)))))))
22719 (goto-char result))
22720 (beginning-of-line 1)))
22722 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22723 "Move backward to the ARG'th subheading at same level as this one.
22724 Stop at the first and last subheadings of a superior heading."
22725 (interactive "p")
22726 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22728 (defun org-next-block (arg &optional backward block-regexp)
22729 "Jump to the next block.
22730 With a prefix argument ARG, jump forward ARG many source blocks.
22731 When BACKWARD is non-nil, jump to the previous block.
22732 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22733 (interactive "p")
22734 (let ((re (or block-regexp org-block-regexp))
22735 (re-search-fn (or (and backward 're-search-backward)
22736 're-search-forward)))
22737 (if (looking-at re) (forward-char 1))
22738 (condition-case nil
22739 (funcall re-search-fn re nil nil arg)
22740 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22741 (goto-char (match-beginning 0)) (org-show-context)))
22743 (defun org-previous-block (arg &optional block-regexp)
22744 "Jump to the previous block.
22745 With a prefix argument ARG, jump backward ARG many source blocks.
22746 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22747 (interactive "p")
22748 (org-next-block arg t block-regexp))
22750 (defun org-forward-element ()
22751 "Move forward by one element.
22752 Move to the next element at the same level, when possible."
22753 (interactive)
22754 (cond ((eobp) (user-error "Cannot move further down"))
22755 ((org-with-limited-levels (org-at-heading-p))
22756 (let ((origin (point)))
22757 (goto-char (org-end-of-subtree nil t))
22758 (unless (org-with-limited-levels (org-at-heading-p))
22759 (goto-char origin)
22760 (user-error "Cannot move further down"))))
22762 (let* ((elem (org-element-at-point))
22763 (end (org-element-property :end elem))
22764 (parent (org-element-property :parent elem)))
22765 (if (and parent (= (org-element-property :contents-end parent) end))
22766 (goto-char (org-element-property :end parent))
22767 (goto-char end))))))
22769 (defun org-backward-element ()
22770 "Move backward by one element.
22771 Move to the previous element at the same level, when possible."
22772 (interactive)
22773 (cond ((bobp) (user-error "Cannot move further up"))
22774 ((org-with-limited-levels (org-at-heading-p))
22775 ;; At a headline, move to the previous one, if any, or stay
22776 ;; here.
22777 (let ((origin (point)))
22778 (org-with-limited-levels (org-backward-heading-same-level 1))
22779 ;; When current headline has no sibling above, move to its
22780 ;; parent.
22781 (when (= (point) origin)
22782 (or (org-with-limited-levels (org-up-heading-safe))
22783 (progn (goto-char origin)
22784 (user-error "Cannot move further up"))))))
22786 (let* ((trail (org-element-at-point 'keep-trail))
22787 (elem (car trail))
22788 (prev-elem (nth 1 trail))
22789 (beg (org-element-property :begin elem)))
22790 (cond
22791 ;; Move to beginning of current element if point isn't
22792 ;; there already.
22793 ((/= (point) beg) (goto-char beg))
22794 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22795 ((org-before-first-heading-p) (goto-char (point-min)))
22796 (t (org-back-to-heading)))))))
22798 (defun org-up-element ()
22799 "Move to upper element."
22800 (interactive)
22801 (if (org-with-limited-levels (org-at-heading-p))
22802 (unless (org-up-heading-safe) (error "No surrounding element"))
22803 (let* ((elem (org-element-at-point))
22804 (parent (org-element-property :parent elem)))
22805 (if parent (goto-char (org-element-property :begin parent))
22806 (if (org-with-limited-levels (org-before-first-heading-p))
22807 (error "No surrounding element")
22808 (org-with-limited-levels (org-back-to-heading)))))))
22810 (defvar org-element-greater-elements)
22811 (defun org-down-element ()
22812 "Move to inner element."
22813 (interactive)
22814 (let ((element (org-element-at-point)))
22815 (cond
22816 ((memq (org-element-type element) '(plain-list table))
22817 (goto-char (org-element-property :contents-begin element))
22818 (forward-char))
22819 ((memq (org-element-type element) org-element-greater-elements)
22820 ;; If contents are hidden, first disclose them.
22821 (when (org-element-property :hiddenp element) (org-cycle))
22822 (goto-char (or (org-element-property :contents-begin element)
22823 (error "No content for this element"))))
22824 (t (error "No inner element")))))
22826 (defun org-drag-element-backward ()
22827 "Move backward element at point."
22828 (interactive)
22829 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22830 (let* ((trail (org-element-at-point 'keep-trail))
22831 (elem (car trail))
22832 (prev-elem (nth 1 trail)))
22833 ;; Error out if no previous element or previous element is
22834 ;; a parent of the current one.
22835 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22836 (error "Cannot drag element backward")
22837 (let ((pos (point)))
22838 (org-element-swap-A-B prev-elem elem)
22839 (goto-char (+ (org-element-property :begin prev-elem)
22840 (- pos (org-element-property :begin elem)))))))))
22842 (defun org-drag-element-forward ()
22843 "Move forward element at point."
22844 (interactive)
22845 (let* ((pos (point))
22846 (elem (org-element-at-point)))
22847 (when (= (point-max) (org-element-property :end elem))
22848 (error "Cannot drag element forward"))
22849 (goto-char (org-element-property :end elem))
22850 (let ((next-elem (org-element-at-point)))
22851 (when (or (org-element-nested-p elem next-elem)
22852 (and (eq (org-element-type next-elem) 'headline)
22853 (not (eq (org-element-type elem) 'headline))))
22854 (goto-char pos)
22855 (error "Cannot drag element forward"))
22856 ;; Compute new position of point: it's shifted by NEXT-ELEM
22857 ;; body's length (without final blanks) and by the length of
22858 ;; blanks between ELEM and NEXT-ELEM.
22859 (let ((size-next (- (save-excursion
22860 (goto-char (org-element-property :end next-elem))
22861 (skip-chars-backward " \r\t\n")
22862 (forward-line)
22863 ;; Small correction if buffer doesn't end
22864 ;; with a newline character.
22865 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22866 (org-element-property :begin next-elem)))
22867 (size-blank (- (org-element-property :end elem)
22868 (save-excursion
22869 (goto-char (org-element-property :end elem))
22870 (skip-chars-backward " \r\t\n")
22871 (forward-line)
22872 (point)))))
22873 (org-element-swap-A-B elem next-elem)
22874 (goto-char (+ pos size-next size-blank))))))
22876 (defun org-drag-line-forward (arg)
22877 "Drag the line at point ARG lines forward."
22878 (interactive "p")
22879 (dotimes (n (abs arg))
22880 (let ((c (current-column)))
22881 (if (< 0 arg)
22882 (progn
22883 (beginning-of-line 2)
22884 (transpose-lines 1)
22885 (beginning-of-line 0))
22886 (transpose-lines 1)
22887 (beginning-of-line -1))
22888 (org-move-to-column c))))
22890 (defun org-drag-line-backward (arg)
22891 "Drag the line at point ARG lines backward."
22892 (interactive "p")
22893 (org-drag-line-forward (- arg)))
22895 (defun org-mark-element ()
22896 "Put point at beginning of this element, mark at end.
22898 Interactively, if this command is repeated or (in Transient Mark
22899 mode) if the mark is active, it marks the next element after the
22900 ones already marked."
22901 (interactive)
22902 (let (deactivate-mark)
22903 (if (and (org-called-interactively-p 'any)
22904 (or (and (eq last-command this-command) (mark t))
22905 (and transient-mark-mode mark-active)))
22906 (set-mark
22907 (save-excursion
22908 (goto-char (mark))
22909 (goto-char (org-element-property :end (org-element-at-point)))))
22910 (let ((element (org-element-at-point)))
22911 (end-of-line)
22912 (push-mark (org-element-property :end element) t t)
22913 (goto-char (org-element-property :begin element))))))
22915 (defun org-narrow-to-element ()
22916 "Narrow buffer to current element."
22917 (interactive)
22918 (let ((elem (org-element-at-point)))
22919 (cond
22920 ((eq (car elem) 'headline)
22921 (narrow-to-region
22922 (org-element-property :begin elem)
22923 (org-element-property :end elem)))
22924 ((memq (car elem) org-element-greater-elements)
22925 (narrow-to-region
22926 (org-element-property :contents-begin elem)
22927 (org-element-property :contents-end elem)))
22929 (narrow-to-region
22930 (org-element-property :begin elem)
22931 (org-element-property :end elem))))))
22933 (defun org-transpose-element ()
22934 "Transpose current and previous elements, keeping blank lines between.
22935 Point is moved after both elements."
22936 (interactive)
22937 (org-skip-whitespace)
22938 (let ((end (org-element-property :end (org-element-at-point))))
22939 (org-drag-element-backward)
22940 (goto-char end)))
22942 (defun org-unindent-buffer ()
22943 "Un-indent the visible part of the buffer.
22944 Relative indentation (between items, inside blocks, etc.) isn't
22945 modified."
22946 (interactive)
22947 (unless (eq major-mode 'org-mode)
22948 (error "Cannot un-indent a buffer not in Org mode"))
22949 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22950 unindent-tree ; For byte-compiler.
22951 (unindent-tree
22952 (function
22953 (lambda (contents)
22954 (mapc
22955 (lambda (element)
22956 (if (memq (org-element-type element) '(headline section))
22957 (funcall unindent-tree (org-element-contents element))
22958 (save-excursion
22959 (save-restriction
22960 (narrow-to-region
22961 (org-element-property :begin element)
22962 (org-element-property :end element))
22963 (org-do-remove-indentation)))))
22964 (reverse contents))))))
22965 (funcall unindent-tree (org-element-contents parse-tree))))
22967 (defun org-show-subtree ()
22968 "Show everything after this heading at deeper levels."
22969 (interactive)
22970 (outline-flag-region
22971 (point)
22972 (save-excursion
22973 (org-end-of-subtree t t))
22974 nil))
22976 (defun org-show-entry ()
22977 "Show the body directly following this heading.
22978 Show the heading too, if it is currently invisible."
22979 (interactive)
22980 (save-excursion
22981 (condition-case nil
22982 (progn
22983 (org-back-to-heading t)
22984 (outline-flag-region
22985 (max (point-min) (1- (point)))
22986 (save-excursion
22987 (if (re-search-forward
22988 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22989 (match-beginning 1)
22990 (point-max)))
22991 nil)
22992 (org-cycle-hide-drawers 'children))
22993 (error nil))))
22995 (defun org-make-options-regexp (kwds &optional extra)
22996 "Make a regular expression for keyword lines."
22997 (concat
22998 "^#\\+\\("
22999 (mapconcat 'regexp-quote kwds "\\|")
23000 (if extra (concat "\\|" extra))
23001 "\\):[ \t]*\\(.*\\)"))
23003 ;; Make isearch reveal the necessary context
23004 (defun org-isearch-end ()
23005 "Reveal context after isearch exits."
23006 (when isearch-success ; only if search was successful
23007 (if (featurep 'xemacs)
23008 ;; Under XEmacs, the hook is run in the correct place,
23009 ;; we directly show the context.
23010 (org-show-context 'isearch)
23011 ;; In Emacs the hook runs *before* restoring the overlays.
23012 ;; So we have to use a one-time post-command-hook to do this.
23013 ;; (Emacs 22 has a special variable, see function `org-mode')
23014 (unless (and (boundp 'isearch-mode-end-hook-quit)
23015 isearch-mode-end-hook-quit)
23016 ;; Only when the isearch was not quitted.
23017 (org-add-hook 'post-command-hook 'org-isearch-post-command
23018 'append 'local)))
23019 (org-fix-ellipsis-at-bol)))
23021 (defun org-isearch-post-command ()
23022 "Remove self from hook, and show context."
23023 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23024 (org-show-context 'isearch))
23027 ;;;; Integration with and fixes for other packages
23029 ;;; Imenu support
23031 (defvar org-imenu-markers nil
23032 "All markers currently used by Imenu.")
23033 (make-variable-buffer-local 'org-imenu-markers)
23035 (defun org-imenu-new-marker (&optional pos)
23036 "Return a new marker for use by Imenu, and remember the marker."
23037 (let ((m (make-marker)))
23038 (move-marker m (or pos (point)))
23039 (push m org-imenu-markers)
23042 (defun org-imenu-get-tree ()
23043 "Produce the index for Imenu."
23044 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23045 (setq org-imenu-markers nil)
23046 (let* ((n org-imenu-depth)
23047 (re (concat "^" (org-get-limited-outline-regexp)))
23048 (subs (make-vector (1+ n) nil))
23049 (last-level 0)
23050 m level head0 head)
23051 (save-excursion
23052 (save-restriction
23053 (widen)
23054 (goto-char (point-max))
23055 (while (re-search-backward re nil t)
23056 (setq level (org-reduced-level (funcall outline-level)))
23057 (when (and (<= level n)
23058 (looking-at org-complex-heading-regexp)
23059 (setq head0 (org-match-string-no-properties 4)))
23060 (setq head (org-link-display-format head0)
23061 m (org-imenu-new-marker))
23062 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23063 (if (>= level last-level)
23064 (push (cons head m) (aref subs level))
23065 (push (cons head (aref subs (1+ level))) (aref subs level))
23066 (loop for i from (1+ level) to n do (aset subs i nil)))
23067 (setq last-level level)))))
23068 (aref subs 1)))
23070 (eval-after-load "imenu"
23071 '(progn
23072 (add-hook 'imenu-after-jump-hook
23073 (lambda ()
23074 (if (derived-mode-p 'org-mode)
23075 (org-show-context 'org-goto))))))
23077 (defun org-link-display-format (link)
23078 "Replace a link with either the description, or the link target
23079 if no description is present"
23080 (save-match-data
23081 (if (string-match org-bracket-link-analytic-regexp link)
23082 (replace-match (if (match-end 5)
23083 (match-string 5 link)
23084 (concat (match-string 1 link)
23085 (match-string 3 link)))
23086 nil t link)
23087 link)))
23089 (defun org-toggle-link-display ()
23090 "Toggle the literal or descriptive display of links."
23091 (interactive)
23092 (if org-descriptive-links
23093 (progn (org-remove-from-invisibility-spec '(org-link))
23094 (org-restart-font-lock)
23095 (setq org-descriptive-links nil))
23096 (progn (add-to-invisibility-spec '(org-link))
23097 (org-restart-font-lock)
23098 (setq org-descriptive-links t))))
23100 ;; Speedbar support
23102 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23103 "Overlay marking the agenda restriction line in speedbar.")
23104 (overlay-put org-speedbar-restriction-lock-overlay
23105 'face 'org-agenda-restriction-lock)
23106 (overlay-put org-speedbar-restriction-lock-overlay
23107 'help-echo "Agendas are currently limited to this item.")
23108 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23110 (defun org-speedbar-set-agenda-restriction ()
23111 "Restrict future agenda commands to the location at point in speedbar.
23112 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23113 (interactive)
23114 (require 'org-agenda)
23115 (let (p m tp np dir txt)
23116 (cond
23117 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23118 'org-imenu t))
23119 (setq m (get-text-property p 'org-imenu-marker))
23120 (with-current-buffer (marker-buffer m)
23121 (goto-char m)
23122 (org-agenda-set-restriction-lock 'subtree)))
23123 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23124 'speedbar-function 'speedbar-find-file))
23125 (setq tp (previous-single-property-change
23126 (1+ p) 'speedbar-function)
23127 np (next-single-property-change
23128 tp 'speedbar-function)
23129 dir (speedbar-line-directory)
23130 txt (buffer-substring-no-properties (or tp (point-min))
23131 (or np (point-max))))
23132 (with-current-buffer (find-file-noselect
23133 (let ((default-directory dir))
23134 (expand-file-name txt)))
23135 (unless (derived-mode-p 'org-mode)
23136 (error "Cannot restrict to non-Org-mode file"))
23137 (org-agenda-set-restriction-lock 'file)))
23138 (t (error "Don't know how to restrict Org-mode's agenda")))
23139 (move-overlay org-speedbar-restriction-lock-overlay
23140 (point-at-bol) (point-at-eol))
23141 (setq current-prefix-arg nil)
23142 (org-agenda-maybe-redo)))
23144 (eval-after-load "speedbar"
23145 '(progn
23146 (speedbar-add-supported-extension ".org")
23147 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23148 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23149 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23150 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23151 (add-hook 'speedbar-visiting-tag-hook
23152 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23154 ;;; Fixes and Hacks for problems with other packages
23156 ;; Make flyspell not check words in links, to not mess up our keymap
23157 (defvar org-element-affiliated-keywords) ; From org-element.el
23158 (defvar org-element-block-name-alist) ; From org-element.el
23159 (defun org-mode-flyspell-verify ()
23160 "Don't let flyspell put overlays at active buttons, or on
23161 {todo,all-time,additional-option-like}-keywords."
23162 (let ((pos (max (1- (point)) (point-min)))
23163 (word (thing-at-point 'word)))
23164 (and (not (get-text-property pos 'keymap))
23165 (not (get-text-property pos 'org-no-flyspell))
23166 (not (member word org-todo-keywords-1))
23167 (not (member word org-all-time-keywords))
23168 (not (member word org-options-keywords))
23169 (not (member word (mapcar 'car org-startup-options)))
23170 (not (member-ignore-case word org-element-affiliated-keywords))
23171 (not (member-ignore-case word (org-get-export-keywords)))
23172 (not (member-ignore-case
23173 word (mapcar 'car org-element-block-name-alist)))
23174 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23176 (defun org-remove-flyspell-overlays-in (beg end)
23177 "Remove flyspell overlays in region."
23178 (and (org-bound-and-true-p flyspell-mode)
23179 (fboundp 'flyspell-delete-region-overlays)
23180 (flyspell-delete-region-overlays beg end))
23181 (add-text-properties beg end '(org-no-flyspell t)))
23183 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23184 (eval-after-load "bookmark"
23185 '(if (boundp 'bookmark-after-jump-hook)
23186 ;; We can use the hook
23187 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23188 ;; Hook not available, use advice
23189 (defadvice bookmark-jump (after org-make-visible activate)
23190 "Make the position visible."
23191 (org-bookmark-jump-unhide))))
23193 ;; Make sure saveplace shows the location if it was hidden
23194 (eval-after-load "saveplace"
23195 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23196 "Make the position visible."
23197 (org-bookmark-jump-unhide)))
23199 ;; Make sure ecb shows the location if it was hidden
23200 (eval-after-load "ecb"
23201 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23202 "Make hierarchy visible when jumping into location from ECB tree buffer."
23203 (if (derived-mode-p 'org-mode)
23204 (org-show-context))))
23206 (defun org-bookmark-jump-unhide ()
23207 "Unhide the current position, to show the bookmark location."
23208 (and (derived-mode-p 'org-mode)
23209 (or (outline-invisible-p)
23210 (save-excursion (goto-char (max (point-min) (1- (point))))
23211 (outline-invisible-p)))
23212 (org-show-context 'bookmark-jump)))
23214 ;; Make session.el ignore our circular variable
23215 (eval-after-load "session"
23216 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23218 ;;;; Experimental code
23220 (defun org-closed-in-range ()
23221 "Sparse tree of items closed in a certain time range.
23222 Still experimental, may disappear in the future."
23223 (interactive)
23224 ;; Get the time interval from the user.
23225 (let* ((time1 (org-float-time
23226 (org-read-date nil 'to-time nil "Starting date: ")))
23227 (time2 (org-float-time
23228 (org-read-date nil 'to-time nil "End date:")))
23229 ;; callback function
23230 (callback (lambda ()
23231 (let ((time
23232 (org-float-time
23233 (apply 'encode-time
23234 (org-parse-time-string
23235 (match-string 1))))))
23236 ;; check if time in interval
23237 (and (>= time time1) (<= time time2))))))
23238 ;; make tree, check each match with the callback
23239 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23241 ;;;; Finish up
23243 (provide 'org)
23245 (run-hooks 'org-load-hook)
23247 ;;; org.el ends here