org.el (org-clone-subtree-with-time-shift): Don't prompt for a time shift by default
[org-mode.git] / lisp / org.el
blobb6a972c1f3909691e0252304f24333b101737879
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 (unless (boundp 'calendar-view-holidays-initially-flag)
107 (org-defvaralias 'calendar-view-holidays-initially-flag
108 'view-calendar-holidays-initially))
109 (unless (boundp 'calendar-view-diary-initially-flag)
110 (org-defvaralias 'calendar-view-diary-initially-flag
111 'view-diary-entries-initially))
112 (unless (boundp 'diary-fancy-buffer)
113 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
115 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
116 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
117 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
118 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
121 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
122 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
124 (declare-function orgtbl-mode "org-table" (&optional arg))
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-beamer-mode "ox-beamer" ())
127 (declare-function org-table-edit-field "org-table" (arg))
128 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
129 (declare-function org-id-get-create "org-id" (&optional force))
130 (declare-function org-id-find-id-file "org-id" (id))
131 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
132 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
133 (declare-function org-table-align "org-table" ())
134 (declare-function org-table-paste-rectangle "org-table" ())
135 (declare-function org-table-maybe-eval-formula "org-table" ())
136 (declare-function org-table-maybe-recalculate-line "org-table" ())
138 (declare-function org-element--parse-objects "org-element"
139 (beg end acc restriction))
140 (declare-function org-element-at-point "org-element" (&optional keep-trail))
141 (declare-function org-element-contents "org-element" (element))
142 (declare-function org-element-context "org-element" (&optional element))
143 (declare-function org-element-interpret-data "org-element"
144 (data &optional parent))
145 (declare-function org-element-map "org-element"
146 (data types fun &optional info first-match no-recursion))
147 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
148 (declare-function org-element-parse-buffer "org-element"
149 (&optional granularity visible-only))
150 (declare-function org-element-property "org-element" (property element))
151 (declare-function org-element-put-property "org-element"
152 (element property value))
153 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
154 (declare-function org-element--parse-objects "org-element"
155 (beg end acc restriction))
156 (declare-function org-element-parse-buffer "org-element"
157 (&optional granularity visible-only))
158 (declare-function org-element-restriction "org-element" (element))
159 (declare-function org-element-type "org-element" (element))
161 ;; load languages based on value of `org-babel-load-languages'
162 (defvar org-babel-load-languages)
164 ;;;###autoload
165 (defun org-babel-do-load-languages (sym value)
166 "Load the languages defined in `org-babel-load-languages'."
167 (set-default sym value)
168 (mapc (lambda (pair)
169 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
170 (if active
171 (progn
172 (require (intern (concat "ob-" lang))))
173 (progn
174 (funcall 'fmakunbound
175 (intern (concat "org-babel-execute:" lang)))
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-expand-body:" lang)))))))
178 org-babel-load-languages))
180 (defcustom org-babel-load-languages '((emacs-lisp . t))
181 "Languages which can be evaluated in Org-mode buffers.
182 This list can be used to load support for any of the languages
183 below, note that each language will depend on a different set of
184 system executables and/or Emacs modes. When a language is
185 \"loaded\", then code blocks in that language can be evaluated
186 with `org-babel-execute-src-block' bound by default to C-c
187 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
188 be set to remove code block evaluation from the C-c C-c
189 keybinding. By default only Emacs Lisp (which has no
190 requirements) is loaded."
191 :group 'org-babel
192 :set 'org-babel-do-load-languages
193 :version "24.1"
194 :type '(alist :tag "Babel Languages"
195 :key-type
196 (choice
197 (const :tag "Awk" awk)
198 (const :tag "C" C)
199 (const :tag "R" R)
200 (const :tag "Asymptote" asymptote)
201 (const :tag "Calc" calc)
202 (const :tag "Clojure" clojure)
203 (const :tag "CSS" css)
204 (const :tag "Ditaa" ditaa)
205 (const :tag "Dot" dot)
206 (const :tag "Emacs Lisp" emacs-lisp)
207 (const :tag "Fortran" fortran)
208 (const :tag "Gnuplot" gnuplot)
209 (const :tag "Haskell" haskell)
210 (const :tag "IO" io)
211 (const :tag "Java" java)
212 (const :tag "Javascript" js)
213 (const :tag "LaTeX" latex)
214 (const :tag "Ledger" ledger)
215 (const :tag "Lilypond" lilypond)
216 (const :tag "Lisp" lisp)
217 (const :tag "Makefile" makefile)
218 (const :tag "Maxima" maxima)
219 (const :tag "Matlab" matlab)
220 (const :tag "Mscgen" mscgen)
221 (const :tag "Ocaml" ocaml)
222 (const :tag "Octave" octave)
223 (const :tag "Org" org)
224 (const :tag "Perl" perl)
225 (const :tag "Pico Lisp" picolisp)
226 (const :tag "PlantUML" plantuml)
227 (const :tag "Python" python)
228 (const :tag "Ruby" ruby)
229 (const :tag "Sass" sass)
230 (const :tag "Scala" scala)
231 (const :tag "Scheme" scheme)
232 (const :tag "Screen" screen)
233 (const :tag "Shell Script" sh)
234 (const :tag "Shen" shen)
235 (const :tag "Sql" sql)
236 (const :tag "Sqlite" sqlite))
237 :value-type (boolean :tag "Activate" :value t)))
239 ;;;; Customization variables
240 (defcustom org-clone-delete-id nil
241 "Remove ID property of clones of a subtree.
242 When non-nil, clones of a subtree don't inherit the ID property.
243 Otherwise they inherit the ID property with a new unique
244 identifier."
245 :type 'boolean
246 :version "24.1"
247 :group 'org-id)
249 ;;; Version
250 (org-check-version)
252 ;;;###autoload
253 (defun org-version (&optional here full message)
254 "Show the org-mode version in the echo area.
255 With prefix argument HERE, insert it at point.
256 When FULL is non-nil, use a verbose version string.
257 When MESSAGE is non-nil, display a message with the version."
258 (interactive "P")
259 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
260 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
261 (load-suffixes (list ".el"))
262 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
263 (org-trash (or
264 (and (fboundp 'org-release) (fboundp 'org-git-version))
265 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
266 (load-suffixes save-load-suffixes)
267 (org-version (org-release))
268 (git-version (org-git-version))
269 (version (format "Org-mode version %s (%s @ %s)"
270 org-version
271 git-version
272 (if org-install-dir
273 (if (string= org-dir org-install-dir)
274 org-install-dir
275 (concat "mixed installation! " org-install-dir " and " org-dir))
276 "org-loaddefs.el can not be found!")))
277 (_version (if full version org-version)))
278 (if (org-called-interactively-p 'interactive)
279 (if here
280 (insert version)
281 (message version))
282 (if message (message _version))
283 _version)))
285 (defconst org-version (org-version))
287 ;;; Compatibility constants
289 ;;; The custom variables
291 (defgroup org nil
292 "Outline-based notes management and organizer."
293 :tag "Org"
294 :group 'outlines
295 :group 'calendar)
297 (defcustom org-mode-hook nil
298 "Mode hook for Org-mode, run after the mode was turned on."
299 :group 'org
300 :type 'hook)
302 (defcustom org-load-hook nil
303 "Hook that is run after org.el has been loaded."
304 :group 'org
305 :type 'hook)
307 (defcustom org-log-buffer-setup-hook nil
308 "Hook that is run after an Org log buffer is created."
309 :group 'org
310 :version "24.1"
311 :type 'hook)
313 (defvar org-modules) ; defined below
314 (defvar org-modules-loaded nil
315 "Have the modules been loaded already?")
317 (defun org-load-modules-maybe (&optional force)
318 "Load all extensions listed in `org-modules'."
319 (when (or force (not org-modules-loaded))
320 (mapc (lambda (ext)
321 (condition-case nil (require ext)
322 (error (message "Problems while trying to load feature `%s'" ext))))
323 org-modules)
324 (setq org-modules-loaded t)))
326 (defun org-set-modules (var value)
327 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
328 (set var value)
329 (when (featurep 'org)
330 (org-load-modules-maybe 'force)))
332 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
333 "Modules that should always be loaded together with org.el.
335 If a description starts with <C>, the file is not part of Emacs
336 and loading it will require that you have downloaded and properly
337 installed the Org mode distribution.
339 You can also use this system to load external packages (i.e. neither Org
340 core modules, nor modules from the CONTRIB directory). Just add symbols
341 to the end of the list. If the package is called org-xyz.el, then you need
342 to add the symbol `xyz', and the package must have a call to:
344 \(provide 'org-xyz)
346 For export specific modules, see also `org-export-backends'."
347 :group 'org
348 :set 'org-set-modules
349 :version "24.4"
350 :package-version '(Org . "8.0")
351 :type
352 '(set :greedy t
353 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
354 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
355 (const :tag " crypt: Encryption of subtrees" org-crypt)
356 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
357 (const :tag " docview: Links to doc-view buffers" org-docview)
358 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
359 (const :tag " id: Global IDs for identifying entries" org-id)
360 (const :tag " info: Links to Info nodes" org-info)
361 (const :tag " habit: Track your consistency with habits" org-habit)
362 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
363 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
364 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
365 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
366 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
367 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
368 (const :tag " mouse: Additional mouse support" org-mouse)
370 (const :tag "C vm: Links to VM folders/messages" org-vm)
371 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
372 (const :tag "C w3m: Special cut/paste from w3m to Org-mode." org-w3m)
373 (const :tag "C mew: Links to Mew folders/messages" org-mew)
374 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
375 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
376 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
377 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
378 (const :tag "C collector: Collect properties into tables" org-collector)
379 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
380 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
381 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
382 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
383 (const :tag "C eval: Include command output as text" org-eval)
384 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
385 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
386 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
387 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
388 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
390 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
392 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
393 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
394 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
395 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
396 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
397 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
398 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
399 (const :tag "C mtags: Support for muse-like tags" org-mtags)
400 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
401 (const :tag "C registry: A registry for Org-mode links" org-registry)
402 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
403 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
404 (const :tag "C secretary: Team management with org-mode" org-secretary)
405 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
406 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
407 (const :tag "C track: Keep up with Org-mode development" org-track)
408 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
409 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
410 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
412 (defvar org-export-registered-backends) ; From ox.el
413 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
414 (defcustom org-export-backends '(ascii html icalendar latex)
415 "List of export back-ends that should be always available.
417 If a description starts with <C>, the file is not part of Emacs
418 and loading it will require that you have downloaded and properly
419 installed the Org mode distribution.
421 Unlike to `org-modules', libraries in this list will not be
422 loaded along with Org, but only once the export framework is
423 needed.
425 This variable needs to be set before org.el is loaded. If you
426 need to make a change while Emacs is running, use the customize
427 interface or run the following code, where VALUE stands for the
428 new value of the variable, after updating it:
430 \(progn
431 \(setq org-export-registered-backends
432 \(org-remove-if-not
433 \(lambda (backend)
434 \(or (memq backend val)
435 \(catch 'parentp
436 \(mapc
437 \(lambda (b)
438 \(and (org-export-derived-backend-p b (car backend))
439 \(throw 'parentp t)))
440 val)
441 nil)))
442 org-export-registered-backends))
443 \(let ((new-list (mapcar 'car org-export-registered-backends)))
444 \(dolist (backend val)
445 \(cond
446 \((not (load (format \"ox-%s\" backend) t t))
447 \(message \"Problems while trying to load export back-end `%s'\"
448 backend))
449 \((not (memq backend new-list)) (push backend new-list))))
450 \(set-default var new-list)))
452 Adding a back-end to this list will also pull the back-end it
453 depends on, if any."
454 :group 'org
455 :group 'org-export
456 :version "24.4"
457 :package-version '(Org . "8.0")
458 :initialize 'custom-initialize-set
459 :set (lambda (var val)
460 (if (not (featurep 'ox)) (set-default var val)
461 ;; Any back-end not required anymore (not present in VAL and not
462 ;; a parent of any back-end in the new value) is removed from the
463 ;; list of registered back-ends.
464 (setq org-export-registered-backends
465 (org-remove-if-not
466 (lambda (backend)
467 (or (memq backend val)
468 (catch 'parentp
469 (mapc
470 (lambda (b)
471 (and (org-export-derived-backend-p b (car backend))
472 (throw 'parentp t)))
473 val)
474 nil)))
475 org-export-registered-backends))
476 ;; Now build NEW-LIST of both new back-ends and required
477 ;; parents.
478 (let ((new-list (mapcar 'car org-export-registered-backends)))
479 (dolist (backend val)
480 (cond
481 ((not (load (format "ox-%s" backend) t t))
482 (message "Problems while trying to load export back-end `%s'"
483 backend))
484 ((not (memq backend new-list)) (push backend new-list))))
485 ;; Set VAR to that list with fixed dependencies.
486 (set-default var new-list))))
487 :type '(set :greedy t
488 (const :tag " ascii Export buffer to ASCII format" ascii)
489 (const :tag " beamer Export buffer to Beamer presentation" beamer)
490 (const :tag " html Export buffer to HTML format" html)
491 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
492 (const :tag " latex Export buffer to LaTeX format" latex)
493 (const :tag " man Export buffer to MAN format" man)
494 (const :tag " md Export buffer to Markdown format" md)
495 (const :tag " odt Export buffer to ODT format" odt)
496 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
497 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
498 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
499 (const :tag "C groff Export buffer to Groff format" groff)
500 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
501 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
503 (eval-after-load 'ox
504 '(mapc
505 (lambda (backend)
506 (condition-case nil (require (intern (format "ox-%s" backend)))
507 (error (message "Problems while trying to load export back-end `%s'"
508 backend))))
509 org-export-backends))
511 (defcustom org-support-shift-select nil
512 "Non-nil means make shift-cursor commands select text when possible.
514 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
515 start selecting a region, or enlarge regions started in this way.
516 In Org-mode, in special contexts, these same keys are used for
517 other purposes, important enough to compete with shift selection.
518 Org tries to balance these needs by supporting `shift-select-mode'
519 outside these special contexts, under control of this variable.
521 The default of this variable is nil, to avoid confusing behavior. Shifted
522 cursor keys will then execute Org commands in the following contexts:
523 - on a headline, changing TODO state (left/right) and priority (up/down)
524 - on a time stamp, changing the time
525 - in a plain list item, changing the bullet type
526 - in a property definition line, switching between allowed values
527 - in the BEGIN line of a clock table (changing the time block).
528 Outside these contexts, the commands will throw an error.
530 When this variable is t and the cursor is not in a special
531 context, Org-mode will support shift-selection for making and
532 enlarging regions. To make this more effective, the bullet
533 cycling will no longer happen anywhere in an item line, but only
534 if the cursor is exactly on the bullet.
536 If you set this variable to the symbol `always', then the keys
537 will not be special in headlines, property lines, and item lines,
538 to make shift selection work there as well. If this is what you
539 want, you can use the following alternative commands: `C-c C-t'
540 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
541 can be used to switch TODO sets, `C-c -' to cycle item bullet
542 types, and properties can be edited by hand or in column view.
544 However, when the cursor is on a timestamp, shift-cursor commands
545 will still edit the time stamp - this is just too good to give up.
547 XEmacs user should have this variable set to nil, because
548 `shift-select-mode' is in Emacs 23 or later only."
549 :group 'org
550 :type '(choice
551 (const :tag "Never" nil)
552 (const :tag "When outside special context" t)
553 (const :tag "Everywhere except timestamps" always)))
555 (defcustom org-loop-over-headlines-in-active-region nil
556 "Shall some commands act upon headlines in the active region?
558 When set to `t', some commands will be performed in all headlines
559 within the active region.
561 When set to `start-level', some commands will be performed in all
562 headlines within the active region, provided that these headlines
563 are of the same level than the first one.
565 When set to a string, those commands will be performed on the
566 matching headlines within the active region. Such string must be
567 a tags/property/todo match as it is used in the agenda tags view.
569 The list of commands is: `org-schedule', `org-deadline',
570 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
571 `org-archive-to-archive-sibling'. The archiving commands skip
572 already archived entries."
573 :type '(choice (const :tag "Don't loop" nil)
574 (const :tag "All headlines in active region" t)
575 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
576 (string :tag "Tags/Property/Todo matcher"))
577 :version "24.1"
578 :group 'org-todo
579 :group 'org-archive)
581 (defgroup org-startup nil
582 "Options concerning startup of Org-mode."
583 :tag "Org Startup"
584 :group 'org)
586 (defcustom org-startup-folded t
587 "Non-nil means entering Org-mode will switch to OVERVIEW.
588 This can also be configured on a per-file basis by adding one of
589 the following lines anywhere in the buffer:
591 #+STARTUP: fold (or `overview', this is equivalent)
592 #+STARTUP: nofold (or `showall', this is equivalent)
593 #+STARTUP: content
594 #+STARTUP: showeverything
596 By default, this option is ignored when Org opens agenda files
597 for the first time. If you want the agenda to honor the startup
598 option, set `org-agenda-inhibit-startup' to nil."
599 :group 'org-startup
600 :type '(choice
601 (const :tag "nofold: show all" nil)
602 (const :tag "fold: overview" t)
603 (const :tag "content: all headlines" content)
604 (const :tag "show everything, even drawers" showeverything)))
606 (defcustom org-startup-truncated t
607 "Non-nil means entering Org-mode will set `truncate-lines'.
608 This is useful since some lines containing links can be very long and
609 uninteresting. Also tables look terrible when wrapped."
610 :group 'org-startup
611 :type 'boolean)
613 (defcustom org-startup-indented nil
614 "Non-nil means turn on `org-indent-mode' on startup.
615 This can also be configured on a per-file basis by adding one of
616 the following lines anywhere in the buffer:
618 #+STARTUP: indent
619 #+STARTUP: noindent"
620 :group 'org-structure
621 :type '(choice
622 (const :tag "Not" nil)
623 (const :tag "Globally (slow on startup in large files)" t)))
625 (defcustom org-use-sub-superscripts t
626 "Non-nil means interpret \"_\" and \"^\" for display.
627 When this option is turned on, you can use TeX-like syntax for sub- and
628 superscripts. Several characters after \"_\" or \"^\" will be
629 considered as a single item - so grouping with {} is normally not
630 needed. For example, the following things will be parsed as single
631 sub- or superscripts.
633 10^24 or 10^tau several digits will be considered 1 item.
634 10^-12 or 10^-tau a leading sign with digits or a word
635 x^2-y^3 will be read as x^2 - y^3, because items are
636 terminated by almost any nonword/nondigit char.
637 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
639 Still, ambiguity is possible - so when in doubt use {} to enclose
640 the sub/superscript. If you set this variable to the symbol
641 `{}', the braces are *required* in order to trigger
642 interpretations as sub/superscript. This can be helpful in
643 documents that need \"_\" frequently in plain text."
644 :group 'org-startup
645 :version "24.1"
646 :type '(choice
647 (const :tag "Always interpret" t)
648 (const :tag "Only with braces" {})
649 (const :tag "Never interpret" nil)))
651 (defcustom org-startup-with-beamer-mode nil
652 "Non-nil means turn on `org-beamer-mode' on startup.
653 This can also be configured on a per-file basis by adding one of
654 the following lines anywhere in the buffer:
656 #+STARTUP: beamer"
657 :group 'org-startup
658 :version "24.1"
659 :type 'boolean)
661 (defcustom org-startup-align-all-tables nil
662 "Non-nil means align all tables when visiting a file.
663 This is useful when the column width in tables is forced with <N> cookies
664 in table fields. Such tables will look correct only after the first re-align.
665 This can also be configured on a per-file basis by adding one of
666 the following lines anywhere in the buffer:
667 #+STARTUP: align
668 #+STARTUP: noalign"
669 :group 'org-startup
670 :type 'boolean)
672 (defcustom org-startup-with-inline-images nil
673 "Non-nil means show inline images when loading a new Org file.
674 This can also be configured on a per-file basis by adding one of
675 the following lines anywhere in the buffer:
676 #+STARTUP: inlineimages
677 #+STARTUP: noinlineimages"
678 :group 'org-startup
679 :version "24.1"
680 :type 'boolean)
682 (defcustom org-startup-with-latex-preview nil
683 "Non-nil means preview LaTeX fragments when loading a new Org file.
685 This can also be configured on a per-file basis by adding one of
686 the followinglines anywhere in the buffer:
687 #+STARTUP: latexpreview
688 #+STARTUP: nolatexpreview"
689 :group 'org-startup
690 :version "24.4"
691 :package-version '(Org . "8.0")
692 :type 'boolean)
694 (defcustom org-insert-mode-line-in-empty-file nil
695 "Non-nil means insert the first line setting Org-mode in empty files.
696 When the function `org-mode' is called interactively in an empty file, this
697 normally means that the file name does not automatically trigger Org-mode.
698 To ensure that the file will always be in Org-mode in the future, a
699 line enforcing Org-mode will be inserted into the buffer, if this option
700 has been set."
701 :group 'org-startup
702 :type 'boolean)
704 (defcustom org-replace-disputed-keys nil
705 "Non-nil means use alternative key bindings for some keys.
706 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
707 These keys are also used by other packages like shift-selection-mode'
708 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
709 If you want to use Org-mode together with one of these other modes,
710 or more generally if you would like to move some Org-mode commands to
711 other keys, set this variable and configure the keys with the variable
712 `org-disputed-keys'.
714 This option is only relevant at load-time of Org-mode, and must be set
715 *before* org.el is loaded. Changing it requires a restart of Emacs to
716 become effective."
717 :group 'org-startup
718 :type 'boolean)
720 (defcustom org-use-extra-keys nil
721 "Non-nil means use extra key sequence definitions for certain commands.
722 This happens automatically if you run XEmacs or if `window-system'
723 is nil. This variable lets you do the same manually. You must
724 set it before loading org.
726 Example: on Carbon Emacs 22 running graphically, with an external
727 keyboard on a Powerbook, the default way of setting M-left might
728 not work for either Alt or ESC. Setting this variable will make
729 it work for ESC."
730 :group 'org-startup
731 :type 'boolean)
733 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
735 (defcustom org-disputed-keys
736 '(([(shift up)] . [(meta p)])
737 ([(shift down)] . [(meta n)])
738 ([(shift left)] . [(meta -)])
739 ([(shift right)] . [(meta +)])
740 ([(control shift right)] . [(meta shift +)])
741 ([(control shift left)] . [(meta shift -)]))
742 "Keys for which Org-mode and other modes compete.
743 This is an alist, cars are the default keys, second element specifies
744 the alternative to use when `org-replace-disputed-keys' is t.
746 Keys can be specified in any syntax supported by `define-key'.
747 The value of this option takes effect only at Org-mode's startup,
748 therefore you'll have to restart Emacs to apply it after changing."
749 :group 'org-startup
750 :type 'alist)
752 (defun org-key (key)
753 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
754 Or return the original if not disputed.
755 Also apply the translations defined in `org-xemacs-key-equivalents'."
756 (when org-replace-disputed-keys
757 (let* ((nkey (key-description key))
758 (x (org-find-if (lambda (x)
759 (equal (key-description (car x)) nkey))
760 org-disputed-keys)))
761 (setq key (if x (cdr x) key))))
762 (when (featurep 'xemacs)
763 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
764 key)
766 (defun org-find-if (predicate seq)
767 (catch 'exit
768 (while seq
769 (if (funcall predicate (car seq))
770 (throw 'exit (car seq))
771 (pop seq)))))
773 (defun org-defkey (keymap key def)
774 "Define a key, possibly translated, as returned by `org-key'."
775 (define-key keymap (org-key key) def))
777 (defcustom org-ellipsis nil
778 "The ellipsis to use in the Org-mode outline.
779 When nil, just use the standard three dots. When a string, use that instead,
780 When a face, use the standard 3 dots, but with the specified face.
781 The change affects only Org-mode (which will then use its own display table).
782 Changing this requires executing `M-x org-mode' in a buffer to become
783 effective."
784 :group 'org-startup
785 :type '(choice (const :tag "Default" nil)
786 (face :tag "Face" :value org-warning)
787 (string :tag "String" :value "...#")))
789 (defvar org-display-table nil
790 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
792 (defgroup org-keywords nil
793 "Keywords in Org-mode."
794 :tag "Org Keywords"
795 :group 'org)
797 (defcustom org-deadline-string "DEADLINE:"
798 "String to mark deadline entries.
799 A deadline is this string, followed by a time stamp. Should be a word,
800 terminated by a colon. You can insert a schedule keyword and
801 a timestamp with \\[org-deadline].
802 Changes become only effective after restarting Emacs."
803 :group 'org-keywords
804 :type 'string)
806 (defcustom org-scheduled-string "SCHEDULED:"
807 "String to mark scheduled TODO entries.
808 A schedule is this string, followed by a time stamp. Should be a word,
809 terminated by a colon. You can insert a schedule keyword and
810 a timestamp with \\[org-schedule].
811 Changes become only effective after restarting Emacs."
812 :group 'org-keywords
813 :type 'string)
815 (defcustom org-closed-string "CLOSED:"
816 "String used as the prefix for timestamps logging closing a TODO entry."
817 :group 'org-keywords
818 :type 'string)
820 (defcustom org-clock-string "CLOCK:"
821 "String used as prefix for timestamps clocking work hours on an item."
822 :group 'org-keywords
823 :type 'string)
825 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
826 org-scheduled-string "\\|"
827 org-deadline-string "\\|"
828 org-closed-string "\\|"
829 org-clock-string "\\)")
830 "Matches a line with planning or clock info.")
832 (defcustom org-comment-string "COMMENT"
833 "Entries starting with this keyword will never be exported.
834 An entry can be toggled between COMMENT and normal with
835 \\[org-toggle-comment].
836 Changes become only effective after restarting Emacs."
837 :group 'org-keywords
838 :type 'string)
840 (defcustom org-quote-string "QUOTE"
841 "Entries starting with this keyword will be exported in fixed-width font.
842 Quoting applies only to the text in the entry following the headline, and does
843 not extend beyond the next headline, even if that is lower level.
844 An entry can be toggled between QUOTE and normal with
845 \\[org-toggle-fixed-width-section]."
846 :group 'org-keywords
847 :type 'string)
849 (defconst org-repeat-re
850 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
851 "Regular expression for specifying repeated events.
852 After a match, group 1 contains the repeat expression.")
854 (defgroup org-structure nil
855 "Options concerning the general structure of Org-mode files."
856 :tag "Org Structure"
857 :group 'org)
859 (defgroup org-reveal-location nil
860 "Options about how to make context of a location visible."
861 :tag "Org Reveal Location"
862 :group 'org-structure)
864 (defconst org-context-choice
865 '(choice
866 (const :tag "Always" t)
867 (const :tag "Never" nil)
868 (repeat :greedy t :tag "Individual contexts"
869 (cons
870 (choice :tag "Context"
871 (const agenda)
872 (const org-goto)
873 (const occur-tree)
874 (const tags-tree)
875 (const link-search)
876 (const mark-goto)
877 (const bookmark-jump)
878 (const isearch)
879 (const default))
880 (boolean))))
881 "Contexts for the reveal options.")
883 (defcustom org-show-hierarchy-above '((default . t))
884 "Non-nil means show full hierarchy when revealing a location.
885 Org-mode often shows locations in an org-mode file which might have
886 been invisible before. When this is set, the hierarchy of headings
887 above the exposed location is shown.
888 Turning this off for example for sparse trees makes them very compact.
889 Instead of t, this can also be an alist specifying this option for different
890 contexts. Valid contexts are
891 agenda when exposing an entry from the agenda
892 org-goto when using the command `org-goto' on key C-c C-j
893 occur-tree when using the command `org-occur' on key C-c /
894 tags-tree when constructing a sparse tree based on tags matches
895 link-search when exposing search matches associated with a link
896 mark-goto when exposing the jump goal of a mark
897 bookmark-jump when exposing a bookmark location
898 isearch when exiting from an incremental search
899 default default for all contexts not set explicitly"
900 :group 'org-reveal-location
901 :type org-context-choice)
903 (defcustom org-show-following-heading '((default . nil))
904 "Non-nil means show following heading when revealing a location.
905 Org-mode often shows locations in an org-mode file which might have
906 been invisible before. When this is set, the heading following the
907 match is shown.
908 Turning this off for example for sparse trees makes them very compact,
909 but makes it harder to edit the location of the match. In such a case,
910 use the command \\[org-reveal] to show more context.
911 Instead of t, this can also be an alist specifying this option for different
912 contexts. See `org-show-hierarchy-above' for valid contexts."
913 :group 'org-reveal-location
914 :type org-context-choice)
916 (defcustom org-show-siblings '((default . nil) (isearch t))
917 "Non-nil means show all sibling heading when revealing a location.
918 Org-mode often shows locations in an org-mode file which might have
919 been invisible before. When this is set, the sibling of the current entry
920 heading are all made visible. If `org-show-hierarchy-above' is t,
921 the same happens on each level of the hierarchy above the current entry.
923 By default this is on for the isearch context, off for all other contexts.
924 Turning this off for example for sparse trees makes them very compact,
925 but makes it harder to edit the location of the match. In such a case,
926 use the command \\[org-reveal] to show more context.
927 Instead of t, this can also be an alist specifying this option for different
928 contexts. See `org-show-hierarchy-above' for valid contexts."
929 :group 'org-reveal-location
930 :type org-context-choice)
932 (defcustom org-show-entry-below '((default . nil))
933 "Non-nil means show the entry below a headline when revealing a location.
934 Org-mode often shows locations in an org-mode file which might have
935 been invisible before. When this is set, the text below the headline that is
936 exposed is also shown.
938 By default this is off for all contexts.
939 Instead of t, this can also be an alist specifying this option for different
940 contexts. See `org-show-hierarchy-above' for valid contexts."
941 :group 'org-reveal-location
942 :type org-context-choice)
944 (defcustom org-indirect-buffer-display 'other-window
945 "How should indirect tree buffers be displayed?
946 This applies to indirect buffers created with the commands
947 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
948 Valid values are:
949 current-window Display in the current window
950 other-window Just display in another window.
951 dedicated-frame Create one new frame, and re-use it each time.
952 new-frame Make a new frame each time. Note that in this case
953 previously-made indirect buffers are kept, and you need to
954 kill these buffers yourself."
955 :group 'org-structure
956 :group 'org-agenda-windows
957 :type '(choice
958 (const :tag "In current window" current-window)
959 (const :tag "In current frame, other window" other-window)
960 (const :tag "Each time a new frame" new-frame)
961 (const :tag "One dedicated frame" dedicated-frame)))
963 (defcustom org-use-speed-commands nil
964 "Non-nil means activate single letter commands at beginning of a headline.
965 This may also be a function to test for appropriate locations where speed
966 commands should be active."
967 :group 'org-structure
968 :type '(choice
969 (const :tag "Never" nil)
970 (const :tag "At beginning of headline stars" t)
971 (function)))
973 (defcustom org-speed-commands-user nil
974 "Alist of additional speed commands.
975 This list will be checked before `org-speed-commands-default'
976 when the variable `org-use-speed-commands' is non-nil
977 and when the cursor is at the beginning of a headline.
978 The car if each entry is a string with a single letter, which must
979 be assigned to `self-insert-command' in the global map.
980 The cdr is either a command to be called interactively, a function
981 to be called, or a form to be evaluated.
982 An entry that is just a list with a single string will be interpreted
983 as a descriptive headline that will be added when listing the speed
984 commands in the Help buffer using the `?' speed command."
985 :group 'org-structure
986 :type '(repeat :value ("k" . ignore)
987 (choice :value ("k" . ignore)
988 (list :tag "Descriptive Headline" (string :tag "Headline"))
989 (cons :tag "Letter and Command"
990 (string :tag "Command letter")
991 (choice
992 (function)
993 (sexp))))))
995 (defgroup org-cycle nil
996 "Options concerning visibility cycling in Org-mode."
997 :tag "Org Cycle"
998 :group 'org-structure)
1000 (defcustom org-cycle-skip-children-state-if-no-children t
1001 "Non-nil means skip CHILDREN state in entries that don't have any."
1002 :group 'org-cycle
1003 :type 'boolean)
1005 (defcustom org-cycle-max-level nil
1006 "Maximum level which should still be subject to visibility cycling.
1007 Levels higher than this will, for cycling, be treated as text, not a headline.
1008 When `org-odd-levels-only' is set, a value of N in this variable actually
1009 means 2N-1 stars as the limiting headline.
1010 When nil, cycle all levels.
1011 Note that the limiting level of cycling is also influenced by
1012 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1013 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1014 than its value."
1015 :group 'org-cycle
1016 :type '(choice
1017 (const :tag "No limit" nil)
1018 (integer :tag "Maximum level")))
1020 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1021 "Names of drawers. Drawers are not opened by cycling on the headline above.
1022 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1023 this:
1024 :DRAWERNAME:
1025 .....
1026 :END:
1027 The drawer \"PROPERTIES\" is special for capturing properties through
1028 the property API.
1030 Drawers can be defined on the per-file basis with a line like:
1032 #+DRAWERS: HIDDEN STATE PROPERTIES"
1033 :group 'org-structure
1034 :group 'org-cycle
1035 :type '(repeat (string :tag "Drawer Name")))
1037 (defcustom org-hide-block-startup nil
1038 "Non-nil means entering Org-mode will fold all blocks.
1039 This can also be set in on a per-file basis with
1041 #+STARTUP: hideblocks
1042 #+STARTUP: showblocks"
1043 :group 'org-startup
1044 :group 'org-cycle
1045 :type 'boolean)
1047 (defcustom org-cycle-global-at-bob nil
1048 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1049 This makes it possible to do global cycling without having to use S-TAB or
1050 \\[universal-argument] TAB. For this special case to work, the first line
1051 of the buffer must not be a headline -- it may be empty or some other text.
1052 When used in this way, `org-cycle-hook' is disabled temporarily to make
1053 sure the cursor stays at the beginning of the buffer. When this option is
1054 nil, don't do anything special at the beginning of the buffer."
1055 :group 'org-cycle
1056 :type 'boolean)
1058 (defcustom org-cycle-level-after-item/entry-creation t
1059 "Non-nil means cycle entry level or item indentation in new empty entries.
1061 When the cursor is at the end of an empty headline, i.e., with only stars
1062 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1063 and then all possible ancestor states, before returning to the original state.
1064 This makes data entry extremely fast: M-RET to create a new headline,
1065 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1067 When the cursor is at the end of an empty plain list item, one TAB will
1068 make it a subitem, two or more tabs will back up to make this an item
1069 higher up in the item hierarchy."
1070 :group 'org-cycle
1071 :type 'boolean)
1073 (defcustom org-cycle-emulate-tab t
1074 "Where should `org-cycle' emulate TAB.
1075 nil Never
1076 white Only in completely white lines
1077 whitestart Only at the beginning of lines, before the first non-white char
1078 t Everywhere except in headlines
1079 exc-hl-bol Everywhere except at the start of a headline
1080 If TAB is used in a place where it does not emulate TAB, the current subtree
1081 visibility is cycled."
1082 :group 'org-cycle
1083 :type '(choice (const :tag "Never" nil)
1084 (const :tag "Only in completely white lines" white)
1085 (const :tag "Before first char in a line" whitestart)
1086 (const :tag "Everywhere except in headlines" t)
1087 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1090 (defcustom org-cycle-separator-lines 2
1091 "Number of empty lines needed to keep an empty line between collapsed trees.
1092 If you leave an empty line between the end of a subtree and the following
1093 headline, this empty line is hidden when the subtree is folded.
1094 Org-mode will leave (exactly) one empty line visible if the number of
1095 empty lines is equal or larger to the number given in this variable.
1096 So the default 2 means at least 2 empty lines after the end of a subtree
1097 are needed to produce free space between a collapsed subtree and the
1098 following headline.
1100 If the number is negative, and the number of empty lines is at least -N,
1101 all empty lines are shown.
1103 Special case: when 0, never leave empty lines in collapsed view."
1104 :group 'org-cycle
1105 :type 'integer)
1106 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1108 (defcustom org-pre-cycle-hook nil
1109 "Hook that is run before visibility cycling is happening.
1110 The function(s) in this hook must accept a single argument which indicates
1111 the new state that will be set right after running this hook. The
1112 argument is a symbol. Before a global state change, it can have the values
1113 `overview', `content', or `all'. Before a local state change, it can have
1114 the values `folded', `children', or `subtree'."
1115 :group 'org-cycle
1116 :type 'hook)
1118 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1119 org-cycle-hide-drawers
1120 org-cycle-hide-inline-tasks
1121 org-cycle-show-empty-lines
1122 org-optimize-window-after-visibility-change)
1123 "Hook that is run after `org-cycle' has changed the buffer visibility.
1124 The function(s) in this hook must accept a single argument which indicates
1125 the new state that was set by the most recent `org-cycle' command. The
1126 argument is a symbol. After a global state change, it can have the values
1127 `overview', `contents', or `all'. After a local state change, it can have
1128 the values `folded', `children', or `subtree'."
1129 :group 'org-cycle
1130 :type 'hook)
1132 (defgroup org-edit-structure nil
1133 "Options concerning structure editing in Org-mode."
1134 :tag "Org Edit Structure"
1135 :group 'org-structure)
1137 (defcustom org-odd-levels-only nil
1138 "Non-nil means skip even levels and only use odd levels for the outline.
1139 This has the effect that two stars are being added/taken away in
1140 promotion/demotion commands. It also influences how levels are
1141 handled by the exporters.
1142 Changing it requires restart of `font-lock-mode' to become effective
1143 for fontification also in regions already fontified.
1144 You may also set this on a per-file basis by adding one of the following
1145 lines to the buffer:
1147 #+STARTUP: odd
1148 #+STARTUP: oddeven"
1149 :group 'org-edit-structure
1150 :group 'org-appearance
1151 :type 'boolean)
1153 (defcustom org-adapt-indentation t
1154 "Non-nil means adapt indentation to outline node level.
1156 When this variable is set, Org assumes that you write outlines by
1157 indenting text in each node to align with the headline (after the stars).
1158 The following issues are influenced by this variable:
1160 - When this is set and the *entire* text in an entry is indented, the
1161 indentation is increased by one space in a demotion command, and
1162 decreased by one in a promotion command. If any line in the entry
1163 body starts with text at column 0, indentation is not changed at all.
1165 - Property drawers and planning information is inserted indented when
1166 this variable s set. When nil, they will not be indented.
1168 - TAB indents a line relative to context. The lines below a headline
1169 will be indented when this variable is set.
1171 Note that this is all about true indentation, by adding and removing
1172 space characters. See also `org-indent.el' which does level-dependent
1173 indentation in a virtual way, i.e. at display time in Emacs."
1174 :group 'org-edit-structure
1175 :type 'boolean)
1177 (defcustom org-special-ctrl-a/e nil
1178 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1180 When t, `C-a' will bring back the cursor to the beginning of the
1181 headline text, i.e. after the stars and after a possible TODO
1182 keyword. In an item, this will be the position after bullet and
1183 check-box, if any. When the cursor is already at that position,
1184 another `C-a' will bring it to the beginning of the line.
1186 `C-e' will jump to the end of the headline, ignoring the presence
1187 of tags in the headline. A second `C-e' will then jump to the
1188 true end of the line, after any tags. This also means that, when
1189 this variable is non-nil, `C-e' also will never jump beyond the
1190 end of the heading of a folded section, i.e. not after the
1191 ellipses.
1193 When set to the symbol `reversed', the first `C-a' or `C-e' works
1194 normally, going to the true line boundary first. Only a directly
1195 following, identical keypress will bring the cursor to the
1196 special positions.
1198 This may also be a cons cell where the behavior for `C-a' and
1199 `C-e' is set separately."
1200 :group 'org-edit-structure
1201 :type '(choice
1202 (const :tag "off" nil)
1203 (const :tag "on: after stars/bullet and before tags first" t)
1204 (const :tag "reversed: true line boundary first" reversed)
1205 (cons :tag "Set C-a and C-e separately"
1206 (choice :tag "Special C-a"
1207 (const :tag "off" nil)
1208 (const :tag "on: after stars/bullet first" t)
1209 (const :tag "reversed: before stars/bullet first" reversed))
1210 (choice :tag "Special C-e"
1211 (const :tag "off" nil)
1212 (const :tag "on: before tags first" t)
1213 (const :tag "reversed: after tags first" reversed)))))
1214 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1216 (defcustom org-special-ctrl-k nil
1217 "Non-nil means `C-k' will behave specially in headlines.
1218 When nil, `C-k' will call the default `kill-line' command.
1219 When t, the following will happen while the cursor is in the headline:
1221 - When the cursor is at the beginning of a headline, kill the entire
1222 line and possible the folded subtree below the line.
1223 - When in the middle of the headline text, kill the headline up to the tags.
1224 - When after the headline text, kill the tags."
1225 :group 'org-edit-structure
1226 :type 'boolean)
1228 (defcustom org-ctrl-k-protect-subtree nil
1229 "Non-nil means, do not delete a hidden subtree with C-k.
1230 When set to the symbol `error', simply throw an error when C-k is
1231 used to kill (part-of) a headline that has hidden text behind it.
1232 Any other non-nil value will result in a query to the user, if it is
1233 OK to kill that hidden subtree. When nil, kill without remorse."
1234 :group 'org-edit-structure
1235 :version "24.1"
1236 :type '(choice
1237 (const :tag "Do not protect hidden subtrees" nil)
1238 (const :tag "Protect hidden subtrees with a security query" t)
1239 (const :tag "Never kill a hidden subtree with C-k" error)))
1241 (defcustom org-catch-invisible-edits nil
1242 "Check if in invisible region before inserting or deleting a character.
1243 Valid values are:
1245 nil Do not check, so just do invisible edits.
1246 error Throw an error and do nothing.
1247 show Make point visible, and do the requested edit.
1248 show-and-error Make point visible, then throw an error and abort the edit.
1249 smart Make point visible, and do insertion/deletion if it is
1250 adjacent to visible text and the change feels predictable.
1251 Never delete a previously invisible character or add in the
1252 middle or right after an invisible region. Basically, this
1253 allows insertion and backward-delete right before ellipses.
1254 FIXME: maybe in this case we should not even show?"
1255 :group 'org-edit-structure
1256 :version "24.1"
1257 :type '(choice
1258 (const :tag "Do not check" nil)
1259 (const :tag "Throw error when trying to edit" error)
1260 (const :tag "Unhide, but do not do the edit" show-and-error)
1261 (const :tag "Show invisible part and do the edit" show)
1262 (const :tag "Be smart and do the right thing" smart)))
1264 (defcustom org-yank-folded-subtrees t
1265 "Non-nil means when yanking subtrees, fold them.
1266 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1267 it starts with a heading and all other headings in it are either children
1268 or siblings, then fold all the subtrees. However, do this only if no
1269 text after the yank would be swallowed into a folded tree by this action."
1270 :group 'org-edit-structure
1271 :type 'boolean)
1273 (defcustom org-yank-adjusted-subtrees nil
1274 "Non-nil means when yanking subtrees, adjust the level.
1275 With this setting, `org-paste-subtree' is used to insert the subtree, see
1276 this function for details."
1277 :group 'org-edit-structure
1278 :type 'boolean)
1280 (defcustom org-M-RET-may-split-line '((default . t))
1281 "Non-nil means M-RET will split the line at the cursor position.
1282 When nil, it will go to the end of the line before making a
1283 new line.
1284 You may also set this option in a different way for different
1285 contexts. Valid contexts are:
1287 headline when creating a new headline
1288 item when creating a new item
1289 table in a table field
1290 default the value to be used for all contexts not explicitly
1291 customized"
1292 :group 'org-structure
1293 :group 'org-table
1294 :type '(choice
1295 (const :tag "Always" t)
1296 (const :tag "Never" nil)
1297 (repeat :greedy t :tag "Individual contexts"
1298 (cons
1299 (choice :tag "Context"
1300 (const headline)
1301 (const item)
1302 (const table)
1303 (const default))
1304 (boolean)))))
1307 (defcustom org-insert-heading-respect-content nil
1308 "Non-nil means insert new headings after the current subtree.
1309 When nil, the new heading is created directly after the current line.
1310 The commands \\[org-insert-heading-respect-content] and
1311 \\[org-insert-todo-heading-respect-content] turn this variable on
1312 for the duration of the command."
1313 :group 'org-structure
1314 :type 'boolean)
1316 (defcustom org-blank-before-new-entry '((heading . auto)
1317 (plain-list-item . auto))
1318 "Should `org-insert-heading' leave a blank line before new heading/item?
1319 The value is an alist, with `heading' and `plain-list-item' as CAR,
1320 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1321 which case Org will look at the surrounding headings/items and try to
1322 make an intelligent decision whether to insert a blank line or not.
1324 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1325 set, the setting here is ignored and no empty line is inserted, to avoid
1326 breaking the list structure."
1327 :group 'org-edit-structure
1328 :type '(list
1329 (cons (const heading)
1330 (choice (const :tag "Never" nil)
1331 (const :tag "Always" t)
1332 (const :tag "Auto" auto)))
1333 (cons (const plain-list-item)
1334 (choice (const :tag "Never" nil)
1335 (const :tag "Always" t)
1336 (const :tag "Auto" auto)))))
1338 (defcustom org-insert-heading-hook nil
1339 "Hook being run after inserting a new heading."
1340 :group 'org-edit-structure
1341 :type 'hook)
1343 (defcustom org-enable-fixed-width-editor t
1344 "Non-nil means lines starting with \":\" are treated as fixed-width.
1345 This currently only means they are never auto-wrapped.
1346 When nil, such lines will be treated like ordinary lines.
1347 See also the QUOTE keyword."
1348 :group 'org-edit-structure
1349 :type 'boolean)
1351 (defcustom org-goto-auto-isearch t
1352 "Non-nil means typing characters in `org-goto' starts incremental search.
1353 When nil, you can use these keybindings to navigate the buffer:
1355 q Quit the org-goto interface
1356 n Go to the next visible heading
1357 p Go to the previous visible heading
1358 f Go one heading forward on same level
1359 b Go one heading backward on same level
1360 u Go one heading up"
1361 :group 'org-edit-structure
1362 :type 'boolean)
1364 (defgroup org-sparse-trees nil
1365 "Options concerning sparse trees in Org-mode."
1366 :tag "Org Sparse Trees"
1367 :group 'org-structure)
1369 (defcustom org-highlight-sparse-tree-matches t
1370 "Non-nil means highlight all matches that define a sparse tree.
1371 The highlights will automatically disappear the next time the buffer is
1372 changed by an edit command."
1373 :group 'org-sparse-trees
1374 :type 'boolean)
1376 (defcustom org-remove-highlights-with-change t
1377 "Non-nil means any change to the buffer will remove temporary highlights.
1378 Such highlights are created by `org-occur' and `org-clock-display'.
1379 When nil, `C-c C-c needs to be used to get rid of the highlights.
1380 The highlights created by `org-preview-latex-fragment' always need
1381 `C-c C-c' to be removed."
1382 :group 'org-sparse-trees
1383 :group 'org-time
1384 :type 'boolean)
1387 (defcustom org-occur-hook '(org-first-headline-recenter)
1388 "Hook that is run after `org-occur' has constructed a sparse tree.
1389 This can be used to recenter the window to show as much of the structure
1390 as possible."
1391 :group 'org-sparse-trees
1392 :type 'hook)
1394 (defgroup org-imenu-and-speedbar nil
1395 "Options concerning imenu and speedbar in Org-mode."
1396 :tag "Org Imenu and Speedbar"
1397 :group 'org-structure)
1399 (defcustom org-imenu-depth 2
1400 "The maximum level for Imenu access to Org-mode headlines.
1401 This also applied for speedbar access."
1402 :group 'org-imenu-and-speedbar
1403 :type 'integer)
1405 (defgroup org-table nil
1406 "Options concerning tables in Org-mode."
1407 :tag "Org Table"
1408 :group 'org)
1410 (defcustom org-enable-table-editor 'optimized
1411 "Non-nil means lines starting with \"|\" are handled by the table editor.
1412 When nil, such lines will be treated like ordinary lines.
1414 When equal to the symbol `optimized', the table editor will be optimized to
1415 do the following:
1416 - Automatic overwrite mode in front of whitespace in table fields.
1417 This makes the structure of the table stay in tact as long as the edited
1418 field does not exceed the column width.
1419 - Minimize the number of realigns. Normally, the table is aligned each time
1420 TAB or RET are pressed to move to another field. With optimization this
1421 happens only if changes to a field might have changed the column width.
1422 Optimization requires replacing the functions `self-insert-command',
1423 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1424 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1425 very good at guessing when a re-align will be necessary, but you can always
1426 force one with \\[org-ctrl-c-ctrl-c].
1428 If you would like to use the optimized version in Org-mode, but the
1429 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1431 This variable can be used to turn on and off the table editor during a session,
1432 but in order to toggle optimization, a restart is required.
1434 See also the variable `org-table-auto-blank-field'."
1435 :group 'org-table
1436 :type '(choice
1437 (const :tag "off" nil)
1438 (const :tag "on" t)
1439 (const :tag "on, optimized" optimized)))
1441 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1442 (version<= emacs-version "24.1"))
1443 "Non-nil means cluster self-insert commands for undo when possible.
1444 If this is set, then, like in the Emacs command loop, 20 consecutive
1445 characters will be undone together.
1446 This is configurable, because there is some impact on typing performance."
1447 :group 'org-table
1448 :type 'boolean)
1450 (defcustom org-table-tab-recognizes-table.el t
1451 "Non-nil means TAB will automatically notice a table.el table.
1452 When it sees such a table, it moves point into it and - if necessary -
1453 calls `table-recognize-table'."
1454 :group 'org-table-editing
1455 :type 'boolean)
1457 (defgroup org-link nil
1458 "Options concerning links in Org-mode."
1459 :tag "Org Link"
1460 :group 'org)
1462 (defvar org-link-abbrev-alist-local nil
1463 "Buffer-local version of `org-link-abbrev-alist', which see.
1464 The value of this is taken from the #+LINK lines.")
1465 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1467 (defcustom org-link-abbrev-alist nil
1468 "Alist of link abbreviations.
1469 The car of each element is a string, to be replaced at the start of a link.
1470 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1471 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1473 [[linkkey:tag][description]]
1475 The 'linkkey' must be a word word, starting with a letter, followed
1476 by letters, numbers, '-' or '_'.
1478 If REPLACE is a string, the tag will simply be appended to create the link.
1479 If the string contains \"%s\", the tag will be inserted there. If the string
1480 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1481 at that point (see the function `url-hexify-string'). If the string contains
1482 the specifier \"%(my-function)\", then the custom function `my-function' will
1483 be invoked: this function takes the tag as its only argument and must return
1484 a string.
1486 REPLACE may also be a function that will be called with the tag as the
1487 only argument to create the link, which should be returned as a string.
1489 See the manual for examples."
1490 :group 'org-link
1491 :type '(repeat
1492 (cons
1493 (string :tag "Protocol")
1494 (choice
1495 (string :tag "Format")
1496 (function)))))
1498 (defcustom org-descriptive-links t
1499 "Non-nil means Org will display descriptive links.
1500 E.g. [[http://orgmode.org][Org website]] will be displayed as
1501 \"Org Website\", hiding the link itself and just displaying its
1502 description. When set to `nil', Org will display the full links
1503 literally.
1505 You can interactively set the value of this variable by calling
1506 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1507 :group 'org-link
1508 :type 'boolean)
1510 (defcustom org-link-file-path-type 'adaptive
1511 "How the path name in file links should be stored.
1512 Valid values are:
1514 relative Relative to the current directory, i.e. the directory of the file
1515 into which the link is being inserted.
1516 absolute Absolute path, if possible with ~ for home directory.
1517 noabbrev Absolute path, no abbreviation of home directory.
1518 adaptive Use relative path for files in the current directory and sub-
1519 directories of it. For other files, use an absolute path."
1520 :group 'org-link
1521 :type '(choice
1522 (const relative)
1523 (const absolute)
1524 (const noabbrev)
1525 (const adaptive)))
1527 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1528 "Types of links that should be activated in Org-mode files.
1529 This is a list of symbols, each leading to the activation of a certain link
1530 type. In principle, it does not hurt to turn on most link types - there may
1531 be a small gain when turning off unused link types. The types are:
1533 bracket The recommended [[link][description]] or [[link]] links with hiding.
1534 angle Links in angular brackets that may contain whitespace like
1535 <bbdb:Carsten Dominik>.
1536 plain Plain links in normal text, no whitespace, like http://google.com.
1537 radio Text that is matched by a radio target, see manual for details.
1538 tag Tag settings in a headline (link to tag search).
1539 date Time stamps (link to calendar).
1540 footnote Footnote labels.
1542 Changing this variable requires a restart of Emacs to become effective."
1543 :group 'org-link
1544 :type '(set :greedy t
1545 (const :tag "Double bracket links" bracket)
1546 (const :tag "Angular bracket links" angle)
1547 (const :tag "Plain text links" plain)
1548 (const :tag "Radio target matches" radio)
1549 (const :tag "Tags" tag)
1550 (const :tag "Timestamps" date)
1551 (const :tag "Footnotes" footnote)))
1553 (defcustom org-make-link-description-function nil
1554 "Function to use for generating link descriptions from links.
1555 When nil, the link location will be used. This function must take
1556 two parameters: the first one is the link, the second one is the
1557 description generated by `org-insert-link'. The function should
1558 return the description to use."
1559 :group 'org-link
1560 :type 'function)
1562 (defgroup org-link-store nil
1563 "Options concerning storing links in Org-mode."
1564 :tag "Org Store Link"
1565 :group 'org-link)
1567 (defcustom org-url-hexify-p t
1568 "When non-nil, hexify URL when creating a link."
1569 :type 'boolean
1570 :version "24.3"
1571 :group 'org-link-store)
1573 (defcustom org-email-link-description-format "Email %c: %.30s"
1574 "Format of the description part of a link to an email or usenet message.
1575 The following %-escapes will be replaced by corresponding information:
1577 %F full \"From\" field
1578 %f name, taken from \"From\" field, address if no name
1579 %T full \"To\" field
1580 %t first name in \"To\" field, address if no name
1581 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1582 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1583 %s subject
1584 %d date
1585 %m message-id.
1587 You may use normal field width specification between the % and the letter.
1588 This is for example useful to limit the length of the subject.
1590 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1591 :group 'org-link-store
1592 :type 'string)
1594 (defcustom org-from-is-user-regexp
1595 (let (r1 r2)
1596 (when (and user-mail-address (not (string= user-mail-address "")))
1597 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1598 (when (and user-full-name (not (string= user-full-name "")))
1599 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1600 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1601 "Regexp matched against the \"From:\" header of an email or usenet message.
1602 It should match if the message is from the user him/herself."
1603 :group 'org-link-store
1604 :type 'regexp)
1606 (defcustom org-context-in-file-links t
1607 "Non-nil means file links from `org-store-link' contain context.
1608 A search string will be added to the file name with :: as separator and
1609 used to find the context when the link is activated by the command
1610 `org-open-at-point'. When this option is t, the entire active region
1611 will be placed in the search string of the file link. If set to a
1612 positive integer, only the first n lines of context will be stored.
1614 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1615 negates this setting for the duration of the command."
1616 :group 'org-link-store
1617 :type '(choice boolean integer))
1619 (defcustom org-keep-stored-link-after-insertion nil
1620 "Non-nil means keep link in list for entire session.
1622 The command `org-store-link' adds a link pointing to the current
1623 location to an internal list. These links accumulate during a session.
1624 The command `org-insert-link' can be used to insert links into any
1625 Org-mode file (offering completion for all stored links). When this
1626 option is nil, every link which has been inserted once using \\[org-insert-link]
1627 will be removed from the list, to make completing the unused links
1628 more efficient."
1629 :group 'org-link-store
1630 :type 'boolean)
1632 (defgroup org-link-follow nil
1633 "Options concerning following links in Org-mode."
1634 :tag "Org Follow Link"
1635 :group 'org-link)
1637 (defcustom org-link-translation-function nil
1638 "Function to translate links with different syntax to Org syntax.
1639 This can be used to translate links created for example by the Planner
1640 or emacs-wiki packages to Org syntax.
1641 The function must accept two parameters, a TYPE containing the link
1642 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1643 which is everything after the link protocol. It should return a cons
1644 with possibly modified values of type and path.
1645 Org contains a function for this, so if you set this variable to
1646 `org-translate-link-from-planner', you should be able follow many
1647 links created by planner."
1648 :group 'org-link-follow
1649 :type 'function)
1651 (defcustom org-follow-link-hook nil
1652 "Hook that is run after a link has been followed."
1653 :group 'org-link-follow
1654 :type 'hook)
1656 (defcustom org-tab-follows-link nil
1657 "Non-nil means on links TAB will follow the link.
1658 Needs to be set before org.el is loaded.
1659 This really should not be used, it does not make sense, and the
1660 implementation is bad."
1661 :group 'org-link-follow
1662 :type 'boolean)
1664 (defcustom org-return-follows-link nil
1665 "Non-nil means on links RET will follow the link.
1666 In tables, the special behavior of RET has precedence."
1667 :group 'org-link-follow
1668 :type 'boolean)
1670 (defcustom org-mouse-1-follows-link
1671 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1672 "Non-nil means mouse-1 on a link will follow the link.
1673 A longer mouse click will still set point. Does not work on XEmacs.
1674 Needs to be set before org.el is loaded."
1675 :group 'org-link-follow
1676 :type 'boolean)
1678 (defcustom org-mark-ring-length 4
1679 "Number of different positions to be recorded in the ring.
1680 Changing this requires a restart of Emacs to work correctly."
1681 :group 'org-link-follow
1682 :type 'integer)
1684 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1685 "Non-nil means internal links in Org files must exactly match a headline.
1686 When nil, the link search tries to match a phrase with all words
1687 in the search text."
1688 :group 'org-link-follow
1689 :version "24.1"
1690 :type '(choice
1691 (const :tag "Use fuzzy text search" nil)
1692 (const :tag "Match only exact headline" t)
1693 (const :tag "Match exact headline or query to create it"
1694 query-to-create)))
1696 (defcustom org-link-frame-setup
1697 '((vm . vm-visit-folder-other-frame)
1698 (vm-imap . vm-visit-imap-folder-other-frame)
1699 (gnus . org-gnus-no-new-news)
1700 (file . find-file-other-window)
1701 (wl . wl-other-frame))
1702 "Setup the frame configuration for following links.
1703 When following a link with Emacs, it may often be useful to display
1704 this link in another window or frame. This variable can be used to
1705 set this up for the different types of links.
1706 For VM, use any of
1707 `vm-visit-folder'
1708 `vm-visit-folder-other-window'
1709 `vm-visit-folder-other-frame'
1710 For Gnus, use any of
1711 `gnus'
1712 `gnus-other-frame'
1713 `org-gnus-no-new-news'
1714 For FILE, use any of
1715 `find-file'
1716 `find-file-other-window'
1717 `find-file-other-frame'
1718 For Wanderlust use any of
1719 `wl'
1720 `wl-other-frame'
1721 For the calendar, use the variable `calendar-setup'.
1722 For BBDB, it is currently only possible to display the matches in
1723 another window."
1724 :group 'org-link-follow
1725 :type '(list
1726 (cons (const vm)
1727 (choice
1728 (const vm-visit-folder)
1729 (const vm-visit-folder-other-window)
1730 (const vm-visit-folder-other-frame)))
1731 (cons (const gnus)
1732 (choice
1733 (const gnus)
1734 (const gnus-other-frame)
1735 (const org-gnus-no-new-news)))
1736 (cons (const file)
1737 (choice
1738 (const find-file)
1739 (const find-file-other-window)
1740 (const find-file-other-frame)))
1741 (cons (const wl)
1742 (choice
1743 (const wl)
1744 (const wl-other-frame)))))
1746 (defcustom org-display-internal-link-with-indirect-buffer nil
1747 "Non-nil means use indirect buffer to display infile links.
1748 Activating internal links (from one location in a file to another location
1749 in the same file) normally just jumps to the location. When the link is
1750 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1751 is displayed in
1752 another window. When this option is set, the other window actually displays
1753 an indirect buffer clone of the current buffer, to avoid any visibility
1754 changes to the current buffer."
1755 :group 'org-link-follow
1756 :type 'boolean)
1758 (defcustom org-open-non-existing-files nil
1759 "Non-nil means `org-open-file' will open non-existing files.
1760 When nil, an error will be generated.
1761 This variable applies only to external applications because they
1762 might choke on non-existing files. If the link is to a file that
1763 will be opened in Emacs, the variable is ignored."
1764 :group 'org-link-follow
1765 :type 'boolean)
1767 (defcustom org-open-directory-means-index-dot-org nil
1768 "Non-nil means a link to a directory really means to index.org.
1769 When nil, following a directory link will run dired or open a finder/explorer
1770 window on that directory."
1771 :group 'org-link-follow
1772 :type 'boolean)
1774 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1775 "Function and arguments to call for following mailto links.
1776 This is a list with the first element being a Lisp function, and the
1777 remaining elements being arguments to the function. In string arguments,
1778 %a will be replaced by the address, and %s will be replaced by the subject
1779 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1780 :group 'org-link-follow
1781 :type '(choice
1782 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1783 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1784 (const :tag "message-mail" (message-mail "%a" "%s"))
1785 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1787 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1788 "Non-nil means ask for confirmation before executing shell links.
1789 Shell links can be dangerous: just think about a link
1791 [[shell:rm -rf ~/*][Google Search]]
1793 This link would show up in your Org-mode document as \"Google Search\",
1794 but really it would remove your entire home directory.
1795 Therefore we advise against setting this variable to nil.
1796 Just change it to `y-or-n-p' if you want to confirm with a
1797 single keystroke rather than having to type \"yes\"."
1798 :group 'org-link-follow
1799 :type '(choice
1800 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1801 (const :tag "with y-or-n (faster)" y-or-n-p)
1802 (const :tag "no confirmation (dangerous)" nil)))
1803 (put 'org-confirm-shell-link-function
1804 'safe-local-variable
1805 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1807 (defcustom org-confirm-shell-link-not-regexp ""
1808 "A regexp to skip confirmation for shell links."
1809 :group 'org-link-follow
1810 :version "24.1"
1811 :type 'regexp)
1813 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1814 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1815 Elisp links can be dangerous: just think about a link
1817 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1819 This link would show up in your Org-mode document as \"Google Search\",
1820 but really it would remove your entire home directory.
1821 Therefore we advise against setting this variable to nil.
1822 Just change it to `y-or-n-p' if you want to confirm with a
1823 single keystroke rather than having to type \"yes\"."
1824 :group 'org-link-follow
1825 :type '(choice
1826 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1827 (const :tag "with y-or-n (faster)" y-or-n-p)
1828 (const :tag "no confirmation (dangerous)" nil)))
1829 (put 'org-confirm-shell-link-function
1830 'safe-local-variable
1831 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1833 (defcustom org-confirm-elisp-link-not-regexp ""
1834 "A regexp to skip confirmation for Elisp links."
1835 :group 'org-link-follow
1836 :version "24.1"
1837 :type 'regexp)
1839 (defconst org-file-apps-defaults-gnu
1840 '((remote . emacs)
1841 (system . mailcap)
1842 (t . mailcap))
1843 "Default file applications on a UNIX or GNU/Linux system.
1844 See `org-file-apps'.")
1846 (defconst org-file-apps-defaults-macosx
1847 '((remote . emacs)
1848 (t . "open %s")
1849 (system . "open %s")
1850 ("ps.gz" . "gv %s")
1851 ("eps.gz" . "gv %s")
1852 ("dvi" . "xdvi %s")
1853 ("fig" . "xfig %s"))
1854 "Default file applications on a MacOS X system.
1855 The system \"open\" is known as a default, but we use X11 applications
1856 for some files for which the OS does not have a good default.
1857 See `org-file-apps'.")
1859 (defconst org-file-apps-defaults-windowsnt
1860 (list
1861 '(remote . emacs)
1862 (cons t
1863 (list (if (featurep 'xemacs)
1864 'mswindows-shell-execute
1865 'w32-shell-execute)
1866 "open" 'file))
1867 (cons 'system
1868 (list (if (featurep 'xemacs)
1869 'mswindows-shell-execute
1870 'w32-shell-execute)
1871 "open" 'file)))
1872 "Default file applications on a Windows NT system.
1873 The system \"open\" is used for most files.
1874 See `org-file-apps'.")
1876 (defcustom org-file-apps
1878 (auto-mode . emacs)
1879 ("\\.mm\\'" . default)
1880 ("\\.x?html?\\'" . default)
1881 ("\\.pdf\\'" . default)
1883 "External applications for opening `file:path' items in a document.
1884 Org-mode uses system defaults for different file types, but
1885 you can use this variable to set the application for a given file
1886 extension. The entries in this list are cons cells where the car identifies
1887 files and the cdr the corresponding command. Possible values for the
1888 file identifier are
1889 \"string\" A string as a file identifier can be interpreted in different
1890 ways, depending on its contents:
1892 - Alphanumeric characters only:
1893 Match links with this file extension.
1894 Example: (\"pdf\" . \"evince %s\")
1895 to open PDFs with evince.
1897 - Regular expression: Match links where the
1898 filename matches the regexp. If you want to
1899 use groups here, use shy groups.
1901 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1902 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1903 to open *.html and *.xhtml with firefox.
1905 - Regular expression which contains (non-shy) groups:
1906 Match links where the whole link, including \"::\", and
1907 anything after that, matches the regexp.
1908 In a custom command string, %1, %2, etc. are replaced with
1909 the parts of the link that were matched by the groups.
1910 For backwards compatibility, if a command string is given
1911 that does not use any of the group matches, this case is
1912 handled identically to the second one (i.e. match against
1913 file name only).
1914 In a custom lisp form, you can access the group matches with
1915 (match-string n link).
1917 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1918 to open [[file:document.pdf::5]] with evince at page 5.
1920 `directory' Matches a directory
1921 `remote' Matches a remote file, accessible through tramp or efs.
1922 Remote files most likely should be visited through Emacs
1923 because external applications cannot handle such paths.
1924 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1925 so all files Emacs knows how to handle. Using this with
1926 command `emacs' will open most files in Emacs. Beware that this
1927 will also open html files inside Emacs, unless you add
1928 (\"html\" . default) to the list as well.
1929 t Default for files not matched by any of the other options.
1930 `system' The system command to open files, like `open' on Windows
1931 and Mac OS X, and mailcap under GNU/Linux. This is the command
1932 that will be selected if you call `C-c C-o' with a double
1933 \\[universal-argument] \\[universal-argument] prefix.
1935 Possible values for the command are:
1936 `emacs' The file will be visited by the current Emacs process.
1937 `default' Use the default application for this file type, which is the
1938 association for t in the list, most likely in the system-specific
1939 part.
1940 This can be used to overrule an unwanted setting in the
1941 system-specific variable.
1942 `system' Use the system command for opening files, like \"open\".
1943 This command is specified by the entry whose car is `system'.
1944 Most likely, the system-specific version of this variable
1945 does define this command, but you can overrule/replace it
1946 here.
1947 string A command to be executed by a shell; %s will be replaced
1948 by the path to the file.
1949 sexp A Lisp form which will be evaluated. The file path will
1950 be available in the Lisp variable `file'.
1951 For more examples, see the system specific constants
1952 `org-file-apps-defaults-macosx'
1953 `org-file-apps-defaults-windowsnt'
1954 `org-file-apps-defaults-gnu'."
1955 :group 'org-link-follow
1956 :type '(repeat
1957 (cons (choice :value ""
1958 (string :tag "Extension")
1959 (const :tag "System command to open files" system)
1960 (const :tag "Default for unrecognized files" t)
1961 (const :tag "Remote file" remote)
1962 (const :tag "Links to a directory" directory)
1963 (const :tag "Any files that have Emacs modes"
1964 auto-mode))
1965 (choice :value ""
1966 (const :tag "Visit with Emacs" emacs)
1967 (const :tag "Use default" default)
1968 (const :tag "Use the system command" system)
1969 (string :tag "Command")
1970 (sexp :tag "Lisp form")))))
1972 (defcustom org-doi-server-url "http://dx.doi.org/"
1973 "The URL of the DOI server."
1974 :type 'string
1975 :version "24.3"
1976 :group 'org-link-follow)
1978 (defgroup org-refile nil
1979 "Options concerning refiling entries in Org-mode."
1980 :tag "Org Refile"
1981 :group 'org)
1983 (defcustom org-directory "~/org"
1984 "Directory with org files.
1985 This is just a default location to look for Org files. There is no need
1986 at all to put your files into this directory. It is only used in the
1987 following situations:
1989 1. When a capture template specifies a target file that is not an
1990 absolute path. The path will then be interpreted relative to
1991 `org-directory'
1992 2. When a capture note is filed away in an interactive way (when exiting the
1993 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1994 with `org-directory' as the default path."
1995 :group 'org-refile
1996 :group 'org-remember
1997 :group 'org-capture
1998 :type 'directory)
2000 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2001 "Default target for storing notes.
2002 Used as a fall back file for org-remember.el and org-capture.el, for
2003 templates that do not specify a target file."
2004 :group 'org-refile
2005 :group 'org-remember
2006 :group 'org-capture
2007 :type '(choice
2008 (const :tag "Default from remember-data-file" nil)
2009 file))
2011 (defcustom org-goto-interface 'outline
2012 "The default interface to be used for `org-goto'.
2013 Allowed values are:
2014 outline The interface shows an outline of the relevant file
2015 and the correct heading is found by moving through
2016 the outline or by searching with incremental search.
2017 outline-path-completion Headlines in the current buffer are offered via
2018 completion. This is the interface also used by
2019 the refile command."
2020 :group 'org-refile
2021 :type '(choice
2022 (const :tag "Outline" outline)
2023 (const :tag "Outline-path-completion" outline-path-completion)))
2025 (defcustom org-goto-max-level 5
2026 "Maximum target level when running `org-goto' with refile interface."
2027 :group 'org-refile
2028 :type 'integer)
2030 (defcustom org-reverse-note-order nil
2031 "Non-nil means store new notes at the beginning of a file or entry.
2032 When nil, new notes will be filed to the end of a file or entry.
2033 This can also be a list with cons cells of regular expressions that
2034 are matched against file names, and values."
2035 :group 'org-remember
2036 :group 'org-capture
2037 :group 'org-refile
2038 :type '(choice
2039 (const :tag "Reverse always" t)
2040 (const :tag "Reverse never" nil)
2041 (repeat :tag "By file name regexp"
2042 (cons regexp boolean))))
2044 (defcustom org-log-refile nil
2045 "Information to record when a task is refiled.
2047 Possible values are:
2049 nil Don't add anything
2050 time Add a time stamp to the task
2051 note Prompt for a note and add it with template `org-log-note-headings'
2053 This option can also be set with on a per-file-basis with
2055 #+STARTUP: nologrefile
2056 #+STARTUP: logrefile
2057 #+STARTUP: lognoterefile
2059 You can have local logging settings for a subtree by setting the LOGGING
2060 property to one or more of these keywords.
2062 When bulk-refiling from the agenda, the value `note' is forbidden and
2063 will temporarily be changed to `time'."
2064 :group 'org-refile
2065 :group 'org-progress
2066 :version "24.1"
2067 :type '(choice
2068 (const :tag "No logging" nil)
2069 (const :tag "Record timestamp" time)
2070 (const :tag "Record timestamp with note." note)))
2072 (defcustom org-refile-targets nil
2073 "Targets for refiling entries with \\[org-refile].
2074 This is a list of cons cells. Each cell contains:
2075 - a specification of the files to be considered, either a list of files,
2076 or a symbol whose function or variable value will be used to retrieve
2077 a file name or a list of file names. If you use `org-agenda-files' for
2078 that, all agenda files will be scanned for targets. Nil means consider
2079 headings in the current buffer.
2080 - A specification of how to find candidate refile targets. This may be
2081 any of:
2082 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2083 This tag has to be present in all target headlines, inheritance will
2084 not be considered.
2085 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2086 todo keyword.
2087 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2088 headlines that are refiling targets.
2089 - a cons cell (:level . N). Any headline of level N is considered a target.
2090 Note that, when `org-odd-levels-only' is set, level corresponds to
2091 order in hierarchy, not to the number of stars.
2092 - a cons cell (:maxlevel . N). Any headline with level <= N is 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.
2096 Each element of this list generates a set of possible targets.
2097 The union of these sets is presented (with completion) to
2098 the user by `org-refile'.
2100 You can set the variable `org-refile-target-verify-function' to a function
2101 to verify each headline found by the simple criteria above.
2103 When this variable is nil, all top-level headlines in the current buffer
2104 are used, equivalent to the value `((nil . (:level . 1))'."
2105 :group 'org-refile
2106 :type '(repeat
2107 (cons
2108 (choice :value org-agenda-files
2109 (const :tag "All agenda files" org-agenda-files)
2110 (const :tag "Current buffer" nil)
2111 (function) (variable) (file))
2112 (choice :tag "Identify target headline by"
2113 (cons :tag "Specific tag" (const :value :tag) (string))
2114 (cons :tag "TODO keyword" (const :value :todo) (string))
2115 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2116 (cons :tag "Level number" (const :value :level) (integer))
2117 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2119 (defcustom org-refile-target-verify-function nil
2120 "Function to verify if the headline at point should be a refile target.
2121 The function will be called without arguments, with point at the
2122 beginning of the headline. It should return t and leave point
2123 where it is if the headline is a valid target for refiling.
2125 If the target should not be selected, the function must return nil.
2126 In addition to this, it may move point to a place from where the search
2127 should be continued. For example, the function may decide that the entire
2128 subtree of the current entry should be excluded and move point to the end
2129 of the subtree."
2130 :group 'org-refile
2131 :type 'function)
2133 (defcustom org-refile-use-cache nil
2134 "Non-nil means cache refile targets to speed up the process.
2135 The cache for a particular file will be updated automatically when
2136 the buffer has been killed, or when any of the marker used for flagging
2137 refile targets no longer points at a live buffer.
2138 If you have added new entries to a buffer that might themselves be targets,
2139 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2140 find that easier, `C-u C-u C-u C-c C-w'."
2141 :group 'org-refile
2142 :version "24.1"
2143 :type 'boolean)
2145 (defcustom org-refile-use-outline-path nil
2146 "Non-nil means provide refile targets as paths.
2147 So a level 3 headline will be available as level1/level2/level3.
2149 When the value is `file', also include the file name (without directory)
2150 into the path. In this case, you can also stop the completion after
2151 the file name, to get entries inserted as top level in the file.
2153 When `full-file-path', include the full file path."
2154 :group 'org-refile
2155 :type '(choice
2156 (const :tag "Not" nil)
2157 (const :tag "Yes" t)
2158 (const :tag "Start with file name" file)
2159 (const :tag "Start with full file path" full-file-path)))
2161 (defcustom org-outline-path-complete-in-steps t
2162 "Non-nil means complete the outline path in hierarchical steps.
2163 When Org-mode uses the refile interface to select an outline path
2164 \(see variable `org-refile-use-outline-path'), the completion of
2165 the path can be done is a single go, or if can be done in steps down
2166 the headline hierarchy. Going in steps is probably the best if you
2167 do not use a special completion package like `ido' or `icicles'.
2168 However, when using these packages, going in one step can be very
2169 fast, while still showing the whole path to the entry."
2170 :group 'org-refile
2171 :type 'boolean)
2173 (defcustom org-refile-allow-creating-parent-nodes nil
2174 "Non-nil means allow to create new nodes as refile targets.
2175 New nodes are then created by adding \"/new node name\" to the completion
2176 of an existing node. When the value of this variable is `confirm',
2177 new node creation must be confirmed by the user (recommended)
2178 When nil, the completion must match an existing entry.
2180 Note that, if the new heading is not seen by the criteria
2181 listed in `org-refile-targets', multiple instances of the same
2182 heading would be created by trying again to file under the new
2183 heading."
2184 :group 'org-refile
2185 :type '(choice
2186 (const :tag "Never" nil)
2187 (const :tag "Always" t)
2188 (const :tag "Prompt for confirmation" confirm)))
2190 (defcustom org-refile-active-region-within-subtree nil
2191 "Non-nil means also refile active region within a subtree.
2193 By default `org-refile' doesn't allow refiling regions if they
2194 don't contain a set of subtrees, but it might be convenient to
2195 do so sometimes: in that case, the first line of the region is
2196 converted to a headline before refiling."
2197 :group 'org-refile
2198 :version "24.1"
2199 :type 'boolean)
2201 (defgroup org-todo nil
2202 "Options concerning TODO items in Org-mode."
2203 :tag "Org TODO"
2204 :group 'org)
2206 (defgroup org-progress nil
2207 "Options concerning Progress logging in Org-mode."
2208 :tag "Org Progress"
2209 :group 'org-time)
2211 (defvar org-todo-interpretation-widgets
2212 '((:tag "Sequence (cycling hits every state)" sequence)
2213 (:tag "Type (cycling directly to DONE)" type))
2214 "The available interpretation symbols for customizing `org-todo-keywords'.
2215 Interested libraries should add to this list.")
2217 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2218 "List of TODO entry keyword sequences and their interpretation.
2219 \\<org-mode-map>This is a list of sequences.
2221 Each sequence starts with a symbol, either `sequence' or `type',
2222 indicating if the keywords should be interpreted as a sequence of
2223 action steps, or as different types of TODO items. The first
2224 keywords are states requiring action - these states will select a headline
2225 for inclusion into the global TODO list Org-mode produces. If one of
2226 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2227 signify that no further action is necessary. If \"|\" is not found,
2228 the last keyword is treated as the only DONE state of the sequence.
2230 The command \\[org-todo] cycles an entry through these states, and one
2231 additional state where no keyword is present. For details about this
2232 cycling, see the manual.
2234 TODO keywords and interpretation can also be set on a per-file basis with
2235 the special #+SEQ_TODO and #+TYP_TODO lines.
2237 Each keyword can optionally specify a character for fast state selection
2238 \(in combination with the variable `org-use-fast-todo-selection')
2239 and specifiers for state change logging, using the same syntax that
2240 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2241 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2242 indicates to record a time stamp each time this state is selected.
2244 Each keyword may also specify if a timestamp or a note should be
2245 recorded when entering or leaving the state, by adding additional
2246 characters in the parenthesis after the keyword. This looks like this:
2247 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2248 record only the time of the state change. With X and Y being either
2249 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2250 Y when leaving the state if and only if the *target* state does not
2251 define X. You may omit any of the fast-selection key or X or /Y,
2252 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2254 For backward compatibility, this variable may also be just a list
2255 of keywords. In this case the interpretation (sequence or type) will be
2256 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2257 :group 'org-todo
2258 :group 'org-keywords
2259 :type '(choice
2260 (repeat :tag "Old syntax, just keywords"
2261 (string :tag "Keyword"))
2262 (repeat :tag "New syntax"
2263 (cons
2264 (choice
2265 :tag "Interpretation"
2266 ;;Quick and dirty way to see
2267 ;;`org-todo-interpretations'. This takes the
2268 ;;place of item arguments
2269 :convert-widget
2270 (lambda (widget)
2271 (widget-put widget
2272 :args (mapcar
2273 #'(lambda (x)
2274 (widget-convert
2275 (cons 'const x)))
2276 org-todo-interpretation-widgets))
2277 widget))
2278 (repeat
2279 (string :tag "Keyword"))))))
2281 (defvar org-todo-keywords-1 nil
2282 "All TODO and DONE keywords active in a buffer.")
2283 (make-variable-buffer-local 'org-todo-keywords-1)
2284 (defvar org-todo-keywords-for-agenda nil)
2285 (defvar org-done-keywords-for-agenda nil)
2286 (defvar org-drawers-for-agenda nil)
2287 (defvar org-todo-keyword-alist-for-agenda nil)
2288 (defvar org-tag-alist-for-agenda nil)
2289 (defvar org-agenda-contributing-files nil)
2290 (defvar org-not-done-keywords nil)
2291 (make-variable-buffer-local 'org-not-done-keywords)
2292 (defvar org-done-keywords nil)
2293 (make-variable-buffer-local 'org-done-keywords)
2294 (defvar org-todo-heads nil)
2295 (make-variable-buffer-local 'org-todo-heads)
2296 (defvar org-todo-sets nil)
2297 (make-variable-buffer-local 'org-todo-sets)
2298 (defvar org-todo-log-states nil)
2299 (make-variable-buffer-local 'org-todo-log-states)
2300 (defvar org-todo-kwd-alist nil)
2301 (make-variable-buffer-local 'org-todo-kwd-alist)
2302 (defvar org-todo-key-alist nil)
2303 (make-variable-buffer-local 'org-todo-key-alist)
2304 (defvar org-todo-key-trigger nil)
2305 (make-variable-buffer-local 'org-todo-key-trigger)
2307 (defcustom org-todo-interpretation 'sequence
2308 "Controls how TODO keywords are interpreted.
2309 This variable is in principle obsolete and is only used for
2310 backward compatibility, if the interpretation of todo keywords is
2311 not given already in `org-todo-keywords'. See that variable for
2312 more information."
2313 :group 'org-todo
2314 :group 'org-keywords
2315 :type '(choice (const sequence)
2316 (const type)))
2318 (defcustom org-use-fast-todo-selection t
2319 "Non-nil means use the fast todo selection scheme with C-c C-t.
2320 This variable describes if and under what circumstances the cycling
2321 mechanism for TODO keywords will be replaced by a single-key, direct
2322 selection scheme.
2324 When nil, fast selection is never used.
2326 When the symbol `prefix', it will be used when `org-todo' is called
2327 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2328 `C-u t' in an agenda buffer.
2330 When t, fast selection is used by default. In this case, the prefix
2331 argument forces cycling instead.
2333 In all cases, the special interface is only used if access keys have
2334 actually been assigned by the user, i.e. if keywords in the configuration
2335 are followed by a letter in parenthesis, like TODO(t)."
2336 :group 'org-todo
2337 :type '(choice
2338 (const :tag "Never" nil)
2339 (const :tag "By default" t)
2340 (const :tag "Only with C-u C-c C-t" prefix)))
2342 (defcustom org-provide-todo-statistics t
2343 "Non-nil means update todo statistics after insert and toggle.
2344 ALL-HEADLINES means update todo statistics by including headlines
2345 with no TODO keyword as well, counting them as not done.
2346 A list of TODO keywords means the same, but skip keywords that are
2347 not in this list.
2349 When this is set, todo statistics is updated in the parent of the
2350 current entry each time a todo state is changed."
2351 :group 'org-todo
2352 :type '(choice
2353 (const :tag "Yes, only for TODO entries" t)
2354 (const :tag "Yes, including all entries" 'all-headlines)
2355 (repeat :tag "Yes, for TODOs in this list"
2356 (string :tag "TODO keyword"))
2357 (other :tag "No TODO statistics" nil)))
2359 (defcustom org-hierarchical-todo-statistics t
2360 "Non-nil means TODO statistics covers just direct children.
2361 When nil, all entries in the subtree are considered.
2362 This has only an effect if `org-provide-todo-statistics' is set.
2363 To set this to nil for only a single subtree, use a COOKIE_DATA
2364 property and include the word \"recursive\" into the value."
2365 :group 'org-todo
2366 :type 'boolean)
2368 (defcustom org-after-todo-state-change-hook nil
2369 "Hook which is run after the state of a TODO item was changed.
2370 The new state (a string with a TODO keyword, or nil) is available in the
2371 Lisp variable `org-state'."
2372 :group 'org-todo
2373 :type 'hook)
2375 (defvar org-blocker-hook nil
2376 "Hook for functions that are allowed to block a state change.
2378 Functions in this hook should not modify the buffer.
2379 Each function gets as its single argument a property list,
2380 see `org-trigger-hook' for more information about this list.
2382 If any of the functions in this hook returns nil, the state change
2383 is blocked.")
2385 (defvar org-trigger-hook nil
2386 "Hook for functions that are triggered by a state change.
2388 Each function gets as its single argument a property list with at
2389 least the following elements:
2391 (:type type-of-change :position pos-at-entry-start
2392 :from old-state :to new-state)
2394 Depending on the type, more properties may be present.
2396 This mechanism is currently implemented for:
2398 TODO state changes
2399 ------------------
2400 :type todo-state-change
2401 :from previous state (keyword as a string), or nil, or a symbol
2402 'todo' or 'done', to indicate the general type of state.
2403 :to new state, like in :from")
2405 (defcustom org-enforce-todo-dependencies nil
2406 "Non-nil means undone TODO entries will block switching the parent to DONE.
2407 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2408 be blocked if any prior sibling is not yet done.
2409 Finally, if the parent is blocked because of ordered siblings of its own,
2410 the child will also be blocked."
2411 :set (lambda (var val)
2412 (set var val)
2413 (if val
2414 (add-hook 'org-blocker-hook
2415 'org-block-todo-from-children-or-siblings-or-parent)
2416 (remove-hook 'org-blocker-hook
2417 'org-block-todo-from-children-or-siblings-or-parent)))
2418 :group 'org-todo
2419 :type 'boolean)
2421 (defcustom org-enforce-todo-checkbox-dependencies nil
2422 "Non-nil means unchecked boxes will block switching the parent to DONE.
2423 When this is nil, checkboxes have no influence on switching TODO states.
2424 When non-nil, you first need to check off all check boxes before the TODO
2425 entry can be switched to DONE.
2426 This variable needs to be set before org.el is loaded, and you need to
2427 restart Emacs after a change to make the change effective. The only way
2428 to change is while Emacs is running is through the customize interface."
2429 :set (lambda (var val)
2430 (set var val)
2431 (if val
2432 (add-hook 'org-blocker-hook
2433 'org-block-todo-from-checkboxes)
2434 (remove-hook 'org-blocker-hook
2435 'org-block-todo-from-checkboxes)))
2436 :group 'org-todo
2437 :type 'boolean)
2439 (defcustom org-treat-insert-todo-heading-as-state-change nil
2440 "Non-nil means inserting a TODO heading is treated as state change.
2441 So when the command \\[org-insert-todo-heading] is used, state change
2442 logging will apply if appropriate. When nil, the new TODO item will
2443 be inserted directly, and no logging will take place."
2444 :group 'org-todo
2445 :type 'boolean)
2447 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2448 "Non-nil means switching TODO states with S-cursor counts as state change.
2449 This is the default behavior. However, setting this to nil allows a
2450 convenient way to select a TODO state and bypass any logging associated
2451 with that."
2452 :group 'org-todo
2453 :type 'boolean)
2455 (defcustom org-todo-state-tags-triggers nil
2456 "Tag changes that should be triggered by TODO state changes.
2457 This is a list. Each entry is
2459 (state-change (tag . flag) .......)
2461 State-change can be a string with a state, and empty string to indicate the
2462 state that has no TODO keyword, or it can be one of the symbols `todo'
2463 or `done', meaning any not-done or done state, respectively."
2464 :group 'org-todo
2465 :group 'org-tags
2466 :type '(repeat
2467 (cons (choice :tag "When changing to"
2468 (const :tag "Not-done state" todo)
2469 (const :tag "Done state" done)
2470 (string :tag "State"))
2471 (repeat
2472 (cons :tag "Tag action"
2473 (string :tag "Tag")
2474 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2476 (defcustom org-log-done nil
2477 "Information to record when a task moves to the DONE state.
2479 Possible values are:
2481 nil Don't add anything, just change the keyword
2482 time Add a time stamp to the task
2483 note Prompt for a note and add it with template `org-log-note-headings'
2485 This option can also be set with on a per-file-basis with
2487 #+STARTUP: nologdone
2488 #+STARTUP: logdone
2489 #+STARTUP: lognotedone
2491 You can have local logging settings for a subtree by setting the LOGGING
2492 property to one or more of these keywords."
2493 :group 'org-todo
2494 :group 'org-progress
2495 :type '(choice
2496 (const :tag "No logging" nil)
2497 (const :tag "Record CLOSED timestamp" time)
2498 (const :tag "Record CLOSED timestamp with note." note)))
2500 ;; Normalize old uses of org-log-done.
2501 (cond
2502 ((eq org-log-done t) (setq org-log-done 'time))
2503 ((and (listp org-log-done) (memq 'done org-log-done))
2504 (setq org-log-done 'note)))
2506 (defcustom org-log-reschedule nil
2507 "Information to record when the scheduling date of a tasks is modified.
2509 Possible values are:
2511 nil Don't add anything, just change the date
2512 time Add a time stamp to the task
2513 note Prompt for a note and add it with template `org-log-note-headings'
2515 This option can also be set with on a per-file-basis with
2517 #+STARTUP: nologreschedule
2518 #+STARTUP: logreschedule
2519 #+STARTUP: lognotereschedule"
2520 :group 'org-todo
2521 :group 'org-progress
2522 :type '(choice
2523 (const :tag "No logging" nil)
2524 (const :tag "Record timestamp" time)
2525 (const :tag "Record timestamp with note." note)))
2527 (defcustom org-log-redeadline nil
2528 "Information to record when the deadline date of a tasks is modified.
2530 Possible values are:
2532 nil Don't add anything, just change the date
2533 time Add a time stamp to the task
2534 note Prompt for a note and add it with template `org-log-note-headings'
2536 This option can also be set with on a per-file-basis with
2538 #+STARTUP: nologredeadline
2539 #+STARTUP: logredeadline
2540 #+STARTUP: lognoteredeadline
2542 You can have local logging settings for a subtree by setting the LOGGING
2543 property to one or more of these keywords."
2544 :group 'org-todo
2545 :group 'org-progress
2546 :type '(choice
2547 (const :tag "No logging" nil)
2548 (const :tag "Record timestamp" time)
2549 (const :tag "Record timestamp with note." note)))
2551 (defcustom org-log-note-clock-out nil
2552 "Non-nil means record a note when clocking out of an item.
2553 This can also be configured on a per-file basis by adding one of
2554 the following lines anywhere in the buffer:
2556 #+STARTUP: lognoteclock-out
2557 #+STARTUP: nolognoteclock-out"
2558 :group 'org-todo
2559 :group 'org-progress
2560 :type 'boolean)
2562 (defcustom org-log-done-with-time t
2563 "Non-nil means the CLOSED time stamp will contain date and time.
2564 When nil, only the date will be recorded."
2565 :group 'org-progress
2566 :type 'boolean)
2568 (defcustom org-log-note-headings
2569 '((done . "CLOSING NOTE %t")
2570 (state . "State %-12s from %-12S %t")
2571 (note . "Note taken on %t")
2572 (reschedule . "Rescheduled from %S on %t")
2573 (delschedule . "Not scheduled, was %S on %t")
2574 (redeadline . "New deadline from %S on %t")
2575 (deldeadline . "Removed deadline, was %S on %t")
2576 (refile . "Refiled on %t")
2577 (clock-out . ""))
2578 "Headings for notes added to entries.
2579 The value is an alist, with the car being a symbol indicating the note
2580 context, and the cdr is the heading to be used. The heading may also be the
2581 empty string.
2582 %t in the heading will be replaced by a time stamp.
2583 %T will be an active time stamp instead the default inactive one
2584 %d will be replaced by a short-format time stamp.
2585 %D will be replaced by an active short-format time stamp.
2586 %s will be replaced by the new TODO state, in double quotes.
2587 %S will be replaced by the old TODO state, in double quotes.
2588 %u will be replaced by the user name.
2589 %U will be replaced by the full user name.
2591 In fact, it is not a good idea to change the `state' entry, because
2592 agenda log mode depends on the format of these entries."
2593 :group 'org-todo
2594 :group 'org-progress
2595 :type '(list :greedy t
2596 (cons (const :tag "Heading when closing an item" done) string)
2597 (cons (const :tag
2598 "Heading when changing todo state (todo sequence only)"
2599 state) string)
2600 (cons (const :tag "Heading when just taking a note" note) string)
2601 (cons (const :tag "Heading when clocking out" clock-out) string)
2602 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2603 (cons (const :tag "Heading when rescheduling" reschedule) string)
2604 (cons (const :tag "Heading when changing deadline" redeadline) string)
2605 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2606 (cons (const :tag "Heading when refiling" refile) string)))
2608 (unless (assq 'note org-log-note-headings)
2609 (push '(note . "%t") org-log-note-headings))
2611 (defcustom org-log-into-drawer nil
2612 "Non-nil means insert state change notes and time stamps into a drawer.
2613 When nil, state changes notes will be inserted after the headline and
2614 any scheduling and clock lines, but not inside a drawer.
2616 The value of this variable should be the name of the drawer to use.
2617 LOGBOOK is proposed as the default drawer for this purpose, you can
2618 also set this to a string to define the drawer of your choice.
2620 A value of t is also allowed, representing \"LOGBOOK\".
2622 A value of t or nil can also be set with on a per-file-basis with
2624 #+STARTUP: logdrawer
2625 #+STARTUP: nologdrawer
2627 If this variable is set, `org-log-state-notes-insert-after-drawers'
2628 will be ignored.
2630 You can set the property LOG_INTO_DRAWER to overrule this setting for
2631 a subtree."
2632 :group 'org-todo
2633 :group 'org-progress
2634 :type '(choice
2635 (const :tag "Not into a drawer" nil)
2636 (const :tag "LOGBOOK" t)
2637 (string :tag "Other")))
2639 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2641 (defun org-log-into-drawer ()
2642 "Return the value of `org-log-into-drawer', but let properties overrule.
2643 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2644 used instead of the default value."
2645 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2646 (cond
2647 ((not p) org-log-into-drawer)
2648 ((equal p "nil") nil)
2649 ((equal p "t") "LOGBOOK")
2650 (t p))))
2652 (defcustom org-log-state-notes-insert-after-drawers nil
2653 "Non-nil means insert state change notes after any drawers in entry.
2654 Only the drawers that *immediately* follow the headline and the
2655 deadline/scheduled line are skipped.
2656 When nil, insert notes right after the heading and perhaps the line
2657 with deadline/scheduling if present.
2659 This variable will have no effect if `org-log-into-drawer' is
2660 set."
2661 :group 'org-todo
2662 :group 'org-progress
2663 :type 'boolean)
2665 (defcustom org-log-states-order-reversed t
2666 "Non-nil means the latest state note will be directly after heading.
2667 When nil, the state change notes will be ordered according to time.
2669 This option can also be set with on a per-file-basis with
2671 #+STARTUP: logstatesreversed
2672 #+STARTUP: nologstatesreversed"
2673 :group 'org-todo
2674 :group 'org-progress
2675 :type 'boolean)
2677 (defcustom org-todo-repeat-to-state nil
2678 "The TODO state to which a repeater should return the repeating task.
2679 By default this is the first task in a TODO sequence, or the previous state
2680 in a TODO_TYP set. But you can specify another task here.
2681 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2682 :group 'org-todo
2683 :version "24.1"
2684 :type '(choice (const :tag "Head of sequence" nil)
2685 (string :tag "Specific state")))
2687 (defcustom org-log-repeat 'time
2688 "Non-nil means record moving through the DONE state when triggering repeat.
2689 An auto-repeating task is immediately switched back to TODO when
2690 marked DONE. If you are not logging state changes (by adding \"@\"
2691 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2692 record a closing note, there will be no record of the task moving
2693 through DONE. This variable forces taking a note anyway.
2695 nil Don't force a record
2696 time Record a time stamp
2697 note Prompt for a note and add it with template `org-log-note-headings'
2699 This option can also be set with on a per-file-basis with
2701 #+STARTUP: nologrepeat
2702 #+STARTUP: logrepeat
2703 #+STARTUP: lognoterepeat
2705 You can have local logging settings for a subtree by setting the LOGGING
2706 property to one or more of these keywords."
2707 :group 'org-todo
2708 :group 'org-progress
2709 :type '(choice
2710 (const :tag "Don't force a record" nil)
2711 (const :tag "Force recording the DONE state" time)
2712 (const :tag "Force recording a note with the DONE state" note)))
2715 (defgroup org-priorities nil
2716 "Priorities in Org-mode."
2717 :tag "Org Priorities"
2718 :group 'org-todo)
2720 (defcustom org-enable-priority-commands t
2721 "Non-nil means priority commands are active.
2722 When nil, these commands will be disabled, so that you never accidentally
2723 set a priority."
2724 :group 'org-priorities
2725 :type 'boolean)
2727 (defcustom org-highest-priority ?A
2728 "The highest priority of TODO items. A character like ?A, ?B etc.
2729 Must have a smaller ASCII number than `org-lowest-priority'."
2730 :group 'org-priorities
2731 :type 'character)
2733 (defcustom org-lowest-priority ?C
2734 "The lowest priority of TODO items. A character like ?A, ?B etc.
2735 Must have a larger ASCII number than `org-highest-priority'."
2736 :group 'org-priorities
2737 :type 'character)
2739 (defcustom org-default-priority ?B
2740 "The default priority of TODO items.
2741 This is the priority an item gets if no explicit priority is given.
2742 When starting to cycle on an empty priority the first step in the cycle
2743 depends on `org-priority-start-cycle-with-default'. The resulting first
2744 step priority must not exceed the range from `org-highest-priority' to
2745 `org-lowest-priority' which means that `org-default-priority' has to be
2746 in this range exclusive or inclusive the range boundaries. Else the
2747 first step refuses to set the default and the second will fall back
2748 to (depending on the command used) the highest or lowest priority."
2749 :group 'org-priorities
2750 :type 'character)
2752 (defcustom org-priority-start-cycle-with-default t
2753 "Non-nil means start with default priority when starting to cycle.
2754 When this is nil, the first step in the cycle will be (depending on the
2755 command used) one higher or lower than the default priority.
2756 See also `org-default-priority'."
2757 :group 'org-priorities
2758 :type 'boolean)
2760 (defcustom org-get-priority-function nil
2761 "Function to extract the priority from a string.
2762 The string is normally the headline. If this is nil Org computes the
2763 priority from the priority cookie like [#A] in the headline. It returns
2764 an integer, increasing by 1000 for each priority level.
2765 The user can set a different function here, which should take a string
2766 as an argument and return the numeric priority."
2767 :group 'org-priorities
2768 :version "24.1"
2769 :type 'function)
2771 (defgroup org-time nil
2772 "Options concerning time stamps and deadlines in Org-mode."
2773 :tag "Org Time"
2774 :group 'org)
2776 (defcustom org-insert-labeled-timestamps-at-point nil
2777 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2778 When nil, these labeled time stamps are forces into the second line of an
2779 entry, just after the headline. When scheduling from the global TODO list,
2780 the time stamp will always be forced into the second line."
2781 :group 'org-time
2782 :type 'boolean)
2784 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2785 "Formats for `format-time-string' which are used for time stamps.
2786 It is not recommended to change this constant.")
2788 (defcustom org-time-stamp-rounding-minutes '(0 5)
2789 "Number of minutes to round time stamps to.
2790 These are two values, the first applies when first creating a time stamp.
2791 The second applies when changing it with the commands `S-up' and `S-down'.
2792 When changing the time stamp, this means that it will change in steps
2793 of N minutes, as given by the second value.
2795 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2796 numbers should be factors of 60, so for example 5, 10, 15.
2798 When this is larger than 1, you can still force an exact time stamp by using
2799 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2800 and by using a prefix arg to `S-up/down' to specify the exact number
2801 of minutes to shift."
2802 :group 'org-time
2803 :get #'(lambda (var) ; Make sure both elements are there
2804 (if (integerp (default-value var))
2805 (list (default-value var) 5)
2806 (default-value var)))
2807 :type '(list
2808 (integer :tag "when inserting times")
2809 (integer :tag "when modifying times")))
2811 ;; Normalize old customizations of this variable.
2812 (when (integerp org-time-stamp-rounding-minutes)
2813 (setq org-time-stamp-rounding-minutes
2814 (list org-time-stamp-rounding-minutes
2815 org-time-stamp-rounding-minutes)))
2817 (defcustom org-display-custom-times nil
2818 "Non-nil means overlay custom formats over all time stamps.
2819 The formats are defined through the variable `org-time-stamp-custom-formats'.
2820 To turn this on on a per-file basis, insert anywhere in the file:
2821 #+STARTUP: customtime"
2822 :group 'org-time
2823 :set 'set-default
2824 :type 'sexp)
2825 (make-variable-buffer-local 'org-display-custom-times)
2827 (defcustom org-time-stamp-custom-formats
2828 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2829 "Custom formats for time stamps. See `format-time-string' for the syntax.
2830 These are overlaid over the default ISO format if the variable
2831 `org-display-custom-times' is set. Time like %H:%M should be at the
2832 end of the second format. The custom formats are also honored by export
2833 commands, if custom time display is turned on at the time of export."
2834 :group 'org-time
2835 :type 'sexp)
2837 (defun org-time-stamp-format (&optional long inactive)
2838 "Get the right format for a time string."
2839 (let ((f (if long (cdr org-time-stamp-formats)
2840 (car org-time-stamp-formats))))
2841 (if inactive
2842 (concat "[" (substring f 1 -1) "]")
2843 f)))
2845 (defcustom org-time-clocksum-format
2846 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2847 "The format string used when creating CLOCKSUM lines.
2848 This is also used when Org mode generates a time duration.
2850 The value can be a single format string containing two
2851 %-sequences, which will be filled with the number of hours and
2852 minutes in that order.
2854 Alternatively, the value can be a plist associating any of the
2855 keys :years, :months, :weeks, :days, :hours or :minutes with
2856 format strings. The time duration is formatted using only the
2857 time components that are needed and concatenating the results.
2858 If a time unit in absent, it falls back to the next smallest
2859 unit.
2861 The keys :require-years, :require-months, :require-days,
2862 :require-weeks, :require-hours, :require-minutes are also
2863 meaningful. A non-nil value for these keys indicates that the
2864 corresponding time component should always be included, even if
2865 its value is 0.
2868 For example,
2870 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2871 :require-minutes t)
2873 means durations longer than a day will be expressed in days,
2874 hours and minutes, and durations less than a day will always be
2875 expressed in hours and minutes (even for durations less than an
2876 hour).
2878 The value
2880 \(:days \"%dd\" :minutes \"%dm\")
2882 means durations longer than a day will be expressed in days and
2883 minutes, and durations less than a day will be expressed entirely
2884 in minutes (even for durations longer than an hour)."
2885 :group 'org-time
2886 :group 'org-clock
2887 :version "24.4"
2888 :package-version '(Org . "8.0")
2889 :type '(choice (string :tag "Format string")
2890 (set :tag "Plist"
2891 (group :inline t (const :tag "Years" :years)
2892 (string :tag "Format string"))
2893 (group :inline t
2894 (const :tag "Always show years" :require-years)
2895 (const t))
2896 (group :inline t (const :tag "Months" :months)
2897 (string :tag "Format string"))
2898 (group :inline t
2899 (const :tag "Always show months" :require-months)
2900 (const t))
2901 (group :inline t (const :tag "Weeks" :weeks)
2902 (string :tag "Format string"))
2903 (group :inline t
2904 (const :tag "Always show weeks" :require-weeks)
2905 (const t))
2906 (group :inline t (const :tag "Days" :days)
2907 (string :tag "Format string"))
2908 (group :inline t
2909 (const :tag "Always show days" :require-days)
2910 (const t))
2911 (group :inline t (const :tag "Hours" :hours)
2912 (string :tag "Format string"))
2913 (group :inline t
2914 (const :tag "Always show hours" :require-hours)
2915 (const t))
2916 (group :inline t (const :tag "Minutes" :minutes)
2917 (string :tag "Format string"))
2918 (group :inline t
2919 (const :tag "Always show minutes" :require-minutes)
2920 (const t)))))
2922 (defcustom org-time-clocksum-use-fractional nil
2923 "When non-nil, \\[org-clock-display] uses fractional times.
2924 See `org-time-clocksum-format' for more on time clock formats."
2925 :group 'org-time
2926 :group 'org-clock
2927 :version "24.3"
2928 :type 'boolean)
2930 (defcustom org-time-clocksum-use-effort-durations nil
2931 "When non-nil, \\[org-clock-display] uses effort durations.
2932 E.g. by default, one day is considered to be a 8 hours effort,
2933 so a task that has been clocked for 16 hours will be displayed
2934 as during 2 days in the clock display or in the clocktable.
2936 See `org-effort-durations' on how to set effort durations
2937 and `org-time-clocksum-format' for more on time clock formats."
2938 :group 'org-time
2939 :group 'org-clock
2940 :version "24.4"
2941 :package-version '(Org . "8.0")
2942 :type 'boolean)
2944 (defcustom org-time-clocksum-fractional-format "%.2f"
2945 "The format string used when creating CLOCKSUM lines,
2946 or when Org mode generates a time duration, if
2947 `org-time-clocksum-use-fractional' is enabled.
2949 The value can be a single format string containing one
2950 %-sequence, which will be filled with the number of hours as
2951 a float.
2953 Alternatively, the value can be a plist associating any of the
2954 keys :years, :months, :weeks, :days, :hours or :minutes with
2955 a format string. The time duration is formatted using the
2956 largest time unit which gives a non-zero integer part. If all
2957 specified formats have zero integer part, the smallest time unit
2958 is used."
2959 :group 'org-time
2960 :type '(choice (string :tag "Format string")
2961 (set (group :inline t (const :tag "Years" :years)
2962 (string :tag "Format string"))
2963 (group :inline t (const :tag "Months" :months)
2964 (string :tag "Format string"))
2965 (group :inline t (const :tag "Weeks" :weeks)
2966 (string :tag "Format string"))
2967 (group :inline t (const :tag "Days" :days)
2968 (string :tag "Format string"))
2969 (group :inline t (const :tag "Hours" :hours)
2970 (string :tag "Format string"))
2971 (group :inline t (const :tag "Minutes" :minutes)
2972 (string :tag "Format string")))))
2974 (defcustom org-deadline-warning-days 14
2975 "Number of days before expiration during which a deadline becomes active.
2976 This variable governs the display in sparse trees and in the agenda.
2977 When 0 or negative, it means use this number (the absolute value of it)
2978 even if a deadline has a different individual lead time specified.
2980 Custom commands can set this variable in the options section."
2981 :group 'org-time
2982 :group 'org-agenda-daily/weekly
2983 :type 'integer)
2985 (defcustom org-scheduled-delay-days 0
2986 "Number of days before a scheduled item becomes active.
2987 This variable governs the display in sparse trees and in the agenda.
2988 The default value (i.e. 0) means: don't delay scheduled item.
2989 When negative, it means use this number (the absolute value of it)
2990 even if a scheduled item has a different individual delay time
2991 specified.
2993 Custom commands can set this variable in the options section."
2994 :group 'org-time
2995 :group 'org-agenda-daily/weekly
2996 :version "24.4"
2997 :package-version '(Org . "8.0")
2998 :type 'integer)
3000 (defcustom org-read-date-prefer-future t
3001 "Non-nil means assume future for incomplete date input from user.
3002 This affects the following situations:
3003 1. The user gives a month but not a year.
3004 For example, if it is April and you enter \"feb 2\", this will be read
3005 as Feb 2, *next* year. \"May 5\", however, will be this year.
3006 2. The user gives a day, but no month.
3007 For example, if today is the 15th, and you enter \"3\", Org-mode will
3008 read this as the third of *next* month. However, if you enter \"17\",
3009 it will be considered as *this* month.
3011 If you set this variable to the symbol `time', then also the following
3012 will work:
3014 3. If the user gives a time.
3015 If the time is before now, it will be interpreted as tomorrow.
3017 Currently none of this works for ISO week specifications.
3019 When this option is nil, the current day, month and year will always be
3020 used as defaults.
3022 See also `org-agenda-jump-prefer-future'."
3023 :group 'org-time
3024 :type '(choice
3025 (const :tag "Never" nil)
3026 (const :tag "Check month and day" t)
3027 (const :tag "Check month, day, and time" time)))
3029 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3030 "Should the agenda jump command prefer the future for incomplete dates?
3031 The default is to do the same as configured in `org-read-date-prefer-future'.
3032 But you can also set a deviating value here.
3033 This may t or nil, or the symbol `org-read-date-prefer-future'."
3034 :group 'org-agenda
3035 :group 'org-time
3036 :version "24.1"
3037 :type '(choice
3038 (const :tag "Use org-read-date-prefer-future"
3039 org-read-date-prefer-future)
3040 (const :tag "Never" nil)
3041 (const :tag "Always" t)))
3043 (defcustom org-read-date-force-compatible-dates t
3044 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3046 Depending on the system Emacs is running on, certain dates cannot
3047 be represented with the type used internally to represent time.
3048 Dates between 1970-1-1 and 2038-1-1 can always be represented
3049 correctly. Some systems allow for earlier dates, some for later,
3050 some for both. One way to find out it to insert any date into an
3051 Org buffer, putting the cursor on the year and hitting S-up and
3052 S-down to test the range.
3054 When this variable is set to t, the date/time prompt will not let
3055 you specify dates outside the 1970-2037 range, so it is certain that
3056 these dates will work in whatever version of Emacs you are
3057 running, and also that you can move a file from one Emacs implementation
3058 to another. WHenever Org is forcing the year for you, it will display
3059 a message and beep.
3061 When this variable is nil, Org will check if the date is
3062 representable in the specific Emacs implementation you are using.
3063 If not, it will force a year, usually the current year, and beep
3064 to remind you. Currently this setting is not recommended because
3065 the likelihood that you will open your Org files in an Emacs that
3066 has limited date range is not negligible.
3068 A workaround for this problem is to use diary sexp dates for time
3069 stamps outside of this range."
3070 :group 'org-time
3071 :version "24.1"
3072 :type 'boolean)
3074 (defcustom org-read-date-display-live t
3075 "Non-nil means display current interpretation of date prompt live.
3076 This display will be in an overlay, in the minibuffer."
3077 :group 'org-time
3078 :type 'boolean)
3080 (defcustom org-read-date-popup-calendar t
3081 "Non-nil means pop up a calendar when prompting for a date.
3082 In the calendar, the date can be selected with mouse-1. However, the
3083 minibuffer will also be active, and you can simply enter the date as well.
3084 When nil, only the minibuffer will be available."
3085 :group 'org-time
3086 :type 'boolean)
3087 (org-defvaralias 'org-popup-calendar-for-date-prompt
3088 'org-read-date-popup-calendar)
3090 (make-obsolete-variable
3091 'org-read-date-minibuffer-setup-hook
3092 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3093 (defcustom org-read-date-minibuffer-setup-hook nil
3094 "Hook to be used to set up keys for the date/time interface.
3095 Add key definitions to `minibuffer-local-map', which will be a
3096 temporary copy.
3098 WARNING: This option is obsolete, you should use
3099 `org-read-date-minibuffer-local-map' to set up keys."
3100 :group 'org-time
3101 :type 'hook)
3103 (defcustom org-extend-today-until 0
3104 "The hour when your day really ends. Must be an integer.
3105 This has influence for the following applications:
3106 - When switching the agenda to \"today\". It it is still earlier than
3107 the time given here, the day recognized as TODAY is actually yesterday.
3108 - When a date is read from the user and it is still before the time given
3109 here, the current date and time will be assumed to be yesterday, 23:59.
3110 Also, timestamps inserted in capture templates follow this rule.
3112 IMPORTANT: This is a feature whose implementation is and likely will
3113 remain incomplete. Really, it is only here because past midnight seems to
3114 be the favorite working time of John Wiegley :-)"
3115 :group 'org-time
3116 :type 'integer)
3118 (defcustom org-use-effective-time nil
3119 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3120 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3121 \"effective time\" of any timestamps between midnight and 8am will be
3122 23:59 of the previous day."
3123 :group 'org-time
3124 :version "24.1"
3125 :type 'boolean)
3127 (defcustom org-use-last-clock-out-time-as-effective-time nil
3128 "When non-nil, use the last clock out time for `org-todo'.
3129 Note that this option has precedence over the combined use of
3130 `org-use-effective-time' and `org-extend-today-until'."
3131 :group 'org-time
3132 :version "24.4"
3133 :package-version '(Org . "8.0")
3134 :type 'boolean)
3136 (defcustom org-edit-timestamp-down-means-later nil
3137 "Non-nil means S-down will increase the time in a time stamp.
3138 When nil, S-up will increase."
3139 :group 'org-time
3140 :type 'boolean)
3142 (defcustom org-calendar-follow-timestamp-change t
3143 "Non-nil means make the calendar window follow timestamp changes.
3144 When a timestamp is modified and the calendar window is visible, it will be
3145 moved to the new date."
3146 :group 'org-time
3147 :type 'boolean)
3149 (defgroup org-tags nil
3150 "Options concerning tags in Org-mode."
3151 :tag "Org Tags"
3152 :group 'org)
3154 (defcustom org-tag-alist nil
3155 "List of tags allowed in Org-mode files.
3156 When this list is nil, Org-mode will base TAG input on what is already in the
3157 buffer.
3158 The value of this variable is an alist, the car of each entry must be a
3159 keyword as a string, the cdr may be a character that is used to select
3160 that tag through the fast-tag-selection interface.
3161 See the manual for details."
3162 :group 'org-tags
3163 :type '(repeat
3164 (choice
3165 (cons (string :tag "Tag name")
3166 (character :tag "Access char"))
3167 (list :tag "Start radio group"
3168 (const :startgroup)
3169 (option (string :tag "Group description")))
3170 (list :tag "End radio group"
3171 (const :endgroup)
3172 (option (string :tag "Group description")))
3173 (const :tag "New line" (:newline)))))
3175 (defcustom org-tag-persistent-alist nil
3176 "List of tags that will always appear in all Org-mode files.
3177 This is in addition to any in buffer settings or customizations
3178 of `org-tag-alist'.
3179 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3180 The value of this variable is an alist, the car of each entry must be a
3181 keyword as a string, the cdr may be a character that is used to select
3182 that tag through the fast-tag-selection interface.
3183 See the manual for details.
3184 To disable these tags on a per-file basis, insert anywhere in the file:
3185 #+STARTUP: noptag"
3186 :group 'org-tags
3187 :type '(repeat
3188 (choice
3189 (cons (string :tag "Tag name")
3190 (character :tag "Access char"))
3191 (const :tag "Start radio group" (:startgroup))
3192 (const :tag "End radio group" (:endgroup))
3193 (const :tag "New line" (:newline)))))
3195 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3196 "If non-nil, always offer completion for all tags of all agenda files.
3197 Instead of customizing this variable directly, you might want to
3198 set it locally for capture buffers, because there no list of
3199 tags in that file can be created dynamically (there are none).
3201 (add-hook 'org-capture-mode-hook
3202 (lambda ()
3203 (set (make-local-variable
3204 'org-complete-tags-always-offer-all-agenda-tags)
3205 t)))"
3206 :group 'org-tags
3207 :version "24.1"
3208 :type 'boolean)
3210 (defvar org-file-tags nil
3211 "List of tags that can be inherited by all entries in the file.
3212 The tags will be inherited if the variable `org-use-tag-inheritance'
3213 says they should be.
3214 This variable is populated from #+FILETAGS lines.")
3216 (defcustom org-use-fast-tag-selection 'auto
3217 "Non-nil means use fast tag selection scheme.
3218 This is a special interface to select and deselect tags with single keys.
3219 When nil, fast selection is never used.
3220 When the symbol `auto', fast selection is used if and only if selection
3221 characters for tags have been configured, either through the variable
3222 `org-tag-alist' or through a #+TAGS line in the buffer.
3223 When t, fast selection is always used and selection keys are assigned
3224 automatically if necessary."
3225 :group 'org-tags
3226 :type '(choice
3227 (const :tag "Always" t)
3228 (const :tag "Never" nil)
3229 (const :tag "When selection characters are configured" 'auto)))
3231 (defcustom org-fast-tag-selection-single-key nil
3232 "Non-nil means fast tag selection exits after first change.
3233 When nil, you have to press RET to exit it.
3234 During fast tag selection, you can toggle this flag with `C-c'.
3235 This variable can also have the value `expert'. In this case, the window
3236 displaying the tags menu is not even shown, until you press C-c again."
3237 :group 'org-tags
3238 :type '(choice
3239 (const :tag "No" nil)
3240 (const :tag "Yes" t)
3241 (const :tag "Expert" expert)))
3243 (defvar org-fast-tag-selection-include-todo nil
3244 "Non-nil means fast tags selection interface will also offer TODO states.
3245 This is an undocumented feature, you should not rely on it.")
3247 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3248 "The column to which tags should be indented in a headline.
3249 If this number is positive, it specifies the column. If it is negative,
3250 it means that the tags should be flushright to that column. For example,
3251 -80 works well for a normal 80 character screen.
3252 When 0, place tags directly after headline text, with only one space in
3253 between."
3254 :group 'org-tags
3255 :type 'integer)
3257 (defcustom org-auto-align-tags t
3258 "Non-nil keeps tags aligned when modifying headlines.
3259 Some operations (i.e. demoting) change the length of a headline and
3260 therefore shift the tags around. With this option turned on, after
3261 each such operation the tags are again aligned to `org-tags-column'."
3262 :group 'org-tags
3263 :type 'boolean)
3265 (defcustom org-use-tag-inheritance t
3266 "Non-nil means tags in levels apply also for sublevels.
3267 When nil, only the tags directly given in a specific line apply there.
3268 This may also be a list of tags that should be inherited, or a regexp that
3269 matches tags that should be inherited. Additional control is possible
3270 with the variable `org-tags-exclude-from-inheritance' which gives an
3271 explicit list of tags to be excluded from inheritance, even if the value of
3272 `org-use-tag-inheritance' would select it for inheritance.
3274 If this option is t, a match early-on in a tree can lead to a large
3275 number of matches in the subtree when constructing the agenda or creating
3276 a sparse tree. If you only want to see the first match in a tree during
3277 a search, check out the variable `org-tags-match-list-sublevels'."
3278 :group 'org-tags
3279 :type '(choice
3280 (const :tag "Not" nil)
3281 (const :tag "Always" t)
3282 (repeat :tag "Specific tags" (string :tag "Tag"))
3283 (regexp :tag "Tags matched by regexp")))
3285 (defcustom org-tags-exclude-from-inheritance nil
3286 "List of tags that should never be inherited.
3287 This is a way to exclude a few tags from inheritance. For way to do
3288 the opposite, to actively allow inheritance for selected tags,
3289 see the variable `org-use-tag-inheritance'."
3290 :group 'org-tags
3291 :type '(repeat (string :tag "Tag")))
3293 (defun org-tag-inherit-p (tag)
3294 "Check if TAG is one that should be inherited."
3295 (cond
3296 ((member tag org-tags-exclude-from-inheritance) nil)
3297 ((eq org-use-tag-inheritance t) t)
3298 ((not org-use-tag-inheritance) nil)
3299 ((stringp org-use-tag-inheritance)
3300 (string-match org-use-tag-inheritance tag))
3301 ((listp org-use-tag-inheritance)
3302 (member tag org-use-tag-inheritance))
3303 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3305 (defcustom org-tags-match-list-sublevels t
3306 "Non-nil means list also sublevels of headlines matching a search.
3307 This variable applies to tags/property searches, and also to stuck
3308 projects because this search is based on a tags match as well.
3310 When set to the symbol `indented', sublevels are indented with
3311 leading dots.
3313 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3314 the sublevels of a headline matching a tag search often also match
3315 the same search. Listing all of them can create very long lists.
3316 Setting this variable to nil causes subtrees of a match to be skipped.
3318 This variable is semi-obsolete and probably should always be true. It
3319 is better to limit inheritance to certain tags using the variables
3320 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3321 :group 'org-tags
3322 :type '(choice
3323 (const :tag "No, don't list them" nil)
3324 (const :tag "Yes, do list them" t)
3325 (const :tag "List them, indented with leading dots" indented)))
3327 (defcustom org-tags-sort-function nil
3328 "When set, tags are sorted using this function as a comparator."
3329 :group 'org-tags
3330 :type '(choice
3331 (const :tag "No sorting" nil)
3332 (const :tag "Alphabetical" string<)
3333 (const :tag "Reverse alphabetical" string>)
3334 (function :tag "Custom function" nil)))
3336 (defvar org-tags-history nil
3337 "History of minibuffer reads for tags.")
3338 (defvar org-last-tags-completion-table nil
3339 "The last used completion table for tags.")
3340 (defvar org-after-tags-change-hook nil
3341 "Hook that is run after the tags in a line have changed.")
3343 (defgroup org-properties nil
3344 "Options concerning properties in Org-mode."
3345 :tag "Org Properties"
3346 :group 'org)
3348 (defcustom org-property-format "%-10s %s"
3349 "How property key/value pairs should be formatted by `indent-line'.
3350 When `indent-line' hits a property definition, it will format the line
3351 according to this format, mainly to make sure that the values are
3352 lined-up with respect to each other."
3353 :group 'org-properties
3354 :type 'string)
3356 (defcustom org-properties-postprocess-alist nil
3357 "Alist of properties and functions to adjust inserted values.
3358 Elements of this alist must be of the form
3360 ([string] [function])
3362 where [string] must be a property name and [function] must be a
3363 lambda expression: this lambda expression must take one argument,
3364 the value to adjust, and return the new value as a string.
3366 For example, this element will allow the property \"Remaining\"
3367 to be updated wrt the relation between the \"Effort\" property
3368 and the clock summary:
3370 ((\"Remaining\" (lambda(value)
3371 (let ((clocksum (org-clock-sum-current-item))
3372 (effort (org-duration-string-to-minutes
3373 (org-entry-get (point) \"Effort\"))))
3374 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3375 :group 'org-properties
3376 :version "24.1"
3377 :type '(alist :key-type (string :tag "Property")
3378 :value-type (function :tag "Function")))
3380 (defcustom org-use-property-inheritance nil
3381 "Non-nil means properties apply also for sublevels.
3383 This setting is chiefly used during property searches. Turning it on can
3384 cause significant overhead when doing a search, which is why it is not
3385 on by default.
3387 When nil, only the properties directly given in the current entry count.
3388 When t, every property is inherited. The value may also be a list of
3389 properties that should have inheritance, or a regular expression matching
3390 properties that should be inherited.
3392 However, note that some special properties use inheritance under special
3393 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3394 and the properties ending in \"_ALL\" when they are used as descriptor
3395 for valid values of a property.
3397 Note for programmers:
3398 When querying an entry with `org-entry-get', you can control if inheritance
3399 should be used. By default, `org-entry-get' looks only at the local
3400 properties. You can request inheritance by setting the inherit argument
3401 to t (to force inheritance) or to `selective' (to respect the setting
3402 in this variable)."
3403 :group 'org-properties
3404 :type '(choice
3405 (const :tag "Not" nil)
3406 (const :tag "Always" t)
3407 (repeat :tag "Specific properties" (string :tag "Property"))
3408 (regexp :tag "Properties matched by regexp")))
3410 (defun org-property-inherit-p (property)
3411 "Check if PROPERTY is one that should be inherited."
3412 (cond
3413 ((eq org-use-property-inheritance t) t)
3414 ((not org-use-property-inheritance) nil)
3415 ((stringp org-use-property-inheritance)
3416 (string-match org-use-property-inheritance property))
3417 ((listp org-use-property-inheritance)
3418 (member property org-use-property-inheritance))
3419 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3421 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3422 "The default column format, if no other format has been defined.
3423 This variable can be set on the per-file basis by inserting a line
3425 #+COLUMNS: %25ITEM ....."
3426 :group 'org-properties
3427 :type 'string)
3429 (defcustom org-columns-ellipses ".."
3430 "The ellipses to be used when a field in column view is truncated.
3431 When this is the empty string, as many characters as possible are shown,
3432 but then there will be no visual indication that the field has been truncated.
3433 When this is a string of length N, the last N characters of a truncated
3434 field are replaced by this string. If the column is narrower than the
3435 ellipses string, only part of the ellipses string will be shown."
3436 :group 'org-properties
3437 :type 'string)
3439 (defcustom org-columns-modify-value-for-display-function nil
3440 "Function that modifies values for display in column view.
3441 For example, it can be used to cut out a certain part from a time stamp.
3442 The function must take 2 arguments:
3444 column-title The title of the column (*not* the property name)
3445 value The value that should be modified.
3447 The function should return the value that should be displayed,
3448 or nil if the normal value should be used."
3449 :group 'org-properties
3450 :type 'function)
3452 (defcustom org-effort-property "Effort"
3453 "The property that is being used to keep track of effort estimates.
3454 Effort estimates given in this property need to have the format H:MM."
3455 :group 'org-properties
3456 :group 'org-progress
3457 :type '(string :tag "Property"))
3459 (defconst org-global-properties-fixed
3460 '(("VISIBILITY_ALL" . "folded children content all")
3461 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3462 "List of property/value pairs that can be inherited by any entry.
3464 These are fixed values, for the preset properties. The user variable
3465 that can be used to add to this list is `org-global-properties'.
3467 The entries in this list are cons cells where the car is a property
3468 name and cdr is a string with the value. If the value represents
3469 multiple items like an \"_ALL\" property, separate the items by
3470 spaces.")
3472 (defcustom org-global-properties nil
3473 "List of property/value pairs that can be inherited by any entry.
3475 This list will be combined with the constant `org-global-properties-fixed'.
3477 The entries in this list are cons cells where the car is a property
3478 name and cdr is a string with the value.
3480 You can set buffer-local values for the same purpose in the variable
3481 `org-file-properties' this by adding lines like
3483 #+PROPERTY: NAME VALUE"
3484 :group 'org-properties
3485 :type '(repeat
3486 (cons (string :tag "Property")
3487 (string :tag "Value"))))
3489 (defvar org-file-properties nil
3490 "List of property/value pairs that can be inherited by any entry.
3491 Valid for the current buffer.
3492 This variable is populated from #+PROPERTY lines.")
3493 (make-variable-buffer-local 'org-file-properties)
3495 (defgroup org-agenda nil
3496 "Options concerning agenda views in Org-mode."
3497 :tag "Org Agenda"
3498 :group 'org)
3500 (defvar org-category nil
3501 "Variable used by org files to set a category for agenda display.
3502 Such files should use a file variable to set it, for example
3504 # -*- mode: org; org-category: \"ELisp\"
3506 or contain a special line
3508 #+CATEGORY: ELisp
3510 If the file does not specify a category, then file's base name
3511 is used instead.")
3512 (make-variable-buffer-local 'org-category)
3513 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3515 (defcustom org-agenda-files nil
3516 "The files to be used for agenda display.
3517 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3518 \\[org-remove-file]. You can also use customize to edit the list.
3520 If an entry is a directory, all files in that directory that are matched by
3521 `org-agenda-file-regexp' will be part of the file list.
3523 If the value of the variable is not a list but a single file name, then
3524 the list of agenda files is actually stored and maintained in that file, one
3525 agenda file per line. In this file paths can be given relative to
3526 `org-directory'. Tilde expansion and environment variable substitution
3527 are also made."
3528 :group 'org-agenda
3529 :type '(choice
3530 (repeat :tag "List of files and directories" file)
3531 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3533 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3534 "Regular expression to match files for `org-agenda-files'.
3535 If any element in the list in that variable contains a directory instead
3536 of a normal file, all files in that directory that are matched by this
3537 regular expression will be included."
3538 :group 'org-agenda
3539 :type 'regexp)
3541 (defcustom org-agenda-text-search-extra-files nil
3542 "List of extra files to be searched by text search commands.
3543 These files will be search in addition to the agenda files by the
3544 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3545 Note that these files will only be searched for text search commands,
3546 not for the other agenda views like todo lists, tag searches or the weekly
3547 agenda. This variable is intended to list notes and possibly archive files
3548 that should also be searched by these two commands.
3549 In fact, if the first element in the list is the symbol `agenda-archives',
3550 than all archive files of all agenda files will be added to the search
3551 scope."
3552 :group 'org-agenda
3553 :type '(set :greedy t
3554 (const :tag "Agenda Archives" agenda-archives)
3555 (repeat :inline t (file))))
3557 (org-defvaralias 'org-agenda-multi-occur-extra-files
3558 'org-agenda-text-search-extra-files)
3560 (defcustom org-agenda-skip-unavailable-files nil
3561 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3562 A nil value means to remove them, after a query, from the list."
3563 :group 'org-agenda
3564 :type 'boolean)
3566 (defcustom org-calendar-to-agenda-key [?c]
3567 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3568 The command `org-calendar-goto-agenda' will be bound to this key. The
3569 default is the character `c' because then `c' can be used to switch back and
3570 forth between agenda and calendar."
3571 :group 'org-agenda
3572 :type 'sexp)
3574 (defcustom org-calendar-insert-diary-entry-key [?i]
3575 "The key to be installed in `calendar-mode-map' for adding diary entries.
3576 This option is irrelevant until `org-agenda-diary-file' has been configured
3577 to point to an Org-mode file. When that is the case, the command
3578 `org-agenda-diary-entry' will be bound to the key given here, by default
3579 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3580 if you want to continue doing this, you need to change this to a different
3581 key."
3582 :group 'org-agenda
3583 :type 'sexp)
3585 (defcustom org-agenda-diary-file 'diary-file
3586 "File to which to add new entries with the `i' key in agenda and calendar.
3587 When this is the symbol `diary-file', the functionality in the Emacs
3588 calendar will be used to add entries to the `diary-file'. But when this
3589 points to a file, `org-agenda-diary-entry' will be used instead."
3590 :group 'org-agenda
3591 :type '(choice
3592 (const :tag "The standard Emacs diary file" diary-file)
3593 (file :tag "Special Org file diary entries")))
3595 (eval-after-load "calendar"
3596 '(progn
3597 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3598 'org-calendar-goto-agenda)
3599 (add-hook 'calendar-mode-hook
3600 (lambda ()
3601 (unless (eq org-agenda-diary-file 'diary-file)
3602 (define-key calendar-mode-map
3603 org-calendar-insert-diary-entry-key
3604 'org-agenda-diary-entry))))))
3606 (defgroup org-latex nil
3607 "Options for embedding LaTeX code into Org-mode."
3608 :tag "Org LaTeX"
3609 :group 'org)
3611 (defcustom org-format-latex-options
3612 '(:foreground default :background default :scale 1.0
3613 :html-foreground "Black" :html-background "Transparent"
3614 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3615 "Options for creating images from LaTeX fragments.
3616 This is a property list with the following properties:
3617 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3618 `default' means use the foreground of the default face.
3619 `auto' means use the foreground from the text face.
3620 :background the background color, or \"Transparent\".
3621 `default' means use the background of the default face.
3622 `auto' means use the background from the text face.
3623 :scale a scaling factor for the size of the images, to get more pixels
3624 :html-foreground, :html-background, :html-scale
3625 the same numbers for HTML export.
3626 :matchers a list indicating which matchers should be used to
3627 find LaTeX fragments. Valid members of this list are:
3628 \"begin\" find environments
3629 \"$1\" find single characters surrounded by $.$
3630 \"$\" find math expressions surrounded by $...$
3631 \"$$\" find math expressions surrounded by $$....$$
3632 \"\\(\" find math expressions surrounded by \\(...\\)
3633 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3634 :group 'org-latex
3635 :type 'plist)
3637 (defcustom org-format-latex-signal-error t
3638 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3639 When nil, just push out a message."
3640 :group 'org-latex
3641 :version "24.1"
3642 :type 'boolean)
3644 (defcustom org-latex-to-mathml-jar-file nil
3645 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3646 Use this to specify additional executable file say a jar file.
3648 When using MathToWeb as the converter, specify the full-path to
3649 your mathtoweb.jar file."
3650 :group 'org-latex
3651 :version "24.1"
3652 :type '(choice
3653 (const :tag "None" nil)
3654 (file :tag "JAR file" :must-match t)))
3656 (defcustom org-latex-to-mathml-convert-command nil
3657 "Command to convert LaTeX fragments to MathML.
3658 Replace format-specifiers in the command as noted below and use
3659 `shell-command' to convert LaTeX to MathML.
3660 %j: Executable file in fully expanded form as specified by
3661 `org-latex-to-mathml-jar-file'.
3662 %I: Input LaTeX file in fully expanded form
3663 %o: Output MathML file
3664 This command is used by `org-create-math-formula'.
3666 When using MathToWeb as the converter, set this to
3667 \"java -jar %j -unicode -force -df %o %I\"."
3668 :group 'org-latex
3669 :version "24.1"
3670 :type '(choice
3671 (const :tag "None" nil)
3672 (string :tag "\nShell command")))
3674 (defcustom org-latex-create-formula-image-program 'dvipng
3675 "Program to convert LaTeX fragments with.
3677 dvipng Process the LaTeX fragments to dvi file, then convert
3678 dvi files to png files using dvipng.
3679 This will also include processing of non-math environments.
3680 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3681 to convert pdf files to png files"
3682 :group 'org-latex
3683 :version "24.1"
3684 :type '(choice
3685 (const :tag "dvipng" dvipng)
3686 (const :tag "imagemagick" imagemagick)))
3688 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3689 "Path to store latex preview images.
3690 A relative path here creates many directories relative to the
3691 processed org files paths. An absolute path puts all preview
3692 images at the same place."
3693 :group 'org-latex
3694 :version "24.3"
3695 :type 'string)
3697 (defun org-format-latex-mathml-available-p ()
3698 "Return t if `org-latex-to-mathml-convert-command' is usable."
3699 (save-match-data
3700 (when (and (boundp 'org-latex-to-mathml-convert-command)
3701 org-latex-to-mathml-convert-command)
3702 (let ((executable (car (split-string
3703 org-latex-to-mathml-convert-command))))
3704 (when (executable-find executable)
3705 (if (string-match
3706 "%j" org-latex-to-mathml-convert-command)
3707 (file-readable-p org-latex-to-mathml-jar-file)
3708 t))))))
3710 (defcustom org-format-latex-header "\\documentclass{article}
3711 \\usepackage[usenames]{color}
3712 \\usepackage{amsmath}
3713 \\usepackage[mathscr]{eucal}
3714 \\pagestyle{empty} % do not remove
3715 \[PACKAGES]
3716 \[DEFAULT-PACKAGES]
3717 % The settings below are copied from fullpage.sty
3718 \\setlength{\\textwidth}{\\paperwidth}
3719 \\addtolength{\\textwidth}{-3cm}
3720 \\setlength{\\oddsidemargin}{1.5cm}
3721 \\addtolength{\\oddsidemargin}{-2.54cm}
3722 \\setlength{\\evensidemargin}{\\oddsidemargin}
3723 \\setlength{\\textheight}{\\paperheight}
3724 \\addtolength{\\textheight}{-\\headheight}
3725 \\addtolength{\\textheight}{-\\headsep}
3726 \\addtolength{\\textheight}{-\\footskip}
3727 \\addtolength{\\textheight}{-3cm}
3728 \\setlength{\\topmargin}{1.5cm}
3729 \\addtolength{\\topmargin}{-2.54cm}"
3730 "The document header used for processing LaTeX fragments.
3731 It is imperative that this header make sure that no page number
3732 appears on the page. The package defined in the variables
3733 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3734 will either replace the placeholder \"[PACKAGES]\" in this
3735 header, or they will be appended."
3736 :group 'org-latex
3737 :type 'string)
3739 (defun org-set-packages-alist (var val)
3740 "Set the packages alist and make sure it has 3 elements per entry."
3741 (set var (mapcar (lambda (x)
3742 (if (and (consp x) (= (length x) 2))
3743 (list (car x) (nth 1 x) t)
3745 val)))
3747 (defun org-get-packages-alist (var)
3748 "Get the packages alist and make sure it has 3 elements per entry."
3749 (mapcar (lambda (x)
3750 (if (and (consp x) (= (length x) 2))
3751 (list (car x) (nth 1 x) t)
3753 (default-value var)))
3755 (defcustom org-latex-default-packages-alist
3756 '(("AUTO" "inputenc" t)
3757 ("T1" "fontenc" t)
3758 ("" "fixltx2e" nil)
3759 ("" "graphicx" t)
3760 ("" "longtable" nil)
3761 ("" "float" nil)
3762 ("" "wrapfig" nil)
3763 ("" "soul" t)
3764 ("" "textcomp" t)
3765 ("" "marvosym" t)
3766 ("" "wasysym" t)
3767 ("" "latexsym" t)
3768 ("" "amssymb" t)
3769 ("" "hyperref" nil)
3770 "\\tolerance=1000")
3771 "Alist of default packages to be inserted in the header.
3773 Change this only if one of the packages here causes an
3774 incompatibility with another package you are using.
3776 The packages in this list are needed by one part or another of
3777 Org mode to function properly:
3779 - inputenc, fontenc: for basic font and character selection
3780 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3781 symbols used for interpreting the entities in `org-entities'.
3782 You can skip some of these packages if you don't use any of the
3783 symbols in it.
3784 - graphicx: for including images
3785 - float, wrapfig: for figure placement
3786 - longtable: for long tables
3787 - hyperref: for cross references
3789 Therefore you should not modify this variable unless you know
3790 what you are doing. The one reason to change it anyway is that
3791 you might be loading some other package that conflicts with one
3792 of the default packages. Each cell is of the format
3793 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3794 the package also needs to be included when compiling LaTeX
3795 snippets into images for inclusion into non-LaTeX output."
3796 :group 'org-latex
3797 :group 'org-export-latex
3798 :set 'org-set-packages-alist
3799 :get 'org-get-packages-alist
3800 :version "24.1"
3801 :type '(repeat
3802 (choice
3803 (list :tag "options/package pair"
3804 (string :tag "options")
3805 (string :tag "package")
3806 (boolean :tag "Snippet"))
3807 (string :tag "A line of LaTeX"))))
3809 (defcustom org-latex-packages-alist nil
3810 "Alist of packages to be inserted in every LaTeX header.
3812 These will be inserted after `org-latex-default-packages-alist'.
3813 Each cell is of the format:
3815 \(\"options\" \"package\" snippet-flag)
3817 SNIPPET-FLAG, when t, indicates that this package is also needed
3818 when turning LaTeX snippets into images for inclusion into
3819 non-LaTeX output.
3821 Make sure that you only list packages here which:
3823 - you want in every file
3824 - do not conflict with the setup in `org-format-latex-header'.
3825 - do not conflict with the default packages in
3826 `org-latex-default-packages-alist'."
3827 :group 'org-latex
3828 :group 'org-export-latex
3829 :set 'org-set-packages-alist
3830 :get 'org-get-packages-alist
3831 :type '(repeat
3832 (choice
3833 (list :tag "options/package pair"
3834 (string :tag "options")
3835 (string :tag "package")
3836 (boolean :tag "Snippet"))
3837 (string :tag "A line of LaTeX"))))
3839 (defgroup org-appearance nil
3840 "Settings for Org-mode appearance."
3841 :tag "Org Appearance"
3842 :group 'org)
3844 (defcustom org-level-color-stars-only nil
3845 "Non-nil means fontify only the stars in each headline.
3846 When nil, the entire headline is fontified.
3847 Changing it requires restart of `font-lock-mode' to become effective
3848 also in regions already fontified."
3849 :group 'org-appearance
3850 :type 'boolean)
3852 (defcustom org-hide-leading-stars nil
3853 "Non-nil means hide the first N-1 stars in a headline.
3854 This works by using the face `org-hide' for these stars. This
3855 face is white for a light background, and black for a dark
3856 background. You may have to customize the face `org-hide' to
3857 make this work.
3858 Changing it requires restart of `font-lock-mode' to become effective
3859 also in regions already fontified.
3860 You may also set this on a per-file basis by adding one of the following
3861 lines to the buffer:
3863 #+STARTUP: hidestars
3864 #+STARTUP: showstars"
3865 :group 'org-appearance
3866 :type 'boolean)
3868 (defcustom org-hidden-keywords nil
3869 "List of symbols corresponding to keywords to be hidden the org buffer.
3870 For example, a value '(title) for this list will make the document's title
3871 appear in the buffer without the initial #+TITLE: keyword."
3872 :group 'org-appearance
3873 :version "24.1"
3874 :type '(set (const :tag "#+AUTHOR" author)
3875 (const :tag "#+DATE" date)
3876 (const :tag "#+EMAIL" email)
3877 (const :tag "#+TITLE" title)))
3879 (defcustom org-custom-properties nil
3880 "List of properties (as strings) with a special meaning.
3881 The default use of these custom properties is to let the user
3882 hide them with `org-toggle-custom-properties-visibility'."
3883 :group 'org-properties
3884 :group 'org-appearance
3885 :version "24.3"
3886 :type '(repeat (string :tag "Property Name")))
3888 (defcustom org-fontify-done-headline nil
3889 "Non-nil means change the face of a headline if it is marked DONE.
3890 Normally, only the TODO/DONE keyword indicates the state of a headline.
3891 When this is non-nil, the headline after the keyword is set to the
3892 `org-headline-done' as an additional indication."
3893 :group 'org-appearance
3894 :type 'boolean)
3896 (defcustom org-fontify-emphasized-text t
3897 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3898 Changing this variable requires a restart of Emacs to take effect."
3899 :group 'org-appearance
3900 :type 'boolean)
3902 (defcustom org-fontify-whole-heading-line nil
3903 "Non-nil means fontify the whole line for headings.
3904 This is useful when setting a background color for the
3905 org-level-* faces."
3906 :group 'org-appearance
3907 :type 'boolean)
3909 (defcustom org-highlight-latex-and-related nil
3910 "Non-nil means highlight LaTeX related syntax in the buffer.
3911 When non nil, the value should be a list containing any of the
3912 following symbols:
3913 `latex' Highlight LaTeX snippets and environments.
3914 `script' Highlight subscript and superscript.
3915 `entities' Highlight entities."
3916 :group 'org-appearance
3917 :version "24.4"
3918 :package-version '(Org . "8.0")
3919 :type '(choice
3920 (const :tag "No highlighting" nil)
3921 (set :greedy t :tag "Highlight"
3922 (const :tag "LaTeX snippets and environments" latex)
3923 (const :tag "Subscript and superscript" script)
3924 (const :tag "Entities" entities))))
3926 (defcustom org-hide-emphasis-markers nil
3927 "Non-nil mean font-lock should hide the emphasis marker characters."
3928 :group 'org-appearance
3929 :type 'boolean)
3931 (defcustom org-pretty-entities nil
3932 "Non-nil means show entities as UTF8 characters.
3933 When nil, the \\name form remains in the buffer."
3934 :group 'org-appearance
3935 :version "24.1"
3936 :type 'boolean)
3938 (defcustom org-pretty-entities-include-sub-superscripts t
3939 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3940 :group 'org-appearance
3941 :version "24.1"
3942 :type 'boolean)
3944 (defvar org-emph-re nil
3945 "Regular expression for matching emphasis.
3946 After a match, the match groups contain these elements:
3947 0 The match of the full regular expression, including the characters
3948 before and after the proper match
3949 1 The character before the proper match, or empty at beginning of line
3950 2 The proper match, including the leading and trailing markers
3951 3 The leading marker like * or /, indicating the type of highlighting
3952 4 The text between the emphasis markers, not including the markers
3953 5 The character after the match, empty at the end of a line")
3954 (defvar org-verbatim-re nil
3955 "Regular expression for matching verbatim text.")
3956 (defvar org-emphasis-regexp-components) ; defined just below
3957 (defvar org-emphasis-alist) ; defined just below
3958 (defun org-set-emph-re (var val)
3959 "Set variable and compute the emphasis regular expression."
3960 (set var val)
3961 (when (and (boundp 'org-emphasis-alist)
3962 (boundp 'org-emphasis-regexp-components)
3963 org-emphasis-alist org-emphasis-regexp-components)
3964 (let* ((e org-emphasis-regexp-components)
3965 (pre (car e))
3966 (post (nth 1 e))
3967 (border (nth 2 e))
3968 (body (nth 3 e))
3969 (nl (nth 4 e))
3970 (body1 (concat body "*?"))
3971 (markers (mapconcat 'car org-emphasis-alist ""))
3972 (vmarkers (mapconcat
3973 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3974 org-emphasis-alist "")))
3975 ;; make sure special characters appear at the right position in the class
3976 (if (string-match "\\^" markers)
3977 (setq markers (concat (replace-match "" t t markers) "^")))
3978 (if (string-match "-" markers)
3979 (setq markers (concat (replace-match "" t t markers) "-")))
3980 (if (string-match "\\^" vmarkers)
3981 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3982 (if (string-match "-" vmarkers)
3983 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3984 (if (> nl 0)
3985 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3986 (int-to-string nl) "\\}")))
3987 ;; Make the regexp
3988 (setq org-emph-re
3989 (concat "\\([" pre "]\\|^\\)"
3990 "\\("
3991 "\\([" markers "]\\)"
3992 "\\("
3993 "[^" border "]\\|"
3994 "[^" border "]"
3995 body1
3996 "[^" border "]"
3997 "\\)"
3998 "\\3\\)"
3999 "\\([" post "]\\|$\\)"))
4000 (setq org-verbatim-re
4001 (concat "\\([" pre "]\\|^\\)"
4002 "\\("
4003 "\\([" vmarkers "]\\)"
4004 "\\("
4005 "[^" border "]\\|"
4006 "[^" border "]"
4007 body1
4008 "[^" border "]"
4009 "\\)"
4010 "\\3\\)"
4011 "\\([" post "]\\|$\\)")))))
4013 (defcustom org-emphasis-regexp-components
4014 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4015 "Components used to build the regular expression for emphasis.
4016 This is a list with five entries. Terminology: In an emphasis string
4017 like \" *strong word* \", we call the initial space PREMATCH, the final
4018 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4019 and \"trong wor\" is the body. The different components in this variable
4020 specify what is allowed/forbidden in each part:
4022 pre Chars allowed as prematch. Beginning of line will be allowed too.
4023 post Chars allowed as postmatch. End of line will be allowed too.
4024 border The chars *forbidden* as border characters.
4025 body-regexp A regexp like \".\" to match a body character. Don't use
4026 non-shy groups here, and don't allow newline here.
4027 newline The maximum number of newlines allowed in an emphasis exp.
4029 Use customize to modify this, or restart Emacs after changing it."
4030 :group 'org-appearance
4031 :set 'org-set-emph-re
4032 :type '(list
4033 (sexp :tag "Allowed chars in pre ")
4034 (sexp :tag "Allowed chars in post ")
4035 (sexp :tag "Forbidden chars in border ")
4036 (sexp :tag "Regexp for body ")
4037 (integer :tag "number of newlines allowed")
4038 (option (boolean :tag "Please ignore this button"))))
4040 (defcustom org-emphasis-alist
4041 `(("*" bold "<b>" "</b>")
4042 ("/" italic "<i>" "</i>")
4043 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4044 ("=" org-code "<code>" "</code>" verbatim)
4045 ("~" org-verbatim "<code>" "</code>" verbatim)
4046 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4047 "<del>" "</del>")
4049 "Special syntax for emphasized text.
4050 Text starting and ending with a special character will be emphasized, for
4051 example *bold*, _underlined_ and /italic/. This variable sets the marker
4052 characters, the face to be used by font-lock for highlighting in Org-mode
4053 Emacs buffers, and the HTML tags to be used for this.
4054 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4055 Use customize to modify this, or restart Emacs after changing it."
4056 :group 'org-appearance
4057 :set 'org-set-emph-re
4058 :type '(repeat
4059 (list
4060 (string :tag "Marker character")
4061 (choice
4062 (face :tag "Font-lock-face")
4063 (plist :tag "Face property list"))
4064 (string :tag "HTML start tag")
4065 (string :tag "HTML end tag")
4066 (option (const verbatim)))))
4068 (defvar org-protecting-blocks
4069 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4070 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4071 This is needed for font-lock setup.")
4073 ;;; Miscellaneous options
4075 (defgroup org-completion nil
4076 "Completion in Org-mode."
4077 :tag "Org Completion"
4078 :group 'org)
4080 (defcustom org-completion-use-ido nil
4081 "Non-nil means use ido completion wherever possible.
4082 Note that `ido-mode' must be active for this variable to be relevant.
4083 If you decide to turn this variable on, you might well want to turn off
4084 `org-outline-path-complete-in-steps'.
4085 See also `org-completion-use-iswitchb'."
4086 :group 'org-completion
4087 :type 'boolean)
4089 (defcustom org-completion-use-iswitchb nil
4090 "Non-nil means use iswitchb completion wherever possible.
4091 Note that `iswitchb-mode' must be active for this variable to be relevant.
4092 If you decide to turn this variable on, you might well want to turn off
4093 `org-outline-path-complete-in-steps'.
4094 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4095 :group 'org-completion
4096 :type 'boolean)
4098 (defcustom org-completion-fallback-command 'hippie-expand
4099 "The expansion command called by \\[pcomplete] in normal context.
4100 Normal means, no org-mode-specific context."
4101 :group 'org-completion
4102 :type 'function)
4104 ;;; Functions and variables from their packages
4105 ;; Declared here to avoid compiler warnings
4107 ;; XEmacs only
4108 (defvar outline-mode-menu-heading)
4109 (defvar outline-mode-menu-show)
4110 (defvar outline-mode-menu-hide)
4111 (defvar zmacs-regions) ; XEmacs regions
4113 ;; Emacs only
4114 (defvar mark-active)
4116 ;; Various packages
4117 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4118 (declare-function calendar-forward-day "cal-move" (arg))
4119 (declare-function calendar-goto-date "cal-move" (date))
4120 (declare-function calendar-goto-today "cal-move" ())
4121 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4122 (defvar calc-embedded-close-formula)
4123 (defvar calc-embedded-open-formula)
4124 (declare-function cdlatex-tab "ext:cdlatex" ())
4125 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4126 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4127 (defvar font-lock-unfontify-region-function)
4128 (declare-function iswitchb-read-buffer "iswitchb"
4129 (prompt &optional default require-match start matches-set))
4130 (defvar iswitchb-temp-buflist)
4131 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4132 (defvar org-agenda-tags-todo-honor-ignore-options)
4133 (declare-function org-agenda-skip "org-agenda" ())
4134 (declare-function
4135 org-agenda-format-item "org-agenda"
4136 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4137 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4138 (declare-function org-agenda-change-all-lines "org-agenda"
4139 (newhead hdmarker &optional fixface just-this))
4140 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4141 (declare-function org-agenda-maybe-redo "org-agenda" ())
4142 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4143 (beg end))
4144 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4145 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4146 "org-agenda" (&optional end))
4147 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4148 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4149 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4150 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4151 (declare-function org-indent-mode "org-indent" (&optional arg))
4152 (declare-function parse-time-string "parse-time" (string))
4153 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4154 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4155 (defvar remember-data-file)
4156 (defvar texmathp-why)
4157 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4158 (declare-function table--at-cell-p "table" (position &optional object at-column))
4160 (defvar org-latex-regexps)
4162 ;;; Autoload and prepare some org modules
4164 ;; Some table stuff that needs to be defined here, because it is used
4165 ;; by the functions setting up org-mode or checking for table context.
4167 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4168 "Detect an org-type or table-type table.")
4169 (defconst org-table-line-regexp "^[ \t]*|"
4170 "Detect an org-type table line.")
4171 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4172 "Detect an org-type table line.")
4173 (defconst org-table-hline-regexp "^[ \t]*|-"
4174 "Detect an org-type table hline.")
4175 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4176 "Detect a table-type table hline.")
4177 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4178 "Detect the first line outside a table when searching from within it.
4179 This works for both table types.")
4181 ;; Autoload the functions in org-table.el that are needed by functions here.
4183 (eval-and-compile
4184 (org-autoload "org-table"
4185 '(org-table-begin org-table-blank-field org-table-end)))
4187 ;;;###autoload
4188 (defun turn-on-orgtbl ()
4189 "Unconditionally turn on `orgtbl-mode'."
4190 (require 'org-table)
4191 (orgtbl-mode 1))
4193 (defun org-at-table-p (&optional table-type)
4194 "Return t if the cursor is inside an org-type table.
4195 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4196 (if org-enable-table-editor
4197 (save-excursion
4198 (beginning-of-line 1)
4199 (looking-at (if table-type org-table-any-line-regexp
4200 org-table-line-regexp)))
4201 nil))
4202 (defsubst org-table-p () (org-at-table-p))
4204 (defun org-at-table.el-p ()
4205 "Return t if and only if we are at a table.el table."
4206 (and (org-at-table-p 'any)
4207 (save-excursion
4208 (goto-char (org-table-begin 'any))
4209 (looking-at org-table1-hline-regexp))))
4211 (defun org-table-recognize-table.el ()
4212 "If there is a table.el table nearby, recognize it and move into it."
4213 (if org-table-tab-recognizes-table.el
4214 (if (org-at-table.el-p)
4215 (progn
4216 (beginning-of-line 1)
4217 (if (looking-at org-table-dataline-regexp)
4219 (if (looking-at org-table1-hline-regexp)
4220 (progn
4221 (beginning-of-line 2)
4222 (if (looking-at org-table-any-border-regexp)
4223 (beginning-of-line -1)))))
4224 (if (re-search-forward "|" (org-table-end t) t)
4225 (progn
4226 (require 'table)
4227 (if (table--at-cell-p (point))
4229 (message "recognizing table.el table...")
4230 (table-recognize-table)
4231 (message "recognizing table.el table...done")))
4232 (error "This should not happen"))
4234 nil)
4235 nil))
4237 (defun org-at-table-hline-p ()
4238 "Return t if the cursor is inside a hline in a table."
4239 (if org-enable-table-editor
4240 (save-excursion
4241 (beginning-of-line 1)
4242 (looking-at org-table-hline-regexp))
4243 nil))
4245 (defvar org-table-clean-did-remove-column nil)
4246 (defun org-table-map-tables (function &optional quietly)
4247 "Apply FUNCTION to the start of all tables in the buffer."
4248 (save-excursion
4249 (save-restriction
4250 (widen)
4251 (goto-char (point-min))
4252 (while (re-search-forward org-table-any-line-regexp nil t)
4253 (unless quietly
4254 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4255 (beginning-of-line 1)
4256 (when (and (looking-at org-table-line-regexp)
4257 ;; Exclude tables in src/example/verbatim/clocktable blocks
4258 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4259 (save-excursion (funcall function))
4260 (or (looking-at org-table-line-regexp)
4261 (forward-char 1)))
4262 (re-search-forward org-table-any-border-regexp nil 1))))
4263 (unless quietly (message "Mapping tables: done")))
4265 ;; Declare and autoload functions from ox.el and al.
4267 (declare-function org-export-get-environment "ox"
4268 (&optional backend subtreep ext-plist))
4269 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4271 ;; Declare and autoload functions from org-agenda.el
4273 (eval-and-compile
4274 (org-autoload "org-agenda"
4275 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4277 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4278 (declare-function org-clock-update-mode-line "org-clock" ())
4279 (declare-function org-resolve-clocks "org-clock"
4280 (&optional also-non-dangling-p prompt last-valid))
4281 (defvar org-clock-start-time)
4282 (defvar org-clock-marker (make-marker)
4283 "Marker recording the last clock-in.")
4284 (defvar org-clock-hd-marker (make-marker)
4285 "Marker recording the last clock-in, but the headline position.")
4286 (defvar org-clock-heading ""
4287 "The heading of the current clock entry.")
4288 (defun org-clock-is-active ()
4289 "Return non-nil if clock is currently running.
4290 The return value is actually the clock marker."
4291 (marker-buffer org-clock-marker))
4293 (eval-and-compile
4294 (org-autoload "org-clock" '(org-clock-remove-overlays
4295 org-clock-update-time-maybe
4296 org-clocktable-shift)))
4298 (defun org-check-running-clock ()
4299 "Check if the current buffer contains the running clock.
4300 If yes, offer to stop it and to save the buffer with the changes."
4301 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4302 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4303 (buffer-name))))
4304 (org-clock-out)
4305 (when (y-or-n-p "Save changed buffer?")
4306 (save-buffer))))
4308 (defun org-clocktable-try-shift (dir n)
4309 "Check if this line starts a clock table, if yes, shift the time block."
4310 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4311 (org-clocktable-shift dir n)))
4313 ;;;###autoload
4314 (defun org-clock-persistence-insinuate ()
4315 "Set up hooks for clock persistence."
4316 (require 'org-clock)
4317 (add-hook 'org-mode-hook 'org-clock-load)
4318 (add-hook 'kill-emacs-hook 'org-clock-save))
4320 ;; Define the variable already here, to make sure we have it.
4321 (defvar org-indent-mode nil
4322 "Non-nil if Org-Indent mode is enabled.
4323 Use the command `org-indent-mode' to change this variable.")
4325 ;; Autoload archiving code
4326 ;; The stuff that is needed for cycling and tags has to be defined here.
4328 (defgroup org-archive nil
4329 "Options concerning archiving in Org-mode."
4330 :tag "Org Archive"
4331 :group 'org-structure)
4333 (defcustom org-archive-location "%s_archive::"
4334 "The location where subtrees should be archived.
4336 The value of this variable is a string, consisting of two parts,
4337 separated by a double-colon. The first part is a filename and
4338 the second part is a headline.
4340 When the filename is omitted, archiving happens in the same file.
4341 %s in the filename will be replaced by the current file
4342 name (without the directory part). Archiving to a different file
4343 is useful to keep archived entries from contributing to the
4344 Org-mode Agenda.
4346 The archived entries will be filed as subtrees of the specified
4347 headline. When the headline is omitted, the subtrees are simply
4348 filed away at the end of the file, as top-level entries. Also in
4349 the heading you can use %s to represent the file name, this can be
4350 useful when using the same archive for a number of different files.
4352 Here are a few examples:
4353 \"%s_archive::\"
4354 If the current file is Projects.org, archive in file
4355 Projects.org_archive, as top-level trees. This is the default.
4357 \"::* Archived Tasks\"
4358 Archive in the current file, under the top-level headline
4359 \"* Archived Tasks\".
4361 \"~/org/archive.org::\"
4362 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4364 \"~/org/archive.org::* From %s\"
4365 Archive in file ~/org/archive.org (absolute path), under headlines
4366 \"From FILENAME\" where file name is the current file name.
4368 \"~/org/datetree.org::datetree/* Finished Tasks\"
4369 The \"datetree/\" string is special, signifying to archive
4370 items to the datetree. Items are placed in either the CLOSED
4371 date of the item, or the current date if there is no CLOSED date.
4372 The heading will be a subentry to the current date. There doesn't
4373 need to be a heading, but there always needs to be a slash after
4374 datetree. For example, to store archived items directly in the
4375 datetree, use \"~/org/datetree.org::datetree/\".
4377 \"basement::** Finished Tasks\"
4378 Archive in file ./basement (relative path), as level 3 trees
4379 below the level 2 heading \"** Finished Tasks\".
4381 You may set this option on a per-file basis by adding to the buffer a
4382 line like
4384 #+ARCHIVE: basement::** Finished Tasks
4386 You may also define it locally for a subtree by setting an ARCHIVE property
4387 in the entry. If such a property is found in an entry, or anywhere up
4388 the hierarchy, it will be used."
4389 :group 'org-archive
4390 :type 'string)
4392 (defcustom org-archive-tag "ARCHIVE"
4393 "The tag that marks a subtree as archived.
4394 An archived subtree does not open during visibility cycling, and does
4395 not contribute to the agenda listings.
4396 After changing this, font-lock must be restarted in the relevant buffers to
4397 get the proper fontification."
4398 :group 'org-archive
4399 :group 'org-keywords
4400 :type 'string)
4402 (defcustom org-agenda-skip-archived-trees t
4403 "Non-nil means the agenda will skip any items located in archived trees.
4404 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4405 variable is no longer recommended, you should leave it at the value t.
4406 Instead, use the key `v' to cycle the archives-mode in the agenda."
4407 :group 'org-archive
4408 :group 'org-agenda-skip
4409 :type 'boolean)
4411 (defcustom org-columns-skip-archived-trees t
4412 "Non-nil means ignore archived trees when creating column view."
4413 :group 'org-archive
4414 :group 'org-properties
4415 :type 'boolean)
4417 (defcustom org-cycle-open-archived-trees nil
4418 "Non-nil means `org-cycle' will open archived trees.
4419 An archived tree is a tree marked with the tag ARCHIVE.
4420 When nil, archived trees will stay folded. You can still open them with
4421 normal outline commands like `show-all', but not with the cycling commands."
4422 :group 'org-archive
4423 :group 'org-cycle
4424 :type 'boolean)
4426 (defcustom org-sparse-tree-open-archived-trees nil
4427 "Non-nil means sparse tree construction shows matches in archived trees.
4428 When nil, matches in these trees are highlighted, but the trees are kept in
4429 collapsed state."
4430 :group 'org-archive
4431 :group 'org-sparse-trees
4432 :type 'boolean)
4434 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4435 "The default date type when building a sparse tree.
4436 When this is nil, a date is a scheduled or a deadline timestamp.
4437 Otherwise, these types are allowed:
4439 all: all timestamps
4440 active: only active timestamps (<...>)
4441 inactive: only inactive timestamps (<...)
4442 scheduled: only scheduled timestamps
4443 deadline: only deadline timestamps"
4444 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4445 (const :tag "All timestamps" all)
4446 (const :tag "Only active timestamps" active)
4447 (const :tag "Only inactive timestamps" inactive)
4448 (const :tag "Only scheduled timestamps" scheduled)
4449 (const :tag "Only deadline timestamps" deadline))
4450 :version "24.3"
4451 :group 'org-sparse-trees)
4453 (defun org-cycle-hide-archived-subtrees (state)
4454 "Re-hide all archived subtrees after a visibility state change."
4455 (when (and (not org-cycle-open-archived-trees)
4456 (not (memq state '(overview folded))))
4457 (save-excursion
4458 (let* ((globalp (memq state '(contents all)))
4459 (beg (if globalp (point-min) (point)))
4460 (end (if globalp (point-max) (org-end-of-subtree t))))
4461 (org-hide-archived-subtrees beg end)
4462 (goto-char beg)
4463 (if (looking-at (concat ".*:" org-archive-tag ":"))
4464 (message "%s" (substitute-command-keys
4465 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4467 (defun org-force-cycle-archived ()
4468 "Cycle subtree even if it is archived."
4469 (interactive)
4470 (setq this-command 'org-cycle)
4471 (let ((org-cycle-open-archived-trees t))
4472 (call-interactively 'org-cycle)))
4474 (defun org-hide-archived-subtrees (beg end)
4475 "Re-hide all archived subtrees after a visibility state change."
4476 (save-excursion
4477 (let* ((re (concat ":" org-archive-tag ":")))
4478 (goto-char beg)
4479 (while (re-search-forward re end t)
4480 (when (org-at-heading-p)
4481 (org-flag-subtree t)
4482 (org-end-of-subtree t))))))
4484 (declare-function outline-end-of-heading "outline" ())
4485 (declare-function outline-flag-region "outline" (from to flag))
4486 (defun org-flag-subtree (flag)
4487 (save-excursion
4488 (org-back-to-heading t)
4489 (outline-end-of-heading)
4490 (outline-flag-region (point)
4491 (progn (org-end-of-subtree t) (point))
4492 flag)))
4494 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4496 (eval-and-compile
4497 (org-autoload "org-archive"
4498 '(org-add-archive-files)))
4500 ;; Autoload Column View Code
4502 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4503 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4504 (declare-function org-columns-compute "org-colview" (property))
4506 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4507 '(org-columns-number-to-string
4508 org-columns-get-format-and-top-level
4509 org-columns-compute
4510 org-columns-remove-overlays))
4512 ;; Autoload ID code
4514 (declare-function org-id-store-link "org-id")
4515 (declare-function org-id-locations-load "org-id")
4516 (declare-function org-id-locations-save "org-id")
4517 (defvar org-id-track-globally)
4518 (org-autoload "org-id"
4519 '(org-id-new
4520 org-id-copy
4521 org-id-get-with-outline-path-completion
4522 org-id-get-with-outline-drilling))
4524 ;;; Variables for pre-computed regular expressions, all buffer local
4526 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4527 "Matches first line of a hidden block.")
4528 (make-variable-buffer-local 'org-drawer-regexp)
4529 (defvar org-todo-regexp nil
4530 "Matches any of the TODO state keywords.")
4531 (make-variable-buffer-local 'org-todo-regexp)
4532 (defvar org-not-done-regexp nil
4533 "Matches any of the TODO state keywords except the last one.")
4534 (make-variable-buffer-local 'org-not-done-regexp)
4535 (defvar org-not-done-heading-regexp nil
4536 "Matches a TODO headline that is not done.")
4537 (make-variable-buffer-local 'org-not-done-regexp)
4538 (defvar org-todo-line-regexp nil
4539 "Matches a headline and puts TODO state into group 2 if present.")
4540 (make-variable-buffer-local 'org-todo-line-regexp)
4541 (defvar org-complex-heading-regexp nil
4542 "Matches a headline and puts everything into groups:
4543 group 1: the stars
4544 group 2: The todo keyword, maybe
4545 group 3: Priority cookie
4546 group 4: True headline
4547 group 5: Tags")
4548 (make-variable-buffer-local 'org-complex-heading-regexp)
4549 (defvar org-complex-heading-regexp-format nil
4550 "Printf format to make regexp to match an exact headline.
4551 This regexp will match the headline of any node which has the
4552 exact headline text that is put into the format, but may have any
4553 TODO state, priority and tags.")
4554 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4555 (defvar org-todo-line-tags-regexp nil
4556 "Matches a headline and puts TODO state into group 2 if present.
4557 Also put tags into group 4 if tags are present.")
4558 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4559 (defvar org-ds-keyword-length 12
4560 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4561 (make-variable-buffer-local 'org-ds-keyword-length)
4562 (defvar org-deadline-regexp nil
4563 "Matches the DEADLINE keyword.")
4564 (make-variable-buffer-local 'org-deadline-regexp)
4565 (defvar org-deadline-time-regexp nil
4566 "Matches the DEADLINE keyword together with a time stamp.")
4567 (make-variable-buffer-local 'org-deadline-time-regexp)
4568 (defvar org-deadline-time-hour-regexp nil
4569 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4570 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4571 (defvar org-deadline-line-regexp nil
4572 "Matches the DEADLINE keyword and the rest of the line.")
4573 (make-variable-buffer-local 'org-deadline-line-regexp)
4574 (defvar org-scheduled-regexp nil
4575 "Matches the SCHEDULED keyword.")
4576 (make-variable-buffer-local 'org-scheduled-regexp)
4577 (defvar org-scheduled-time-regexp nil
4578 "Matches the SCHEDULED keyword together with a time stamp.")
4579 (make-variable-buffer-local 'org-scheduled-time-regexp)
4580 (defvar org-scheduled-time-hour-regexp nil
4581 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4582 (make-variable-buffer-local 'org-scheduled-time-hour-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-time-hour-regexp
4992 (concat "\\<" org-deadline-string
4993 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
4994 org-deadline-line-regexp
4995 (concat "\\<\\(" org-deadline-string "\\).*")
4996 org-scheduled-regexp
4997 (concat "\\<" org-scheduled-string)
4998 org-scheduled-time-regexp
4999 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5000 org-scheduled-time-hour-regexp
5001 (concat "\\<" org-scheduled-string
5002 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5003 org-closed-time-regexp
5004 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5005 org-keyword-time-regexp
5006 (concat "\\<\\(" org-scheduled-string
5007 "\\|" org-deadline-string
5008 "\\|" org-closed-string
5009 "\\|" org-clock-string "\\)"
5010 " *[[<]\\([^]>]+\\)[]>]")
5011 org-keyword-time-not-clock-regexp
5012 (concat "\\<\\(" org-scheduled-string
5013 "\\|" org-deadline-string
5014 "\\|" org-closed-string
5015 "\\)"
5016 " *[[<]\\([^]>]+\\)[]>]")
5017 org-maybe-keyword-time-regexp
5018 (concat "\\(\\<\\(" org-scheduled-string
5019 "\\|" org-deadline-string
5020 "\\|" org-closed-string
5021 "\\|" org-clock-string "\\)\\)?"
5022 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5023 org-all-time-keywords
5024 (mapcar (lambda (w) (substring w 0 -1))
5025 (list org-scheduled-string org-deadline-string
5026 org-clock-string org-closed-string)))
5027 (org-compute-latex-and-related-regexp)
5028 (org-set-font-lock-defaults))))
5030 (defun org-file-contents (file &optional noerror)
5031 "Return the contents of FILE, as a string."
5032 (if (or (not file)
5033 (not (file-readable-p file)))
5034 (if noerror
5035 (progn
5036 (message "Cannot read file \"%s\"" file)
5037 (ding) (sit-for 2)
5039 (error "Cannot read file \"%s\"" file))
5040 (with-temp-buffer
5041 (insert-file-contents file)
5042 (buffer-string))))
5044 (defun org-extract-log-state-settings (x)
5045 "Extract the log state setting from a TODO keyword string.
5046 This will extract info from a string like \"WAIT(w@/!)\"."
5047 (let (kw key log1 log2)
5048 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5049 (setq kw (match-string 1 x)
5050 key (and (match-end 2) (match-string 2 x))
5051 log1 (and (match-end 3) (match-string 3 x))
5052 log2 (and (match-end 4) (match-string 4 x)))
5053 (and (or log1 log2)
5054 (list kw
5055 (and log1 (if (equal log1 "!") 'time 'note))
5056 (and log2 (if (equal log2 "!") 'time 'note)))))))
5058 (defun org-remove-keyword-keys (list)
5059 "Remove a pair of parenthesis at the end of each string in LIST."
5060 (mapcar (lambda (x)
5061 (if (string-match "(.*)$" x)
5062 (substring x 0 (match-beginning 0))
5064 list))
5066 (defun org-assign-fast-keys (alist)
5067 "Assign fast keys to a keyword-key alist.
5068 Respect keys that are already there."
5069 (let (new e (alt ?0))
5070 (while (setq e (pop alist))
5071 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5072 (cdr e)) ;; Key already assigned.
5073 (push e new)
5074 (let ((clist (string-to-list (downcase (car e))))
5075 (used (append new alist)))
5076 (when (= (car clist) ?@)
5077 (pop clist))
5078 (while (and clist (rassoc (car clist) used))
5079 (pop clist))
5080 (unless clist
5081 (while (rassoc alt used)
5082 (incf alt)))
5083 (push (cons (car e) (or (car clist) alt)) new))))
5084 (nreverse new)))
5086 ;;; Some variables used in various places
5088 (defvar org-window-configuration nil
5089 "Used in various places to store a window configuration.")
5090 (defvar org-selected-window nil
5091 "Used in various places to store a window configuration.")
5092 (defvar org-finish-function nil
5093 "Function to be called when `C-c C-c' is used.
5094 This is for getting out of special buffers like capture.")
5097 ;; FIXME: Occasionally check by commenting these, to make sure
5098 ;; no other functions uses these, forgetting to let-bind them.
5099 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5100 (defvar org-last-state)
5101 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5103 ;; Defined somewhere in this file, but used before definition.
5104 (defvar org-entities) ;; defined in org-entities.el
5105 (defvar org-struct-menu)
5106 (defvar org-org-menu)
5107 (defvar org-tbl-menu)
5109 ;;;; Define the Org-mode
5111 ;; We use a before-change function to check if a table might need
5112 ;; an update.
5113 (defvar org-table-may-need-update t
5114 "Indicates that a table might need an update.
5115 This variable is set by `org-before-change-function'.
5116 `org-table-align' sets it back to nil.")
5117 (defun org-before-change-function (beg end)
5118 "Every change indicates that a table might need an update."
5119 (setq org-table-may-need-update t))
5120 (defvar org-mode-map)
5121 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5122 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5123 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5124 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5125 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5126 (defvar org-table-buffer-is-an nil)
5128 (defvar bidi-paragraph-direction)
5129 (defvar buffer-face-mode-face)
5131 (require 'outline)
5132 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5133 (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"))
5134 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5136 ;; Other stuff we need.
5137 (require 'time-date)
5138 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5139 (require 'easymenu)
5140 (require 'overlay)
5142 ;; (require 'org-macs) moved higher up in the file before it is first used
5143 (require 'org-entities)
5144 ;; (require 'org-compat) moved higher up in the file before it is first used
5145 (require 'org-faces)
5146 (require 'org-list)
5147 (require 'org-pcomplete)
5148 (require 'org-src)
5149 (require 'org-footnote)
5150 (require 'org-macro)
5152 ;; babel
5153 (require 'ob)
5155 ;;;###autoload
5156 (define-derived-mode org-mode outline-mode "Org"
5157 "Outline-based notes management and organizer, alias
5158 \"Carsten's outline-mode for keeping track of everything.\"
5160 Org-mode develops organizational tasks around a NOTES file which
5161 contains information about projects as plain text. Org-mode is
5162 implemented on top of outline-mode, which is ideal to keep the content
5163 of large files well structured. It supports ToDo items, deadlines and
5164 time stamps, which magically appear in the diary listing of the Emacs
5165 calendar. Tables are easily created with a built-in table editor.
5166 Plain text URL-like links connect to websites, emails (VM), Usenet
5167 messages (Gnus), BBDB entries, and any files related to the project.
5168 For printing and sharing of notes, an Org-mode file (or a part of it)
5169 can be exported as a structured ASCII or HTML file.
5171 The following commands are available:
5173 \\{org-mode-map}"
5175 ;; Get rid of Outline menus, they are not needed
5176 ;; Need to do this here because define-derived-mode sets up
5177 ;; the keymap so late. Still, it is a waste to call this each time
5178 ;; we switch another buffer into org-mode.
5179 (if (featurep 'xemacs)
5180 (when (boundp 'outline-mode-menu-heading)
5181 ;; Assume this is Greg's port, it uses easymenu
5182 (easy-menu-remove outline-mode-menu-heading)
5183 (easy-menu-remove outline-mode-menu-show)
5184 (easy-menu-remove outline-mode-menu-hide))
5185 (define-key org-mode-map [menu-bar headings] 'undefined)
5186 (define-key org-mode-map [menu-bar hide] 'undefined)
5187 (define-key org-mode-map [menu-bar show] 'undefined))
5189 (org-load-modules-maybe)
5190 (easy-menu-add org-org-menu)
5191 (easy-menu-add org-tbl-menu)
5192 (org-install-agenda-files-menu)
5193 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5194 (add-to-invisibility-spec '(org-cwidth))
5195 (add-to-invisibility-spec '(org-hide-block . t))
5196 (when (featurep 'xemacs)
5197 (org-set-local 'line-move-ignore-invisible t))
5198 (org-set-local 'outline-regexp org-outline-regexp)
5199 (org-set-local 'outline-level 'org-outline-level)
5200 (setq bidi-paragraph-direction 'left-to-right)
5201 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5202 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5203 (when (and org-ellipsis
5204 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5205 (fboundp 'make-glyph-code))
5206 (unless org-display-table
5207 (setq org-display-table (make-display-table)))
5208 (set-display-table-slot
5209 org-display-table 4
5210 (vconcat (mapcar
5211 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5212 org-ellipsis)))
5213 (if (stringp org-ellipsis) org-ellipsis "..."))))
5214 (setq buffer-display-table org-display-table))
5215 (org-set-regexps-and-options)
5216 (when (and org-tag-faces (not org-tags-special-faces-re))
5217 ;; tag faces set outside customize.... force initialization.
5218 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5219 ;; Calc embedded
5220 (org-set-local 'calc-embedded-open-mode "# ")
5221 ;; Modify a few syntax entries
5222 (modify-syntax-entry ?@ "w")
5223 (modify-syntax-entry ?\" "\"")
5224 (if org-startup-truncated (setq truncate-lines t))
5225 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5226 (org-set-local 'font-lock-unfontify-region-function
5227 'org-unfontify-region)
5228 ;; Activate before-change-function
5229 (org-set-local 'org-table-may-need-update t)
5230 (org-add-hook 'before-change-functions 'org-before-change-function nil
5231 'local)
5232 ;; Check for running clock before killing a buffer
5233 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5234 ;; Initialize macros templates.
5235 (org-macro-initialize-templates)
5236 ;; Initialize radio targets.
5237 (org-update-radio-target-regexp)
5238 ;; Indentation.
5239 (org-set-local 'indent-line-function 'org-indent-line)
5240 (org-set-local 'indent-region-function 'org-indent-region)
5241 ;; Filling and auto-filling.
5242 (org-setup-filling)
5243 ;; Comments.
5244 (org-setup-comments-handling)
5245 ;; Beginning/end of defun
5246 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5247 (org-set-local 'end-of-defun-function 'org-forward-element)
5248 ;; Next error for sparse trees
5249 (org-set-local 'next-error-function 'org-occur-next-match)
5250 ;; Make sure dependence stuff works reliably, even for users who set it
5251 ;; too late :-(
5252 (if org-enforce-todo-dependencies
5253 (add-hook 'org-blocker-hook
5254 'org-block-todo-from-children-or-siblings-or-parent)
5255 (remove-hook 'org-blocker-hook
5256 'org-block-todo-from-children-or-siblings-or-parent))
5257 (if org-enforce-todo-checkbox-dependencies
5258 (add-hook 'org-blocker-hook
5259 'org-block-todo-from-checkboxes)
5260 (remove-hook 'org-blocker-hook
5261 'org-block-todo-from-checkboxes))
5263 ;; Align options lines
5264 (org-set-local
5265 'align-mode-rules-list
5266 '((org-in-buffer-settings
5267 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5268 (modes . '(org-mode)))))
5270 ;; Imenu
5271 (org-set-local 'imenu-create-index-function
5272 'org-imenu-get-tree)
5274 ;; Make isearch reveal context
5275 (if (or (featurep 'xemacs)
5276 (not (boundp 'outline-isearch-open-invisible-function)))
5277 ;; Emacs 21 and XEmacs make use of the hook
5278 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5279 ;; Emacs 22 deals with this through a special variable
5280 (org-set-local 'outline-isearch-open-invisible-function
5281 (lambda (&rest ignore) (org-show-context 'isearch)))
5282 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5284 ;; Setup the pcomplete hooks
5285 (set (make-local-variable 'pcomplete-command-completion-function)
5286 'org-pcomplete-initial)
5287 (set (make-local-variable 'pcomplete-command-name-function)
5288 'org-command-at-point)
5289 (set (make-local-variable 'pcomplete-default-completion-function)
5290 'ignore)
5291 (set (make-local-variable 'pcomplete-parse-arguments-function)
5292 'org-parse-arguments)
5293 (set (make-local-variable 'pcomplete-termination-string) "")
5294 (when (>= emacs-major-version 23)
5295 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5297 ;; If empty file that did not turn on org-mode automatically, make it to.
5298 (if (and org-insert-mode-line-in-empty-file
5299 (org-called-interactively-p 'any)
5300 (= (point-min) (point-max)))
5301 (insert "# -*- mode: org -*-\n\n"))
5302 (unless org-inhibit-startup
5303 (org-unmodified
5304 (and org-startup-with-beamer-mode (org-beamer-mode))
5305 (when org-startup-align-all-tables
5306 (org-table-map-tables 'org-table-align 'quietly))
5307 (when org-startup-with-inline-images
5308 (org-display-inline-images))
5309 (when org-startup-with-latex-preview
5310 (org-preview-latex-fragment))
5311 (unless org-inhibit-startup-visibility-stuff
5312 (org-set-startup-visibility))))
5313 ;; Try to set org-hide correctly
5314 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5316 ;; Update `customize-package-emacs-version-alist'
5317 (add-to-list 'customize-package-emacs-version-alist
5318 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5319 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5320 ("8.0" . "24.4")))
5322 (defvar org-mode-transpose-word-syntax-table
5323 (let ((st (make-syntax-table)))
5324 (mapc (lambda(c) (modify-syntax-entry
5325 (string-to-char (car c)) "w p" st))
5326 org-emphasis-alist)
5327 st))
5329 (when (fboundp 'abbrev-table-put)
5330 (abbrev-table-put org-mode-abbrev-table
5331 :parents (list text-mode-abbrev-table)))
5333 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5335 (defsubst org-fix-ellipsis-at-bol ()
5336 (save-excursion (goto-char (window-start)) (recenter 0)))
5338 (defun org-find-invisible-foreground ()
5339 (let ((candidates (remove
5340 "unspecified-bg"
5341 (nconc
5342 (list (face-background 'default)
5343 (face-background 'org-default))
5344 (mapcar
5345 (lambda (alist)
5346 (when (boundp alist)
5347 (cdr (assoc 'background-color (symbol-value alist)))))
5348 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5349 (list (face-foreground 'org-hide))))))
5350 (car (remove nil candidates))))
5352 (defun org-current-time (&optional rounding-minutes past)
5353 "Current time, possibly rounded to ROUNDING-MINUTES.
5354 When ROUNDING-MINUTES is not an integer, fall back on the car of
5355 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5356 the rounding returns a past time."
5357 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5358 (car org-time-stamp-rounding-minutes)))
5359 (time (decode-time)) res)
5360 (if (< r 1)
5361 (current-time)
5362 (setq res
5363 (apply 'encode-time
5364 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5365 (nthcdr 2 time))))
5366 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5367 (seconds-to-time (- (org-float-time res) (* r 60)))
5368 res))))
5370 (defun org-today ()
5371 "Return today date, considering `org-extend-today-until'."
5372 (time-to-days
5373 (time-subtract (current-time)
5374 (list 0 (* 3600 org-extend-today-until) 0))))
5376 ;;;; Font-Lock stuff, including the activators
5378 (defvar org-mouse-map (make-sparse-keymap))
5379 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5380 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5381 (when org-mouse-1-follows-link
5382 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5383 (when org-tab-follows-link
5384 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5385 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5387 (require 'font-lock)
5389 (defconst org-non-link-chars "]\t\n\r<>")
5390 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5391 "shell" "elisp" "doi" "message"))
5392 (defvar org-link-types-re nil
5393 "Matches a link that has a url-like prefix like \"http:\"")
5394 (defvar org-link-re-with-space nil
5395 "Matches a link with spaces, optional angular brackets around it.")
5396 (defvar org-link-re-with-space2 nil
5397 "Matches a link with spaces, optional angular brackets around it.")
5398 (defvar org-link-re-with-space3 nil
5399 "Matches a link with spaces, only for internal part in bracket links.")
5400 (defvar org-angle-link-re nil
5401 "Matches link with angular brackets, spaces are allowed.")
5402 (defvar org-plain-link-re nil
5403 "Matches plain link, without spaces.")
5404 (defvar org-bracket-link-regexp nil
5405 "Matches a link in double brackets.")
5406 (defvar org-bracket-link-analytic-regexp nil
5407 "Regular expression used to analyze links.
5408 Here is what the match groups contain after a match:
5409 1: http:
5410 2: http
5411 3: path
5412 4: [desc]
5413 5: desc")
5414 (defvar org-bracket-link-analytic-regexp++ nil
5415 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5416 (defvar org-any-link-re nil
5417 "Regular expression matching any link.")
5419 (defconst org-match-sexp-depth 3
5420 "Number of stacked braces for sub/superscript matching.")
5422 (defun org-create-multibrace-regexp (left right n)
5423 "Create a regular expression which will match a balanced sexp.
5424 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5425 as single character strings.
5426 The regexp returned will match the entire expression including the
5427 delimiters. It will also define a single group which contains the
5428 match except for the outermost delimiters. The maximum depth of
5429 stacked delimiters is N. Escaping delimiters is not possible."
5430 (let* ((nothing (concat "[^" left right "]*?"))
5431 (or "\\|")
5432 (re nothing)
5433 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5434 (while (> n 1)
5435 (setq n (1- n)
5436 re (concat re or next)
5437 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5438 (concat left "\\(" re "\\)" right)))
5440 (defvar org-match-substring-regexp
5441 (concat
5442 "\\(\\S-\\)\\([_^]\\)\\("
5443 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5444 "\\|"
5445 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5446 "\\|"
5447 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5448 "The regular expression matching a sub- or superscript.")
5450 (defvar org-match-substring-with-braces-regexp
5451 (concat
5452 "\\(\\S-\\)\\([_^]\\)\\("
5453 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5454 "\\)")
5455 "The regular expression matching a sub- or superscript, forcing braces.")
5457 (defun org-make-link-regexps ()
5458 "Update the link regular expressions.
5459 This should be called after the variable `org-link-types' has changed."
5460 (setq org-link-types-re
5461 (concat
5462 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5463 org-link-re-with-space
5464 (concat
5465 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5466 "\\([^" org-non-link-chars " ]"
5467 "[^" org-non-link-chars "]*"
5468 "[^" org-non-link-chars " ]\\)>?")
5469 org-link-re-with-space2
5470 (concat
5471 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5472 "\\([^" org-non-link-chars " ]"
5473 "[^\t\n\r]*"
5474 "[^" org-non-link-chars " ]\\)>?")
5475 org-link-re-with-space3
5476 (concat
5477 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5478 "\\([^" org-non-link-chars " ]"
5479 "[^\t\n\r]*\\)")
5480 org-angle-link-re
5481 (concat
5482 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5483 "\\([^" org-non-link-chars " ]"
5484 "[^" org-non-link-chars "]*"
5485 "\\)>")
5486 org-plain-link-re
5487 (concat
5488 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5489 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5490 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5491 org-bracket-link-regexp
5492 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5493 org-bracket-link-analytic-regexp
5494 (concat
5495 "\\[\\["
5496 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5497 "\\([^]]+\\)"
5498 "\\]"
5499 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5500 "\\]")
5501 org-bracket-link-analytic-regexp++
5502 (concat
5503 "\\[\\["
5504 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5505 "\\([^]]+\\)"
5506 "\\]"
5507 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5508 "\\]")
5509 org-any-link-re
5510 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5511 org-angle-link-re "\\)\\|\\("
5512 org-plain-link-re "\\)")))
5514 (org-make-link-regexps)
5516 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5517 "Regular expression for fast time stamp matching.")
5518 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5519 "Regular expression for fast time stamp matching.")
5520 (defconst org-ts-regexp0
5521 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5522 "Regular expression matching time strings for analysis.
5523 This one does not require the space after the date, so it can be used
5524 on a string that terminates immediately after the date.")
5525 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5526 "Regular expression matching time strings for analysis.")
5527 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5528 "Regular expression matching time stamps, with groups.")
5529 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5530 "Regular expression matching time stamps (also [..]), with groups.")
5531 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5532 "Regular expression matching a time stamp range.")
5533 (defconst org-tr-regexp-both
5534 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5535 "Regular expression matching a time stamp range.")
5536 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5537 org-ts-regexp "\\)?")
5538 "Regular expression matching a time stamp or time stamp range.")
5539 (defconst org-tsr-regexp-both
5540 (concat org-ts-regexp-both "\\(--?-?"
5541 org-ts-regexp-both "\\)?")
5542 "Regular expression matching a time stamp or time stamp range.
5543 The time stamps may be either active or inactive.")
5545 (defvar org-emph-face nil)
5547 (defun org-do-emphasis-faces (limit)
5548 "Run through the buffer and add overlays to emphasized strings."
5549 (let (rtn a)
5550 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5551 (if (not (= (char-after (match-beginning 3))
5552 (char-after (match-beginning 4))))
5553 (progn
5554 (setq rtn t)
5555 (setq a (assoc (match-string 3) org-emphasis-alist))
5556 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5557 'face
5558 (nth 1 a))
5559 (and (nth 4 a)
5560 (org-remove-flyspell-overlays-in
5561 (match-beginning 0) (match-end 0)))
5562 (add-text-properties (match-beginning 2) (match-end 2)
5563 '(font-lock-multiline t org-emphasis t))
5564 (when org-hide-emphasis-markers
5565 (add-text-properties (match-end 4) (match-beginning 5)
5566 '(invisible org-link))
5567 (add-text-properties (match-beginning 3) (match-end 3)
5568 '(invisible org-link)))))
5569 (backward-char 1))
5570 rtn))
5572 (defun org-emphasize (&optional char)
5573 "Insert or change an emphasis, i.e. a font like bold or italic.
5574 If there is an active region, change that region to a new emphasis.
5575 If there is no region, just insert the marker characters and position
5576 the cursor between them.
5577 CHAR should be either the marker character, or the first character of the
5578 HTML tag associated with that emphasis. If CHAR is a space, the means
5579 to remove the emphasis of the selected region.
5580 If char is not given (for example in an interactive call) it
5581 will be prompted for."
5582 (interactive)
5583 (let ((eal org-emphasis-alist) e det
5584 (erc org-emphasis-regexp-components)
5585 (prompt "")
5586 (string "") beg end move tag c s)
5587 (if (org-region-active-p)
5588 (setq beg (region-beginning) end (region-end)
5589 string (buffer-substring beg end))
5590 (setq move t))
5592 (while (setq e (pop eal))
5593 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5594 c (aref tag 0))
5595 (push (cons c (string-to-char (car e))) det)
5596 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5597 (substring tag 1)))))
5598 (setq det (nreverse det))
5599 (unless char
5600 (message "%s" (concat "Emphasis marker or tag:" prompt))
5601 (setq char (read-char-exclusive)))
5602 (setq char (or (cdr (assoc char det)) char))
5603 (if (equal char ?\ )
5604 (setq s "" move nil)
5605 (unless (assoc (char-to-string char) org-emphasis-alist)
5606 (error "No such emphasis marker: \"%c\"" char))
5607 (setq s (char-to-string char)))
5608 (while (and (> (length string) 1)
5609 (equal (substring string 0 1) (substring string -1))
5610 (assoc (substring string 0 1) org-emphasis-alist))
5611 (setq string (substring string 1 -1)))
5612 (setq string (concat s string s))
5613 (if beg (delete-region beg end))
5614 (unless (or (bolp)
5615 (string-match (concat "[" (nth 0 erc) "\n]")
5616 (char-to-string (char-before (point)))))
5617 (insert " "))
5618 (unless (or (eobp)
5619 (string-match (concat "[" (nth 1 erc) "\n]")
5620 (char-to-string (char-after (point)))))
5621 (insert " ") (backward-char 1))
5622 (insert string)
5623 (and move (backward-char 1))))
5625 (defconst org-nonsticky-props
5626 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5628 (defsubst org-rear-nonsticky-at (pos)
5629 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5631 (defun org-activate-plain-links (limit)
5632 "Run through the buffer and add overlays to links."
5633 (let (f hl)
5634 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5635 (not (org-in-src-block-p)))
5636 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5637 (setq f (get-text-property (match-beginning 0) 'face))
5638 (setq hl (org-match-string-no-properties 0))
5639 (if (or (eq f 'org-tag)
5640 (and (listp f) (memq 'org-tag f)))
5642 (add-text-properties (match-beginning 0) (match-end 0)
5643 (list 'mouse-face 'highlight
5644 'face 'org-link
5645 'htmlize-link `(:uri ,hl)
5646 'keymap org-mouse-map))
5647 (org-rear-nonsticky-at (match-end 0)))
5648 t)))
5650 (defun org-activate-code (limit)
5651 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5652 (progn
5653 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5654 (remove-text-properties (match-beginning 0) (match-end 0)
5655 '(display t invisible t intangible t))
5656 t)))
5658 (defcustom org-src-fontify-natively nil
5659 "When non-nil, fontify code in code blocks."
5660 :type 'boolean
5661 :version "24.1"
5662 :group 'org-appearance
5663 :group 'org-babel)
5665 (defcustom org-allow-promoting-top-level-subtree nil
5666 "When non-nil, allow promoting a top level subtree.
5667 The leading star of the top level headline will be replaced
5668 by a #."
5669 :type 'boolean
5670 :version "24.1"
5671 :group 'org-appearance)
5673 (defun org-fontify-meta-lines-and-blocks (limit)
5674 (condition-case nil
5675 (org-fontify-meta-lines-and-blocks-1 limit)
5676 (error (message "org-mode fontification error"))))
5678 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5679 "Fontify #+ lines and blocks, in the correct ways."
5680 (let ((case-fold-search t))
5681 (if (re-search-forward
5682 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5683 limit t)
5684 (let ((beg (match-beginning 0))
5685 (block-start (match-end 0))
5686 (block-end nil)
5687 (lang (match-string 7))
5688 (beg1 (line-beginning-position 2))
5689 (dc1 (downcase (match-string 2)))
5690 (dc3 (downcase (match-string 3)))
5691 end end1 quoting block-type ovl)
5692 (cond
5693 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5694 ;; a single line of backend-specific content
5695 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5696 (remove-text-properties (match-beginning 0) (match-end 0)
5697 '(display t invisible t intangible t))
5698 (add-text-properties (match-beginning 1) (match-end 3)
5699 '(font-lock-fontified t face org-meta-line))
5700 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5701 '(font-lock-fontified t face org-block))
5702 ; for backend-specific code
5704 ((and (match-end 4) (equal dc3 "+begin"))
5705 ;; Truly a block
5706 (setq block-type (downcase (match-string 5))
5707 quoting (member block-type org-protecting-blocks))
5708 (when (re-search-forward
5709 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5710 nil t) ;; on purpose, we look further than LIMIT
5711 (setq end (min (point-max) (match-end 0))
5712 end1 (min (point-max) (1- (match-beginning 0))))
5713 (setq block-end (match-beginning 0))
5714 (when quoting
5715 (remove-text-properties beg end
5716 '(display t invisible t intangible t)))
5717 (add-text-properties
5718 beg end
5719 '(font-lock-fontified t font-lock-multiline t))
5720 (add-text-properties beg beg1 '(face org-meta-line))
5721 (add-text-properties end1 (min (point-max) (1+ end))
5722 '(face org-meta-line)) ; for end_src
5723 (cond
5724 ((and lang (not (string= lang "")) org-src-fontify-natively)
5725 (org-src-font-lock-fontify-block lang block-start block-end)
5726 ;; remove old background overlays
5727 (mapc (lambda (ov)
5728 (if (eq (overlay-get ov 'face) 'org-block-background)
5729 (delete-overlay ov)))
5730 (overlays-at (/ (+ beg1 block-end) 2)))
5731 ;; add a background overlay
5732 (setq ovl (make-overlay beg1 block-end))
5733 (overlay-put ovl 'face 'org-block-background)
5734 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5735 (quoting
5736 (add-text-properties beg1 (min (point-max) (1+ end1))
5737 '(face org-block))) ; end of source block
5738 ((not org-fontify-quote-and-verse-blocks))
5739 ((string= block-type "quote")
5740 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5741 ((string= block-type "verse")
5742 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5743 (add-text-properties beg beg1 '(face org-block-begin-line))
5744 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5745 '(face org-block-end-line))
5747 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5748 (add-text-properties
5749 beg (match-end 3)
5750 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5751 '(font-lock-fontified t invisible t)
5752 '(font-lock-fontified t face org-document-info-keyword)))
5753 (add-text-properties
5754 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5755 (if (string-equal dc1 "+title:")
5756 '(font-lock-fontified t face org-document-title)
5757 '(font-lock-fontified t face org-document-info))))
5758 ((or (equal dc1 "+results")
5759 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5760 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5761 "+call:" "+header:" "+headers:" "+name:"))
5762 (and (match-end 4) (equal dc3 "+attr")))
5763 (add-text-properties
5764 beg (match-end 0)
5765 '(font-lock-fontified t face org-meta-line))
5767 ((member dc3 '(" " ""))
5768 (add-text-properties
5769 beg (match-end 0)
5770 '(font-lock-fontified t face font-lock-comment-face)))
5771 ((not (member (char-after beg) '(?\ ?\t)))
5772 ;; just any other in-buffer setting, but not indented
5773 (add-text-properties
5774 beg (match-end 0)
5775 '(font-lock-fontified t face org-meta-line))
5777 (t nil))))))
5779 (defun org-activate-angle-links (limit)
5780 "Run through the buffer and add overlays to links."
5781 (if (and (re-search-forward org-angle-link-re limit t)
5782 (not (org-in-src-block-p)))
5783 (progn
5784 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5785 (add-text-properties (match-beginning 0) (match-end 0)
5786 (list 'mouse-face 'highlight
5787 'keymap org-mouse-map))
5788 (org-rear-nonsticky-at (match-end 0))
5789 t)))
5791 (defun org-activate-footnote-links (limit)
5792 "Run through the buffer and add overlays to footnotes."
5793 (let ((fn (org-footnote-next-reference-or-definition limit)))
5794 (when fn
5795 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5796 (org-remove-flyspell-overlays-in beg end)
5797 (add-text-properties beg end
5798 (list 'mouse-face 'highlight
5799 'keymap org-mouse-map
5800 'help-echo
5801 (if (= (point-at-bol) beg)
5802 "Footnote definition"
5803 "Footnote reference")
5804 'font-lock-fontified t
5805 'font-lock-multiline t
5806 'face 'org-footnote))))))
5808 (defun org-activate-bracket-links (limit)
5809 "Run through the buffer and add overlays to bracketed links."
5810 (if (and (re-search-forward org-bracket-link-regexp limit t)
5811 (not (org-in-src-block-p)))
5812 (let* ((hl (org-match-string-no-properties 1))
5813 (help (concat "LINK: " hl))
5814 ;; FIXME: Above we should remove the escapes. But that
5815 ;; requires another match, protecting match data, a lot
5816 ;; of overhead for font-lock.
5817 (ip (org-maybe-intangible
5818 (list 'invisible 'org-link
5819 'keymap org-mouse-map 'mouse-face 'highlight
5820 'font-lock-multiline t 'help-echo help
5821 'htmlize-link `(:uri ,hl))))
5822 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5823 'font-lock-multiline t 'help-echo help
5824 'htmlize-link `(:uri ,hl))))
5825 ;; We need to remove the invisible property here. Table narrowing
5826 ;; may have made some of this invisible.
5827 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5828 (remove-text-properties (match-beginning 0) (match-end 0)
5829 '(invisible nil))
5830 (if (match-end 3)
5831 (progn
5832 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5833 (org-rear-nonsticky-at (match-beginning 3))
5834 (add-text-properties (match-beginning 3) (match-end 3) vp)
5835 (org-rear-nonsticky-at (match-end 3))
5836 (add-text-properties (match-end 3) (match-end 0) ip)
5837 (org-rear-nonsticky-at (match-end 0)))
5838 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5839 (org-rear-nonsticky-at (match-beginning 1))
5840 (add-text-properties (match-beginning 1) (match-end 1) vp)
5841 (org-rear-nonsticky-at (match-end 1))
5842 (add-text-properties (match-end 1) (match-end 0) ip)
5843 (org-rear-nonsticky-at (match-end 0)))
5844 t)))
5846 (defun org-activate-dates (limit)
5847 "Run through the buffer and add overlays to dates."
5848 (if (and (re-search-forward org-tsr-regexp-both limit t)
5849 (not (equal (char-before (match-beginning 0)) 91)))
5850 (progn
5851 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5852 (add-text-properties (match-beginning 0) (match-end 0)
5853 (list 'mouse-face 'highlight
5854 'keymap org-mouse-map))
5855 (org-rear-nonsticky-at (match-end 0))
5856 (when org-display-custom-times
5857 (if (match-end 3)
5858 (org-display-custom-time (match-beginning 3) (match-end 3)))
5859 (org-display-custom-time (match-beginning 1) (match-end 1)))
5860 t)))
5862 (defvar org-target-link-regexp nil
5863 "Regular expression matching radio targets in plain text.")
5864 (make-variable-buffer-local 'org-target-link-regexp)
5865 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5866 "Regular expression matching a link target.")
5867 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5868 "Regular expression matching a radio target.")
5869 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5870 "Regular expression matching any target.")
5872 (defun org-activate-target-links (limit)
5873 "Run through the buffer and add overlays to target matches."
5874 (when org-target-link-regexp
5875 (let ((case-fold-search t))
5876 (if (re-search-forward org-target-link-regexp limit t)
5877 (progn
5878 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5879 (add-text-properties (match-beginning 0) (match-end 0)
5880 (list 'mouse-face 'highlight
5881 'keymap org-mouse-map
5882 'help-echo "Radio target link"
5883 'org-linked-text t))
5884 (org-rear-nonsticky-at (match-end 0))
5885 t)))))
5887 (defun org-update-radio-target-regexp ()
5888 "Find all radio targets in this file and update the regular expression."
5889 (interactive)
5890 (when (memq 'radio org-activate-links)
5891 (setq org-target-link-regexp
5892 (org-make-target-link-regexp (org-all-targets 'radio)))
5893 (org-restart-font-lock)))
5895 (defun org-hide-wide-columns (limit)
5896 (let (s e)
5897 (setq s (text-property-any (point) (or limit (point-max))
5898 'org-cwidth t))
5899 (when s
5900 (setq e (next-single-property-change s 'org-cwidth))
5901 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5902 (goto-char e)
5903 t)))
5905 (defvar org-latex-and-related-regexp nil
5906 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5907 (defvar org-match-substring-regexp)
5908 (defvar org-match-substring-with-braces-regexp)
5910 (defun org-compute-latex-and-related-regexp ()
5911 "Compute regular expression for LaTeX, entities and sub/superscript.
5912 Result depends on variable `org-highlight-latex-and-related'."
5913 (org-set-local
5914 'org-latex-and-related-regexp
5915 (let* ((re-sub
5916 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5917 ((eq org-use-sub-superscripts '{})
5918 (list org-match-substring-with-braces-regexp))
5919 (org-use-sub-superscripts (list org-match-substring-regexp))))
5920 (re-latex
5921 (when (memq 'latex org-highlight-latex-and-related)
5922 (let ((matchers (plist-get org-format-latex-options :matchers)))
5923 (delq nil
5924 (mapcar (lambda (x)
5925 (and (member (car x) matchers) (nth 1 x)))
5926 org-latex-regexps)))))
5927 (re-entities
5928 (when (memq 'entities org-highlight-latex-and-related)
5929 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5930 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
5932 (defun org-do-latex-and-related (limit)
5933 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5934 LIMIT bounds the search for syntax to highlight. Stop at first
5935 highlighted object, if any. Return t if some highlighting was
5936 done, nil otherwise."
5937 (when (org-string-nw-p org-latex-and-related-regexp)
5938 (catch 'found
5939 (while (re-search-forward org-latex-and-related-regexp limit t)
5940 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
5941 'face))
5942 '(org-code org-verbatim underline))
5943 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
5944 '(?_ ?^))
5946 0)))
5947 (font-lock-prepend-text-property
5948 (+ offset (match-beginning 0)) (match-end 0)
5949 'face 'org-latex-and-related)
5950 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
5951 '(font-lock-multiline t)))
5952 (throw 'found t)))
5953 nil)))
5955 (defun org-restart-font-lock ()
5956 "Restart `font-lock-mode', to force refontification."
5957 (when (and (boundp 'font-lock-mode) font-lock-mode)
5958 (font-lock-mode -1)
5959 (font-lock-mode 1)))
5961 (defun org-all-targets (&optional radio)
5962 "Return a list of all targets in this file.
5963 When optional argument RADIO is non-nil, only find radio
5964 targets."
5965 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5966 (save-excursion
5967 (goto-char (point-min))
5968 (while (re-search-forward re nil t)
5969 ;; Make sure point is really within the object.
5970 (backward-char)
5971 (let ((obj (org-element-context)))
5972 (when (memq (org-element-type obj) '(radio-target target))
5973 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5974 rtn)))
5976 (defun org-make-target-link-regexp (targets)
5977 "Make regular expression matching all strings in TARGETS.
5978 The regular expression finds the targets also if there is a line break
5979 between words."
5980 (and targets
5981 (concat
5982 "\\<\\("
5983 (mapconcat
5984 (lambda (x)
5985 (setq x (regexp-quote x))
5986 (while (string-match " +" x)
5987 (setq x (replace-match "\\s-+" t t x)))
5989 targets
5990 "\\|")
5991 "\\)\\>")))
5993 (defun org-activate-tags (limit)
5994 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5995 (progn
5996 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5997 (add-text-properties (match-beginning 1) (match-end 1)
5998 (list 'mouse-face 'highlight
5999 'keymap org-mouse-map))
6000 (org-rear-nonsticky-at (match-end 1))
6001 t)))
6003 (defun org-outline-level ()
6004 "Compute the outline level of the heading at point.
6005 If this is called at a normal headline, the level is the number of stars.
6006 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6007 (save-excursion
6008 (if (not (condition-case nil
6009 (org-back-to-heading t)
6010 (error nil)))
6012 (looking-at org-outline-regexp)
6013 (1- (- (match-end 0) (match-beginning 0))))))
6015 (defvar org-font-lock-keywords nil)
6017 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6018 "Regular expression matching a property line.")
6020 (defvar org-font-lock-hook nil
6021 "Functions to be called for special font lock stuff.")
6023 (defvar org-font-lock-set-keywords-hook nil
6024 "Functions that can manipulate `org-font-lock-extra-keywords'.
6025 This is called after `org-font-lock-extra-keywords' is defined, but before
6026 it is installed to be used by font lock. This can be useful if something
6027 needs to be inserted at a specific position in the font-lock sequence.")
6029 (defun org-font-lock-hook (limit)
6030 "Run `org-font-lock-hook' within LIMIT."
6031 (run-hook-with-args 'org-font-lock-hook limit))
6033 (defun org-set-font-lock-defaults ()
6034 "Set font lock defaults for the current buffer."
6035 (let* ((em org-fontify-emphasized-text)
6036 (lk org-activate-links)
6037 (org-font-lock-extra-keywords
6038 (list
6039 ;; Call the hook
6040 '(org-font-lock-hook)
6041 ;; Headlines
6042 `(,(if org-fontify-whole-heading-line
6043 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6044 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6045 (1 (org-get-level-face 1))
6046 (2 (org-get-level-face 2))
6047 (3 (org-get-level-face 3)))
6048 ;; Table lines
6049 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6050 (1 'org-table t))
6051 ;; Table internals
6052 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6053 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6054 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6055 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6056 ;; Drawers
6057 (list org-drawer-regexp '(0 'org-special-keyword t))
6058 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6059 ;; Properties
6060 (list org-property-re
6061 '(1 'org-special-keyword t)
6062 '(3 'org-property-value t))
6063 ;; Links
6064 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6065 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6066 (if (memq 'plain lk) '(org-activate-plain-links))
6067 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6068 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6069 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6070 (if (memq 'footnote lk) '(org-activate-footnote-links))
6071 ;; Targets.
6072 (list org-any-target-regexp '(0 'org-target t))
6073 ;; Diary sexps.
6074 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6075 '(org-hide-wide-columns (0 nil append))
6076 ;; TODO keyword
6077 (list (format org-heading-keyword-regexp-format
6078 org-todo-regexp)
6079 '(2 (org-get-todo-face 2) t))
6080 ;; DONE
6081 (if org-fontify-done-headline
6082 (list (format org-heading-keyword-regexp-format
6083 (concat
6084 "\\(?:"
6085 (mapconcat 'regexp-quote org-done-keywords "\\|")
6086 "\\)"))
6087 '(2 'org-headline-done t))
6088 nil)
6089 ;; Priorities
6090 '(org-font-lock-add-priority-faces)
6091 ;; Tags
6092 '(org-font-lock-add-tag-faces)
6093 ;; Special keywords
6094 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6095 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6096 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6097 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6098 ;; Emphasis
6099 (if em
6100 (if (featurep 'xemacs)
6101 '(org-do-emphasis-faces (0 nil append))
6102 '(org-do-emphasis-faces)))
6103 ;; Checkboxes
6104 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6105 1 'org-checkbox prepend)
6106 (if (cdr (assq 'checkbox org-list-automatic-rules))
6107 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6108 (0 (org-get-checkbox-statistics-face) t)))
6109 ;; Description list items
6110 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6111 1 'org-list-dt prepend)
6112 ;; ARCHIVEd headings
6113 (list (concat
6114 org-outline-regexp-bol
6115 "\\(.*:" org-archive-tag ":.*\\)")
6116 '(1 'org-archived prepend))
6117 ;; Specials
6118 '(org-do-latex-and-related)
6119 '(org-fontify-entities)
6120 '(org-raise-scripts)
6121 ;; Code
6122 '(org-activate-code (1 'org-code t))
6123 ;; COMMENT
6124 (list (format org-heading-keyword-regexp-format
6125 (concat "\\("
6126 org-comment-string "\\|" org-quote-string
6127 "\\)"))
6128 '(2 'org-special-keyword t))
6129 ;; Blocks and meta lines
6130 '(org-fontify-meta-lines-and-blocks)
6132 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6133 (run-hooks 'org-font-lock-set-keywords-hook)
6134 ;; Now set the full font-lock-keywords
6135 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6136 (org-set-local 'font-lock-defaults
6137 '(org-font-lock-keywords t nil nil backward-paragraph))
6138 (kill-local-variable 'font-lock-keywords) nil))
6140 (defun org-toggle-pretty-entities ()
6141 "Toggle the composition display of entities as UTF8 characters."
6142 (interactive)
6143 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6144 (org-restart-font-lock)
6145 (if org-pretty-entities
6146 (message "Entities are displayed as UTF8 characters")
6147 (save-restriction
6148 (widen)
6149 (org-decompose-region (point-min) (point-max))
6150 (message "Entities are displayed plain"))))
6152 (defvar org-custom-properties-overlays nil
6153 "List of overlays used for custom properties.")
6154 (make-variable-buffer-local 'org-custom-properties-overlays)
6156 (defun org-toggle-custom-properties-visibility ()
6157 "Display or hide properties in `org-custom-properties'."
6158 (interactive)
6159 (if org-custom-properties-overlays
6160 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6161 (setq org-custom-properties-overlays nil))
6162 (unless (not org-custom-properties)
6163 (save-excursion
6164 (save-restriction
6165 (widen)
6166 (goto-char (point-min))
6167 (while (re-search-forward org-property-re nil t)
6168 (mapc (lambda(p)
6169 (when (equal p (substring (match-string 1) 1 -1))
6170 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6171 (overlay-put o 'invisible t)
6172 (overlay-put o 'org-custom-property t)
6173 (push o org-custom-properties-overlays))))
6174 org-custom-properties)))))))
6176 (defun org-fontify-entities (limit)
6177 "Find an entity to fontify."
6178 (let (ee)
6179 (when org-pretty-entities
6180 (catch 'match
6181 (while (re-search-forward
6182 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6183 limit t)
6184 (if (and (not (org-in-indented-comment-line))
6185 (setq ee (org-entity-get (match-string 1)))
6186 (= (length (nth 6 ee)) 1))
6187 (let*
6188 ((end (if (equal (match-string 2) "{}")
6189 (match-end 2)
6190 (match-end 1))))
6191 (add-text-properties
6192 (match-beginning 0) end
6193 (list 'font-lock-fontified t))
6194 (compose-region (match-beginning 0) end
6195 (nth 6 ee) nil)
6196 (backward-char 1)
6197 (throw 'match t))))
6198 nil))))
6200 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6201 "Fontify string S like in Org-mode."
6202 (with-temp-buffer
6203 (insert s)
6204 (let ((org-odd-levels-only odd-levels))
6205 (org-mode)
6206 (font-lock-fontify-buffer)
6207 (buffer-string))))
6209 (defvar org-m nil)
6210 (defvar org-l nil)
6211 (defvar org-f nil)
6212 (defun org-get-level-face (n)
6213 "Get the right face for match N in font-lock matching of headlines."
6214 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6215 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6216 (if org-cycle-level-faces
6217 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6218 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6219 (cond
6220 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6221 ((eq n 2) org-f)
6222 (t (if org-level-color-stars-only nil org-f))))
6225 (defun org-get-todo-face (kwd)
6226 "Get the right face for a TODO keyword KWD.
6227 If KWD is a number, get the corresponding match group."
6228 (if (numberp kwd) (setq kwd (match-string kwd)))
6229 (or (org-face-from-face-or-color
6230 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6231 (and (member kwd org-done-keywords) 'org-done)
6232 'org-todo))
6234 (defun org-face-from-face-or-color (context inherit face-or-color)
6235 "Create a face list that inherits INHERIT, but sets the foreground color.
6236 When FACE-OR-COLOR is not a string, just return it."
6237 (if (stringp face-or-color)
6238 (list :inherit inherit
6239 (cdr (assoc context org-faces-easy-properties))
6240 face-or-color)
6241 face-or-color))
6243 (defun org-font-lock-add-tag-faces (limit)
6244 "Add the special tag faces."
6245 (when (and org-tag-faces org-tags-special-faces-re)
6246 (while (re-search-forward org-tags-special-faces-re limit t)
6247 (add-text-properties (match-beginning 1) (match-end 1)
6248 (list 'face (org-get-tag-face 1)
6249 'font-lock-fontified t))
6250 (backward-char 1))))
6252 (defun org-font-lock-add-priority-faces (limit)
6253 "Add the special priority faces."
6254 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6255 (when (save-match-data (org-at-heading-p))
6256 (add-text-properties
6257 (match-beginning 0) (match-end 0)
6258 (list 'face (or (org-face-from-face-or-color
6259 'priority 'org-priority
6260 (cdr (assoc (char-after (match-beginning 1))
6261 org-priority-faces)))
6262 'org-priority)
6263 'font-lock-fontified t)))))
6265 (defun org-get-tag-face (kwd)
6266 "Get the right face for a TODO keyword KWD.
6267 If KWD is a number, get the corresponding match group."
6268 (if (numberp kwd) (setq kwd (match-string kwd)))
6269 (or (org-face-from-face-or-color
6270 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6271 'org-tag))
6273 (defun org-unfontify-region (beg end &optional maybe_loudly)
6274 "Remove fontification and activation overlays from links."
6275 (font-lock-default-unfontify-region beg end)
6276 (let* ((buffer-undo-list t)
6277 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6278 (inhibit-modification-hooks t)
6279 deactivate-mark buffer-file-name buffer-file-truename)
6280 (org-decompose-region beg end)
6281 (remove-text-properties beg end
6282 '(mouse-face t keymap t org-linked-text t
6283 invisible t intangible t
6284 org-no-flyspell t org-emphasis t))
6285 (org-remove-font-lock-display-properties beg end)))
6287 (defconst org-script-display '(((raise -0.3) (height 0.7))
6288 ((raise 0.3) (height 0.7))
6289 ((raise -0.5))
6290 ((raise 0.5)))
6291 "Display properties for showing superscripts and subscripts.")
6293 (defun org-remove-font-lock-display-properties (beg end)
6294 "Remove specific display properties that have been added by font lock.
6295 The will remove the raise properties that are used to show superscripts
6296 and subscripts."
6297 (let (next prop)
6298 (while (< beg end)
6299 (setq next (next-single-property-change beg 'display nil end)
6300 prop (get-text-property beg 'display))
6301 (if (member prop org-script-display)
6302 (put-text-property beg next 'display nil))
6303 (setq beg next))))
6305 (defun org-raise-scripts (limit)
6306 "Add raise properties to sub/superscripts."
6307 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6308 (if (re-search-forward
6309 (if (eq org-use-sub-superscripts t)
6310 org-match-substring-regexp
6311 org-match-substring-with-braces-regexp)
6312 limit t)
6313 (let* ((pos (point)) table-p comment-p
6314 (mpos (match-beginning 3))
6315 (emph-p (get-text-property mpos 'org-emphasis))
6316 (link-p (get-text-property mpos 'mouse-face))
6317 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6318 (goto-char (point-at-bol))
6319 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6320 comment-p (org-looking-at-p "[ \t]*#"))
6321 (goto-char pos)
6322 ;; FIXME: Should we go back one character here, for a_b^c
6323 ;; (goto-char (1- pos)) ;????????????????????
6324 (if (or comment-p emph-p link-p keyw-p)
6326 (put-text-property (match-beginning 3) (match-end 0)
6327 'display
6328 (if (equal (char-after (match-beginning 2)) ?^)
6329 (nth (if table-p 3 1) org-script-display)
6330 (nth (if table-p 2 0) org-script-display)))
6331 (add-text-properties (match-beginning 2) (match-end 2)
6332 (list 'invisible t
6333 'org-dwidth t 'org-dwidth-n 1))
6334 (if (and (eq (char-after (match-beginning 3)) ?{)
6335 (eq (char-before (match-end 3)) ?}))
6336 (progn
6337 (add-text-properties
6338 (match-beginning 3) (1+ (match-beginning 3))
6339 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6340 (add-text-properties
6341 (1- (match-end 3)) (match-end 3)
6342 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6343 t)))))
6345 ;;;; Visibility cycling, including org-goto and indirect buffer
6347 ;;; Cycling
6349 (defvar org-cycle-global-status nil)
6350 (make-variable-buffer-local 'org-cycle-global-status)
6351 (put 'org-cycle-global-status 'org-state t)
6352 (defvar org-cycle-subtree-status nil)
6353 (make-variable-buffer-local 'org-cycle-subtree-status)
6354 (put 'org-cycle-subtree-status 'org-state t)
6356 (defvar org-inlinetask-min-level)
6358 ;;;###autoload
6359 (defun org-cycle (&optional arg)
6360 "TAB-action and visibility cycling for Org-mode.
6362 This is the command invoked in Org-mode by the TAB key. Its main purpose
6363 is outline visibility cycling, but it also invokes other actions
6364 in special contexts.
6366 - When this function is called with a prefix argument, rotate the entire
6367 buffer through 3 states (global cycling)
6368 1. OVERVIEW: Show only top-level headlines.
6369 2. CONTENTS: Show all headlines of all levels, but no body text.
6370 3. SHOW ALL: Show everything.
6371 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6372 determined by the variable `org-startup-folded', and by any VISIBILITY
6373 properties in the buffer.
6374 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6375 including any drawers.
6377 - When inside a table, re-align the table and move to the next field.
6379 - When point is at the beginning of a headline, rotate the subtree started
6380 by this line through 3 different states (local cycling)
6381 1. FOLDED: Only the main headline is shown.
6382 2. CHILDREN: The main headline and the direct children are shown.
6383 From this state, you can move to one of the children
6384 and zoom in further.
6385 3. SUBTREE: Show the entire subtree, including body text.
6386 If there is no subtree, switch directly from CHILDREN to FOLDED.
6388 - When point is at the beginning of an empty headline and the variable
6389 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6390 of the headline by demoting and promoting it to likely levels. This
6391 speeds up creation document structure by pressing TAB once or several
6392 times right after creating a new headline.
6394 - When there is a numeric prefix, go up to a heading with level ARG, do
6395 a `show-subtree' and return to the previous cursor position. If ARG
6396 is negative, go up that many levels.
6398 - When point is not at the beginning of a headline, execute the global
6399 binding for TAB, which is re-indenting the line. See the option
6400 `org-cycle-emulate-tab' for details.
6402 - Special case: if point is at the beginning of the buffer and there is
6403 no headline in line 1, this function will act as if called with prefix arg
6404 (C-u TAB, same as S-TAB) also when called without prefix arg.
6405 But only if also the variable `org-cycle-global-at-bob' is t."
6406 (interactive "P")
6407 (org-load-modules-maybe)
6408 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6409 (and org-cycle-level-after-item/entry-creation
6410 (or (org-cycle-level)
6411 (org-cycle-item-indentation))))
6412 (let* (message-log-max ; Don't populate the *Messages* buffer
6413 (limit-level
6414 (or org-cycle-max-level
6415 (and (boundp 'org-inlinetask-min-level)
6416 org-inlinetask-min-level
6417 (1- org-inlinetask-min-level))))
6418 (nstars (and limit-level
6419 (if org-odd-levels-only
6420 (and limit-level (1- (* limit-level 2)))
6421 limit-level)))
6422 (org-outline-regexp
6423 (if (not (derived-mode-p 'org-mode))
6424 outline-regexp
6425 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6426 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6427 (not (looking-at org-outline-regexp))))
6428 (org-cycle-hook
6429 (if bob-special
6430 (delq 'org-optimize-window-after-visibility-change
6431 (copy-sequence org-cycle-hook))
6432 org-cycle-hook))
6433 (pos (point)))
6435 (if (or bob-special (equal arg '(4)))
6436 ;; special case: use global cycling
6437 (setq arg t))
6439 (cond
6441 ((equal arg '(16))
6442 (setq last-command 'dummy)
6443 (org-set-startup-visibility)
6444 (message "Startup visibility, plus VISIBILITY properties"))
6446 ((equal arg '(64))
6447 (show-all)
6448 (message "Entire buffer visible, including drawers"))
6450 ;; Table: enter it or move to the next field.
6451 ((org-at-table-p 'any)
6452 (if (org-at-table.el-p)
6453 (message "Use C-c ' to edit table.el tables")
6454 (if arg (org-table-edit-field t)
6455 (org-table-justify-field-maybe)
6456 (call-interactively 'org-table-next-field))))
6458 ((run-hook-with-args-until-success
6459 'org-tab-after-check-for-table-hook))
6461 ;; Global cycling: delegate to `org-cycle-internal-global'.
6462 ((eq arg t) (org-cycle-internal-global))
6464 ;; Drawers: delegate to `org-flag-drawer'.
6465 ((and org-drawers org-drawer-regexp
6466 (save-excursion
6467 (beginning-of-line 1)
6468 (looking-at org-drawer-regexp)))
6469 (org-flag-drawer ; toggle block visibility
6470 (not (get-char-property (match-end 0) 'invisible))))
6472 ;; Show-subtree, ARG levels up from here.
6473 ((integerp arg)
6474 (save-excursion
6475 (org-back-to-heading)
6476 (outline-up-heading (if (< arg 0) (- arg)
6477 (- (funcall outline-level) arg)))
6478 (org-show-subtree)))
6480 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6481 ((and (featurep 'org-inlinetask)
6482 (org-inlinetask-at-task-p)
6483 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6484 (org-inlinetask-toggle-visibility))
6486 ((org-try-cdlatex-tab))
6488 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6489 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6490 (save-excursion (beginning-of-line 1)
6491 (looking-at org-outline-regexp)))
6492 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6493 (org-cycle-internal-local))
6495 ;; From there: TAB emulation and template completion.
6496 (buffer-read-only (org-back-to-heading))
6498 ((run-hook-with-args-until-success
6499 'org-tab-after-check-for-cycling-hook))
6501 ((org-try-structure-completion))
6503 ((run-hook-with-args-until-success
6504 'org-tab-before-tab-emulation-hook))
6506 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6507 (or (not (bolp))
6508 (not (looking-at org-outline-regexp))))
6509 (call-interactively (global-key-binding "\t")))
6511 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6512 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6513 (or (and (eq org-cycle-emulate-tab 'white)
6514 (= (match-end 0) (point-at-eol)))
6515 (and (eq org-cycle-emulate-tab 'whitestart)
6516 (>= (match-end 0) pos))))
6518 (eq org-cycle-emulate-tab t))
6519 (call-interactively (global-key-binding "\t")))
6521 (t (save-excursion
6522 (org-back-to-heading)
6523 (org-cycle)))))))
6525 (defun org-cycle-internal-global ()
6526 "Do the global cycling action."
6527 ;; Hack to avoid display of messages for .org attachments in Gnus
6528 (let (message-log-max ; Don't populate the *Messages* buffer
6529 (ga (string-match "\\*fontification" (buffer-name))))
6530 (cond
6531 ((and (eq last-command this-command)
6532 (eq org-cycle-global-status 'overview))
6533 ;; We just created the overview - now do table of contents
6534 ;; This can be slow in very large buffers, so indicate action
6535 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6536 (unless ga (message "CONTENTS..."))
6537 (org-content)
6538 (unless ga (message "CONTENTS...done"))
6539 (setq org-cycle-global-status 'contents)
6540 (run-hook-with-args 'org-cycle-hook 'contents))
6542 ((and (eq last-command this-command)
6543 (eq org-cycle-global-status 'contents))
6544 ;; We just showed the table of contents - now show everything
6545 (run-hook-with-args 'org-pre-cycle-hook 'all)
6546 (show-all)
6547 (unless ga (message "SHOW ALL"))
6548 (setq org-cycle-global-status 'all)
6549 (run-hook-with-args 'org-cycle-hook 'all))
6552 ;; Default action: go to overview
6553 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6554 (org-overview)
6555 (unless ga (message "OVERVIEW"))
6556 (setq org-cycle-global-status 'overview)
6557 (run-hook-with-args 'org-cycle-hook 'overview)))))
6559 (defun org-cycle-internal-local ()
6560 "Do the local cycling action."
6561 (let (message-log-max ; Don't populate the *Messages* buffer
6562 (goal-column 0) eoh eol eos has-children children-skipped struct)
6563 ;; First, determine end of headline (EOH), end of subtree or item
6564 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6565 (save-excursion
6566 (if (org-at-item-p)
6567 (progn
6568 (beginning-of-line)
6569 (setq struct (org-list-struct))
6570 (setq eoh (point-at-eol))
6571 (setq eos (org-list-get-item-end-before-blank (point) struct))
6572 (setq has-children (org-list-has-child-p (point) struct)))
6573 (org-back-to-heading)
6574 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6575 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6576 (setq has-children
6577 (or (save-excursion
6578 (let ((level (funcall outline-level)))
6579 (outline-next-heading)
6580 (and (org-at-heading-p t)
6581 (> (funcall outline-level) level))))
6582 (save-excursion
6583 (org-list-search-forward (org-item-beginning-re) eos t)))))
6584 ;; Determine end invisible part of buffer (EOL)
6585 (beginning-of-line 2)
6586 ;; XEmacs doesn't have `next-single-char-property-change'
6587 (if (featurep 'xemacs)
6588 (while (and (not (eobp)) ;; this is like `next-line'
6589 (get-char-property (1- (point)) 'invisible))
6590 (beginning-of-line 2))
6591 (while (and (not (eobp)) ;; this is like `next-line'
6592 (get-char-property (1- (point)) 'invisible))
6593 (goto-char (next-single-char-property-change (point) 'invisible))
6594 (and (eolp) (beginning-of-line 2))))
6595 (setq eol (point)))
6596 ;; Find out what to do next and set `this-command'
6597 (cond
6598 ((= eos eoh)
6599 ;; Nothing is hidden behind this heading
6600 (unless (org-before-first-heading-p)
6601 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6602 (message "EMPTY ENTRY")
6603 (setq org-cycle-subtree-status nil)
6604 (save-excursion
6605 (goto-char eos)
6606 (outline-next-heading)
6607 (if (outline-invisible-p) (org-flag-heading nil))))
6608 ((and (or (>= eol eos)
6609 (not (string-match "\\S-" (buffer-substring eol eos))))
6610 (or has-children
6611 (not (setq children-skipped
6612 org-cycle-skip-children-state-if-no-children))))
6613 ;; Entire subtree is hidden in one line: children view
6614 (unless (org-before-first-heading-p)
6615 (run-hook-with-args 'org-pre-cycle-hook 'children))
6616 (if (org-at-item-p)
6617 (org-list-set-item-visibility (point-at-bol) struct 'children)
6618 (org-show-entry)
6619 (org-with-limited-levels (show-children))
6620 ;; FIXME: This slows down the func way too much.
6621 ;; How keep drawers hidden in subtree anyway?
6622 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6623 ;; (org-cycle-hide-drawers 'subtree))
6625 ;; Fold every list in subtree to top-level items.
6626 (when (eq org-cycle-include-plain-lists 'integrate)
6627 (save-excursion
6628 (org-back-to-heading)
6629 (while (org-list-search-forward (org-item-beginning-re) eos t)
6630 (beginning-of-line 1)
6631 (let* ((struct (org-list-struct))
6632 (prevs (org-list-prevs-alist struct))
6633 (end (org-list-get-bottom-point struct)))
6634 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6635 (org-list-get-all-items (point) struct prevs))
6636 (goto-char end))))))
6637 (message "CHILDREN")
6638 (save-excursion
6639 (goto-char eos)
6640 (outline-next-heading)
6641 (if (outline-invisible-p) (org-flag-heading nil)))
6642 (setq org-cycle-subtree-status 'children)
6643 (unless (org-before-first-heading-p)
6644 (run-hook-with-args 'org-cycle-hook 'children)))
6645 ((or children-skipped
6646 (and (eq last-command this-command)
6647 (eq org-cycle-subtree-status 'children)))
6648 ;; We just showed the children, or no children are there,
6649 ;; now show everything.
6650 (unless (org-before-first-heading-p)
6651 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6652 (outline-flag-region eoh eos nil)
6653 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6654 (setq org-cycle-subtree-status 'subtree)
6655 (unless (org-before-first-heading-p)
6656 (run-hook-with-args 'org-cycle-hook 'subtree)))
6658 ;; Default action: hide the subtree.
6659 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6660 (outline-flag-region eoh eos t)
6661 (message "FOLDED")
6662 (setq org-cycle-subtree-status 'folded)
6663 (unless (org-before-first-heading-p)
6664 (run-hook-with-args 'org-cycle-hook 'folded))))))
6666 ;;;###autoload
6667 (defun org-global-cycle (&optional arg)
6668 "Cycle the global visibility. For details see `org-cycle'.
6669 With \\[universal-argument] prefix arg, switch to startup visibility.
6670 With a numeric prefix, show all headlines up to that level."
6671 (interactive "P")
6672 (let ((org-cycle-include-plain-lists
6673 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6674 (cond
6675 ((integerp arg)
6676 (show-all)
6677 (hide-sublevels arg)
6678 (setq org-cycle-global-status 'contents))
6679 ((equal arg '(4))
6680 (org-set-startup-visibility)
6681 (message "Startup visibility, plus VISIBILITY properties."))
6683 (org-cycle '(4))))))
6685 (defun org-set-startup-visibility ()
6686 "Set the visibility required by startup options and properties."
6687 (cond
6688 ((eq org-startup-folded t)
6689 (org-cycle '(4)))
6690 ((eq org-startup-folded 'content)
6691 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6692 (org-cycle '(4)) (org-cycle '(4)))))
6693 (unless (eq org-startup-folded 'showeverything)
6694 (if org-hide-block-startup (org-hide-block-all))
6695 (org-set-visibility-according-to-property 'no-cleanup)
6696 (org-cycle-hide-archived-subtrees 'all)
6697 (org-cycle-hide-drawers 'all)
6698 (org-cycle-show-empty-lines t)))
6700 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6701 "Switch subtree visibilities according to :VISIBILITY: property."
6702 (interactive)
6703 (let (org-show-entry-below state)
6704 (save-excursion
6705 (goto-char (point-min))
6706 (while (re-search-forward
6707 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6708 nil t)
6709 (setq state (match-string 1))
6710 (save-excursion
6711 (org-back-to-heading t)
6712 (hide-subtree)
6713 (org-reveal)
6714 (cond
6715 ((equal state '("fold" "folded"))
6716 (hide-subtree))
6717 ((equal state "children")
6718 (org-show-hidden-entry)
6719 (show-children))
6720 ((equal state "content")
6721 (save-excursion
6722 (save-restriction
6723 (org-narrow-to-subtree)
6724 (org-content))))
6725 ((member state '("all" "showall"))
6726 (show-subtree)))))
6727 (unless no-cleanup
6728 (org-cycle-hide-archived-subtrees 'all)
6729 (org-cycle-hide-drawers 'all)
6730 (org-cycle-show-empty-lines 'all)))))
6732 ;; This function uses outline-regexp instead of the more fundamental
6733 ;; org-outline-regexp so that org-cycle-global works outside of Org
6734 ;; buffers, where outline-regexp is needed.
6735 (defun org-overview ()
6736 "Switch to overview mode, showing only top-level headlines.
6737 Really, this shows all headlines with level equal or greater than the level
6738 of the first headline in the buffer. This is important, because if the
6739 first headline is not level one, then (hide-sublevels 1) gives confusing
6740 results."
6741 (interactive)
6742 (let ((l (org-current-line))
6743 (level (save-excursion
6744 (goto-char (point-min))
6745 (if (re-search-forward (concat "^" outline-regexp) nil t)
6746 (progn
6747 (goto-char (match-beginning 0))
6748 (funcall outline-level))))))
6749 (and level (hide-sublevels level))
6750 (recenter '(4))
6751 (org-goto-line l)))
6753 (defun org-content (&optional arg)
6754 "Show all headlines in the buffer, like a table of contents.
6755 With numerical argument N, show content up to level N."
6756 (interactive "P")
6757 (save-excursion
6758 ;; Visit all headings and show their offspring
6759 (and (integerp arg) (org-overview))
6760 (goto-char (point-max))
6761 (catch 'exit
6762 (while (and (progn (condition-case nil
6763 (outline-previous-visible-heading 1)
6764 (error (goto-char (point-min))))
6766 (looking-at org-outline-regexp))
6767 (if (integerp arg)
6768 (show-children (1- arg))
6769 (show-branches))
6770 (if (bobp) (throw 'exit nil))))))
6773 (defun org-optimize-window-after-visibility-change (state)
6774 "Adjust the window after a change in outline visibility.
6775 This function is the default value of the hook `org-cycle-hook'."
6776 (when (get-buffer-window (current-buffer))
6777 (cond
6778 ((eq state 'content) nil)
6779 ((eq state 'all) nil)
6780 ((eq state 'folded) nil)
6781 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6782 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6784 (defun org-remove-empty-overlays-at (pos)
6785 "Remove outline overlays that do not contain non-white stuff."
6786 (mapc
6787 (lambda (o)
6788 (and (eq 'outline (overlay-get o 'invisible))
6789 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6790 (overlay-end o))))
6791 (delete-overlay o)))
6792 (overlays-at pos)))
6794 (defun org-clean-visibility-after-subtree-move ()
6795 "Fix visibility issues after moving a subtree."
6796 ;; First, find a reasonable region to look at:
6797 ;; Start two siblings above, end three below
6798 (let* ((beg (save-excursion
6799 (and (org-get-last-sibling)
6800 (org-get-last-sibling))
6801 (point)))
6802 (end (save-excursion
6803 (and (org-get-next-sibling)
6804 (org-get-next-sibling)
6805 (org-get-next-sibling))
6806 (if (org-at-heading-p)
6807 (point-at-eol)
6808 (point))))
6809 (level (looking-at "\\*+"))
6810 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6811 (save-excursion
6812 (save-restriction
6813 (narrow-to-region beg end)
6814 (when re
6815 ;; Properly fold already folded siblings
6816 (goto-char (point-min))
6817 (while (re-search-forward re nil t)
6818 (if (and (not (outline-invisible-p))
6819 (save-excursion
6820 (goto-char (point-at-eol)) (outline-invisible-p)))
6821 (hide-entry))))
6822 (org-cycle-show-empty-lines 'overview)
6823 (org-cycle-hide-drawers 'overview)))))
6825 (defun org-cycle-show-empty-lines (state)
6826 "Show empty lines above all visible headlines.
6827 The region to be covered depends on STATE when called through
6828 `org-cycle-hook'. Lisp program can use t for STATE to get the
6829 entire buffer covered. Note that an empty line is only shown if there
6830 are at least `org-cycle-separator-lines' empty lines before the headline."
6831 (when (not (= org-cycle-separator-lines 0))
6832 (save-excursion
6833 (let* ((n (abs org-cycle-separator-lines))
6834 (re (cond
6835 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6836 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6837 (t (let ((ns (number-to-string (- n 2))))
6838 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6839 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6840 beg end b e)
6841 (cond
6842 ((memq state '(overview contents t))
6843 (setq beg (point-min) end (point-max)))
6844 ((memq state '(children folded))
6845 (setq beg (point) end (progn (org-end-of-subtree t t)
6846 (beginning-of-line 2)
6847 (point)))))
6848 (when beg
6849 (goto-char beg)
6850 (while (re-search-forward re end t)
6851 (unless (get-char-property (match-end 1) 'invisible)
6852 (setq e (match-end 1))
6853 (if (< org-cycle-separator-lines 0)
6854 (setq b (save-excursion
6855 (goto-char (match-beginning 0))
6856 (org-back-over-empty-lines)
6857 (if (save-excursion
6858 (goto-char (max (point-min) (1- (point))))
6859 (org-at-heading-p))
6860 (1- (point))
6861 (point))))
6862 (setq b (match-beginning 1)))
6863 (outline-flag-region b e nil)))))))
6864 ;; Never hide empty lines at the end of the file.
6865 (save-excursion
6866 (goto-char (point-max))
6867 (outline-previous-heading)
6868 (outline-end-of-heading)
6869 (if (and (looking-at "[ \t\n]+")
6870 (= (match-end 0) (point-max)))
6871 (outline-flag-region (point) (match-end 0) nil))))
6873 (defun org-show-empty-lines-in-parent ()
6874 "Move to the parent and re-show empty lines before visible headlines."
6875 (save-excursion
6876 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6877 (org-cycle-show-empty-lines context))))
6879 (defun org-files-list ()
6880 "Return `org-agenda-files' list, plus all open org-mode files.
6881 This is useful for operations that need to scan all of a user's
6882 open and agenda-wise Org files."
6883 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6884 (dolist (buf (buffer-list))
6885 (with-current-buffer buf
6886 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6887 (let ((file (expand-file-name (buffer-file-name))))
6888 (unless (member file files)
6889 (push file files))))))
6890 files))
6892 (defsubst org-entry-beginning-position ()
6893 "Return the beginning position of the current entry."
6894 (save-excursion (outline-back-to-heading t) (point)))
6896 (defsubst org-entry-end-position ()
6897 "Return the end position of the current entry."
6898 (save-excursion (outline-next-heading) (point)))
6900 (defun org-cycle-hide-drawers (state)
6901 "Re-hide all drawers after a visibility state change."
6902 (when (and (derived-mode-p 'org-mode)
6903 (not (memq state '(overview folded contents))))
6904 (save-excursion
6905 (let* ((globalp (memq state '(contents all)))
6906 (beg (if globalp (point-min) (point)))
6907 (end (if globalp (point-max)
6908 (if (eq state 'children)
6909 (save-excursion (outline-next-heading) (point))
6910 (org-end-of-subtree t)))))
6911 (goto-char beg)
6912 (while (re-search-forward org-drawer-regexp end t)
6913 (org-flag-drawer t))))))
6915 (defun org-cycle-hide-inline-tasks (state)
6916 "Re-hide inline task when switching to 'contents visibility state."
6917 (when (and (eq state 'contents)
6918 (boundp 'org-inlinetask-min-level)
6919 org-inlinetask-min-level)
6920 (hide-sublevels (1- org-inlinetask-min-level))))
6922 (defun org-flag-drawer (flag)
6923 "When FLAG is non-nil, hide the drawer we are within.
6924 Otherwise make it visible."
6925 (save-excursion
6926 (beginning-of-line 1)
6927 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6928 (let ((b (match-end 0)))
6929 (if (re-search-forward
6930 "^[ \t]*:END:"
6931 (save-excursion (outline-next-heading) (point)) t)
6932 (outline-flag-region b (point-at-eol) flag)
6933 (error ":END: line missing at position %s" b))))))
6935 (defun org-subtree-end-visible-p ()
6936 "Is the end of the current subtree visible?"
6937 (pos-visible-in-window-p
6938 (save-excursion (org-end-of-subtree t) (point))))
6940 (defun org-first-headline-recenter (&optional N)
6941 "Move cursor to the first headline and recenter the headline.
6942 Optional argument N means put the headline into the Nth line of the window."
6943 (goto-char (point-min))
6944 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6945 (beginning-of-line)
6946 (recenter (prefix-numeric-value N))))
6948 ;;; Saving and restoring visibility
6950 (defun org-outline-overlay-data (&optional use-markers)
6951 "Return a list of the locations of all outline overlays.
6952 These are overlays with the `invisible' property value `outline'.
6953 The return value is a list of cons cells, with start and stop
6954 positions for each overlay.
6955 If USE-MARKERS is set, return the positions as markers."
6956 (let (beg end)
6957 (save-excursion
6958 (save-restriction
6959 (widen)
6960 (delq nil
6961 (mapcar (lambda (o)
6962 (when (eq (overlay-get o 'invisible) 'outline)
6963 (setq beg (overlay-start o)
6964 end (overlay-end o))
6965 (and beg end (> end beg)
6966 (if use-markers
6967 (cons (move-marker (make-marker) beg)
6968 (move-marker (make-marker) end))
6969 (cons beg end)))))
6970 (overlays-in (point-min) (point-max))))))))
6972 (defun org-set-outline-overlay-data (data)
6973 "Create visibility overlays for all positions in DATA.
6974 DATA should have been made by `org-outline-overlay-data'."
6975 (let (o)
6976 (save-excursion
6977 (save-restriction
6978 (widen)
6979 (show-all)
6980 (mapc (lambda (c)
6981 (outline-flag-region (car c) (cdr c) t))
6982 data)))))
6984 ;;; Folding of blocks
6986 (defvar org-hide-block-overlays nil
6987 "Overlays hiding blocks.")
6988 (make-variable-buffer-local 'org-hide-block-overlays)
6990 (defun org-block-map (function &optional start end)
6991 "Call FUNCTION at the head of all source blocks in the current buffer.
6992 Optional arguments START and END can be used to limit the range."
6993 (let ((start (or start (point-min)))
6994 (end (or end (point-max))))
6995 (save-excursion
6996 (goto-char start)
6997 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6998 (save-excursion
6999 (save-match-data
7000 (goto-char (match-beginning 0))
7001 (funcall function)))))))
7003 (defun org-hide-block-toggle-all ()
7004 "Toggle the visibility of all blocks in the current buffer."
7005 (org-block-map #'org-hide-block-toggle))
7007 (defun org-hide-block-all ()
7008 "Fold all blocks in the current buffer."
7009 (interactive)
7010 (org-show-block-all)
7011 (org-block-map #'org-hide-block-toggle-maybe))
7013 (defun org-show-block-all ()
7014 "Unfold all blocks in the current buffer."
7015 (interactive)
7016 (mapc 'delete-overlay org-hide-block-overlays)
7017 (setq org-hide-block-overlays nil))
7019 (defun org-hide-block-toggle-maybe ()
7020 "Toggle visibility of block at point."
7021 (interactive)
7022 (let ((case-fold-search t))
7023 (if (save-excursion
7024 (beginning-of-line 1)
7025 (looking-at org-block-regexp))
7026 (progn (org-hide-block-toggle)
7027 t) ;; to signal that we took action
7028 nil))) ;; to signal that we did not
7030 (defun org-hide-block-toggle (&optional force)
7031 "Toggle the visibility of the current block."
7032 (interactive)
7033 (save-excursion
7034 (beginning-of-line)
7035 (if (re-search-forward org-block-regexp nil t)
7036 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7037 (end (match-end 0)) ;; end of entire body
7039 (if (memq t (mapcar (lambda (overlay)
7040 (eq (overlay-get overlay 'invisible)
7041 'org-hide-block))
7042 (overlays-at start)))
7043 (if (or (not force) (eq force 'off))
7044 (mapc (lambda (ov)
7045 (when (member ov org-hide-block-overlays)
7046 (setq org-hide-block-overlays
7047 (delq ov org-hide-block-overlays)))
7048 (when (eq (overlay-get ov 'invisible)
7049 'org-hide-block)
7050 (delete-overlay ov)))
7051 (overlays-at start)))
7052 (setq ov (make-overlay start end))
7053 (overlay-put ov 'invisible 'org-hide-block)
7054 ;; make the block accessible to isearch
7055 (overlay-put
7056 ov 'isearch-open-invisible
7057 (lambda (ov)
7058 (when (member ov org-hide-block-overlays)
7059 (setq org-hide-block-overlays
7060 (delq ov org-hide-block-overlays)))
7061 (when (eq (overlay-get ov 'invisible)
7062 'org-hide-block)
7063 (delete-overlay ov))))
7064 (push ov org-hide-block-overlays)))
7065 (error "Not looking at a source block"))))
7067 ;; org-tab-after-check-for-cycling-hook
7068 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7069 ;; Remove overlays when changing major mode
7070 (add-hook 'org-mode-hook
7071 (lambda () (org-add-hook 'change-major-mode-hook
7072 'org-show-block-all 'append 'local)))
7074 ;;; Org-goto
7076 (defvar org-goto-window-configuration nil)
7077 (defvar org-goto-marker nil)
7078 (defvar org-goto-map)
7079 (defun org-goto-map ()
7080 "Set the keymap `org-goto'."
7081 (setq org-goto-map
7082 (let ((map (make-sparse-keymap)))
7083 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7084 mouse-drag-region universal-argument org-occur))
7085 cmd)
7086 (while (setq cmd (pop cmds))
7087 (substitute-key-definition cmd cmd map global-map)))
7088 (suppress-keymap map)
7089 (org-defkey map "\C-m" 'org-goto-ret)
7090 (org-defkey map [(return)] 'org-goto-ret)
7091 (org-defkey map [(left)] 'org-goto-left)
7092 (org-defkey map [(right)] 'org-goto-right)
7093 (org-defkey map [(control ?g)] 'org-goto-quit)
7094 (org-defkey map "\C-i" 'org-cycle)
7095 (org-defkey map [(tab)] 'org-cycle)
7096 (org-defkey map [(down)] 'outline-next-visible-heading)
7097 (org-defkey map [(up)] 'outline-previous-visible-heading)
7098 (if org-goto-auto-isearch
7099 (if (fboundp 'define-key-after)
7100 (define-key-after map [t] 'org-goto-local-auto-isearch)
7101 nil)
7102 (org-defkey map "q" 'org-goto-quit)
7103 (org-defkey map "n" 'outline-next-visible-heading)
7104 (org-defkey map "p" 'outline-previous-visible-heading)
7105 (org-defkey map "f" 'outline-forward-same-level)
7106 (org-defkey map "b" 'outline-backward-same-level)
7107 (org-defkey map "u" 'outline-up-heading))
7108 (org-defkey map "/" 'org-occur)
7109 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7110 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7111 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7112 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7113 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7114 map)))
7116 (defconst org-goto-help
7117 "Browse buffer copy, to find location or copy text.%s
7118 RET=jump to location C-g=quit and return to previous location
7119 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7121 (defvar org-goto-start-pos) ; dynamically scoped parameter
7123 ;; FIXME: Docstring does not mention both interfaces
7124 (defun org-goto (&optional alternative-interface)
7125 "Look up a different location in the current file, keeping current visibility.
7127 When you want look-up or go to a different location in a
7128 document, the fastest way is often to fold the entire buffer and
7129 then dive into the tree. This method has the disadvantage, that
7130 the previous location will be folded, which may not be what you
7131 want.
7133 This command works around this by showing a copy of the current
7134 buffer in an indirect buffer, in overview mode. You can dive
7135 into the tree in that copy, use org-occur and incremental search
7136 to find a location. When pressing RET or `Q', the command
7137 returns to the original buffer in which the visibility is still
7138 unchanged. After RET it will also jump to the location selected
7139 in the indirect buffer and expose the headline hierarchy above.
7141 With a prefix argument, use the alternative interface: e.g. if
7142 `org-goto-interface' is 'outline use 'outline-path-completion."
7143 (interactive "P")
7144 (org-goto-map)
7145 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7146 (org-refile-use-outline-path t)
7147 (org-refile-target-verify-function nil)
7148 (interface
7149 (if (not alternative-interface)
7150 org-goto-interface
7151 (if (eq org-goto-interface 'outline)
7152 'outline-path-completion
7153 'outline)))
7154 (org-goto-start-pos (point))
7155 (selected-point
7156 (if (eq interface 'outline)
7157 (car (org-get-location (current-buffer) org-goto-help))
7158 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7159 (org-refile-check-position pa)
7160 (nth 3 pa)))))
7161 (if selected-point
7162 (progn
7163 (org-mark-ring-push org-goto-start-pos)
7164 (goto-char selected-point)
7165 (if (or (outline-invisible-p) (org-invisible-p2))
7166 (org-show-context 'org-goto)))
7167 (message "Quit"))))
7169 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7170 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7171 (defvar org-goto-local-auto-isearch-map) ; defined below
7173 (defun org-get-location (buf help)
7174 "Let the user select a location in the Org-mode buffer BUF.
7175 This function uses a recursive edit. It returns the selected position
7176 or nil."
7177 (org-no-popups
7178 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7179 (isearch-hide-immediately nil)
7180 (isearch-search-fun-function
7181 (lambda () 'org-goto-local-search-headings))
7182 (org-goto-selected-point org-goto-exit-command))
7183 (save-excursion
7184 (save-window-excursion
7185 (delete-other-windows)
7186 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7187 (org-pop-to-buffer-same-window
7188 (condition-case nil
7189 (make-indirect-buffer (current-buffer) "*org-goto*")
7190 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7191 (with-output-to-temp-buffer "*Org Help*"
7192 (princ (format help (if org-goto-auto-isearch
7193 " Just type for auto-isearch."
7194 " n/p/f/b/u to navigate, q to quit."))))
7195 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7196 (setq buffer-read-only nil)
7197 (let ((org-startup-truncated t)
7198 (org-startup-folded nil)
7199 (org-startup-align-all-tables nil))
7200 (org-mode)
7201 (org-overview))
7202 (setq buffer-read-only t)
7203 (if (and (boundp 'org-goto-start-pos)
7204 (integer-or-marker-p org-goto-start-pos))
7205 (let ((org-show-hierarchy-above t)
7206 (org-show-siblings t)
7207 (org-show-following-heading t))
7208 (goto-char org-goto-start-pos)
7209 (and (outline-invisible-p) (org-show-context)))
7210 (goto-char (point-min)))
7211 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7212 (message "Select location and press RET")
7213 (use-local-map org-goto-map)
7214 (recursive-edit)))
7215 (kill-buffer "*org-goto*")
7216 (cons org-goto-selected-point org-goto-exit-command))))
7218 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7219 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7220 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7221 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7223 (defun org-goto-local-search-headings (string bound noerror)
7224 "Search and make sure that any matches are in headlines."
7225 (catch 'return
7226 (while (if isearch-forward
7227 (search-forward string bound noerror)
7228 (search-backward string bound noerror))
7229 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7230 (and (member :headline context)
7231 (not (member :tags context))))
7232 (throw 'return (point))))))
7234 (defun org-goto-local-auto-isearch ()
7235 "Start isearch."
7236 (interactive)
7237 (goto-char (point-min))
7238 (let ((keys (this-command-keys)))
7239 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7240 (isearch-mode t)
7241 (isearch-process-search-char (string-to-char keys)))))
7243 (defun org-goto-ret (&optional arg)
7244 "Finish `org-goto' by going to the new location."
7245 (interactive "P")
7246 (setq org-goto-selected-point (point)
7247 org-goto-exit-command 'return)
7248 (throw 'exit nil))
7250 (defun org-goto-left ()
7251 "Finish `org-goto' by going to the new location."
7252 (interactive)
7253 (if (org-at-heading-p)
7254 (progn
7255 (beginning-of-line 1)
7256 (setq org-goto-selected-point (point)
7257 org-goto-exit-command 'left)
7258 (throw 'exit nil))
7259 (error "Not on a heading")))
7261 (defun org-goto-right ()
7262 "Finish `org-goto' by going to the new location."
7263 (interactive)
7264 (if (org-at-heading-p)
7265 (progn
7266 (setq org-goto-selected-point (point)
7267 org-goto-exit-command 'right)
7268 (throw 'exit nil))
7269 (error "Not on a heading")))
7271 (defun org-goto-quit ()
7272 "Finish `org-goto' without cursor motion."
7273 (interactive)
7274 (setq org-goto-selected-point nil)
7275 (setq org-goto-exit-command 'quit)
7276 (throw 'exit nil))
7278 ;;; Indirect buffer display of subtrees
7280 (defvar org-indirect-dedicated-frame nil
7281 "This is the frame being used for indirect tree display.")
7282 (defvar org-last-indirect-buffer nil)
7284 (defun org-tree-to-indirect-buffer (&optional arg)
7285 "Create indirect buffer and narrow it to current subtree.
7286 With a numerical prefix ARG, go up to this level and then take that tree.
7287 If ARG is negative, go up that many levels.
7289 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7290 indirect buffer previously made with this command, to avoid proliferation of
7291 indirect buffers. However, when you call the command with a \
7292 \\[universal-argument] prefix, or
7293 when `org-indirect-buffer-display' is `new-frame', the last buffer
7294 is kept so that you can work with several indirect buffers at the same time.
7295 If `org-indirect-buffer-display' is `dedicated-frame', the \
7296 \\[universal-argument] prefix also
7297 requests that a new frame be made for the new buffer, so that the dedicated
7298 frame is not changed."
7299 (interactive "P")
7300 (let ((cbuf (current-buffer))
7301 (cwin (selected-window))
7302 (pos (point))
7303 beg end level heading ibuf)
7304 (save-excursion
7305 (org-back-to-heading t)
7306 (when (numberp arg)
7307 (setq level (org-outline-level))
7308 (if (< arg 0) (setq arg (+ level arg)))
7309 (while (> (setq level (org-outline-level)) arg)
7310 (org-up-heading-safe)))
7311 (setq beg (point)
7312 heading (org-get-heading))
7313 (org-end-of-subtree t t)
7314 (if (org-at-heading-p) (backward-char 1))
7315 (setq end (point)))
7316 (if (and (buffer-live-p org-last-indirect-buffer)
7317 (not (eq org-indirect-buffer-display 'new-frame))
7318 (not arg))
7319 (kill-buffer org-last-indirect-buffer))
7320 (setq ibuf (org-get-indirect-buffer cbuf)
7321 org-last-indirect-buffer ibuf)
7322 (cond
7323 ((or (eq org-indirect-buffer-display 'new-frame)
7324 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7325 (select-frame (make-frame))
7326 (delete-other-windows)
7327 (org-pop-to-buffer-same-window ibuf)
7328 (org-set-frame-title heading))
7329 ((eq org-indirect-buffer-display 'dedicated-frame)
7330 (raise-frame
7331 (select-frame (or (and org-indirect-dedicated-frame
7332 (frame-live-p org-indirect-dedicated-frame)
7333 org-indirect-dedicated-frame)
7334 (setq org-indirect-dedicated-frame (make-frame)))))
7335 (delete-other-windows)
7336 (org-pop-to-buffer-same-window ibuf)
7337 (org-set-frame-title (concat "Indirect: " heading)))
7338 ((eq org-indirect-buffer-display 'current-window)
7339 (org-pop-to-buffer-same-window ibuf))
7340 ((eq org-indirect-buffer-display 'other-window)
7341 (pop-to-buffer ibuf))
7342 (t (error "Invalid value")))
7343 (if (featurep 'xemacs)
7344 (save-excursion (org-mode) (turn-on-font-lock)))
7345 (narrow-to-region beg end)
7346 (show-all)
7347 (goto-char pos)
7348 (run-hook-with-args 'org-cycle-hook 'all)
7349 (and (window-live-p cwin) (select-window cwin))))
7351 (defun org-get-indirect-buffer (&optional buffer)
7352 (setq buffer (or buffer (current-buffer)))
7353 (let ((n 1) (base (buffer-name buffer)) bname)
7354 (while (buffer-live-p
7355 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7356 (setq n (1+ n)))
7357 (condition-case nil
7358 (make-indirect-buffer buffer bname 'clone)
7359 (error (make-indirect-buffer buffer bname)))))
7361 (defun org-set-frame-title (title)
7362 "Set the title of the current frame to the string TITLE."
7363 ;; FIXME: how to name a single frame in XEmacs???
7364 (unless (featurep 'xemacs)
7365 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7367 ;;;; Structure editing
7369 ;;; Inserting headlines
7371 (defun org-previous-line-empty-p (&optional next)
7372 "Is the previous line a blank line?
7373 When NEXT is non-nil, check the next line instead."
7374 (save-excursion
7375 (and (not (bobp))
7376 (or (beginning-of-line (if next 2 0)) t)
7377 (save-match-data
7378 (looking-at "[ \t]*$")))))
7380 (defun org-insert-heading (&optional arg invisible-ok)
7381 "Insert a new heading or item with same depth at point.
7382 If point is in a plain list and ARG is nil, create a new list item.
7383 With one universal prefix argument, insert a heading even in lists.
7384 With two universal prefix arguments, insert the heading at the end
7385 of the parent subtree.
7387 If point is at the beginning of a headline, insert a sibling before
7388 the current headline. If point is not at the beginning, split the line
7389 and create a new headline with the text in the current line after point
7390 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7392 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7393 This is important for non-interactive uses of the command."
7394 (interactive "P")
7395 (cond
7396 ((or (= (buffer-size) 0)
7397 (and (not (save-excursion
7398 (and (ignore-errors (org-back-to-heading invisible-ok))
7399 (org-at-heading-p))))
7400 (or arg (not (org-in-item-p)))))
7401 (insert
7402 (if (org-previous-line-empty-p) "" "\n")
7403 (if (org-in-src-block-p) ",* " "* "))
7404 (run-hooks 'org-insert-heading-hook))
7405 ((or arg (not (org-insert-item
7406 (save-excursion
7407 (beginning-of-line)
7408 (looking-at org-list-full-item-re)
7409 (match-string 3)))))
7410 (let (begn endn)
7411 (when (org-buffer-narrowed-p)
7412 (setq begn (point-min) endn (point-max))
7413 (widen))
7414 (let* ((empty-line-p nil)
7415 (eops (equal arg '(16))) ; insert at end of parent subtree
7416 (org-insert-heading-respect-content
7417 (or (not (null arg)) org-insert-heading-respect-content))
7418 (level nil)
7419 (on-heading (org-at-heading-p))
7420 (head (save-excursion
7421 (condition-case nil
7422 (progn
7423 (org-back-to-heading invisible-ok)
7424 (when (and (not on-heading)
7425 (featurep 'org-inlinetask)
7426 (integerp org-inlinetask-min-level)
7427 (>= (length (match-string 0))
7428 org-inlinetask-min-level))
7429 ;; Find a heading level before the inline task
7430 (while (and (setq level (org-up-heading-safe))
7431 (>= level org-inlinetask-min-level)))
7432 (if (org-at-heading-p)
7433 (org-back-to-heading invisible-ok)
7434 (error "This should not happen")))
7435 (unless (and (save-excursion
7436 (save-match-data
7437 (org-backward-heading-same-level 1 invisible-ok))
7438 (= (point) (match-beginning 0)))
7439 (not (org-previous-line-empty-p t)))
7440 (setq empty-line-p (org-previous-line-empty-p)))
7441 (match-string 0))
7442 (error "* "))))
7443 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7444 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7445 pos hide-previous previous-pos)
7446 (if ;; At the beginning of a heading, open a new line for insertiong
7447 (and (bolp) (org-at-heading-p)
7448 (not eops)
7449 (or (bobp)
7450 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7451 (open-line (if blank 2 1))
7452 (save-excursion
7453 (setq previous-pos (point-at-bol))
7454 (end-of-line)
7455 (setq hide-previous (outline-invisible-p)))
7456 (and org-insert-heading-respect-content
7457 (save-excursion
7458 (while (outline-invisible-p)
7459 (org-show-subtree)
7460 (org-up-heading-safe))))
7461 (let ((split
7462 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7463 (save-excursion
7464 (let ((p (point)))
7465 (goto-char (point-at-bol))
7466 (and (looking-at org-complex-heading-regexp)
7467 (match-beginning 4)
7468 (> p (match-beginning 4)))))))
7469 tags pos)
7470 (cond
7471 ;; Insert a new line, possibly at end of parent subtree
7472 (org-insert-heading-respect-content
7473 (if (not eops)
7474 (progn
7475 (org-end-of-subtree nil t)
7476 (and (looking-at "^\\*") (backward-char 1))
7477 (while (and (not (bobp))
7478 ;; Don't delete spaces in empty headlines
7479 (not (looking-back org-outline-regexp))
7480 (member (char-before) '(?\ ?\t ?\n)))
7481 (backward-delete-char 1)))
7482 (let ((p (point)))
7483 (org-up-heading-safe)
7484 (if (= p (point))
7485 (goto-char (point-max))
7486 (org-end-of-subtree nil t))))
7487 (when (featurep 'org-inlinetask)
7488 (while (and (not (eobp))
7489 (looking-at "\\(\\*+\\)[ \t]+")
7490 (>= (length (match-string 1))
7491 org-inlinetask-min-level))
7492 (org-end-of-subtree nil t)))
7493 (or (bolp) (newline))
7494 (or (org-previous-line-empty-p)
7495 (and blank (newline)))
7496 (if (or empty-line-p eops) (open-line 1)))
7497 ;; Insert a headling containing text after point
7498 ((org-at-heading-p)
7499 (when hide-previous
7500 (show-children)
7501 (org-show-entry))
7502 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7503 (setq tags (and (match-end 2) (match-string 2)))
7504 (and (match-end 1)
7505 (delete-region (match-beginning 1) (match-end 1)))
7506 (setq pos (point-at-bol))
7507 (or split (end-of-line 1))
7508 (delete-horizontal-space)
7509 (if (string-match "\\`\\*+\\'"
7510 (buffer-substring (point-at-bol) (point)))
7511 (insert " "))
7512 (newline (if blank 2 1))
7513 (when tags
7514 (save-excursion
7515 (goto-char pos)
7516 (end-of-line 1)
7517 (insert " " tags)
7518 (org-set-tags nil 'align))))
7520 (or split (end-of-line 1))
7521 (newline (if blank 2 1))))))
7522 (insert head) (just-one-space)
7523 (setq pos (point))
7524 (end-of-line 1)
7525 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7526 (when (and org-insert-heading-respect-content hide-previous)
7527 (save-excursion
7528 (goto-char previous-pos)
7529 (hide-subtree)))
7530 (when (and begn endn)
7531 (narrow-to-region (min (point) begn) (max (point) endn)))
7532 (run-hooks 'org-insert-heading-hook))))))
7534 (defun org-get-heading (&optional no-tags no-todo)
7535 "Return the heading of the current entry, without the stars.
7536 When NO-TAGS is non-nil, don't include tags.
7537 When NO-TODO is non-nil, don't include TODO keywords."
7538 (save-excursion
7539 (org-back-to-heading t)
7540 (cond
7541 ((and no-tags no-todo)
7542 (looking-at org-complex-heading-regexp)
7543 (match-string 4))
7544 (no-tags
7545 (looking-at (concat org-outline-regexp
7546 "\\(.*?\\)"
7547 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7548 (match-string 1))
7549 (no-todo
7550 (looking-at org-todo-line-regexp)
7551 (match-string 3))
7552 (t (looking-at org-heading-regexp)
7553 (match-string 2)))))
7555 (defvar orgstruct-mode) ; defined below
7557 (defun org-heading-components ()
7558 "Return the components of the current heading.
7559 This is a list with the following elements:
7560 - the level as an integer
7561 - the reduced level, different if `org-odd-levels-only' is set.
7562 - the TODO keyword, or nil
7563 - the priority character, like ?A, or nil if no priority is given
7564 - the headline text itself, or the tags string if no headline text
7565 - the tags string, or nil."
7566 (save-excursion
7567 (org-back-to-heading t)
7568 (if (let (case-fold-search)
7569 (looking-at
7570 (if orgstruct-mode
7571 org-heading-regexp
7572 org-complex-heading-regexp)))
7573 (if orgstruct-mode
7574 (list (length (match-string 1))
7575 (org-reduced-level (length (match-string 1)))
7578 (match-string 2)
7579 nil)
7580 (list (length (match-string 1))
7581 (org-reduced-level (length (match-string 1)))
7582 (org-match-string-no-properties 2)
7583 (and (match-end 3) (aref (match-string 3) 2))
7584 (org-match-string-no-properties 4)
7585 (org-match-string-no-properties 5))))))
7587 (defun org-get-entry ()
7588 "Get the entry text, after heading, entire subtree."
7589 (save-excursion
7590 (org-back-to-heading t)
7591 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7593 (defun org-insert-heading-after-current ()
7594 "Insert a new heading with same level as current, after current subtree."
7595 (interactive)
7596 (org-back-to-heading)
7597 (org-insert-heading)
7598 (org-move-subtree-down)
7599 (end-of-line 1))
7601 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7602 "Insert heading with `org-insert-heading-respect-content' set to t."
7603 (interactive "P")
7604 (let ((org-insert-heading-respect-content t))
7605 (org-insert-heading arg invisible-ok)))
7607 (defun org-insert-todo-heading-respect-content (&optional force-state)
7608 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7609 (interactive "P")
7610 (let ((org-insert-heading-respect-content t))
7611 (org-insert-todo-heading force-state t)))
7613 (defun org-insert-todo-heading (arg &optional force-heading)
7614 "Insert a new heading with the same level and TODO state as current heading.
7615 If the heading has no TODO state, or if the state is DONE, use the first
7616 state (TODO by default). Also one prefix arg, force first state. With two
7617 prefix args, force inserting at the end of the parent subtree."
7618 (interactive "P")
7619 (when (or force-heading (not (org-insert-item 'checkbox)))
7620 (org-insert-heading (or (and (equal arg '(16)) '(16))
7621 force-heading))
7622 (save-excursion
7623 (org-back-to-heading)
7624 (outline-previous-heading)
7625 (looking-at org-todo-line-regexp))
7626 (let*
7627 ((new-mark-x
7628 (if (or arg
7629 (not (match-beginning 2))
7630 (member (match-string 2) org-done-keywords))
7631 (car org-todo-keywords-1)
7632 (match-string 2)))
7633 (new-mark
7635 (run-hook-with-args-until-success
7636 'org-todo-get-default-hook new-mark-x nil)
7637 new-mark-x)))
7638 (beginning-of-line 1)
7639 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7640 (if org-treat-insert-todo-heading-as-state-change
7641 (org-todo new-mark)
7642 (insert new-mark " "))))
7643 (when org-provide-todo-statistics
7644 (org-update-parent-todo-statistics))))
7646 (defun org-insert-subheading (arg)
7647 "Insert a new subheading and demote it.
7648 Works for outline headings and for plain lists alike."
7649 (interactive "P")
7650 (org-insert-heading arg)
7651 (cond
7652 ((org-at-heading-p) (org-do-demote))
7653 ((org-at-item-p) (org-indent-item))))
7655 (defun org-insert-todo-subheading (arg)
7656 "Insert a new subheading with TODO keyword or checkbox and demote it.
7657 Works for outline headings and for plain lists alike."
7658 (interactive "P")
7659 (org-insert-todo-heading arg)
7660 (cond
7661 ((org-at-heading-p) (org-do-demote))
7662 ((org-at-item-p) (org-indent-item))))
7664 ;;; Promotion and Demotion
7666 (defvar org-after-demote-entry-hook nil
7667 "Hook run after an entry has been demoted.
7668 The cursor will be at the beginning of the entry.
7669 When a subtree is being demoted, the hook will be called for each node.")
7671 (defvar org-after-promote-entry-hook nil
7672 "Hook run after an entry has been promoted.
7673 The cursor will be at the beginning of the entry.
7674 When a subtree is being promoted, the hook will be called for each node.")
7676 (defun org-promote-subtree ()
7677 "Promote the entire subtree.
7678 See also `org-promote'."
7679 (interactive)
7680 (save-excursion
7681 (org-with-limited-levels (org-map-tree 'org-promote)))
7682 (org-fix-position-after-promote))
7684 (defun org-demote-subtree ()
7685 "Demote the entire subtree. See `org-demote'.
7686 See also `org-promote'."
7687 (interactive)
7688 (save-excursion
7689 (org-with-limited-levels (org-map-tree 'org-demote)))
7690 (org-fix-position-after-promote))
7693 (defun org-do-promote ()
7694 "Promote the current heading higher up the tree.
7695 If the region is active in `transient-mark-mode', promote all headings
7696 in the region."
7697 (interactive)
7698 (save-excursion
7699 (if (org-region-active-p)
7700 (org-map-region 'org-promote (region-beginning) (region-end))
7701 (org-promote)))
7702 (org-fix-position-after-promote))
7704 (defun org-do-demote ()
7705 "Demote the current heading lower down the tree.
7706 If the region is active in `transient-mark-mode', demote all headings
7707 in the region."
7708 (interactive)
7709 (save-excursion
7710 (if (org-region-active-p)
7711 (org-map-region 'org-demote (region-beginning) (region-end))
7712 (org-demote)))
7713 (org-fix-position-after-promote))
7715 (defun org-fix-position-after-promote ()
7716 "Make sure that after pro/demotion cursor position is right."
7717 (let ((pos (point)))
7718 (when (save-excursion
7719 (beginning-of-line 1)
7720 (looking-at org-todo-line-regexp)
7721 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7722 (cond ((eobp) (insert " "))
7723 ((eolp) (insert " "))
7724 ((equal (char-after) ?\ ) (forward-char 1))))))
7726 (defun org-current-level ()
7727 "Return the level of the current entry, or nil if before the first headline.
7728 The level is the number of stars at the beginning of the headline."
7729 (save-excursion
7730 (org-with-limited-levels
7731 (if (ignore-errors (org-back-to-heading t))
7732 (funcall outline-level)))))
7734 (defun org-get-previous-line-level ()
7735 "Return the outline depth of the last headline before the current line.
7736 Returns 0 for the first headline in the buffer, and nil if before the
7737 first headline."
7738 (let ((current-level (org-current-level))
7739 (prev-level (when (> (line-number-at-pos) 1)
7740 (save-excursion
7741 (beginning-of-line 0)
7742 (org-current-level)))))
7743 (cond ((null current-level) nil) ; Before first headline
7744 ((null prev-level) 0) ; At first headline
7745 (prev-level))))
7747 (defun org-reduced-level (l)
7748 "Compute the effective level of a heading.
7749 This takes into account the setting of `org-odd-levels-only'."
7750 (cond
7751 ((zerop l) 0)
7752 (org-odd-levels-only (1+ (floor (/ l 2))))
7753 (t l)))
7755 (defun org-level-increment ()
7756 "Return the number of stars that will be added or removed at a
7757 time to headlines when structure editing, based on the value of
7758 `org-odd-levels-only'."
7759 (if org-odd-levels-only 2 1))
7761 (defun org-get-valid-level (level &optional change)
7762 "Rectify a level change under the influence of `org-odd-levels-only'
7763 LEVEL is a current level, CHANGE is by how much the level should be
7764 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7765 even level numbers will become the next higher odd number."
7766 (if org-odd-levels-only
7767 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7768 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7769 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7770 (max 1 (+ level (or change 0)))))
7772 (if (boundp 'define-obsolete-function-alias)
7773 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7774 (define-obsolete-function-alias 'org-get-legal-level
7775 'org-get-valid-level)
7776 (define-obsolete-function-alias 'org-get-legal-level
7777 'org-get-valid-level "23.1")))
7779 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7780 ;; ̀org-with-limited-levels'
7781 (defun org-promote ()
7782 "Promote the current heading higher up the tree.
7783 If the region is active in `transient-mark-mode', promote all headings
7784 in the region."
7785 (org-back-to-heading t)
7786 (let* ((level (save-match-data (funcall outline-level)))
7787 (after-change-functions (remove 'flyspell-after-change-function
7788 after-change-functions))
7789 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7790 (diff (abs (- level (length up-head) -1))))
7791 (cond ((and (= level 1) org-called-with-limited-levels
7792 org-allow-promoting-top-level-subtree)
7793 (replace-match "# " nil t))
7794 ((= level 1)
7795 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7796 (t (replace-match up-head nil t)))
7797 ;; Fixup tag positioning
7798 (unless (= level 1)
7799 (and org-auto-align-tags (org-set-tags nil t))
7800 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7801 (run-hooks 'org-after-promote-entry-hook)))
7803 (defun org-demote ()
7804 "Demote the current heading lower down the tree.
7805 If the region is active in `transient-mark-mode', demote all headings
7806 in the region."
7807 (org-back-to-heading t)
7808 (let* ((level (save-match-data (funcall outline-level)))
7809 (after-change-functions (remove 'flyspell-after-change-function
7810 after-change-functions))
7811 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7812 (diff (abs (- level (length down-head) -1))))
7813 (replace-match down-head nil t)
7814 ;; Fixup tag positioning
7815 (and org-auto-align-tags (org-set-tags nil t))
7816 (if org-adapt-indentation (org-fixup-indentation diff))
7817 (run-hooks 'org-after-demote-entry-hook)))
7819 (defun org-cycle-level ()
7820 "Cycle the level of an empty headline through possible states.
7821 This goes first to child, then to parent, level, then up the hierarchy.
7822 After top level, it switches back to sibling level."
7823 (interactive)
7824 (let ((org-adapt-indentation nil))
7825 (when (org-point-at-end-of-empty-headline)
7826 (setq this-command 'org-cycle-level) ; Only needed for caching
7827 (let ((cur-level (org-current-level))
7828 (prev-level (org-get-previous-line-level)))
7829 (cond
7830 ;; If first headline in file, promote to top-level.
7831 ((= prev-level 0)
7832 (loop repeat (/ (- cur-level 1) (org-level-increment))
7833 do (org-do-promote)))
7834 ;; If same level as prev, demote one.
7835 ((= prev-level cur-level)
7836 (org-do-demote))
7837 ;; If parent is top-level, promote to top level if not already.
7838 ((= prev-level 1)
7839 (loop repeat (/ (- cur-level 1) (org-level-increment))
7840 do (org-do-promote)))
7841 ;; If top-level, return to prev-level.
7842 ((= cur-level 1)
7843 (loop repeat (/ (- prev-level 1) (org-level-increment))
7844 do (org-do-demote)))
7845 ;; If less than prev-level, promote one.
7846 ((< cur-level prev-level)
7847 (org-do-promote))
7848 ;; If deeper than prev-level, promote until higher than
7849 ;; prev-level.
7850 ((> cur-level prev-level)
7851 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7852 do (org-do-promote))))
7853 t))))
7855 (defun org-map-tree (fun)
7856 "Call FUN for every heading underneath the current one."
7857 (org-back-to-heading)
7858 (let ((level (funcall outline-level)))
7859 (save-excursion
7860 (funcall fun)
7861 (while (and (progn
7862 (outline-next-heading)
7863 (> (funcall outline-level) level))
7864 (not (eobp)))
7865 (funcall fun)))))
7867 (defun org-map-region (fun beg end)
7868 "Call FUN for every heading between BEG and END."
7869 (let ((org-ignore-region t))
7870 (save-excursion
7871 (setq end (copy-marker end))
7872 (goto-char beg)
7873 (if (and (re-search-forward org-outline-regexp-bol nil t)
7874 (< (point) end))
7875 (funcall fun))
7876 (while (and (progn
7877 (outline-next-heading)
7878 (< (point) end))
7879 (not (eobp)))
7880 (funcall fun)))))
7882 (defvar org-property-end-re) ; silence byte-compiler
7883 (defun org-fixup-indentation (diff)
7884 "Change the indentation in the current entry by DIFF.
7885 However, if any line in the current entry has no indentation, or if it
7886 would end up with no indentation after the change, nothing at all is done."
7887 (save-excursion
7888 (let ((end (save-excursion (outline-next-heading)
7889 (point-marker)))
7890 (prohibit (if (> diff 0)
7891 "^\\S-"
7892 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7893 col)
7894 (unless (save-excursion (end-of-line 1)
7895 (re-search-forward prohibit end t))
7896 (while (and (< (point) end)
7897 (re-search-forward "^[ \t]+" end t))
7898 (goto-char (match-end 0))
7899 (setq col (current-column))
7900 (if (< diff 0) (replace-match ""))
7901 (org-indent-to-column (+ diff col))))
7902 (move-marker end nil))))
7904 (defun org-convert-to-odd-levels ()
7905 "Convert an org-mode file with all levels allowed to one with odd levels.
7906 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7907 level 5 etc."
7908 (interactive)
7909 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7910 (let ((outline-level 'org-outline-level)
7911 (org-odd-levels-only nil) n)
7912 (save-excursion
7913 (goto-char (point-min))
7914 (while (re-search-forward "^\\*\\*+ " nil t)
7915 (setq n (- (length (match-string 0)) 2))
7916 (while (>= (setq n (1- n)) 0)
7917 (org-demote))
7918 (end-of-line 1))))))
7920 (defun org-convert-to-oddeven-levels ()
7921 "Convert an org-mode file with only odd levels to one with odd/even levels.
7922 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7923 file contains a section with an even level, conversion would
7924 destroy the structure of the file. An error is signaled in this
7925 case."
7926 (interactive)
7927 (goto-char (point-min))
7928 ;; First check if there are no even levels
7929 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7930 (org-show-context t)
7931 (error "Not all levels are odd in this file. Conversion not possible"))
7932 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7933 (let ((outline-regexp org-outline-regexp)
7934 (outline-level 'org-outline-level)
7935 (org-odd-levels-only nil) n)
7936 (save-excursion
7937 (goto-char (point-min))
7938 (while (re-search-forward "^\\*\\*+ " nil t)
7939 (setq n (/ (1- (length (match-string 0))) 2))
7940 (while (>= (setq n (1- n)) 0)
7941 (org-promote))
7942 (end-of-line 1))))))
7944 (defun org-tr-level (n)
7945 "Make N odd if required."
7946 (if org-odd-levels-only (1+ (/ n 2)) n))
7948 ;;; Vertical tree motion, cutting and pasting of subtrees
7950 (defun org-move-subtree-up (&optional arg)
7951 "Move the current subtree up past ARG headlines of the same level."
7952 (interactive "p")
7953 (org-move-subtree-down (- (prefix-numeric-value arg))))
7955 (defun org-move-subtree-down (&optional arg)
7956 "Move the current subtree down past ARG headlines of the same level."
7957 (interactive "p")
7958 (setq arg (prefix-numeric-value arg))
7959 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7960 'org-get-last-sibling))
7961 (ins-point (make-marker))
7962 (cnt (abs arg))
7963 (col (current-column))
7964 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7965 ;; Select the tree
7966 (org-back-to-heading)
7967 (setq beg0 (point))
7968 (save-excursion
7969 (setq ne-beg (org-back-over-empty-lines))
7970 (setq beg (point)))
7971 (save-match-data
7972 (save-excursion (outline-end-of-heading)
7973 (setq folded (outline-invisible-p)))
7974 (outline-end-of-subtree))
7975 (outline-next-heading)
7976 (setq ne-end (org-back-over-empty-lines))
7977 (setq end (point))
7978 (goto-char beg0)
7979 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7980 ;; include less whitespace
7981 (save-excursion
7982 (goto-char beg)
7983 (forward-line (- ne-beg ne-end))
7984 (setq beg (point))))
7985 ;; Find insertion point, with error handling
7986 (while (> cnt 0)
7987 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7988 (progn (goto-char beg0)
7989 (user-error "Cannot move past superior level or buffer limit")))
7990 (setq cnt (1- cnt)))
7991 (if (> arg 0)
7992 ;; Moving forward - still need to move over subtree
7993 (progn (org-end-of-subtree t t)
7994 (save-excursion
7995 (org-back-over-empty-lines)
7996 (or (bolp) (newline)))))
7997 (setq ne-ins (org-back-over-empty-lines))
7998 (move-marker ins-point (point))
7999 (setq txt (buffer-substring beg end))
8000 (org-save-markers-in-region beg end)
8001 (delete-region beg end)
8002 (org-remove-empty-overlays-at beg)
8003 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8004 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8005 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8006 (let ((bbb (point)))
8007 (insert-before-markers txt)
8008 (org-reinstall-markers-in-region bbb)
8009 (move-marker ins-point bbb))
8010 (or (bolp) (insert "\n"))
8011 (setq ins-end (point))
8012 (goto-char ins-point)
8013 (org-skip-whitespace)
8014 (when (and (< arg 0)
8015 (org-first-sibling-p)
8016 (> ne-ins ne-beg))
8017 ;; Move whitespace back to beginning
8018 (save-excursion
8019 (goto-char ins-end)
8020 (let ((kill-whole-line t))
8021 (kill-line (- ne-ins ne-beg)) (point)))
8022 (insert (make-string (- ne-ins ne-beg) ?\n)))
8023 (move-marker ins-point nil)
8024 (if folded
8025 (hide-subtree)
8026 (org-show-entry)
8027 (show-children)
8028 (org-cycle-hide-drawers 'children))
8029 (org-clean-visibility-after-subtree-move)
8030 ;; move back to the initial column we were at
8031 (move-to-column col)))
8033 (defvar org-subtree-clip ""
8034 "Clipboard for cut and paste of subtrees.
8035 This is actually only a copy of the kill, because we use the normal kill
8036 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8038 (defvar org-subtree-clip-folded nil
8039 "Was the last copied subtree folded?
8040 This is used to fold the tree back after pasting.")
8042 (defun org-cut-subtree (&optional n)
8043 "Cut the current subtree into the clipboard.
8044 With prefix arg N, cut this many sequential subtrees.
8045 This is a short-hand for marking the subtree and then cutting it."
8046 (interactive "p")
8047 (org-copy-subtree n 'cut))
8049 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8050 "Cut the current subtree into the clipboard.
8051 With prefix arg N, cut this many sequential subtrees.
8052 This is a short-hand for marking the subtree and then copying it.
8053 If CUT is non-nil, actually cut the subtree.
8054 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8055 of some markers in the region, even if CUT is non-nil. This is
8056 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8057 (interactive "p")
8058 (let (beg end folded (beg0 (point)))
8059 (if (org-called-interactively-p 'any)
8060 (org-back-to-heading nil) ; take what looks like a subtree
8061 (org-back-to-heading t)) ; take what is really there
8062 (setq beg (point))
8063 (skip-chars-forward " \t\r\n")
8064 (save-match-data
8065 (if nosubtrees
8066 (outline-next-heading)
8067 (save-excursion (outline-end-of-heading)
8068 (setq folded (outline-invisible-p)))
8069 (condition-case nil
8070 (org-forward-heading-same-level (1- n) t)
8071 (error nil))
8072 (org-end-of-subtree t t)))
8073 (setq end (point))
8074 (goto-char beg0)
8075 (when (> end beg)
8076 (setq org-subtree-clip-folded folded)
8077 (when (or cut force-store-markers)
8078 (org-save-markers-in-region beg end))
8079 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8080 (setq org-subtree-clip (current-kill 0))
8081 (message "%s: Subtree(s) with %d characters"
8082 (if cut "Cut" "Copied")
8083 (length org-subtree-clip)))))
8085 (defun org-paste-subtree (&optional level tree for-yank)
8086 "Paste the clipboard as a subtree, with modification of headline level.
8087 The entire subtree is promoted or demoted in order to match a new headline
8088 level.
8090 If the cursor is at the beginning of a headline, the same level as
8091 that headline is used to paste the tree.
8093 If not, the new level is derived from the *visible* headings
8094 before and after the insertion point, and taken to be the inferior headline
8095 level of the two. So if the previous visible heading is level 3 and the
8096 next is level 4 (or vice versa), level 4 will be used for insertion.
8097 This makes sure that the subtree remains an independent subtree and does
8098 not swallow low level entries.
8100 You can also force a different level, either by using a numeric prefix
8101 argument, or by inserting the heading marker by hand. For example, if the
8102 cursor is after \"*****\", then the tree will be shifted to level 5.
8104 If optional TREE is given, use this text instead of the kill ring.
8106 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8107 move back over whitespace before inserting, and move point to the end of
8108 the inserted text when done."
8109 (interactive "P")
8110 (setq tree (or tree (and kill-ring (current-kill 0))))
8111 (unless (org-kill-is-subtree-p tree)
8112 (error "%s"
8113 (substitute-command-keys
8114 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8115 (org-with-limited-levels
8116 (let* ((visp (not (outline-invisible-p)))
8117 (txt tree)
8118 (^re_ "\\(\\*+\\)[ \t]*")
8119 (old-level (if (string-match org-outline-regexp-bol txt)
8120 (- (match-end 0) (match-beginning 0) 1)
8121 -1))
8122 (force-level (cond (level (prefix-numeric-value level))
8123 ((and (looking-at "[ \t]*$")
8124 (string-match
8125 "^\\*+$" (buffer-substring
8126 (point-at-bol) (point))))
8127 (- (match-end 1) (match-beginning 1)))
8128 ((and (bolp)
8129 (looking-at org-outline-regexp))
8130 (- (match-end 0) (point) 1))))
8131 (previous-level (save-excursion
8132 (condition-case nil
8133 (progn
8134 (outline-previous-visible-heading 1)
8135 (if (looking-at ^re_)
8136 (- (match-end 0) (match-beginning 0) 1)
8138 (error 1))))
8139 (next-level (save-excursion
8140 (condition-case nil
8141 (progn
8142 (or (looking-at org-outline-regexp)
8143 (outline-next-visible-heading 1))
8144 (if (looking-at ^re_)
8145 (- (match-end 0) (match-beginning 0) 1)
8147 (error 1))))
8148 (new-level (or force-level (max previous-level next-level)))
8149 (shift (if (or (= old-level -1)
8150 (= new-level -1)
8151 (= old-level new-level))
8153 (- new-level old-level)))
8154 (delta (if (> shift 0) -1 1))
8155 (func (if (> shift 0) 'org-demote 'org-promote))
8156 (org-odd-levels-only nil)
8157 beg end newend)
8158 ;; Remove the forced level indicator
8159 (if force-level
8160 (delete-region (point-at-bol) (point)))
8161 ;; Paste
8162 (beginning-of-line (if (bolp) 1 2))
8163 (setq beg (point))
8164 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8165 (insert-before-markers txt)
8166 (unless (string-match "\n\\'" txt) (insert "\n"))
8167 (setq newend (point))
8168 (org-reinstall-markers-in-region beg)
8169 (setq end (point))
8170 (goto-char beg)
8171 (skip-chars-forward " \t\n\r")
8172 (setq beg (point))
8173 (if (and (outline-invisible-p) visp)
8174 (save-excursion (outline-show-heading)))
8175 ;; Shift if necessary
8176 (unless (= shift 0)
8177 (save-restriction
8178 (narrow-to-region beg end)
8179 (while (not (= shift 0))
8180 (org-map-region func (point-min) (point-max))
8181 (setq shift (+ delta shift)))
8182 (goto-char (point-min))
8183 (setq newend (point-max))))
8184 (when (or (org-called-interactively-p 'interactive) for-yank)
8185 (message "Clipboard pasted as level %d subtree" new-level))
8186 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8187 kill-ring
8188 (eq org-subtree-clip (current-kill 0))
8189 org-subtree-clip-folded)
8190 ;; The tree was folded before it was killed/copied
8191 (hide-subtree))
8192 (and for-yank (goto-char newend)))))
8194 (defun org-kill-is-subtree-p (&optional txt)
8195 "Check if the current kill is an outline subtree, or a set of trees.
8196 Returns nil if kill does not start with a headline, or if the first
8197 headline level is not the largest headline level in the tree.
8198 So this will actually accept several entries of equal levels as well,
8199 which is OK for `org-paste-subtree'.
8200 If optional TXT is given, check this string instead of the current kill."
8201 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8202 (re (org-get-limited-outline-regexp))
8203 (^re (concat "^" re))
8204 (start-level (and kill
8205 (string-match
8206 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8207 kill)
8208 (- (match-end 2) (match-beginning 2) 1)))
8209 (start (1+ (or (match-beginning 2) -1))))
8210 (if (not start-level)
8211 (progn
8212 nil) ;; does not even start with a heading
8213 (catch 'exit
8214 (while (setq start (string-match ^re kill (1+ start)))
8215 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8216 (throw 'exit nil)))
8217 t))))
8219 (defvar org-markers-to-move nil
8220 "Markers that should be moved with a cut-and-paste operation.
8221 Those markers are stored together with their positions relative to
8222 the start of the region.")
8224 (defun org-save-markers-in-region (beg end)
8225 "Check markers in region.
8226 If these markers are between BEG and END, record their position relative
8227 to BEG, so that after moving the block of text, we can put the markers back
8228 into place.
8229 This function gets called just before an entry or tree gets cut from the
8230 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8231 called immediately, to move the markers with the entries."
8232 (setq org-markers-to-move nil)
8233 (when (featurep 'org-clock)
8234 (org-clock-save-markers-for-cut-and-paste beg end))
8235 (when (featurep 'org-agenda)
8236 (org-agenda-save-markers-for-cut-and-paste beg end)))
8238 (defun org-check-and-save-marker (marker beg end)
8239 "Check if MARKER is between BEG and END.
8240 If yes, remember the marker and the distance to BEG."
8241 (when (and (marker-buffer marker)
8242 (equal (marker-buffer marker) (current-buffer)))
8243 (if (and (>= marker beg) (< marker end))
8244 (push (cons marker (- marker beg)) org-markers-to-move))))
8246 (defun org-reinstall-markers-in-region (beg)
8247 "Move all remembered markers to their position relative to BEG."
8248 (mapc (lambda (x)
8249 (move-marker (car x) (+ beg (cdr x))))
8250 org-markers-to-move)
8251 (setq org-markers-to-move nil))
8253 (defun org-narrow-to-subtree ()
8254 "Narrow buffer to the current subtree."
8255 (interactive)
8256 (save-excursion
8257 (save-match-data
8258 (org-with-limited-levels
8259 (narrow-to-region
8260 (progn (org-back-to-heading t) (point))
8261 (progn (org-end-of-subtree t t)
8262 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8263 (point)))))))
8265 (defun org-narrow-to-block ()
8266 "Narrow buffer to the current block."
8267 (interactive)
8268 (let* ((case-fold-search t)
8269 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8270 "^[ \t]*#\\+end_.*")))
8271 (if blockp
8272 (narrow-to-region (car blockp) (cdr blockp))
8273 (error "Not in a block"))))
8275 (eval-when-compile
8276 (defvar org-property-drawer-re))
8278 (defvar org-property-start-re) ;; defined below
8279 (defun org-clone-subtree-with-time-shift (n &optional shift)
8280 "Clone the task (subtree) at point N times.
8281 The clones will be inserted as siblings.
8283 In interactive use, the user will be prompted for the number of
8284 clones to be produced. When called with a universal prefix argument
8285 and if the entry has a timestamp, the user will also be prompted for
8286 a time shift, which may be a repeater as used in time stamps, for
8287 example `+3d'.
8289 When a valid repeater is given and the entry contains any time
8290 stamps, the clones will become a sequence in time, with time
8291 stamps in the subtree shifted for each clone produced. If SHIFT
8292 is nil or the empty string, time stamps will be left alone. The
8293 ID property of the original subtree is removed.
8295 If the original subtree did contain time stamps with a repeater,
8296 the following will happen:
8297 - the repeater will be removed in each clone
8298 - an additional clone will be produced, with the current, unshifted
8299 date(s) in the entry.
8300 - the original entry will be placed *after* all the clones, with
8301 repeater intact.
8302 - the start days in the repeater in the original entry will be shifted
8303 to past the last clone.
8304 In this way you can spell out a number of instances of a repeating task,
8305 and still retain the repeater to cover future instances of the task."
8306 (interactive "nNumber of clones to produce: ")
8307 (let ((shift
8308 (or shift
8309 (if (and (equal current-prefix-arg '(4))
8310 (save-excursion
8311 (re-search-forward org-ts-regexp-both
8312 (save-excursion
8313 (org-end-of-subtree t)
8314 (point)) t)))
8315 (read-from-minibuffer
8316 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8317 ""))) ;; No time shift
8318 (n-no-remove -1)
8319 (drawer-re org-drawer-regexp)
8320 beg end template task idprop
8321 shift-n shift-what doshift nmin nmax)
8322 (if (not (and (integerp n) (> n 0)))
8323 (error "Invalid number of replications %s" n))
8324 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8325 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8326 shift)))
8327 (error "Invalid shift specification %s" shift))
8328 (when doshift
8329 (setq shift-n (string-to-number (match-string 1 shift))
8330 shift-what (cdr (assoc (match-string 2 shift)
8331 '(("d" . day) ("w" . week)
8332 ("m" . month) ("y" . year))))))
8333 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8334 (setq nmin 1 nmax n)
8335 (org-back-to-heading t)
8336 (setq beg (point))
8337 (setq idprop (org-entry-get nil "ID"))
8338 (org-end-of-subtree t t)
8339 (or (bolp) (insert "\n"))
8340 (setq end (point))
8341 (setq template (buffer-substring beg end))
8342 (when (and doshift
8343 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8344 (delete-region beg end)
8345 (setq end beg)
8346 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8347 (goto-char end)
8348 (loop for n from nmin to nmax do
8349 ;; prepare clone
8350 (with-temp-buffer
8351 (insert template)
8352 (org-mode)
8353 (goto-char (point-min))
8354 (org-show-subtree)
8355 (and idprop (if org-clone-delete-id
8356 (org-entry-delete nil "ID")
8357 (org-id-get-create t)))
8358 (unless (= n 0)
8359 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8360 (kill-whole-line))
8361 (goto-char (point-min))
8362 (while (re-search-forward drawer-re nil t)
8363 (mapc (lambda (d)
8364 (org-remove-empty-drawer-at d (point))) org-drawers)))
8365 (goto-char (point-min))
8366 (when doshift
8367 (while (re-search-forward org-ts-regexp-both nil t)
8368 (org-timestamp-change (* n shift-n) shift-what))
8369 (unless (= n n-no-remove)
8370 (goto-char (point-min))
8371 (while (re-search-forward org-ts-regexp nil t)
8372 (save-excursion
8373 (goto-char (match-beginning 0))
8374 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8375 (delete-region (match-beginning 1) (match-end 1)))))))
8376 (setq task (buffer-string)))
8377 (insert task))
8378 (goto-char beg)))
8380 ;;; Outline Sorting
8382 (defun org-sort (with-case)
8383 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8384 Optional argument WITH-CASE means sort case-sensitively."
8385 (interactive "P")
8386 (cond
8387 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8388 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8390 (org-call-with-arg 'org-sort-entries with-case))))
8392 (defun org-sort-remove-invisible (s)
8393 "Remove invisible links from string S."
8394 (remove-text-properties 0 (length s) org-rm-props s)
8395 (while (string-match org-bracket-link-regexp s)
8396 (setq s (replace-match (if (match-end 2)
8397 (match-string 3 s)
8398 (match-string 1 s)) t t s)))
8399 (let ((st (format " %s " s)))
8400 (while (string-match org-emph-re st)
8401 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8402 (setq s (substring st 1 -1)))
8405 (defvar org-priority-regexp) ; defined later in the file
8407 (defvar org-after-sorting-entries-or-items-hook nil
8408 "Hook that is run after a bunch of entries or items have been sorted.
8409 When children are sorted, the cursor is in the parent line when this
8410 hook gets called. When a region or a plain list is sorted, the cursor
8411 will be in the first entry of the sorted region/list.")
8413 (defun org-sort-entries
8414 (&optional with-case sorting-type getkey-func compare-func property)
8415 "Sort entries on a certain level of an outline tree.
8416 If there is an active region, the entries in the region are sorted.
8417 Else, if the cursor is before the first entry, sort the top-level items.
8418 Else, the children of the entry at point are sorted.
8420 Sorting can be alphabetically, numerically, by date/time as given by
8421 a time stamp, by a property, by priority order, or by a custom function.
8423 The command prompts for the sorting type unless it has been given to the
8424 function through the SORTING-TYPE argument, which needs to be a character,
8425 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8426 precise meaning of each character:
8428 n Numerically, by converting the beginning of the entry/item to a number.
8429 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8430 o By order of TODO keywords.
8431 t By date/time, either the first active time stamp in the entry, or, if
8432 none exist, by the first inactive one.
8433 s By the scheduled date/time.
8434 d By deadline date/time.
8435 c By creation time, which is assumed to be the first inactive time stamp
8436 at the beginning of a line.
8437 p By priority according to the cookie.
8438 r By the value of a property.
8440 Capital letters will reverse the sort order.
8442 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8443 called with point at the beginning of the record. It must return either
8444 a string or a number that should serve as the sorting key for that record.
8446 Comparing entries ignores case by default. However, with an optional argument
8447 WITH-CASE, the sorting considers case as well.
8449 Sorting is done against the visible part of the headlines, it ignores hidden
8450 links."
8451 (interactive "P")
8452 (let ((case-func (if with-case 'identity 'downcase))
8453 (cmstr
8454 ;; The clock marker is lost when using `sort-subr', let's
8455 ;; store the clocking string.
8456 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8457 (save-excursion
8458 (goto-char org-clock-marker)
8459 (looking-back "^.*") (match-string-no-properties 0))))
8460 start beg end stars re re2
8461 txt what tmp)
8462 ;; Find beginning and end of region to sort
8463 (cond
8464 ((org-region-active-p)
8465 ;; we will sort the region
8466 (setq end (region-end)
8467 what "region")
8468 (goto-char (region-beginning))
8469 (if (not (org-at-heading-p)) (outline-next-heading))
8470 (setq start (point)))
8471 ((or (org-at-heading-p)
8472 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8473 ;; we will sort the children of the current headline
8474 (org-back-to-heading)
8475 (setq start (point)
8476 end (progn (org-end-of-subtree t t)
8477 (or (bolp) (insert "\n"))
8478 (org-back-over-empty-lines)
8479 (point))
8480 what "children")
8481 (goto-char start)
8482 (show-subtree)
8483 (outline-next-heading))
8485 ;; we will sort the top-level entries in this file
8486 (goto-char (point-min))
8487 (or (org-at-heading-p) (outline-next-heading))
8488 (setq start (point))
8489 (goto-char (point-max))
8490 (beginning-of-line 1)
8491 (when (looking-at ".*?\\S-")
8492 ;; File ends in a non-white line
8493 (end-of-line 1)
8494 (insert "\n"))
8495 (setq end (point-max))
8496 (setq what "top-level")
8497 (goto-char start)
8498 (show-all)))
8500 (setq beg (point))
8501 (if (>= beg end) (error "Nothing to sort"))
8503 (looking-at "\\(\\*+\\)")
8504 (setq stars (match-string 1)
8505 re (concat "^" (regexp-quote stars) " +")
8506 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8507 txt (buffer-substring beg end))
8508 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8509 (if (and (not (equal stars "*")) (string-match re2 txt))
8510 (error "Region to sort contains a level above the first entry"))
8512 (unless sorting-type
8513 (message
8514 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8515 [t]ime [s]cheduled [d]eadline [c]reated
8516 A/N/P/R/O/F/T/S/D/C means reversed:"
8517 what)
8518 (setq sorting-type (read-char-exclusive))
8520 (unless getkey-func
8521 (and (= (downcase sorting-type) ?f)
8522 (setq getkey-func
8523 (org-icompleting-read "Sort using function: "
8524 obarray 'fboundp t nil nil))
8525 (setq getkey-func (intern getkey-func))))
8527 (and (= (downcase sorting-type) ?r)
8528 (not property)
8529 (setq property
8530 (org-icompleting-read "Property: "
8531 (mapcar 'list (org-buffer-property-keys t))
8532 nil t))))
8534 (message "Sorting entries...")
8536 (save-restriction
8537 (narrow-to-region start end)
8538 (let ((dcst (downcase sorting-type))
8539 (case-fold-search nil)
8540 (now (current-time)))
8541 (sort-subr
8542 (/= dcst sorting-type)
8543 ;; This function moves to the beginning character of the "record" to
8544 ;; be sorted.
8545 (lambda nil
8546 (if (re-search-forward re nil t)
8547 (goto-char (match-beginning 0))
8548 (goto-char (point-max))))
8549 ;; This function moves to the last character of the "record" being
8550 ;; sorted.
8551 (lambda nil
8552 (save-match-data
8553 (condition-case nil
8554 (outline-forward-same-level 1)
8555 (error
8556 (goto-char (point-max))))))
8557 ;; This function returns the value that gets sorted against.
8558 (lambda nil
8559 (cond
8560 ((= dcst ?n)
8561 (if (looking-at org-complex-heading-regexp)
8562 (string-to-number (org-sort-remove-invisible (match-string 4)))
8563 nil))
8564 ((= dcst ?a)
8565 (if (looking-at org-complex-heading-regexp)
8566 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8567 nil))
8568 ((= dcst ?t)
8569 (let ((end (save-excursion (outline-next-heading) (point))))
8570 (if (or (re-search-forward org-ts-regexp end t)
8571 (re-search-forward org-ts-regexp-both end t))
8572 (org-time-string-to-seconds (match-string 0))
8573 (org-float-time now))))
8574 ((= dcst ?c)
8575 (let ((end (save-excursion (outline-next-heading) (point))))
8576 (if (re-search-forward
8577 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8578 end t)
8579 (org-time-string-to-seconds (match-string 0))
8580 (org-float-time now))))
8581 ((= dcst ?s)
8582 (let ((end (save-excursion (outline-next-heading) (point))))
8583 (if (re-search-forward org-scheduled-time-regexp end t)
8584 (org-time-string-to-seconds (match-string 1))
8585 (org-float-time now))))
8586 ((= dcst ?d)
8587 (let ((end (save-excursion (outline-next-heading) (point))))
8588 (if (re-search-forward org-deadline-time-regexp end t)
8589 (org-time-string-to-seconds (match-string 1))
8590 (org-float-time now))))
8591 ((= dcst ?p)
8592 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8593 (string-to-char (match-string 2))
8594 org-default-priority))
8595 ((= dcst ?r)
8596 (or (org-entry-get nil property) ""))
8597 ((= dcst ?o)
8598 (if (looking-at org-complex-heading-regexp)
8599 (- 9999 (length (member (match-string 2)
8600 org-todo-keywords-1)))))
8601 ((= dcst ?f)
8602 (if getkey-func
8603 (progn
8604 (setq tmp (funcall getkey-func))
8605 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8606 tmp)
8607 (error "Invalid key function `%s'" getkey-func)))
8608 (t (error "Invalid sorting type `%c'" sorting-type))))
8610 (cond
8611 ((= dcst ?a) 'string<)
8612 ((= dcst ?f) compare-func)
8613 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8614 (run-hooks 'org-after-sorting-entries-or-items-hook)
8615 ;; Reset the clock marker if needed
8616 (when cmstr
8617 (save-excursion
8618 (goto-char start)
8619 (search-forward cmstr nil t)
8620 (move-marker org-clock-marker (point))))
8621 (message "Sorting entries...done")))
8623 (defun org-do-sort (table what &optional with-case sorting-type)
8624 "Sort TABLE of WHAT according to SORTING-TYPE.
8625 The user will be prompted for the SORTING-TYPE if the call to this
8626 function does not specify it. WHAT is only for the prompt, to indicate
8627 what is being sorted. The sorting key will be extracted from
8628 the car of the elements of the table.
8629 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8630 (unless sorting-type
8631 (message
8632 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8633 what)
8634 (setq sorting-type (read-char-exclusive)))
8635 (let ((dcst (downcase sorting-type))
8636 extractfun comparefun)
8637 ;; Define the appropriate functions
8638 (cond
8639 ((= dcst ?n)
8640 (setq extractfun 'string-to-number
8641 comparefun (if (= dcst sorting-type) '< '>)))
8642 ((= dcst ?a)
8643 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8644 (lambda(x) (downcase (org-sort-remove-invisible x))))
8645 comparefun (if (= dcst sorting-type)
8646 'string<
8647 (lambda (a b) (and (not (string< a b))
8648 (not (string= a b)))))))
8649 ((= dcst ?t)
8650 (setq extractfun
8651 (lambda (x)
8652 (if (or (string-match org-ts-regexp x)
8653 (string-match org-ts-regexp-both x))
8654 (org-float-time
8655 (org-time-string-to-time (match-string 0 x)))
8657 comparefun (if (= dcst sorting-type) '< '>)))
8658 (t (error "Invalid sorting type `%c'" sorting-type)))
8660 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8661 table)
8662 (lambda (a b) (funcall comparefun (car a) (car b))))))
8665 ;;; The orgstruct minor mode
8667 ;; Define a minor mode which can be used in other modes in order to
8668 ;; integrate the org-mode structure editing commands.
8670 ;; This is really a hack, because the org-mode structure commands use
8671 ;; keys which normally belong to the major mode. Here is how it
8672 ;; works: The minor mode defines all the keys necessary to operate the
8673 ;; structure commands, but wraps the commands into a function which
8674 ;; tests if the cursor is currently at a headline or a plain list
8675 ;; item. If that is the case, the structure command is used,
8676 ;; temporarily setting many Org-mode variables like regular
8677 ;; expressions for filling etc. However, when any of those keys is
8678 ;; used at a different location, function uses `key-binding' to look
8679 ;; up if the key has an associated command in another currently active
8680 ;; keymap (minor modes, major mode, global), and executes that
8681 ;; command. There might be problems if any of the keys is otherwise
8682 ;; used as a prefix key.
8684 (defcustom orgstruct-heading-prefix-regexp nil
8685 "Regexp that matches the custom prefix of Org headlines in
8686 orgstruct(++)-mode."
8687 :group 'org
8688 :version "24.4"
8689 :package-version '(Org . "8.0")
8690 :type 'string)
8691 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8693 (defcustom orgstruct-setup-hook nil
8694 "Hook run after orgstruct-mode-map is filled."
8695 :group 'org
8696 :version "24.4"
8697 :package-version '(Org . "8.0")
8698 :type 'hook)
8700 (defvar orgstruct-initialized nil)
8702 (defvar org-local-vars nil
8703 "List of local variables, for use by `orgstruct-mode'.")
8705 ;;;###autoload
8706 (define-minor-mode orgstruct-mode
8707 "Toggle the minor mode `orgstruct-mode'.
8708 This mode is for using Org-mode structure commands in other
8709 modes. The following keys behave as if Org-mode were active, if
8710 the cursor is on a headline, or on a plain list item (both as
8711 defined by Org-mode)."
8712 nil " OrgStruct" (make-sparse-keymap)
8713 (when orgstruct-mode
8714 (org-load-modules-maybe)
8715 (unless orgstruct-initialized
8716 (orgstruct-setup)
8717 (setq orgstruct-initialized t))))
8719 ;;;###autoload
8720 (defun turn-on-orgstruct ()
8721 "Unconditionally turn on `orgstruct-mode'."
8722 (orgstruct-mode 1))
8724 (defvar org-fb-vars nil)
8725 (make-variable-buffer-local 'org-fb-vars)
8726 (defun orgstruct++-mode (&optional arg)
8727 "Toggle `orgstruct-mode', the enhanced version of it.
8728 In addition to setting orgstruct-mode, this also exports all
8729 indentation and autofilling variables from org-mode into the
8730 buffer. It will also recognize item context in multiline items."
8731 (interactive "P")
8732 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8733 (if (< arg 1)
8734 (progn (orgstruct-mode -1)
8735 (mapc (lambda(v)
8736 (org-set-local (car v)
8737 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8738 org-fb-vars))
8739 (orgstruct-mode 1)
8740 (setq org-fb-vars nil)
8741 (let (var val)
8742 (mapc
8743 (lambda (x)
8744 (when (string-match
8745 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8746 (symbol-name (car x)))
8747 (setq var (car x) val (nth 1 x))
8748 (push (list var `(quote ,(eval var))) org-fb-vars)
8749 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8750 org-local-vars)
8751 (org-set-local 'orgstruct-is-++ t))))
8753 (defvar orgstruct-is-++ nil
8754 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8755 (make-variable-buffer-local 'orgstruct-is-++)
8757 ;;;###autoload
8758 (defun turn-on-orgstruct++ ()
8759 "Unconditionally turn on `orgstruct++-mode'."
8760 (orgstruct++-mode 1))
8762 (defun orgstruct-error ()
8763 "Error when there is no default binding for a structure key."
8764 (interactive)
8765 (funcall (if (fboundp 'user-error)
8766 'user-error
8767 'error)
8768 "This key has no function outside structure elements"))
8770 (defun orgstruct-setup ()
8771 "Setup orgstruct keymap."
8772 (dolist (cell '((org-demote . t)
8773 (org-metaleft . t)
8774 (org-metaright . t)
8775 (org-promote . t)
8776 (org-shiftmetaleft . t)
8777 (org-shiftmetaright . t)
8778 org-backward-element
8779 org-backward-heading-same-level
8780 org-ctrl-c-ret
8781 org-ctrl-c-minus
8782 org-ctrl-c-star
8783 org-cycle
8784 org-forward-heading-same-level
8785 org-insert-heading
8786 org-insert-heading-respect-content
8787 org-kill-note-or-show-branches
8788 org-mark-subtree
8789 org-meta-return
8790 org-metadown
8791 org-metaup
8792 org-narrow-to-subtree
8793 org-promote-subtree
8794 org-reveal
8795 org-shiftdown
8796 org-shiftleft
8797 org-shiftmetadown
8798 org-shiftmetaup
8799 org-shiftright
8800 org-shifttab
8801 org-shifttab
8802 org-shiftup
8803 org-show-subtree
8804 org-sort
8805 org-up-element
8806 outline-demote
8807 outline-next-visible-heading
8808 outline-previous-visible-heading
8809 outline-promote
8810 outline-up-heading
8811 show-children))
8812 (let ((f (or (car-safe cell) cell))
8813 (disable-when-heading-prefix (cdr-safe cell)))
8814 (when (fboundp f)
8815 (dolist (binding (nconc (where-is-internal f org-mode-map)
8816 (where-is-internal f outline-mode-map)))
8817 ;; TODO use local-function-key-map
8818 (dolist (rep '(("<tab>" . "TAB")
8819 ("<return>" . "RET")
8820 ("<escape>" . "ESC")
8821 ("<delete>" . "DEL")))
8822 (setq binding (read-kbd-macro (replace-regexp-in-string
8823 (regexp-quote (car rep))
8824 (cdr rep)
8825 (key-description binding)))))
8826 (let ((key (lookup-key orgstruct-mode-map binding)))
8827 (when (or (not key) (numberp key))
8828 (condition-case nil
8829 (org-defkey orgstruct-mode-map
8830 binding
8831 (orgstruct-make-binding f binding disable-when-heading-prefix))
8832 (error nil))))))))
8833 (run-hooks 'orgstruct-setup-hook))
8835 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8836 "Create a function for binding in the structure minor mode.
8837 FUN is the command to call inside a table. KEY is the key that
8838 should be checked in for a command to execute outside of tables.
8839 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8840 if `orgstruct-heading-prefix-regexp' is non-nil."
8841 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8842 (let ((nname name)
8843 (i 0))
8844 (while (fboundp (intern nname))
8845 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8846 (setq name (intern nname)))
8847 (eval
8848 (let ((bindings '((org-heading-regexp
8849 (concat "^"
8850 orgstruct-heading-prefix-regexp
8851 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8852 (org-outline-regexp
8853 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8854 (org-outline-regexp-bol
8855 (concat "^" org-outline-regexp))
8856 (outline-regexp org-outline-regexp)
8857 (outline-heading-end-regexp "\n")
8858 (outline-level 'org-outline-level)
8859 (outline-heading-alist))))
8860 `(defun ,name (arg)
8861 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8862 "Outside of structure, run the binding of `"
8863 (key-description key) "'."
8864 (when disable-when-heading-prefix
8865 (concat
8866 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
8867 "back to the default binding due to limitations of Org's implementation of\n"
8868 "`" (symbol-name fun) "'.")))
8869 (interactive "p")
8870 (let* ((disable
8871 ,(when disable-when-heading-prefix
8872 '(and orgstruct-heading-prefix-regexp
8873 (not (string= orgstruct-heading-prefix-regexp "")))))
8874 (fallback
8875 (or disable
8876 (not
8877 (let* ,bindings
8878 (org-context-p 'headline 'item
8879 ,(when (memq fun '(org-insert-heading))
8880 '(when orgstruct-is-++
8881 'item-body))))))))
8882 (if fallback
8883 (let* ((orgstruct-mode)
8884 (binding (key-binding ,key)))
8885 (if (keymapp binding)
8886 (set-temporary-overlay-map binding)
8887 (let ((func (or binding
8888 (unless disable
8889 'orgstruct-error))))
8890 (when func
8891 (call-interactively func)))))
8892 (org-run-like-in-org-mode
8893 (lambda ()
8894 (interactive)
8895 (let* ,bindings
8896 (call-interactively ',fun)))))))))
8897 name))
8899 (defun org-contextualize-keys (alist contexts)
8900 "Return valid elements in ALIST depending on CONTEXTS.
8902 `org-agenda-custom-commands' or `org-capture-templates' are the
8903 values used for ALIST, and `org-agenda-custom-commands-contexts'
8904 or `org-capture-templates-contexts' are the associated contexts
8905 definitions."
8906 (let ((contexts
8907 ;; normalize contexts
8908 (mapcar
8909 (lambda(c) (cond ((listp (cadr c))
8910 (list (car c) (car c) (cadr c)))
8911 ((string= "" (cadr c))
8912 (list (car c) (car c) (caddr c)))
8913 (t c))) contexts))
8914 (a alist) c r s)
8915 ;; loop over all commands or templates
8916 (while (setq c (pop a))
8917 (let (vrules repl)
8918 (cond
8919 ((not (assoc (car c) contexts))
8920 (push c r))
8921 ((and (assoc (car c) contexts)
8922 (setq vrules (org-contextualize-validate-key
8923 (car c) contexts)))
8924 (mapc (lambda (vr)
8925 (when (not (equal (car vr) (cadr vr)))
8926 (setq repl vr))) vrules)
8927 (if (not repl) (push c r)
8928 (push (cadr repl) s)
8929 (push
8930 (cons (car c)
8931 (cdr (or (assoc (cadr repl) alist)
8932 (error "Undefined key `%s' as contextual replacement for `%s'"
8933 (cadr repl) (car c)))))
8934 r))))))
8935 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8936 (delq
8938 (delete-dups
8939 (mapcar (lambda (x)
8940 (let ((tpl (car x)))
8941 (when (not (delq
8943 (mapcar (lambda(y)
8944 (equal y tpl)) s))) x)))
8945 (reverse r))))))
8947 (defun org-contextualize-validate-key (key contexts)
8948 "Check CONTEXTS for agenda or capture KEY."
8949 (let (r rr res)
8950 (while (setq r (pop contexts))
8951 (mapc
8952 (lambda (rr)
8953 (when
8954 (and (equal key (car r))
8955 (if (functionp rr) (funcall rr)
8956 (or (and (eq (car rr) 'in-file)
8957 (buffer-file-name)
8958 (string-match (cdr rr) (buffer-file-name)))
8959 (and (eq (car rr) 'in-mode)
8960 (string-match (cdr rr) (symbol-name major-mode)))
8961 (and (eq (car rr) 'in-buffer)
8962 (string-match (cdr rr) (buffer-name)))
8963 (when (and (eq (car rr) 'not-in-file)
8964 (buffer-file-name))
8965 (not (string-match (cdr rr) (buffer-file-name))))
8966 (when (eq (car rr) 'not-in-mode)
8967 (not (string-match (cdr rr) (symbol-name major-mode))))
8968 (when (eq (car rr) 'not-in-buffer)
8969 (not (string-match (cdr rr) (buffer-name)))))))
8970 (push r res)))
8971 (car (last r))))
8972 (delete-dups (delq nil res))))
8974 (defun org-context-p (&rest contexts)
8975 "Check if local context is any of CONTEXTS.
8976 Possible values in the list of contexts are `table', `headline', and `item'."
8977 (let ((pos (point)))
8978 (goto-char (point-at-bol))
8979 (prog1 (or (and (memq 'table contexts)
8980 (looking-at "[ \t]*|"))
8981 (and (memq 'headline contexts)
8982 (looking-at org-outline-regexp))
8983 (and (memq 'item contexts)
8984 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8985 (and (memq 'item-body contexts)
8986 (org-in-item-p)))
8987 (goto-char pos))))
8989 (defun org-get-local-variables ()
8990 "Return a list of all local variables in an Org mode buffer."
8991 (let (varlist)
8992 (with-current-buffer (get-buffer-create "*Org tmp*")
8993 (erase-buffer)
8994 (org-mode)
8995 (setq varlist (buffer-local-variables)))
8996 (kill-buffer "*Org tmp*")
8997 (delq nil
8998 (mapcar
8999 (lambda (x)
9000 (setq x
9001 (if (symbolp x)
9002 (list x)
9003 (list (car x) (cdr x))))
9004 (if (and (not (get (car x) 'org-state))
9005 (string-match
9006 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9007 (symbol-name (car x))))
9008 x nil))
9009 varlist))))
9011 (defun org-clone-local-variables (from-buffer &optional regexp)
9012 "Clone local variables from FROM-BUFFER.
9013 Optional argument REGEXP selects variables to clone."
9014 (mapc
9015 (lambda (pair)
9016 (and (symbolp (car pair))
9017 (or (null regexp)
9018 (string-match regexp (symbol-name (car pair))))
9019 (set (make-local-variable (car pair))
9020 (cdr pair))))
9021 (buffer-local-variables from-buffer)))
9023 ;;;###autoload
9024 (defun org-run-like-in-org-mode (cmd)
9025 "Run a command, pretending that the current buffer is in Org-mode.
9026 This will temporarily bind local variables that are typically bound in
9027 Org-mode to the values they have in Org-mode, and then interactively
9028 call CMD."
9029 (org-load-modules-maybe)
9030 (unless org-local-vars
9031 (setq org-local-vars (org-get-local-variables)))
9032 (let (binds)
9033 (dolist (var org-local-vars)
9034 (when (or (not (boundp (car var)))
9035 (eq (symbol-value (car var))
9036 (default-value (car var))))
9037 (push (list (car var) `(quote ,(cadr var))) binds)))
9038 (eval `(let ,binds
9039 (call-interactively (quote ,cmd))))))
9041 ;;;; Archiving
9043 (defun org-get-category (&optional pos force-refresh)
9044 "Get the category applying to position POS."
9045 (save-match-data
9046 (if force-refresh (org-refresh-category-properties))
9047 (let ((pos (or pos (point))))
9048 (or (get-text-property pos 'org-category)
9049 (progn (org-refresh-category-properties)
9050 (get-text-property pos 'org-category))))))
9052 (defun org-refresh-category-properties ()
9053 "Refresh category text properties in the buffer."
9054 (let ((case-fold-search t)
9055 (inhibit-read-only t)
9056 (def-cat (cond
9057 ((null org-category)
9058 (if buffer-file-name
9059 (file-name-sans-extension
9060 (file-name-nondirectory buffer-file-name))
9061 "???"))
9062 ((symbolp org-category) (symbol-name org-category))
9063 (t org-category)))
9064 beg end cat pos optionp)
9065 (org-with-silent-modifications
9066 (save-excursion
9067 (save-restriction
9068 (widen)
9069 (goto-char (point-min))
9070 (put-text-property (point) (point-max) 'org-category def-cat)
9071 (while (re-search-forward
9072 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9073 (setq pos (match-end 0)
9074 optionp (equal (char-after (match-beginning 0)) ?#)
9075 cat (org-trim (match-string 2)))
9076 (if optionp
9077 (setq beg (point-at-bol) end (point-max))
9078 (org-back-to-heading t)
9079 (setq beg (point) end (org-end-of-subtree t t)))
9080 (put-text-property beg end 'org-category cat)
9081 (put-text-property beg end 'org-category-position beg)
9082 (goto-char pos)))))))
9084 (defun org-refresh-properties (dprop tprop)
9085 "Refresh buffer text properties.
9086 DPROP is the drawer property and TPROP is the corresponding text
9087 property to set."
9088 (let ((case-fold-search t)
9089 (inhibit-read-only t) p)
9090 (org-with-silent-modifications
9091 (save-excursion
9092 (save-restriction
9093 (widen)
9094 (goto-char (point-min))
9095 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9096 (setq p (org-match-string-no-properties 1))
9097 (save-excursion
9098 (org-back-to-heading t)
9099 (put-text-property
9100 (point-at-bol) (point-at-eol) tprop p))))))))
9103 ;;;; Link Stuff
9105 ;;; Link abbreviations
9107 (defun org-link-expand-abbrev (link)
9108 "Apply replacements as defined in `org-link-abbrev-alist'."
9109 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9110 (let* ((key (match-string 1 link))
9111 (as (or (assoc key org-link-abbrev-alist-local)
9112 (assoc key org-link-abbrev-alist)))
9113 (tag (and (match-end 2) (match-string 3 link)))
9114 rpl)
9115 (if (not as)
9116 link
9117 (setq rpl (cdr as))
9118 (cond
9119 ((symbolp rpl) (funcall rpl tag))
9120 ((string-match "%(\\([^)]+\\))" rpl)
9121 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9122 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9123 ((string-match "%h" rpl)
9124 (replace-match (url-hexify-string (or tag "")) t t rpl))
9125 (t (concat rpl tag)))))
9126 link))
9128 ;;; Storing and inserting links
9130 (defvar org-insert-link-history nil
9131 "Minibuffer history for links inserted with `org-insert-link'.")
9133 (defvar org-stored-links nil
9134 "Contains the links stored with `org-store-link'.")
9136 (defvar org-store-link-plist nil
9137 "Plist with info about the most recently link created with `org-store-link'.")
9139 (defvar org-link-protocols nil
9140 "Link protocols added to Org-mode using `org-add-link-type'.")
9142 (defvar org-store-link-functions nil
9143 "List of functions that are called to create and store a link.
9144 Each function will be called in turn until one returns a non-nil
9145 value. Each function should check if it is responsible for creating
9146 this link (for example by looking at the major mode).
9147 If not, it must exit and return nil.
9148 If yes, it should return a non-nil value after a calling
9149 `org-store-link-props' with a list of properties and values.
9150 Special properties are:
9152 :type The link prefix, like \"http\". This must be given.
9153 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9154 This is obligatory as well.
9155 :description Optional default description for the second pair
9156 of brackets in an Org-mode link. The user can still change
9157 this when inserting this link into an Org-mode buffer.
9159 In addition to these, any additional properties can be specified
9160 and then used in capture templates.")
9162 (defun org-add-link-type (type &optional follow export)
9163 "Add TYPE to the list of `org-link-types'.
9164 Re-compute all regular expressions depending on `org-link-types'
9166 FOLLOW and EXPORT are two functions.
9168 FOLLOW should take the link path as the single argument and do whatever
9169 is necessary to follow the link, for example find a file or display
9170 a mail message.
9172 EXPORT should format the link path for export to one of the export formats.
9173 It should be a function accepting three arguments:
9175 path the path of the link, the text after the prefix (like \"http:\")
9176 desc the description of the link, if any, or a description added by
9177 org-export-normalize-links if there is none
9178 format the export format, a symbol like `html' or `latex' or `ascii'..
9180 The function may use the FORMAT information to return different values
9181 depending on the format. The return value will be put literally into
9182 the exported file. If the return value is nil, this means Org should
9183 do what it normally does with links which do not have EXPORT defined.
9185 Org-mode has a built-in default for exporting links. If you are happy with
9186 this default, there is no need to define an export function for the link
9187 type. For a simple example of an export function, see `org-bbdb.el'."
9188 (add-to-list 'org-link-types type t)
9189 (org-make-link-regexps)
9190 (if (assoc type org-link-protocols)
9191 (setcdr (assoc type org-link-protocols) (list follow export))
9192 (push (list type follow export) org-link-protocols)))
9194 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9195 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9197 ;;;###autoload
9198 (defun org-store-link (arg)
9199 "\\<org-mode-map>Store an org-link to the current location.
9200 This link is added to `org-stored-links' and can later be inserted
9201 into an org-buffer with \\[org-insert-link].
9203 For some link types, a prefix arg is interpreted.
9204 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9205 For file links, arg negates `org-context-in-file-links'.
9207 A double prefix arg force skipping storing functions that are not
9208 part of Org's core."
9209 (interactive "P")
9210 (org-load-modules-maybe)
9211 (setq org-store-link-plist nil) ; reset
9212 (org-with-limited-levels
9213 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9214 (cond
9215 ((and (not (equal arg '(16)))
9216 (setq sfuns
9217 (delq
9218 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9219 org-store-link-functions))
9220 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9221 (or (and (cdr sfuns)
9222 (funcall (intern
9223 (completing-read "Which function for creating the link? "
9224 sfunsn t (car sfunsn)))))
9225 (funcall (caar sfuns)))
9226 (setq link (plist-get org-store-link-plist :link)
9227 desc (or (plist-get org-store-link-plist :description) link))))
9228 ((org-src-edit-buffer-p)
9229 (let (label gc)
9230 (while (or (not label)
9231 (save-excursion
9232 (save-restriction
9233 (widen)
9234 (goto-char (point-min))
9235 (re-search-forward
9236 (regexp-quote (format org-coderef-label-format label))
9237 nil t))))
9238 (when label (message "Label exists already") (sit-for 2))
9239 (setq label (read-string "Code line label: " label)))
9240 (end-of-line 1)
9241 (setq link (format org-coderef-label-format label))
9242 (setq gc (- 79 (length link)))
9243 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9244 (insert link)
9245 (setq link (concat "(" label ")") desc nil)))
9247 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9248 ;; We are in the agenda, link to referenced location
9249 (let ((m (or (get-text-property (point) 'org-hd-marker)
9250 (get-text-property (point) 'org-marker))))
9251 (when m
9252 (org-with-point-at m
9253 (setq agenda-link
9254 (if (org-called-interactively-p 'any)
9255 (call-interactively 'org-store-link)
9256 (org-store-link nil)))))))
9258 ((eq major-mode 'calendar-mode)
9259 (let ((cd (calendar-cursor-to-date)))
9260 (setq link
9261 (format-time-string
9262 (car org-time-stamp-formats)
9263 (apply 'encode-time
9264 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9265 nil nil nil))))
9266 (org-store-link-props :type "calendar" :date cd)))
9268 ((eq major-mode 'help-mode)
9269 (setq link (concat "help:" (save-excursion
9270 (goto-char (point-min))
9271 (looking-at "^[^ ]+")
9272 (match-string 0))))
9273 (org-store-link-props :type "help"))
9275 ((eq major-mode 'w3-mode)
9276 (setq cpltxt (if (and (buffer-name)
9277 (not (string-match "Untitled" (buffer-name))))
9278 (buffer-name)
9279 (url-view-url t))
9280 link (url-view-url t))
9281 (org-store-link-props :type "w3" :url (url-view-url t)))
9283 ((setq search (run-hook-with-args-until-success
9284 'org-create-file-search-functions))
9285 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9286 "::" search))
9287 (setq cpltxt (or description link)))
9289 ((eq major-mode 'image-mode)
9290 (setq cpltxt (concat "file:"
9291 (abbreviate-file-name buffer-file-name))
9292 link cpltxt)
9293 (org-store-link-props :type "image" :file buffer-file-name))
9295 ((eq major-mode 'dired-mode)
9296 ;; link to the file in the current line
9297 (let ((file (dired-get-filename nil t)))
9298 (setq file (if file
9299 (abbreviate-file-name
9300 (expand-file-name (dired-get-filename nil t)))
9301 ;; otherwise, no file so use current directory.
9302 default-directory))
9303 (setq cpltxt (concat "file:" file)
9304 link cpltxt)))
9306 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9307 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9308 (cond
9309 ((org-in-regexp "<<\\(.*?\\)>>")
9310 (setq cpltxt
9311 (concat "file:"
9312 (abbreviate-file-name
9313 (buffer-file-name (buffer-base-buffer)))
9314 "::" (match-string 1))
9315 link cpltxt))
9316 ((and (featurep 'org-id)
9317 (or (eq org-id-link-to-org-use-id t)
9318 (and (org-called-interactively-p 'any)
9319 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9320 (and (eq org-id-link-to-org-use-id
9321 'create-if-interactive-and-no-custom-id)
9322 (not custom-id))))
9323 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9324 ;; We can make a link using the ID.
9325 (setq link (condition-case nil
9326 (prog1 (org-id-store-link)
9327 (setq desc (plist-get org-store-link-plist :description)))
9328 (error
9329 ;; probably before first headline, link to file only
9330 (concat "file:"
9331 (abbreviate-file-name
9332 (buffer-file-name (buffer-base-buffer))))))))
9334 ;; Just link to current headline
9335 (setq cpltxt (concat "file:"
9336 (abbreviate-file-name
9337 (buffer-file-name (buffer-base-buffer)))))
9338 ;; Add a context search string
9339 (when (org-xor org-context-in-file-links arg)
9340 (let* ((ee (org-element-at-point))
9341 (et (org-element-type ee))
9342 (ev (plist-get (cadr ee) :value)))
9343 (setq txt (cond
9344 ((org-at-heading-p) nil)
9345 ((eq et 'keyword) ev)
9346 ((org-region-active-p)
9347 (buffer-substring (region-beginning) (region-end)))))
9348 (when (or (null txt) (string-match "\\S-" txt))
9349 (setq cpltxt
9350 (concat cpltxt "::"
9351 (condition-case nil
9352 (org-make-org-heading-search-string txt)
9353 (error "")))
9354 desc (or (and (eq et 'keyword) ev)
9355 (nth 4 (ignore-errors (org-heading-components)))
9356 "NONE")))))
9357 (if (string-match "::\\'" cpltxt)
9358 (setq cpltxt (substring cpltxt 0 -2)))
9359 (setq link cpltxt))))
9361 ((buffer-file-name (buffer-base-buffer))
9362 ;; Just link to this file here.
9363 (setq cpltxt (concat "file:"
9364 (abbreviate-file-name
9365 (buffer-file-name (buffer-base-buffer)))))
9366 ;; Add a context string
9367 (when (org-xor org-context-in-file-links arg)
9368 (setq txt (if (org-region-active-p)
9369 (buffer-substring (region-beginning) (region-end))
9370 (buffer-substring (point-at-bol) (point-at-eol))))
9371 ;; Only use search option if there is some text.
9372 (when (string-match "\\S-" txt)
9373 (setq cpltxt
9374 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9375 desc "NONE")))
9376 (setq link cpltxt))
9378 ((org-called-interactively-p 'interactive)
9379 (user-error "No method for storing a link from this buffer"))
9381 (t (setq link nil)))
9383 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9384 (setq link (or link cpltxt)
9385 desc (or desc cpltxt))
9386 (cond ((equal desc "NONE") (setq desc nil))
9387 ((string-match org-bracket-link-regexp desc)
9388 (setq desc (replace-regexp-in-string
9389 org-bracket-link-regexp
9390 (concat "\\3" (if (equal (length (match-string 0 desc))
9391 (length desc)) "*" "")) desc))))
9393 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9394 (progn
9395 (setq org-stored-links
9396 (cons (list link desc) org-stored-links))
9397 (message "Stored: %s" (or desc link))
9398 (when custom-id
9399 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9400 "::#" custom-id))
9401 (setq org-stored-links
9402 (cons (list link desc) org-stored-links))))
9403 (or agenda-link (and link (org-make-link-string link desc)))))))
9405 (defun org-store-link-props (&rest plist)
9406 "Store link properties, extract names and addresses."
9407 (let (x adr)
9408 (when (setq x (plist-get plist :from))
9409 (setq adr (mail-extract-address-components x))
9410 (setq plist (plist-put plist :fromname (car adr)))
9411 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9412 (when (setq x (plist-get plist :to))
9413 (setq adr (mail-extract-address-components x))
9414 (setq plist (plist-put plist :toname (car adr)))
9415 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9416 (let ((from (plist-get plist :from))
9417 (to (plist-get plist :to)))
9418 (when (and from to org-from-is-user-regexp)
9419 (setq plist
9420 (plist-put plist :fromto
9421 (if (string-match org-from-is-user-regexp from)
9422 (concat "to %t")
9423 (concat "from %f"))))))
9424 (setq org-store-link-plist plist))
9426 (defun org-add-link-props (&rest plist)
9427 "Add these properties to the link property list."
9428 (let (key value)
9429 (while plist
9430 (setq key (pop plist) value (pop plist))
9431 (setq org-store-link-plist
9432 (plist-put org-store-link-plist key value)))))
9434 (defun org-email-link-description (&optional fmt)
9435 "Return the description part of an email link.
9436 This takes information from `org-store-link-plist' and formats it
9437 according to FMT (default from `org-email-link-description-format')."
9438 (setq fmt (or fmt org-email-link-description-format))
9439 (let* ((p org-store-link-plist)
9440 (to (plist-get p :toaddress))
9441 (from (plist-get p :fromaddress))
9442 (table
9443 (list
9444 (cons "%c" (plist-get p :fromto))
9445 (cons "%F" (plist-get p :from))
9446 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9447 (cons "%T" (plist-get p :to))
9448 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9449 (cons "%s" (plist-get p :subject))
9450 (cons "%d" (plist-get p :date))
9451 (cons "%m" (plist-get p :message-id)))))
9452 (when (string-match "%c" fmt)
9453 ;; Check if the user wrote this message
9454 (if (and org-from-is-user-regexp from to
9455 (save-match-data (string-match org-from-is-user-regexp from)))
9456 (setq fmt (replace-match "to %t" t t fmt))
9457 (setq fmt (replace-match "from %f" t t fmt))))
9458 (org-replace-escapes fmt table)))
9460 (defun org-make-org-heading-search-string (&optional string)
9461 "Make search string for the current headline or STRING."
9462 (let ((s (or string
9463 (and (derived-mode-p 'org-mode)
9464 (save-excursion
9465 (org-back-to-heading t)
9466 (org-element-property :raw-value (org-element-at-point))))))
9467 (lines org-context-in-file-links))
9468 (or string (setq s (concat "*" s))) ; Add * for headlines
9469 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9470 (when (and string (integerp lines) (> lines 0))
9471 (let ((slines (org-split-string s "\n")))
9472 (when (< lines (length slines))
9473 (setq s (mapconcat
9474 'identity
9475 (reverse (nthcdr (- (length slines) lines)
9476 (reverse slines))) "\n")))))
9477 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9479 (defun org-make-link-string (link &optional description)
9480 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9481 (unless (string-match "\\S-" link)
9482 (error "Empty link"))
9483 (when (and description
9484 (stringp description)
9485 (not (string-match "\\S-" description)))
9486 (setq description nil))
9487 (when (stringp description)
9488 ;; Remove brackets from the description, they are fatal.
9489 (while (string-match "\\[" description)
9490 (setq description (replace-match "{" t t description)))
9491 (while (string-match "\\]" description)
9492 (setq description (replace-match "}" t t description))))
9493 (when (equal link description)
9494 ;; No description needed, it is identical
9495 (setq description nil))
9496 (when (and (not description)
9497 (not (string-match (org-image-file-name-regexp) link))
9498 (not (equal link (org-link-escape link))))
9499 (setq description (org-extract-attributes link)))
9500 (setq link
9501 (cond ((string-match (org-image-file-name-regexp) link) link)
9502 ((string-match org-link-types-re link)
9503 (concat (match-string 1 link)
9504 (org-link-escape (substring link (match-end 1)))))
9505 (t (org-link-escape link))))
9506 (concat "[[" link "]"
9507 (if description (concat "[" description "]") "")
9508 "]"))
9510 (defconst org-link-escape-chars
9511 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9512 "List of characters that should be escaped in link.
9513 This is the list that is used for internal purposes.")
9515 (defconst org-link-escape-chars-browser
9516 '(?\ )
9517 "List of escapes for characters that are problematic in links.
9518 This is the list that is used before handing over to the browser.")
9520 (defun org-link-escape (text &optional table merge)
9521 "Return percent escaped representation of TEXT.
9522 TEXT is a string with the text to escape.
9523 Optional argument TABLE is a list with characters that should be
9524 escaped. When nil, `org-link-escape-chars' is used.
9525 If optional argument MERGE is set, merge TABLE into
9526 `org-link-escape-chars'."
9527 (cond
9528 ((and table merge)
9529 (mapc (lambda (defchr)
9530 (unless (member defchr table)
9531 (setq table (cons defchr table)))) org-link-escape-chars))
9532 ((null table)
9533 (setq table org-link-escape-chars)))
9534 (mapconcat
9535 (lambda (char)
9536 (if (or (member char table)
9537 (and (or (< char 32) (= char 37) (> char 126))
9538 org-url-hexify-p))
9539 (mapconcat (lambda (sequence-element)
9540 (format "%%%.2X" sequence-element))
9541 (or (encode-coding-char char 'utf-8)
9542 (error "Unable to percent escape character: %s"
9543 (char-to-string char))) "")
9544 (char-to-string char))) text ""))
9546 (defun org-link-unescape (str)
9547 "Unhex hexified Unicode strings as returned from the JavaScript function
9548 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9549 (unless (and (null str) (string= "" str))
9550 (let ((pos 0) (case-fold-search t) unhexed)
9551 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9552 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9553 (setq str (replace-match unhexed t t str))
9554 (setq pos (+ pos (length unhexed))))))
9555 str)
9557 (defun org-link-unescape-compound (hex)
9558 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9559 Note: this function also decodes single byte encodings like
9560 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9561 (save-match-data
9562 (let* ((bytes (cdr (split-string hex "%")))
9563 (ret "")
9564 (eat 0)
9565 (sum 0))
9566 (while bytes
9567 (let* ((val (string-to-number (pop bytes) 16))
9568 (shift-xor
9569 (if (= 0 eat)
9570 (cond
9571 ((>= val 252) (cons 6 252))
9572 ((>= val 248) (cons 5 248))
9573 ((>= val 240) (cons 4 240))
9574 ((>= val 224) (cons 3 224))
9575 ((>= val 192) (cons 2 192))
9576 (t (cons 0 0)))
9577 (cons 6 128))))
9578 (if (>= val 192) (setq eat (car shift-xor)))
9579 (setq val (logxor val (cdr shift-xor)))
9580 (setq sum (+ (lsh sum (car shift-xor)) val))
9581 (if (> eat 0) (setq eat (- eat 1)))
9582 (cond
9583 ((= 0 eat) ;multi byte
9584 (setq ret (concat ret (org-char-to-string sum)))
9585 (setq sum 0))
9586 ((not bytes) ; single byte(s)
9587 (setq ret (org-link-unescape-single-byte-sequence hex))))
9588 )) ;; end (while bytes
9589 ret )))
9591 (defun org-link-unescape-single-byte-sequence (hex)
9592 "Unhexify hex-encoded single byte character sequences."
9593 (mapconcat (lambda (byte)
9594 (char-to-string (string-to-number byte 16)))
9595 (cdr (split-string hex "%")) ""))
9597 (defun org-xor (a b)
9598 "Exclusive or."
9599 (if a (not b) b))
9601 (defun org-fixup-message-id-for-http (s)
9602 "Replace special characters in a message id, so it can be used in an http query."
9603 (when (string-match "%" s)
9604 (setq s (mapconcat (lambda (c)
9605 (if (eq c ?%)
9606 "%25"
9607 (char-to-string c)))
9608 s "")))
9609 (while (string-match "<" s)
9610 (setq s (replace-match "%3C" t t s)))
9611 (while (string-match ">" s)
9612 (setq s (replace-match "%3E" t t s)))
9613 (while (string-match "@" s)
9614 (setq s (replace-match "%40" t t s)))
9617 (defun org-link-prettify (link)
9618 "Return a human-readable representation of LINK.
9619 The car of LINK must be a raw link the cdr of LINK must be either
9620 a link description or nil."
9621 (let ((desc (or (cadr link) "<no description>")))
9622 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9623 "<" (car link) ">")))
9625 ;;;###autoload
9626 (defun org-insert-link-global ()
9627 "Insert a link like Org-mode does.
9628 This command can be called in any mode to insert a link in Org-mode syntax."
9629 (interactive)
9630 (org-load-modules-maybe)
9631 (org-run-like-in-org-mode 'org-insert-link))
9633 (defun org-insert-all-links (&optional keep)
9634 "Insert all links in `org-stored-links'."
9635 (interactive "P")
9636 (let ((links (copy-sequence org-stored-links)) l)
9637 (while (setq l (if keep (pop links) (pop org-stored-links)))
9638 (insert "- ")
9639 (org-insert-link nil (car l) (cadr l))
9640 (insert "\n"))))
9642 (defun org-link-fontify-links-to-this-file ()
9643 "Fontify links to the current file in `org-stored-links'."
9644 (let ((f (buffer-file-name)) a b)
9645 (setq a (mapcar (lambda(l)
9646 (let ((ll (car l)))
9647 (when (and (string-match "^file:\\(.+\\)::" ll)
9648 (equal f (expand-file-name (match-string 1 ll))))
9649 ll)))
9650 org-stored-links))
9651 (when (featurep 'org-id)
9652 (setq b (mapcar (lambda(l)
9653 (let ((ll (car l)))
9654 (when (and (string-match "^id:\\(.+\\)$" ll)
9655 (equal f (expand-file-name
9656 (or (org-id-find-id-file
9657 (match-string 1 ll)) ""))))
9658 ll)))
9659 org-stored-links)))
9660 (mapcar (lambda(l)
9661 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9662 (delq nil (append a b)))))
9664 (defvar org-link-links-in-this-file nil)
9665 (defun org-insert-link (&optional complete-file link-location default-description)
9666 "Insert a link. At the prompt, enter the link.
9668 Completion can be used to insert any of the link protocol prefixes like
9669 http or ftp in use.
9671 The history can be used to select a link previously stored with
9672 `org-store-link'. When the empty string is entered (i.e. if you just
9673 press RET at the prompt), the link defaults to the most recently
9674 stored link. As SPC triggers completion in the minibuffer, you need to
9675 use M-SPC or C-q SPC to force the insertion of a space character.
9677 You will also be prompted for a description, and if one is given, it will
9678 be displayed in the buffer instead of the link.
9680 If there is already a link at point, this command will allow you to edit link
9681 and description parts.
9683 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9684 be selected using completion. The path to the file will be relative to the
9685 current directory if the file is in the current directory or a subdirectory.
9686 Otherwise, the link will be the absolute path as completed in the minibuffer
9687 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9688 option `org-link-file-path-type'.
9690 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9691 the current directory or below.
9693 With three \\[universal-argument] prefixes, negate the meaning of
9694 `org-keep-stored-link-after-insertion'.
9696 If `org-make-link-description-function' is non-nil, this function will be
9697 called with the link target, and the result will be the default
9698 link description.
9700 If the LINK-LOCATION parameter is non-nil, this value will be
9701 used as the link location instead of reading one interactively.
9703 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9704 be used as the default description."
9705 (interactive "P")
9706 (let* ((wcf (current-window-configuration))
9707 (origbuf (current-buffer))
9708 (region (if (org-region-active-p)
9709 (buffer-substring (region-beginning) (region-end))))
9710 (remove (and region (list (region-beginning) (region-end))))
9711 (desc region)
9712 tmphist ; byte-compile incorrectly complains about this
9713 (link link-location)
9714 (abbrevs org-link-abbrev-alist-local)
9715 entry file all-prefixes auto-desc)
9716 (cond
9717 (link-location) ; specified by arg, just use it.
9718 ((org-in-regexp org-bracket-link-regexp 1)
9719 ;; We do have a link at point, and we are going to edit it.
9720 (setq remove (list (match-beginning 0) (match-end 0)))
9721 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9722 (setq link (read-string "Link: "
9723 (org-link-unescape
9724 (org-match-string-no-properties 1)))))
9725 ((or (org-in-regexp org-angle-link-re)
9726 (org-in-regexp org-plain-link-re))
9727 ;; Convert to bracket link
9728 (setq remove (list (match-beginning 0) (match-end 0))
9729 link (read-string "Link: "
9730 (org-remove-angle-brackets (match-string 0)))))
9731 ((member complete-file '((4) (16)))
9732 ;; Completing read for file names.
9733 (setq link (org-file-complete-link complete-file)))
9735 ;; Read link, with completion for stored links.
9736 (org-link-fontify-links-to-this-file)
9737 (org-switch-to-buffer-other-window "*Org Links*")
9738 (with-current-buffer "*Org Links*"
9739 (erase-buffer)
9740 (insert "Insert a link.
9741 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9742 (when org-stored-links
9743 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9744 (insert (mapconcat 'org-link-prettify
9745 (reverse org-stored-links) "\n")))
9746 (goto-char (point-min)))
9747 (let ((cw (selected-window)))
9748 (select-window (get-buffer-window "*Org Links*" 'visible))
9749 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9750 (unless (pos-visible-in-window-p (point-max))
9751 (org-fit-window-to-buffer))
9752 (and (window-live-p cw) (select-window cw)))
9753 ;; Fake a link history, containing the stored links.
9754 (setq tmphist (append (mapcar 'car org-stored-links)
9755 org-insert-link-history))
9756 (setq all-prefixes (append (mapcar 'car abbrevs)
9757 (mapcar 'car org-link-abbrev-alist)
9758 org-link-types))
9759 (unwind-protect
9760 (progn
9761 (setq link
9762 (org-completing-read
9763 "Link: "
9764 (append
9765 (mapcar (lambda (x) (concat x ":"))
9766 all-prefixes)
9767 (mapcar 'car org-stored-links))
9768 nil nil nil
9769 'tmphist
9770 (caar org-stored-links)))
9771 (if (not (string-match "\\S-" link))
9772 (error "No link selected"))
9773 (mapc (lambda(l)
9774 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9775 org-stored-links)
9776 (if (or (member link all-prefixes)
9777 (and (equal ":" (substring link -1))
9778 (member (substring link 0 -1) all-prefixes)
9779 (setq link (substring link 0 -1))))
9780 (setq link (with-current-buffer origbuf
9781 (org-link-try-special-completion link)))))
9782 (set-window-configuration wcf)
9783 (kill-buffer "*Org Links*"))
9784 (setq entry (assoc link org-stored-links))
9785 (or entry (push link org-insert-link-history))
9786 (setq desc (or desc (nth 1 entry)))))
9788 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9789 (not org-keep-stored-link-after-insertion))
9790 (setq org-stored-links (delq (assoc link org-stored-links)
9791 org-stored-links)))
9793 (if (string-match org-plain-link-re link)
9794 ;; URL-like link, normalize the use of angular brackets.
9795 (setq link (org-remove-angle-brackets link)))
9797 ;; Check if we are linking to the current file with a search
9798 ;; option If yes, simplify the link by using only the search
9799 ;; option.
9800 (when (and buffer-file-name
9801 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9802 (let* ((path (match-string 1 link))
9803 (case-fold-search nil)
9804 (search (match-string 2 link)))
9805 (save-match-data
9806 (if (equal (file-truename buffer-file-name) (file-truename path))
9807 ;; We are linking to this same file, with a search option
9808 (setq link search)))))
9810 ;; Check if we can/should use a relative path. If yes, simplify the link
9811 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9812 (let* ((type (match-string 1 link))
9813 (path (match-string 2 link))
9814 (origpath path)
9815 (case-fold-search nil))
9816 (cond
9817 ((or (eq org-link-file-path-type 'absolute)
9818 (equal complete-file '(16)))
9819 (setq path (abbreviate-file-name (expand-file-name path))))
9820 ((eq org-link-file-path-type 'noabbrev)
9821 (setq path (expand-file-name path)))
9822 ((eq org-link-file-path-type 'relative)
9823 (setq path (file-relative-name path)))
9825 (save-match-data
9826 (if (string-match (concat "^" (regexp-quote
9827 (expand-file-name
9828 (file-name-as-directory
9829 default-directory))))
9830 (expand-file-name path))
9831 ;; We are linking a file with relative path name.
9832 (setq path (substring (expand-file-name path)
9833 (match-end 0)))
9834 (setq path (abbreviate-file-name (expand-file-name path)))))))
9835 (setq link (concat type path))
9836 (if (equal desc origpath)
9837 (setq desc path))))
9839 (if org-make-link-description-function
9840 (setq desc
9841 (or (condition-case nil
9842 (funcall org-make-link-description-function link desc)
9843 (error (progn (message "Can't get link description from `%s'"
9844 (symbol-name org-make-link-description-function))
9845 (sit-for 2) nil)))
9846 (read-string "Description: " default-description)))
9847 (if default-description (setq desc default-description)
9848 (setq desc (or (and auto-desc desc)
9849 (read-string "Description: " desc)))))
9851 (unless (string-match "\\S-" desc) (setq desc nil))
9852 (if remove (apply 'delete-region remove))
9853 (insert (org-make-link-string link desc))))
9855 (defun org-link-try-special-completion (type)
9856 "If there is completion support for link type TYPE, offer it."
9857 (let ((fun (intern (concat "org-" type "-complete-link"))))
9858 (if (functionp fun)
9859 (funcall fun)
9860 (read-string "Link (no completion support): " (concat type ":")))))
9862 (defun org-file-complete-link (&optional arg)
9863 "Create a file link using completion."
9864 (let (file link)
9865 (setq file (org-iread-file-name "File: "))
9866 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9867 (pwd1 (file-name-as-directory (abbreviate-file-name
9868 (expand-file-name ".")))))
9869 (cond
9870 ((equal arg '(16))
9871 (setq link (concat
9872 "file:"
9873 (abbreviate-file-name (expand-file-name file)))))
9874 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9875 (setq link (concat "file:" (match-string 1 file))))
9876 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9877 (expand-file-name file))
9878 (setq link (concat
9879 "file:" (match-string 1 (expand-file-name file)))))
9880 (t (setq link (concat "file:" file)))))
9881 link))
9883 (defun org-iread-file-name (&rest args)
9884 "Read-file-name using `ido-mode' speedup if available.
9885 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9886 See `read-file-name' for a description of parameters."
9887 (org-without-partial-completion
9888 (if (and org-completion-use-ido
9889 (fboundp 'ido-read-file-name)
9890 (boundp 'ido-mode) ido-mode
9891 (listp (second args)))
9892 (let ((ido-enter-matching-directory nil))
9893 (apply 'ido-read-file-name args))
9894 (apply 'read-file-name args))))
9896 (defun org-completing-read (&rest args)
9897 "Completing-read with SPACE being a normal character."
9898 (let ((enable-recursive-minibuffers t)
9899 (minibuffer-local-completion-map
9900 (copy-keymap minibuffer-local-completion-map)))
9901 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9902 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9903 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9904 (apply 'org-icompleting-read args)))
9906 (defun org-completing-read-no-i (&rest args)
9907 (let (org-completion-use-ido org-completion-use-iswitchb)
9908 (apply 'org-completing-read args)))
9910 (defun org-iswitchb-completing-read (prompt choices &rest args)
9911 "Use iswitch as a completing-read replacement to choose from choices.
9912 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9913 from."
9914 (let* ((iswitchb-use-virtual-buffers nil)
9915 (iswitchb-make-buflist-hook
9916 (lambda ()
9917 (setq iswitchb-temp-buflist choices))))
9918 (iswitchb-read-buffer prompt)))
9920 (defun org-icompleting-read (&rest args)
9921 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9922 (org-without-partial-completion
9923 (if (and org-completion-use-ido
9924 (fboundp 'ido-completing-read)
9925 (boundp 'ido-mode) ido-mode
9926 (listp (second args)))
9927 (let ((ido-enter-matching-directory nil))
9928 (apply 'ido-completing-read (concat (car args))
9929 (if (consp (car (nth 1 args)))
9930 (mapcar 'car (nth 1 args))
9931 (nth 1 args))
9932 (cddr args)))
9933 (if (and org-completion-use-iswitchb
9934 (boundp 'iswitchb-mode) iswitchb-mode
9935 (listp (second args)))
9936 (apply 'org-iswitchb-completing-read (concat (car args))
9937 (if (consp (car (nth 1 args)))
9938 (mapcar 'car (nth 1 args))
9939 (nth 1 args))
9940 (cddr args))
9941 (apply 'completing-read args)))))
9943 (defun org-extract-attributes (s)
9944 "Extract the attributes cookie from a string and set as text property."
9945 (let (a attr (start 0) key value)
9946 (save-match-data
9947 (when (string-match "{{\\([^}]+\\)}}$" s)
9948 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9949 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9950 (setq key (match-string 1 a) value (match-string 2 a)
9951 start (match-end 0)
9952 attr (plist-put attr (intern key) value))))
9953 (org-add-props s nil 'org-attr attr))
9956 (defun org-extract-attributes-from-string (tag)
9957 (let (key value attr)
9958 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9959 (setq key (match-string 1 tag) value (match-string 2 tag)
9960 tag (replace-match "" t t tag)
9961 attr (plist-put attr (intern key) value)))
9962 (cons tag attr)))
9964 (defun org-attributes-to-string (plist)
9965 "Format a property list into an HTML attribute list."
9966 (let ((s "") key value)
9967 (while plist
9968 (setq key (pop plist) value (pop plist))
9969 (and value
9970 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9973 ;;; Opening/following a link
9975 (defvar org-link-search-failed nil)
9977 (defvar org-open-link-functions nil
9978 "Hook for functions finding a plain text link.
9979 These functions must take a single argument, the link content.
9980 They will be called for links that look like [[link text][description]]
9981 when LINK TEXT does not have a protocol like \"http:\" and does not look
9982 like a filename (e.g. \"./blue.png\").
9984 These functions will be called *before* Org attempts to resolve the
9985 link by doing text searches in the current buffer - so if you want a
9986 link \"[[target]]\" to still find \"<<target>>\", your function should
9987 handle this as a special case.
9989 When the function does handle the link, it must return a non-nil value.
9990 If it decides that it is not responsible for this link, it must return
9991 nil to indicate that that Org-mode can continue with other options
9992 like exact and fuzzy text search.")
9994 (defun org-next-link (&optional search-backward)
9995 "Move forward to the next link.
9996 If the link is in hidden text, expose it."
9997 (interactive "P")
9998 (when (and org-link-search-failed (eq this-command last-command))
9999 (goto-char (point-min))
10000 (message "Link search wrapped back to beginning of buffer"))
10001 (setq org-link-search-failed nil)
10002 (let* ((pos (point))
10003 (ct (org-context))
10004 (a (assoc :link ct))
10005 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10006 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10007 ((looking-at org-any-link-re)
10008 ;; Don't stay stuck at link without an org-link face
10009 (forward-char (if search-backward -1 1))))
10010 (if (funcall srch-fun org-any-link-re nil t)
10011 (progn
10012 (goto-char (match-beginning 0))
10013 (if (outline-invisible-p) (org-show-context)))
10014 (goto-char pos)
10015 (setq org-link-search-failed t)
10016 (message "No further link found"))))
10018 (defun org-previous-link ()
10019 "Move backward to the previous link.
10020 If the link is in hidden text, expose it."
10021 (interactive)
10022 (funcall 'org-next-link t))
10024 (defun org-translate-link (s)
10025 "Translate a link string if a translation function has been defined."
10026 (if (and org-link-translation-function
10027 (fboundp org-link-translation-function)
10028 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10029 (progn
10030 (setq s (funcall org-link-translation-function
10031 (match-string 1 s) (match-string 2 s)))
10032 (concat (car s) ":" (cdr s)))
10035 (defun org-translate-link-from-planner (type path)
10036 "Translate a link from Emacs Planner syntax so that Org can follow it.
10037 This is still an experimental function, your mileage may vary."
10038 (cond
10039 ((member type '("http" "https" "news" "ftp"))
10040 ;; standard Internet links are the same.
10041 nil)
10042 ((and (equal type "irc") (string-match "^//" path))
10043 ;; Planner has two / at the beginning of an irc link, we have 1.
10044 ;; We should have zero, actually....
10045 (setq path (substring path 1)))
10046 ((and (equal type "lisp") (string-match "^/" path))
10047 ;; Planner has a slash, we do not.
10048 (setq type "elisp" path (substring path 1)))
10049 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10050 ;; A typical message link. Planner has the id after the final slash,
10051 ;; we separate it with a hash mark
10052 (setq path (concat (match-string 1 path) "#"
10053 (org-remove-angle-brackets (match-string 2 path)))))
10055 (cons type path))
10057 (defun org-find-file-at-mouse (ev)
10058 "Open file link or URL at mouse."
10059 (interactive "e")
10060 (mouse-set-point ev)
10061 (org-open-at-point 'in-emacs))
10063 (defun org-open-at-mouse (ev)
10064 "Open file link or URL at mouse.
10065 See the docstring of `org-open-file' for details."
10066 (interactive "e")
10067 (mouse-set-point ev)
10068 (if (eq major-mode 'org-agenda-mode)
10069 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10070 (org-open-at-point))
10072 (defvar org-window-config-before-follow-link nil
10073 "The window configuration before following a link.
10074 This is saved in case the need arises to restore it.")
10076 (defvar org-open-link-marker (make-marker)
10077 "Marker pointing to the location where `org-open-at-point; was called.")
10079 ;;;###autoload
10080 (defun org-open-at-point-global ()
10081 "Follow a link like Org-mode does.
10082 This command can be called in any mode to follow a link that has
10083 Org-mode syntax."
10084 (interactive)
10085 (org-run-like-in-org-mode 'org-open-at-point))
10087 ;;;###autoload
10088 (defun org-open-link-from-string (s &optional arg reference-buffer)
10089 "Open a link in the string S, as if it was in Org-mode."
10090 (interactive "sLink: \nP")
10091 (let ((reference-buffer (or reference-buffer (current-buffer))))
10092 (with-temp-buffer
10093 (let ((org-inhibit-startup (not reference-buffer)))
10094 (org-mode)
10095 (insert s)
10096 (goto-char (point-min))
10097 (when reference-buffer
10098 (setq org-link-abbrev-alist-local
10099 (with-current-buffer reference-buffer
10100 org-link-abbrev-alist-local)))
10101 (org-open-at-point arg reference-buffer)))))
10103 (defvar org-open-at-point-functions nil
10104 "Hook that is run when following a link at point.
10106 Functions in this hook must return t if they identify and follow
10107 a link at point. If they don't find anything interesting at point,
10108 they must return nil.")
10110 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10111 (defun org-open-at-point (&optional arg reference-buffer)
10112 "Open link at or after point.
10113 If there is no link at point, this function will search forward up to
10114 the end of the current line.
10115 Normally, files will be opened by an appropriate application. If the
10116 optional prefix argument ARG is non-nil, Emacs will visit the file.
10117 With a double prefix argument, try to open outside of Emacs, in the
10118 application the system uses for this file type."
10119 (interactive "P")
10120 ;; if in a code block, then open the block's results
10121 (unless (call-interactively #'org-babel-open-src-block-result)
10122 (org-load-modules-maybe)
10123 (move-marker org-open-link-marker (point))
10124 (setq org-window-config-before-follow-link (current-window-configuration))
10125 (org-remove-occur-highlights nil nil t)
10126 (cond
10127 ((and (org-at-heading-p)
10128 (not (org-at-timestamp-p t))
10129 (not (org-in-regexp
10130 (concat org-plain-link-re "\\|"
10131 org-bracket-link-regexp "\\|"
10132 org-angle-link-re "\\|"
10133 "[ \t]:[^ \t\n]+:[ \t]*$")))
10134 (not (get-text-property (point) 'org-linked-text)))
10135 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10136 (lk0 (car lkall))
10137 (lk (if (stringp lk0) (list lk0) lk0))
10138 (lkend (cdr lkall)))
10139 (mapcar (lambda(l)
10140 (search-forward l nil lkend)
10141 (goto-char (match-beginning 0))
10142 (org-open-at-point))
10143 lk))
10144 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10145 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10146 ((and (org-at-timestamp-p t)
10147 (not (org-in-regexp org-bracket-link-regexp)))
10148 (org-follow-timestamp-link))
10149 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10150 (not (org-in-regexp org-any-link-re)))
10151 (org-footnote-action))
10153 (let (type path link line search (pos (point)))
10154 (catch 'match
10155 (save-excursion
10156 (skip-chars-forward "^]\n\r")
10157 (when (org-in-regexp org-bracket-link-regexp 1)
10158 (setq link (org-extract-attributes
10159 (org-link-unescape (org-match-string-no-properties 1))))
10160 (while (string-match " *\n *" link)
10161 (setq link (replace-match " " t t link)))
10162 (setq link (org-link-expand-abbrev link))
10163 (cond
10164 ((or (file-name-absolute-p link)
10165 (string-match "^\\.\\.?/" link))
10166 (setq type "file" path link))
10167 ((string-match org-link-re-with-space3 link)
10168 (setq type (match-string 1 link) path (match-string 2 link)))
10169 ((string-match "^help:+\\(.+\\)" link)
10170 (setq type "help" path (match-string 1 link)))
10171 (t (setq type "thisfile" path link)))
10172 (throw 'match t)))
10174 (when (get-text-property (point) 'org-linked-text)
10175 (setq type "thisfile"
10176 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10177 (1+ (point)) (point))
10178 path (buffer-substring
10179 (or (previous-single-property-change pos 'org-linked-text)
10180 (point-min))
10181 (or (next-single-property-change pos 'org-linked-text)
10182 (point-max))))
10183 (throw 'match t))
10185 (save-excursion
10186 (when (or (org-in-regexp org-angle-link-re)
10187 (let ((match (org-in-regexp org-plain-link-re)))
10188 ;; Check a plain link is not within a bracket link
10189 (and match
10190 (save-excursion
10191 (progn
10192 (goto-char (car match))
10193 (not (org-in-regexp org-bracket-link-regexp))))))
10194 (let ((line_ending (save-excursion (end-of-line) (point))))
10195 ;; We are in a line before a plain or bracket link
10196 (or (re-search-forward org-plain-link-re line_ending t)
10197 (re-search-forward org-bracket-link-regexp line_ending t))))
10198 (setq type (match-string 1)
10199 path (org-link-unescape (match-string 2)))
10200 (throw 'match t)))
10201 (save-excursion
10202 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10203 (setq type "tags"
10204 path (match-string 1))
10205 (while (string-match ":" path)
10206 (setq path (replace-match "+" t t path)))
10207 (throw 'match t)))
10208 (when (org-in-regexp "<\\([^><\n]+\\)>")
10209 (setq type "tree-match"
10210 path (match-string 1))
10211 (throw 'match t)))
10212 (unless path
10213 (user-error "No link found"))
10215 ;; switch back to reference buffer
10216 ;; needed when if called in a temporary buffer through
10217 ;; org-open-link-from-string
10218 (with-current-buffer (or reference-buffer (current-buffer))
10220 ;; Remove any trailing spaces in path
10221 (if (string-match " +\\'" path)
10222 (setq path (replace-match "" t t path)))
10223 (if (and org-link-translation-function
10224 (fboundp org-link-translation-function))
10225 ;; Check if we need to translate the link
10226 (let ((tmp (funcall org-link-translation-function type path)))
10227 (setq type (car tmp) path (cdr tmp))))
10229 (cond
10231 ((assoc type org-link-protocols)
10232 (funcall (nth 1 (assoc type org-link-protocols)) path))
10234 ((equal type "help")
10235 (let ((f-or-v (intern path)))
10236 (cond ((fboundp f-or-v)
10237 (describe-function f-or-v))
10238 ((boundp f-or-v)
10239 (describe-variable f-or-v))
10240 (t (error "Not a known function or variable")))))
10242 ((equal type "mailto")
10243 (let ((cmd (car org-link-mailto-program))
10244 (args (cdr org-link-mailto-program)) args1
10245 (address path) (subject "") a)
10246 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10247 (setq address (match-string 1 path)
10248 subject (org-link-escape (match-string 2 path))))
10249 (while args
10250 (cond
10251 ((not (stringp (car args))) (push (pop args) args1))
10252 (t (setq a (pop args))
10253 (if (string-match "%a" a)
10254 (setq a (replace-match address t t a)))
10255 (if (string-match "%s" a)
10256 (setq a (replace-match subject t t a)))
10257 (push a args1))))
10258 (apply cmd (nreverse args1))))
10260 ((member type '("http" "https" "ftp" "news"))
10261 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10262 (org-link-escape
10263 path org-link-escape-chars-browser)
10264 path))))
10266 ((string= type "doi")
10267 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10268 (org-link-escape
10269 path org-link-escape-chars-browser)
10270 path))))
10272 ((member type '("message"))
10273 (browse-url (concat type ":" path)))
10275 ((string= type "tags")
10276 (org-tags-view arg path))
10278 ((string= type "tree-match")
10279 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10281 ((string= type "file")
10282 (if (string-match "::\\([0-9]+\\)\\'" path)
10283 (setq line (string-to-number (match-string 1 path))
10284 path (substring path 0 (match-beginning 0)))
10285 (if (string-match "::\\(.+\\)\\'" path)
10286 (setq search (match-string 1 path)
10287 path (substring path 0 (match-beginning 0)))))
10288 (if (string-match "[*?{]" (file-name-nondirectory path))
10289 (dired path)
10290 (org-open-file path arg line search)))
10292 ((string= type "shell")
10293 (let ((buf (generate-new-buffer "*Org Shell Output"))
10294 (cmd path))
10295 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10296 (string-match org-confirm-shell-link-not-regexp cmd))
10297 (not org-confirm-shell-link-function)
10298 (funcall org-confirm-shell-link-function
10299 (format "Execute \"%s\" in shell? "
10300 (org-add-props cmd nil
10301 'face 'org-warning))))
10302 (progn
10303 (message "Executing %s" cmd)
10304 (shell-command cmd buf)
10305 (if (featurep 'midnight)
10306 (setq clean-buffer-list-kill-buffer-names
10307 (cons buf clean-buffer-list-kill-buffer-names))))
10308 (error "Abort"))))
10310 ((string= type "elisp")
10311 (let ((cmd path))
10312 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10313 (string-match org-confirm-elisp-link-not-regexp cmd))
10314 (not org-confirm-elisp-link-function)
10315 (funcall org-confirm-elisp-link-function
10316 (format "Execute \"%s\" as elisp? "
10317 (org-add-props cmd nil
10318 'face 'org-warning))))
10319 (message "%s => %s" cmd
10320 (if (equal (string-to-char cmd) ?\()
10321 (eval (read cmd))
10322 (call-interactively (read cmd))))
10323 (error "Abort"))))
10325 ((and (string= type "thisfile")
10326 (run-hook-with-args-until-success
10327 'org-open-link-functions path)))
10329 ((string= type "thisfile")
10330 (if arg
10331 (switch-to-buffer-other-window
10332 (org-get-buffer-for-internal-link (current-buffer)))
10333 (org-mark-ring-push))
10334 (let ((cmd `(org-link-search
10335 ,path
10336 ,(cond ((equal arg '(4)) ''occur)
10337 ((equal arg '(16)) ''org-occur))
10338 ,pos)))
10339 (condition-case nil (let ((org-link-search-inhibit-query t))
10340 (eval cmd))
10341 (error (progn (widen) (eval cmd))))))
10343 (t (browse-url-at-point)))))))
10344 (move-marker org-open-link-marker nil)
10345 (run-hook-with-args 'org-follow-link-hook)))
10347 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10348 "Offer links in the current entry and return the selected link.
10349 If there is only one link, return it.
10350 If NTH is an integer, return the NTH link found.
10351 If ZERO is a string, check also this string for a link, and if
10352 there is one, return it."
10353 (with-current-buffer buffer
10354 (save-excursion
10355 (save-restriction
10356 (widen)
10357 (goto-char marker)
10358 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10359 "\\(" org-angle-link-re "\\)\\|"
10360 "\\(" org-plain-link-re "\\)"))
10361 (cnt ?0)
10362 (in-emacs (if (integerp nth) nil nth))
10363 have-zero end links link c)
10364 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10365 (push (match-string 0 zero) links)
10366 (setq cnt (1- cnt) have-zero t))
10367 (save-excursion
10368 (org-back-to-heading t)
10369 (setq end (save-excursion (outline-next-heading) (point)))
10370 (while (re-search-forward re end t)
10371 (push (match-string 0) links))
10372 (setq links (org-uniquify (reverse links))))
10373 (cond
10374 ((null links)
10375 (message "No links"))
10376 ((equal (length links) 1)
10377 (setq link (car links)))
10378 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10379 (setq link (nth (if have-zero nth (1- nth)) links)))
10380 (t ; we have to select a link
10381 (save-excursion
10382 (save-window-excursion
10383 (delete-other-windows)
10384 (with-output-to-temp-buffer "*Select Link*"
10385 (mapc (lambda (l)
10386 (if (not (string-match org-bracket-link-regexp l))
10387 (princ (format "[%c] %s\n" (incf cnt)
10388 (org-remove-angle-brackets l)))
10389 (if (match-end 3)
10390 (princ (format "[%c] %s (%s)\n" (incf cnt)
10391 (match-string 3 l) (match-string 1 l)))
10392 (princ (format "[%c] %s\n" (incf cnt)
10393 (match-string 1 l))))))
10394 links))
10395 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10396 (message "Select link to open, RET to open all:")
10397 (setq c (read-char-exclusive))
10398 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10399 (when (equal c ?q) (error "Abort"))
10400 (if (equal c ?\C-m)
10401 (setq link links)
10402 (setq nth (- c ?0))
10403 (if have-zero (setq nth (1+ nth)))
10404 (unless (and (integerp nth) (>= (length links) nth))
10405 (error "Invalid link selection"))
10406 (setq link (nth (1- nth) links)))))
10407 (cons link end))))))
10409 ;; Add special file links that specify the way of opening
10411 (org-add-link-type "file+sys" 'org-open-file-with-system)
10412 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10413 (defun org-open-file-with-system (path)
10414 "Open file at PATH using the system way of opening it."
10415 (org-open-file path 'system))
10416 (defun org-open-file-with-emacs (path)
10417 "Open file at PATH in Emacs."
10418 (org-open-file path 'emacs))
10421 ;;; File search
10423 (defvar org-create-file-search-functions nil
10424 "List of functions to construct the right search string for a file link.
10425 These functions are called in turn with point at the location to
10426 which the link should point.
10428 A function in the hook should first test if it would like to
10429 handle this file type, for example by checking the `major-mode'
10430 or the file extension. If it decides not to handle this file, it
10431 should just return nil to give other functions a chance. If it
10432 does handle the file, it must return the search string to be used
10433 when following the link. The search string will be part of the
10434 file link, given after a double colon, and `org-open-at-point'
10435 will automatically search for it. If special measures must be
10436 taken to make the search successful, another function should be
10437 added to the companion hook `org-execute-file-search-functions',
10438 which see.
10440 A function in this hook may also use `setq' to set the variable
10441 `description' to provide a suggestion for the descriptive text to
10442 be used for this link when it gets inserted into an Org-mode
10443 buffer with \\[org-insert-link].")
10445 (defvar org-execute-file-search-functions nil
10446 "List of functions to execute a file search triggered by a link.
10448 Functions added to this hook must accept a single argument, the
10449 search string that was part of the file link, the part after the
10450 double colon. The function must first check if it would like to
10451 handle this search, for example by checking the `major-mode' or
10452 the file extension. If it decides not to handle this search, it
10453 should just return nil to give other functions a chance. If it
10454 does handle the search, it must return a non-nil value to keep
10455 other functions from trying.
10457 Each function can access the current prefix argument through the
10458 variable `current-prefix-arg'. Note that a single prefix is used
10459 to force opening a link in Emacs, so it may be good to only use a
10460 numeric or double prefix to guide the search function.
10462 In case this is needed, a function in this hook can also restore
10463 the window configuration before `org-open-at-point' was called using:
10465 (set-window-configuration org-window-config-before-follow-link)")
10467 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10468 (defun org-link-search (s &optional type avoid-pos stealth)
10469 "Search for a link search option.
10470 If S is surrounded by forward slashes, it is interpreted as a
10471 regular expression. In org-mode files, this will create an `org-occur'
10472 sparse tree. In ordinary files, `occur' will be used to list matches.
10473 If the current buffer is in `dired-mode', grep will be used to search
10474 in all files. If AVOID-POS is given, ignore matches near that position.
10476 When optional argument STEALTH is non-nil, do not modify
10477 visibility around point, thus ignoring
10478 `org-show-hierarchy-above', `org-show-following-heading' and
10479 `org-show-siblings' variables."
10480 (let ((case-fold-search t)
10481 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10482 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10483 (append '(("") (" ") ("\t") ("\n"))
10484 org-emphasis-alist)
10485 "\\|") "\\)"))
10486 (pos (point))
10487 (pre nil) (post nil)
10488 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10489 (cond
10490 ;; First check if there are any special search functions
10491 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10492 ;; Now try the builtin stuff
10493 ((and (equal (string-to-char s0) ?#)
10494 (> (length s0) 1)
10495 (save-excursion
10496 (goto-char (point-min))
10497 (and
10498 (re-search-forward
10499 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10500 (setq type 'dedicated
10501 pos (match-beginning 0))))
10502 ;; There is an exact target for this
10503 (goto-char pos)
10504 (org-back-to-heading t)))
10505 ((save-excursion
10506 (goto-char (point-min))
10507 (and
10508 (re-search-forward
10509 (concat "<<" (regexp-quote s0) ">>") nil t)
10510 (setq type 'dedicated
10511 pos (match-beginning 0))))
10512 ;; There is an exact target for this
10513 (goto-char pos))
10514 ((save-excursion
10515 (goto-char (point-min))
10516 (and
10517 (re-search-forward
10518 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10519 (setq type 'dedicated pos (match-beginning 0))))
10520 ;; Found an invisible target.
10521 (goto-char pos))
10522 ((save-excursion
10523 (goto-char (point-min))
10524 (and
10525 (re-search-forward
10526 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10527 (setq type 'dedicated pos (match-beginning 0))))
10528 ;; Found an element with a matching #+name affiliated keyword.
10529 (goto-char pos))
10530 ((and (string-match "^(\\(.*\\))$" s0)
10531 (save-excursion
10532 (goto-char (point-min))
10533 (and
10534 (re-search-forward
10535 (concat "[^[]" (regexp-quote
10536 (format org-coderef-label-format
10537 (match-string 1 s0))))
10538 nil t)
10539 (setq type 'dedicated
10540 pos (1+ (match-beginning 0))))))
10541 ;; There is a coderef target for this
10542 (goto-char pos))
10543 ((string-match "^/\\(.*\\)/$" s)
10544 ;; A regular expression
10545 (cond
10546 ((derived-mode-p 'org-mode)
10547 (org-occur (match-string 1 s)))
10548 (t (org-do-occur (match-string 1 s)))))
10549 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10550 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10551 (goto-char (point-min))
10552 (cond
10553 ((let (case-fold-search)
10554 (re-search-forward (format org-complex-heading-regexp-format
10555 (regexp-quote s))
10556 nil t))
10557 ;; OK, found a match
10558 (setq type 'dedicated)
10559 (goto-char (match-beginning 0)))
10560 ((and (not org-link-search-inhibit-query)
10561 (eq org-link-search-must-match-exact-headline 'query-to-create)
10562 (y-or-n-p "No match - create this as a new heading? "))
10563 (goto-char (point-max))
10564 (or (bolp) (newline))
10565 (insert "* " s "\n")
10566 (beginning-of-line 0))
10568 (goto-char pos)
10569 (error "No match"))))
10571 ;; A normal search string
10572 (when (equal (string-to-char s) ?*)
10573 ;; Anchor on headlines, post may include tags.
10574 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10575 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10576 s (substring s 1)))
10577 (remove-text-properties
10578 0 (length s)
10579 '(face nil mouse-face nil keymap nil fontified nil) s)
10580 ;; Make a series of regular expressions to find a match
10581 (setq words (org-split-string s "[ \n\r\t]+")
10583 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10584 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10585 "\\)" markers)
10586 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10587 re2a (concat "[ \t\r\n]" re2a_)
10588 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10589 re4 (concat "[^a-zA-Z_]" re4_)
10591 re1 (concat pre re2 post)
10592 re3 (concat pre (if pre re4_ re4) post)
10593 re5 (concat pre ".*" re4)
10594 re2 (concat pre re2)
10595 re2a (concat pre (if pre re2a_ re2a))
10596 re4 (concat pre (if pre re4_ re4))
10597 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10598 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10599 re5 "\\)"
10601 (cond
10602 ((eq type 'org-occur) (org-occur reall))
10603 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10604 (t (goto-char (point-min))
10605 (setq type 'fuzzy)
10606 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10607 (org-search-not-self 1 re1 nil t)
10608 (org-search-not-self 1 re2 nil t)
10609 (org-search-not-self 1 re2a nil t)
10610 (org-search-not-self 1 re3 nil t)
10611 (org-search-not-self 1 re4 nil t)
10612 (org-search-not-self 1 re5 nil t)
10614 (goto-char (match-beginning 1))
10615 (goto-char pos)
10616 (error "No match"))))))
10617 (and (derived-mode-p 'org-mode)
10618 (not stealth)
10619 (org-show-context 'link-search))
10620 type))
10622 (defun org-search-not-self (group &rest args)
10623 "Execute `re-search-forward', but only accept matches that do not
10624 enclose the position of `org-open-link-marker'."
10625 (let ((m org-open-link-marker))
10626 (catch 'exit
10627 (while (apply 're-search-forward args)
10628 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10629 (goto-char (match-end group))
10630 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10631 (> (match-beginning 0) (marker-position m))
10632 (< (match-end 0) (marker-position m)))
10633 (save-match-data
10634 (or (not (org-in-regexp
10635 org-bracket-link-analytic-regexp 1))
10636 (not (match-end 4)) ; no description
10637 (and (<= (match-beginning 4) (point))
10638 (>= (match-end 4) (point))))))
10639 (throw 'exit (point))))))))
10641 (defun org-get-buffer-for-internal-link (buffer)
10642 "Return a buffer to be used for displaying the link target of internal links."
10643 (cond
10644 ((not org-display-internal-link-with-indirect-buffer)
10645 buffer)
10646 ((string-match "(Clone)$" (buffer-name buffer))
10647 (message "Buffer is already a clone, not making another one")
10648 ;; we also do not modify visibility in this case
10649 buffer)
10650 (t ; make a new indirect buffer for displaying the link
10651 (let* ((bn (buffer-name buffer))
10652 (ibn (concat bn "(Clone)"))
10653 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10654 (with-current-buffer ib (org-overview))
10655 ib))))
10657 (defun org-do-occur (regexp &optional cleanup)
10658 "Call the Emacs command `occur'.
10659 If CLEANUP is non-nil, remove the printout of the regular expression
10660 in the *Occur* buffer. This is useful if the regex is long and not useful
10661 to read."
10662 (occur regexp)
10663 (when cleanup
10664 (let ((cwin (selected-window)) win beg end)
10665 (when (setq win (get-buffer-window "*Occur*"))
10666 (select-window win))
10667 (goto-char (point-min))
10668 (when (re-search-forward "match[a-z]+" nil t)
10669 (setq beg (match-end 0))
10670 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10671 (setq end (1- (match-beginning 0)))))
10672 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10673 (goto-char (point-min))
10674 (select-window cwin))))
10676 ;;; The mark ring for links jumps
10678 (defvar org-mark-ring nil
10679 "Mark ring for positions before jumps in Org-mode.")
10680 (defvar org-mark-ring-last-goto nil
10681 "Last position in the mark ring used to go back.")
10682 ;; Fill and close the ring
10683 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10684 (loop for i from 1 to org-mark-ring-length do
10685 (push (make-marker) org-mark-ring))
10686 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10687 org-mark-ring)
10689 (defun org-mark-ring-push (&optional pos buffer)
10690 "Put the current position or POS into the mark ring and rotate it."
10691 (interactive)
10692 (setq pos (or pos (point)))
10693 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10694 (move-marker (car org-mark-ring)
10695 (or pos (point))
10696 (or buffer (current-buffer)))
10697 (message "%s"
10698 (substitute-command-keys
10699 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10701 (defun org-mark-ring-goto (&optional n)
10702 "Jump to the previous position in the mark ring.
10703 With prefix arg N, jump back that many stored positions. When
10704 called several times in succession, walk through the entire ring.
10705 Org-mode commands jumping to a different position in the current file,
10706 or to another Org-mode file, automatically push the old position
10707 onto the ring."
10708 (interactive "p")
10709 (let (p m)
10710 (if (eq last-command this-command)
10711 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10712 (setq p org-mark-ring))
10713 (setq org-mark-ring-last-goto p)
10714 (setq m (car p))
10715 (org-pop-to-buffer-same-window (marker-buffer m))
10716 (goto-char m)
10717 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10719 (defun org-remove-angle-brackets (s)
10720 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10721 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10723 (defun org-add-angle-brackets (s)
10724 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10725 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10727 (defun org-remove-double-quotes (s)
10728 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10729 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10732 ;;; Following specific links
10734 (defun org-follow-timestamp-link ()
10735 "Open an agenda view for the time-stamp date/range at point."
10736 (cond
10737 ((org-at-date-range-p t)
10738 (let ((org-agenda-start-on-weekday)
10739 (t1 (match-string 1))
10740 (t2 (match-string 2)) tt1 tt2)
10741 (setq tt1 (time-to-days (org-time-string-to-time t1))
10742 tt2 (time-to-days (org-time-string-to-time t2)))
10743 (let ((org-agenda-buffer-tmp-name
10744 (format "*Org Agenda(a:%s)"
10745 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10746 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10747 ((org-at-timestamp-p t)
10748 (let ((org-agenda-buffer-tmp-name
10749 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10750 (org-agenda-list nil (time-to-days (org-time-string-to-time
10751 (substring (match-string 1) 0 10)))
10752 1)))
10753 (t (error "This should not happen"))))
10756 ;;; Following file links
10757 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10758 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10759 (declare-function mailcap-mime-info
10760 "mailcap" (string &optional request no-decode))
10761 (defvar org-wait nil)
10762 (defun org-open-file (path &optional in-emacs line search)
10763 "Open the file at PATH.
10764 First, this expands any special file name abbreviations. Then the
10765 configuration variable `org-file-apps' is checked if it contains an
10766 entry for this file type, and if yes, the corresponding command is launched.
10768 If no application is found, Emacs simply visits the file.
10770 With optional prefix argument IN-EMACS, Emacs will visit the file.
10771 With a double \\[universal-argument] \\[universal-argument] \
10772 prefix arg, Org tries to avoid opening in Emacs
10773 and to use an external application to visit the file.
10775 Optional LINE specifies a line to go to, optional SEARCH a string
10776 to search for. If LINE or SEARCH is given, the file will be
10777 opened in Emacs, unless an entry from org-file-apps that makes
10778 use of groups in a regexp matches.
10780 If you want to change the way frames are used when following a
10781 link, please customize `org-link-frame-setup'.
10783 If the file does not exist, an error is thrown."
10784 (let* ((file (if (equal path "")
10785 buffer-file-name
10786 (substitute-in-file-name (expand-file-name path))))
10787 (file-apps (append org-file-apps (org-default-apps)))
10788 (apps (org-remove-if
10789 'org-file-apps-entry-match-against-dlink-p file-apps))
10790 (apps-dlink (org-remove-if-not
10791 'org-file-apps-entry-match-against-dlink-p file-apps))
10792 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10793 (dirp (if remp nil (file-directory-p file)))
10794 (file (if (and dirp org-open-directory-means-index-dot-org)
10795 (concat (file-name-as-directory file) "index.org")
10796 file))
10797 (a-m-a-p (assq 'auto-mode apps))
10798 (dfile (downcase file))
10799 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10800 (link (cond ((and (eq line nil)
10801 (eq search nil))
10802 file)
10803 (line
10804 (concat file "::" (number-to-string line)))
10805 (search
10806 (concat file "::" search))))
10807 (dlink (downcase link))
10808 (old-buffer (current-buffer))
10809 (old-pos (point))
10810 (old-mode major-mode)
10811 ext cmd link-match-data)
10812 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10813 (setq ext (match-string 1 dfile))
10814 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10815 (setq ext (match-string 1 dfile))))
10816 (cond
10817 ((member in-emacs '((16) system))
10818 (setq cmd (cdr (assoc 'system apps))))
10819 (in-emacs (setq cmd 'emacs))
10821 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10822 (and dirp (cdr (assoc 'directory apps)))
10823 ; first, try matching against apps-dlink
10824 ; if we get a match here, store the match data for later
10825 (let ((match (assoc-default dlink apps-dlink
10826 'string-match)))
10827 (if match
10828 (progn (setq link-match-data (match-data))
10829 match)
10830 (progn (setq in-emacs (or in-emacs line search))
10831 nil))) ; if we have no match in apps-dlink,
10832 ; always open the file in emacs if line or search
10833 ; is given (for backwards compatibility)
10834 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10835 'string-match)
10836 (cdr (assoc ext apps))
10837 (cdr (assoc t apps))))))
10838 (when (eq cmd 'system)
10839 (setq cmd (cdr (assoc 'system apps))))
10840 (when (eq cmd 'default)
10841 (setq cmd (cdr (assoc t apps))))
10842 (when (eq cmd 'mailcap)
10843 (require 'mailcap)
10844 (mailcap-parse-mailcaps)
10845 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10846 (command (mailcap-mime-info mime-type)))
10847 (if (stringp command)
10848 (setq cmd command)
10849 (setq cmd 'emacs))))
10850 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10851 (not (file-exists-p file))
10852 (not org-open-non-existing-files))
10853 (error "No such file: %s" file))
10854 (cond
10855 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10856 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10857 (while (string-match "['\"]%s['\"]" cmd)
10858 (setq cmd (replace-match "%s" t t cmd)))
10859 (while (string-match "%s" cmd)
10860 (setq cmd (replace-match
10861 (save-match-data
10862 (shell-quote-argument
10863 (convert-standard-filename file)))
10864 t t cmd)))
10866 ;; Replace "%1", "%2" etc. in command with group matches from regex
10867 (save-match-data
10868 (let ((match-index 1)
10869 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10870 (set-match-data link-match-data)
10871 (while (<= match-index number-of-groups)
10872 (let ((regex (concat "%" (number-to-string match-index)))
10873 (replace-with (match-string match-index dlink)))
10874 (while (string-match regex cmd)
10875 (setq cmd (replace-match replace-with t t cmd))))
10876 (setq match-index (+ match-index 1)))))
10878 (save-window-excursion
10879 (message "Running %s...done" cmd)
10880 (start-process-shell-command cmd nil cmd)
10881 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10882 ((or (stringp cmd)
10883 (eq cmd 'emacs))
10884 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10885 (widen)
10886 (if line (org-goto-line line)
10887 (if search (org-link-search search))))
10888 ((consp cmd)
10889 (let ((file (convert-standard-filename file)))
10890 (save-match-data
10891 (set-match-data link-match-data)
10892 (eval cmd))))
10893 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10894 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10895 (or (not (equal old-buffer (current-buffer)))
10896 (not (equal old-pos (point))))
10897 (org-mark-ring-push old-pos old-buffer))))
10899 (defun org-file-apps-entry-match-against-dlink-p (entry)
10900 "This function returns non-nil if `entry' uses a regular
10901 expression which should be matched against the whole link by
10902 org-open-file.
10904 It assumes that is the case when the entry uses a regular
10905 expression which has at least one grouping construct and the
10906 action is either a lisp form or a command string containing
10907 '%1', i.e. using at least one subexpression match as a
10908 parameter."
10909 (let ((selector (car entry))
10910 (action (cdr entry)))
10911 (if (stringp selector)
10912 (and (> (regexp-opt-depth selector) 0)
10913 (or (and (stringp action)
10914 (string-match "%[0-9]" action))
10915 (consp action)))
10916 nil)))
10918 (defun org-default-apps ()
10919 "Return the default applications for this operating system."
10920 (cond
10921 ((eq system-type 'darwin)
10922 org-file-apps-defaults-macosx)
10923 ((eq system-type 'windows-nt)
10924 org-file-apps-defaults-windowsnt)
10925 (t org-file-apps-defaults-gnu)))
10927 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10928 "Convert extensions to regular expressions in the cars of LIST.
10929 Also, weed out any non-string entries, because the return value is used
10930 only for regexp matching.
10931 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10932 point to the symbol `emacs', indicating that the file should
10933 be opened in Emacs."
10934 (append
10935 (delq nil
10936 (mapcar (lambda (x)
10937 (if (not (stringp (car x)))
10939 (if (string-match "\\W" (car x))
10941 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10942 list))
10943 (if add-auto-mode
10944 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10946 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10947 (defun org-file-remote-p (file)
10948 "Test whether FILE specifies a location on a remote system.
10949 Return non-nil if the location is indeed remote.
10951 For example, the filename \"/user@host:/foo\" specifies a location
10952 on the system \"/user@host:\"."
10953 (cond ((fboundp 'file-remote-p)
10954 (file-remote-p file))
10955 ((fboundp 'tramp-handle-file-remote-p)
10956 (tramp-handle-file-remote-p file))
10957 ((and (boundp 'ange-ftp-name-format)
10958 (string-match (car ange-ftp-name-format) file))
10959 t)))
10962 ;;;; Refiling
10964 (defun org-get-org-file ()
10965 "Read a filename, with default directory `org-directory'."
10966 (let ((default (or org-default-notes-file remember-data-file)))
10967 (read-file-name (format "File name [%s]: " default)
10968 (file-name-as-directory org-directory)
10969 default)))
10971 (defun org-notes-order-reversed-p ()
10972 "Check if the current file should receive notes in reversed order."
10973 (cond
10974 ((not org-reverse-note-order) nil)
10975 ((eq t org-reverse-note-order) t)
10976 ((not (listp org-reverse-note-order)) nil)
10977 (t (catch 'exit
10978 (let ((all org-reverse-note-order)
10979 entry)
10980 (while (setq entry (pop all))
10981 (if (string-match (car entry) buffer-file-name)
10982 (throw 'exit (cdr entry))))
10983 nil)))))
10985 (defvar org-refile-target-table nil
10986 "The list of refile targets, created by `org-refile'.")
10988 (defvar org-agenda-new-buffers nil
10989 "Buffers created to visit agenda files.")
10991 (defvar org-refile-cache nil
10992 "Cache for refile targets.")
10994 (defvar org-refile-markers nil
10995 "All the markers used for caching refile locations.")
10997 (defun org-refile-marker (pos)
10998 "Get a new refile marker, but only if caching is in use."
10999 (if (not org-refile-use-cache)
11001 (let ((m (make-marker)))
11002 (move-marker m pos)
11003 (push m org-refile-markers)
11004 m)))
11006 (defun org-refile-cache-clear ()
11007 "Clear the refile cache and disable all the markers."
11008 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11009 (setq org-refile-markers nil)
11010 (setq org-refile-cache nil)
11011 (message "Refile cache has been cleared"))
11013 (defun org-refile-cache-check-set (set)
11014 "Check if all the markers in the cache still have live buffers."
11015 (let (marker)
11016 (catch 'exit
11017 (while (and set (setq marker (nth 3 (pop set))))
11018 ;; if org-refile-use-outline-path is 'file, marker may be nil
11019 (when (and marker (null (marker-buffer marker)))
11020 (message "not found") (sit-for 3)
11021 (throw 'exit nil)))
11022 t)))
11024 (defun org-refile-cache-put (set &rest identifiers)
11025 "Push the refile targets SET into the cache, under IDENTIFIERS."
11026 (let* ((key (sha1 (prin1-to-string identifiers)))
11027 (entry (assoc key org-refile-cache)))
11028 (if entry
11029 (setcdr entry set)
11030 (push (cons key set) org-refile-cache))))
11032 (defun org-refile-cache-get (&rest identifiers)
11033 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11034 (cond
11035 ((not org-refile-cache) nil)
11036 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11038 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11039 org-refile-cache))))
11040 (and set (org-refile-cache-check-set set) set)))))
11042 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11043 "Produce a table with refile targets."
11044 (let ((case-fold-search nil)
11045 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11046 (entries (or org-refile-targets '((nil . (:level . 1)))))
11047 targets tgs txt re files f desc descre fast-path-p level pos0)
11048 (message "Getting targets...")
11049 (with-current-buffer (or default-buffer (current-buffer))
11050 (while (setq entry (pop entries))
11051 (setq files (car entry) desc (cdr entry))
11052 (setq fast-path-p nil)
11053 (cond
11054 ((null files) (setq files (list (current-buffer))))
11055 ((eq files 'org-agenda-files)
11056 (setq files (org-agenda-files 'unrestricted)))
11057 ((and (symbolp files) (fboundp files))
11058 (setq files (funcall files)))
11059 ((and (symbolp files) (boundp files))
11060 (setq files (symbol-value files))))
11061 (if (stringp files) (setq files (list files)))
11062 (cond
11063 ((eq (car desc) :tag)
11064 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11065 ((eq (car desc) :todo)
11066 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11067 ((eq (car desc) :regexp)
11068 (setq descre (cdr desc)))
11069 ((eq (car desc) :level)
11070 (setq descre (concat "^\\*\\{" (number-to-string
11071 (if org-odd-levels-only
11072 (1- (* 2 (cdr desc)))
11073 (cdr desc)))
11074 "\\}[ \t]")))
11075 ((eq (car desc) :maxlevel)
11076 (setq fast-path-p t)
11077 (setq descre (concat "^\\*\\{1," (number-to-string
11078 (if org-odd-levels-only
11079 (1- (* 2 (cdr desc)))
11080 (cdr desc)))
11081 "\\}[ \t]")))
11082 (t (error "Bad refiling target description %s" desc)))
11083 (while (setq f (pop files))
11084 (with-current-buffer
11085 (if (bufferp f) f (org-get-agenda-file-buffer f))
11087 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11088 (progn
11089 (if (bufferp f) (setq f (buffer-file-name
11090 (buffer-base-buffer f))))
11091 (setq f (and f (expand-file-name f)))
11092 (if (eq org-refile-use-outline-path 'file)
11093 (push (list (file-name-nondirectory f) f nil nil) tgs))
11094 (save-excursion
11095 (save-restriction
11096 (widen)
11097 (goto-char (point-min))
11098 (while (re-search-forward descre nil t)
11099 (goto-char (setq pos0 (point-at-bol)))
11100 (catch 'next
11101 (when org-refile-target-verify-function
11102 (save-match-data
11103 (or (funcall org-refile-target-verify-function)
11104 (throw 'next t))))
11105 (when (and (looking-at org-complex-heading-regexp)
11106 (not (member (match-string 4) excluded-entries))
11107 (match-string 4))
11108 (setq level (org-reduced-level
11109 (- (match-end 1) (match-beginning 1)))
11110 txt (org-link-display-format (match-string 4))
11111 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11112 re (format org-complex-heading-regexp-format
11113 (regexp-quote (match-string 4))))
11114 (when org-refile-use-outline-path
11115 (setq txt (mapconcat
11116 'org-protect-slash
11117 (append
11118 (if (eq org-refile-use-outline-path
11119 'file)
11120 (list (file-name-nondirectory
11121 (buffer-file-name
11122 (buffer-base-buffer))))
11123 (if (eq org-refile-use-outline-path
11124 'full-file-path)
11125 (list (buffer-file-name
11126 (buffer-base-buffer)))))
11127 (org-get-outline-path fast-path-p
11128 level txt)
11129 (list txt))
11130 "/")))
11131 (push (list txt f re (org-refile-marker (point)))
11132 tgs)))
11133 (when (= (point) pos0)
11134 ;; verification function has not moved point
11135 (goto-char (point-at-eol))))))))
11136 (when org-refile-use-cache
11137 (org-refile-cache-put tgs (buffer-file-name) descre))
11138 (setq targets (append tgs targets))
11139 ))))
11140 (message "Getting targets...done")
11141 (nreverse targets)))
11143 (defun org-protect-slash (s)
11144 (while (string-match "/" s)
11145 (setq s (replace-match "\\" t t s)))
11148 (defvar org-olpa (make-vector 20 nil))
11150 (defun org-get-outline-path (&optional fastp level heading)
11151 "Return the outline path to the current entry, as a list.
11153 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11154 routine which makes outline path derivations for an entire file,
11155 avoiding backtracing. Refile target collection makes use of that."
11156 (if fastp
11157 (progn
11158 (if (> level 19)
11159 (error "Outline path failure, more than 19 levels"))
11160 (loop for i from level upto 19 do
11161 (aset org-olpa i nil))
11162 (prog1
11163 (delq nil (append org-olpa nil))
11164 (aset org-olpa level heading)))
11165 (let (rtn case-fold-search)
11166 (save-excursion
11167 (save-restriction
11168 (widen)
11169 (while (org-up-heading-safe)
11170 (when (looking-at org-complex-heading-regexp)
11171 (push (org-match-string-no-properties 4) rtn)))
11172 rtn)))))
11174 (defun org-format-outline-path (path &optional width prefix separator)
11175 "Format the outline path PATH for display.
11176 WIDTH is the maximum number of characters that is available.
11177 PREFIX is a prefix to be included in the returned string,
11178 such as the file name.
11179 SEPARATOR is inserted between the different parts of the path,
11180 the default is \"/\"."
11181 (setq width (or width 79))
11182 (if prefix (setq width (- width (length prefix))))
11183 (if (not path)
11184 (or prefix "")
11185 (let* ((nsteps (length path))
11186 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11187 (maxwidth (if (<= total-width width)
11188 10000 ;; everything fits
11189 ;; we need to shorten the level headings
11190 (/ (- width nsteps) nsteps)))
11191 (org-odd-levels-only nil)
11192 (n 0)
11193 (total (1+ (length prefix))))
11194 (setq maxwidth (max maxwidth 10))
11195 (concat prefix
11196 (if prefix (or separator "/"))
11197 (mapconcat
11198 (lambda (h)
11199 (setq n (1+ n))
11200 (if (and (= n nsteps) (< maxwidth 10000))
11201 (setq maxwidth (- total-width total)))
11202 (if (< (length h) maxwidth)
11203 (progn (setq total (+ total (length h) 1)) h)
11204 (setq h (substring h 0 (- maxwidth 2))
11205 total (+ total maxwidth 1))
11206 (if (string-match "[ \t]+\\'" h)
11207 (setq h (substring h 0 (match-beginning 0))))
11208 (setq h (concat h "..")))
11209 (org-add-props h nil 'face
11210 (nth (% (1- n) org-n-level-faces)
11211 org-level-faces))
11213 path (or separator "/"))))))
11215 (defun org-display-outline-path (&optional file current separator just-return-string)
11216 "Display the current outline path in the echo area.
11218 If FILE is non-nil, prepend the output with the file name.
11219 If CURRENT is non-nil, append the current heading to the output.
11220 SEPARATOR is passed through to `org-format-outline-path'. It separates
11221 the different parts of the path and defaults to \"/\".
11222 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11223 (interactive "P")
11224 (let* (case-fold-search
11225 message-log-max ; Don't populate the *Messages* buffer
11226 (bfn (buffer-file-name (buffer-base-buffer)))
11227 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11228 res)
11229 (if current (setq path (append path
11230 (save-excursion
11231 (org-back-to-heading t)
11232 (if (looking-at org-complex-heading-regexp)
11233 (list (match-string 4)))))))
11234 (setq res
11235 (org-format-outline-path
11236 path
11237 (1- (frame-width))
11238 (and file bfn (concat (file-name-nondirectory bfn) separator))
11239 separator))
11240 (if just-return-string
11241 (org-no-properties res)
11242 (message "%s" res))))
11244 (defvar org-refile-history nil
11245 "History for refiling operations.")
11247 (defvar org-after-refile-insert-hook nil
11248 "Hook run after `org-refile' has inserted its stuff at the new location.
11249 Note that this is still *before* the stuff will be removed from
11250 the *old* location.")
11252 (defvar org-capture-last-stored-marker)
11253 (defvar org-refile-keep nil
11254 "Non-nil means `org-refile' will copy instead of refile.")
11256 (defun org-copy ()
11257 "Like `org-refile', but copy."
11258 (interactive)
11259 (let ((org-refile-keep t))
11260 (funcall 'org-refile nil nil nil "Copy")))
11262 (defun org-refile (&optional goto default-buffer rfloc msg)
11263 "Move the entry or entries at point to another heading.
11264 The list of target headings is compiled using the information in
11265 `org-refile-targets', which see.
11267 At the target location, the entry is filed as a subitem of the target
11268 heading. Depending on `org-reverse-note-order', the new subitem will
11269 either be the first or the last subitem.
11271 If there is an active region, all entries in that region will be moved.
11272 However, the region must fulfill the requirement that the first heading
11273 is the first one sets the top-level of the moved text - at most siblings
11274 below it are allowed.
11276 With prefix arg GOTO, the command will only visit the target location
11277 and not actually move anything.
11279 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11280 go to the location where the last refiling operation has put the subtree.
11281 With a prefix argument of `2', refile to the running clock.
11283 RFLOC can be a refile location obtained in a different way.
11285 MSG is a string to replace \"Refile\" in the default prompt with
11286 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11288 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11290 If you are using target caching (see `org-refile-use-cache'),
11291 you have to clear the target cache in order to find new targets.
11292 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11293 prefix argument (`C-u C-u C-u C-c C-w')."
11295 (interactive "P")
11296 (if (member goto '(0 (64)))
11297 (org-refile-cache-clear)
11298 (let* ((actionmsg (or msg "Refile"))
11299 (cbuf (current-buffer))
11300 (regionp (org-region-active-p))
11301 (region-start (and regionp (region-beginning)))
11302 (region-end (and regionp (region-end)))
11303 (region-length (and regionp (- region-end region-start)))
11304 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11305 pos it nbuf file re level reversed)
11306 (setq last-command nil)
11307 (when regionp
11308 (goto-char region-start)
11309 (or (bolp) (goto-char (point-at-bol)))
11310 (setq region-start (point))
11311 (unless (or (org-kill-is-subtree-p
11312 (buffer-substring region-start region-end))
11313 (prog1 org-refile-active-region-within-subtree
11314 (org-toggle-heading)))
11315 (error "The region is not a (sequence of) subtree(s)")))
11316 (if (equal goto '(16))
11317 (org-refile-goto-last-stored)
11318 (when (or
11319 (and (equal goto 2)
11320 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11321 (prog1
11322 (setq it (list (or org-clock-heading "running clock")
11323 (buffer-file-name
11324 (marker-buffer org-clock-hd-marker))
11326 (marker-position org-clock-hd-marker)))
11327 (setq goto nil)))
11328 (setq it (or rfloc
11329 (let (heading-text)
11330 (save-excursion
11331 (unless goto
11332 (org-back-to-heading t)
11333 (setq heading-text
11334 (nth 4 (org-heading-components))))
11336 (org-refile-get-location
11337 (cond (goto "Goto")
11338 (regionp (concat actionmsg " region to"))
11339 (t (concat actionmsg " subtree \""
11340 heading-text "\" to")))
11341 default-buffer
11342 (and (not (equal '(4) goto))
11343 org-refile-allow-creating-parent-nodes)
11344 goto))))))
11345 (setq file (nth 1 it)
11346 re (nth 2 it)
11347 pos (nth 3 it))
11348 (if (and (not goto)
11350 (equal (buffer-file-name) file)
11351 (if regionp
11352 (and (>= pos region-start)
11353 (<= pos region-end))
11354 (and (>= pos (point))
11355 (< pos (save-excursion
11356 (org-end-of-subtree t t))))))
11357 (error "Cannot refile to position inside the tree or region"))
11359 (setq nbuf (or (find-buffer-visiting file)
11360 (find-file-noselect file)))
11361 (if goto
11362 (progn
11363 (org-pop-to-buffer-same-window nbuf)
11364 (goto-char pos)
11365 (org-show-context 'org-goto))
11366 (if regionp
11367 (progn
11368 (org-kill-new (buffer-substring region-start region-end))
11369 (org-save-markers-in-region region-start region-end))
11370 (org-copy-subtree 1 nil t))
11371 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11372 (find-file-noselect file)))
11373 (setq reversed (org-notes-order-reversed-p))
11374 (save-excursion
11375 (save-restriction
11376 (widen)
11377 (if pos
11378 (progn
11379 (goto-char pos)
11380 (looking-at org-outline-regexp)
11381 (setq level (org-get-valid-level (funcall outline-level) 1))
11382 (goto-char
11383 (if reversed
11384 (or (outline-next-heading) (point-max))
11385 (or (save-excursion (org-get-next-sibling))
11386 (org-end-of-subtree t t)
11387 (point-max)))))
11388 (setq level 1)
11389 (if (not reversed)
11390 (goto-char (point-max))
11391 (goto-char (point-min))
11392 (or (outline-next-heading) (goto-char (point-max)))))
11393 (if (not (bolp)) (newline))
11394 (org-paste-subtree level)
11395 (when org-log-refile
11396 (org-add-log-setup 'refile nil nil 'findpos
11397 org-log-refile)
11398 (unless (eq org-log-refile 'note)
11399 (save-excursion (org-add-log-note))))
11400 (and org-auto-align-tags
11401 (let ((org-loop-over-headlines-in-active-region nil))
11402 (org-set-tags nil t)))
11403 (with-demoted-errors
11404 (bookmark-set "org-refile-last-stored"))
11405 ;; If we are refiling for capture, make sure that the
11406 ;; last-capture pointers point here
11407 (when (org-bound-and-true-p org-refile-for-capture)
11408 (with-demoted-errors
11409 (bookmark-set "org-capture-last-stored-marker"))
11410 (move-marker org-capture-last-stored-marker (point)))
11411 (if (fboundp 'deactivate-mark) (deactivate-mark))
11412 (run-hooks 'org-after-refile-insert-hook))))
11413 (unless org-refile-keep
11414 (if regionp
11415 (delete-region (point) (+ (point) region-length))
11416 (org-cut-subtree)))
11417 (when (featurep 'org-inlinetask)
11418 (org-inlinetask-remove-END-maybe))
11419 (setq org-markers-to-move nil)
11420 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11422 (defun org-refile-goto-last-stored ()
11423 "Go to the location where the last refile was stored."
11424 (interactive)
11425 (bookmark-jump "org-refile-last-stored")
11426 (message "This is the location of the last refile"))
11428 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11429 no-exclude)
11430 "Prompt the user for a refile location, using PROMPT.
11431 PROMPT should not be suffixed with a colon and a space, because
11432 this function appends the default value from
11433 `org-refile-history' automatically, if that is not empty.
11434 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11435 this is used for the GOTO interface."
11436 (let ((org-refile-targets org-refile-targets)
11437 (org-refile-use-outline-path org-refile-use-outline-path)
11438 excluded-entries)
11439 (when (and (derived-mode-p 'org-mode)
11440 (not org-refile-use-cache)
11441 (not no-exclude))
11442 (org-map-tree
11443 (lambda()
11444 (setq excluded-entries
11445 (append excluded-entries (list (org-get-heading t t)))))))
11446 (setq org-refile-target-table
11447 (org-refile-get-targets default-buffer excluded-entries)))
11448 (unless org-refile-target-table
11449 (error "No refile targets"))
11450 (let* ((cbuf (current-buffer))
11451 (partial-completion-mode nil)
11452 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11453 (cfunc (if (and org-refile-use-outline-path
11454 org-outline-path-complete-in-steps)
11455 'org-olpath-completing-read
11456 'org-icompleting-read))
11457 (extra (if org-refile-use-outline-path "/" ""))
11458 (cbnex (concat (buffer-name) extra))
11459 (filename (and cfn (expand-file-name cfn)))
11460 (tbl (mapcar
11461 (lambda (x)
11462 (if (and (not (member org-refile-use-outline-path
11463 '(file full-file-path)))
11464 (not (equal filename (nth 1 x))))
11465 (cons (concat (car x) extra " ("
11466 (file-name-nondirectory (nth 1 x)) ")")
11467 (cdr x))
11468 (cons (concat (car x) extra) (cdr x))))
11469 org-refile-target-table))
11470 (completion-ignore-case t)
11471 cdef
11472 (prompt (concat prompt
11473 (or (and (car org-refile-history)
11474 (concat " (default " (car org-refile-history) ")"))
11475 (and (assoc cbnex tbl) (setq cdef cbnex)
11476 (concat " (default " cbnex ")"))) ": "))
11477 pa answ parent-target child parent old-hist)
11478 (setq old-hist org-refile-history)
11479 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11480 nil 'org-refile-history (or cdef (car org-refile-history))))
11481 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11482 (org-refile-check-position pa)
11483 (if pa
11484 (progn
11485 (when (or (not org-refile-history)
11486 (not (eq old-hist org-refile-history))
11487 (not (equal (car pa) (car org-refile-history))))
11488 (setq org-refile-history
11489 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11490 org-refile-history
11491 (cdr org-refile-history))))
11492 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11493 (pop org-refile-history)))
11495 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11496 (progn
11497 (setq parent (match-string 1 answ)
11498 child (match-string 2 answ))
11499 (setq parent-target (or (assoc parent tbl)
11500 (assoc (concat parent "/") tbl)))
11501 (when (and parent-target
11502 (or (eq new-nodes t)
11503 (and (eq new-nodes 'confirm)
11504 (y-or-n-p (format "Create new node \"%s\"? "
11505 child)))))
11506 (org-refile-new-child parent-target child)))
11507 (error "Invalid target location")))))
11509 (declare-function org-string-nw-p "org-macs" (s))
11510 (defun org-refile-check-position (refile-pointer)
11511 "Check if the refile pointer matches the headline to which it points."
11512 (let* ((file (nth 1 refile-pointer))
11513 (re (nth 2 refile-pointer))
11514 (pos (nth 3 refile-pointer))
11515 buffer)
11516 (if (and (not (markerp pos)) (not file))
11517 (error "Please save the buffer to a file before refiling")
11518 (when (org-string-nw-p re)
11519 (setq buffer (if (markerp pos)
11520 (marker-buffer pos)
11521 (or (find-buffer-visiting file)
11522 (find-file-noselect file))))
11523 (with-current-buffer buffer
11524 (save-excursion
11525 (save-restriction
11526 (widen)
11527 (goto-char pos)
11528 (beginning-of-line 1)
11529 (unless (org-looking-at-p re)
11530 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11532 (defun org-refile-new-child (parent-target child)
11533 "Use refile target PARENT-TARGET to add new CHILD below it."
11534 (unless parent-target
11535 (error "Cannot find parent for new node"))
11536 (let ((file (nth 1 parent-target))
11537 (pos (nth 3 parent-target))
11538 level)
11539 (with-current-buffer (or (find-buffer-visiting file)
11540 (find-file-noselect file))
11541 (save-excursion
11542 (save-restriction
11543 (widen)
11544 (if pos
11545 (goto-char pos)
11546 (goto-char (point-max))
11547 (if (not (bolp)) (newline)))
11548 (when (looking-at org-outline-regexp)
11549 (setq level (funcall outline-level))
11550 (org-end-of-subtree t t))
11551 (org-back-over-empty-lines)
11552 (insert "\n" (make-string
11553 (if pos (org-get-valid-level level 1) 1) ?*)
11554 " " child "\n")
11555 (beginning-of-line 0)
11556 (list (concat (car parent-target) "/" child) file "" (point)))))))
11558 (defun org-olpath-completing-read (prompt collection &rest args)
11559 "Read an outline path like a file name."
11560 (let ((thetable collection)
11561 (org-completion-use-ido nil) ; does not work with ido.
11562 (org-completion-use-iswitchb nil)) ; or iswitchb
11563 (apply
11564 'org-icompleting-read prompt
11565 (lambda (string predicate &optional flag)
11566 (let (rtn r f (l (length string)))
11567 (cond
11568 ((eq flag nil)
11569 ;; try completion
11570 (try-completion string thetable))
11571 ((eq flag t)
11572 ;; all-completions
11573 (setq rtn (all-completions string thetable predicate))
11574 (mapcar
11575 (lambda (x)
11576 (setq r (substring x l))
11577 (if (string-match " ([^)]*)$" x)
11578 (setq f (match-string 0 x))
11579 (setq f ""))
11580 (if (string-match "/" r)
11581 (concat string (substring r 0 (match-end 0)) f)
11583 rtn))
11584 ((eq flag 'lambda)
11585 ;; exact match?
11586 (assoc string thetable)))))
11587 args)))
11589 ;;;; Dynamic blocks
11591 (defun org-find-dblock (name)
11592 "Find the first dynamic block with name NAME in the buffer.
11593 If not found, stay at current position and return nil."
11594 (let ((case-fold-search t) pos)
11595 (save-excursion
11596 (goto-char (point-min))
11597 (setq pos (and (re-search-forward
11598 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11599 (match-beginning 0))))
11600 (if pos (goto-char pos))
11601 pos))
11603 (defconst org-dblock-start-re
11604 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11605 "Matches the start line of a dynamic block, with parameters.")
11607 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11608 "Matches the end of a dynamic block.")
11610 (defun org-create-dblock (plist)
11611 "Create a dynamic block section, with parameters taken from PLIST.
11612 PLIST must contain a :name entry which is used as name of the block."
11613 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11614 (end-of-line 1)
11615 (newline))
11616 (let ((col (current-column))
11617 (name (plist-get plist :name)))
11618 (insert "#+BEGIN: " name)
11619 (while plist
11620 (if (eq (car plist) :name)
11621 (setq plist (cddr plist))
11622 (insert " " (prin1-to-string (pop plist)))))
11623 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11624 (beginning-of-line -2)))
11626 (defun org-prepare-dblock ()
11627 "Prepare dynamic block for refresh.
11628 This empties the block, puts the cursor at the insert position and returns
11629 the property list including an extra property :name with the block name."
11630 (unless (looking-at org-dblock-start-re)
11631 (error "Not at a dynamic block"))
11632 (let* ((begdel (1+ (match-end 0)))
11633 (name (org-no-properties (match-string 1)))
11634 (params (append (list :name name)
11635 (read (concat "(" (match-string 3) ")")))))
11636 (save-excursion
11637 (beginning-of-line 1)
11638 (skip-chars-forward " \t")
11639 (setq params (plist-put params :indentation-column (current-column))))
11640 (unless (re-search-forward org-dblock-end-re nil t)
11641 (error "Dynamic block not terminated"))
11642 (setq params
11643 (append params
11644 (list :content (buffer-substring
11645 begdel (match-beginning 0)))))
11646 (delete-region begdel (match-beginning 0))
11647 (goto-char begdel)
11648 (open-line 1)
11649 params))
11651 (defun org-map-dblocks (&optional command)
11652 "Apply COMMAND to all dynamic blocks in the current buffer.
11653 If COMMAND is not given, use `org-update-dblock'."
11654 (let ((cmd (or command 'org-update-dblock)))
11655 (save-excursion
11656 (goto-char (point-min))
11657 (while (re-search-forward org-dblock-start-re nil t)
11658 (goto-char (match-beginning 0))
11659 (save-excursion
11660 (condition-case nil
11661 (funcall cmd)
11662 (error (message "Error during update of dynamic block"))))
11663 (unless (re-search-forward org-dblock-end-re nil t)
11664 (error "Dynamic block not terminated"))))))
11666 (defun org-dblock-update (&optional arg)
11667 "User command for updating dynamic blocks.
11668 Update the dynamic block at point. With prefix ARG, update all dynamic
11669 blocks in the buffer."
11670 (interactive "P")
11671 (if arg
11672 (org-update-all-dblocks)
11673 (or (looking-at org-dblock-start-re)
11674 (org-beginning-of-dblock))
11675 (org-update-dblock)))
11677 (defun org-update-dblock ()
11678 "Update the dynamic block at point.
11679 This means to empty the block, parse for parameters and then call
11680 the correct writing function."
11681 (interactive)
11682 (save-window-excursion
11683 (let* ((pos (point))
11684 (line (org-current-line))
11685 (params (org-prepare-dblock))
11686 (name (plist-get params :name))
11687 (indent (plist-get params :indentation-column))
11688 (cmd (intern (concat "org-dblock-write:" name))))
11689 (message "Updating dynamic block `%s' at line %d..." name line)
11690 (funcall cmd params)
11691 (message "Updating dynamic block `%s' at line %d...done" name line)
11692 (goto-char pos)
11693 (when (and indent (> indent 0))
11694 (setq indent (make-string indent ?\ ))
11695 (save-excursion
11696 (org-beginning-of-dblock)
11697 (forward-line 1)
11698 (while (not (looking-at org-dblock-end-re))
11699 (insert indent)
11700 (beginning-of-line 2))
11701 (when (looking-at org-dblock-end-re)
11702 (and (looking-at "[ \t]+")
11703 (replace-match ""))
11704 (insert indent)))))))
11706 (defun org-beginning-of-dblock ()
11707 "Find the beginning of the dynamic block at point.
11708 Error if there is no such block at point."
11709 (let ((pos (point))
11710 beg)
11711 (end-of-line 1)
11712 (if (and (re-search-backward org-dblock-start-re nil t)
11713 (setq beg (match-beginning 0))
11714 (re-search-forward org-dblock-end-re nil t)
11715 (> (match-end 0) pos))
11716 (goto-char beg)
11717 (goto-char pos)
11718 (error "Not in a dynamic block"))))
11720 (defun org-update-all-dblocks ()
11721 "Update all dynamic blocks in the buffer.
11722 This function can be used in a hook."
11723 (interactive)
11724 (when (derived-mode-p 'org-mode)
11725 (org-map-dblocks 'org-update-dblock)))
11728 ;;;; Completion
11730 (defun org-get-export-keywords ()
11731 "Return a list of all currently understood export keywords.
11732 Export keywords include options, block names, attributes and
11733 keywords relative to each registered export back-end."
11734 (delq nil
11735 (let (keywords)
11736 (mapc
11737 (lambda (back-end)
11738 (let ((props (cdr back-end)))
11739 ;; Back-end name (for keywords, like #+LATEX:)
11740 (push (upcase (symbol-name (car back-end))) keywords)
11741 ;; Back-end options.
11742 (mapc (lambda (option) (push (cadr option) keywords))
11743 (plist-get (cdr back-end) :options-alist))))
11744 (org-bound-and-true-p org-export-registered-backends))
11745 keywords)))
11747 (defconst org-options-keywords
11748 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11749 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11750 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11751 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11752 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "INFOJS_OPT:"))
11754 (defcustom org-structure-template-alist
11755 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11756 "<src lang=\"?\">\n\n</src>")
11757 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11758 "<example>\n?\n</example>")
11759 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11760 "<quote>\n?\n</quote>")
11761 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11762 "<verse>\n?\n</verse>")
11763 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11764 "<verbatim>\n?\n</verbatim>")
11765 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11766 "<center>\n?\n</center>")
11767 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11768 "<literal style=\"latex\">\n?\n</literal>")
11769 ("L" "#+LaTeX: "
11770 "<literal style=\"latex\">?</literal>")
11771 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11772 "<literal style=\"html\">\n?\n</literal>")
11773 ("H" "#+HTML: "
11774 "<literal style=\"html\">?</literal>")
11775 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11776 ("A" "#+ASCII: ")
11777 ("i" "#+INDEX: ?"
11778 "#+INDEX: ?")
11779 ("I" "#+INCLUDE: %file ?"
11780 "<include file=%file markup=\"?\">"))
11781 "Structure completion elements.
11782 This is a list of abbreviation keys and values. The value gets inserted
11783 if you type `<' followed by the key and then press the completion key,
11784 usually `M-TAB'. %file will be replaced by a file name after prompting
11785 for the file using completion. The cursor will be placed at the position
11786 of the `?` in the template.
11787 There are two templates for each key, the first uses the original Org syntax,
11788 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11789 the default when the /org-mtags.el/ module has been loaded. See also the
11790 variable `org-mtags-prefer-muse-templates'."
11791 :group 'org-completion
11792 :type '(repeat
11793 (string :tag "Key")
11794 (string :tag "Template")
11795 (string :tag "Muse Template")))
11797 (defun org-try-structure-completion ()
11798 "Try to complete a structure template before point.
11799 This looks for strings like \"<e\" on an otherwise empty line and
11800 expands them."
11801 (let ((l (buffer-substring (point-at-bol) (point)))
11803 (when (and (looking-at "[ \t]*$")
11804 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11805 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11806 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11807 (match-beginning 1)) a)
11808 t)))
11810 (defun org-complete-expand-structure-template (start cell)
11811 "Expand a structure template."
11812 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11813 (rpl (nth (if musep 2 1) cell))
11814 (ind ""))
11815 (delete-region start (point))
11816 (when (string-match "\\`#\\+" rpl)
11817 (cond
11818 ((bolp))
11819 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11820 (setq ind (buffer-substring (point-at-bol) (point))))
11821 (t (newline))))
11822 (setq start (point))
11823 (if (string-match "%file" rpl)
11824 (setq rpl (replace-match
11825 (concat
11826 "\""
11827 (save-match-data
11828 (abbreviate-file-name (read-file-name "Include file: ")))
11829 "\"")
11830 t t rpl)))
11831 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11832 (concat "\n" ind)))
11833 (insert rpl)
11834 (if (re-search-backward "\\?" start t) (delete-char 1))))
11836 ;;;; TODO, DEADLINE, Comments
11838 (defun org-toggle-comment ()
11839 "Change the COMMENT state of an entry."
11840 (interactive)
11841 (save-excursion
11842 (org-back-to-heading)
11843 (let (case-fold-search)
11844 (cond
11845 ((looking-at (format org-heading-keyword-regexp-format
11846 org-comment-string))
11847 (goto-char (match-end 1))
11848 (looking-at (concat " +" org-comment-string))
11849 (replace-match "" t t)
11850 (when (eolp) (insert " ")))
11851 ((looking-at org-outline-regexp)
11852 (goto-char (match-end 0))
11853 (insert org-comment-string " "))))))
11855 (defvar org-last-todo-state-is-todo nil
11856 "This is non-nil when the last TODO state change led to a TODO state.
11857 If the last change removed the TODO tag or switched to DONE, then
11858 this is nil.")
11860 (defvar org-setting-tags nil) ; dynamically skipped
11862 (defvar org-todo-setup-filter-hook nil
11863 "Hook for functions that pre-filter todo specs.
11864 Each function takes a todo spec and returns either nil or the spec
11865 transformed into canonical form." )
11867 (defvar org-todo-get-default-hook nil
11868 "Hook for functions that get a default item for todo.
11869 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11870 nil or a string to be used for the todo mark." )
11872 (defvar org-agenda-headline-snapshot-before-repeat)
11874 (defun org-current-effective-time ()
11875 "Return current time adjusted for `org-extend-today-until' variable."
11876 (let* ((ct (org-current-time))
11877 (dct (decode-time ct))
11878 (ct1
11879 (cond
11880 (org-use-last-clock-out-time-as-effective-time
11881 (or (org-clock-get-last-clock-out-time) ct))
11882 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11883 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11884 (t ct))))
11885 ct1))
11887 (defun org-todo-yesterday (&optional arg)
11888 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11889 (interactive "P")
11890 (if (eq major-mode 'org-agenda-mode)
11891 (apply 'org-agenda-todo-yesterday arg)
11892 (let* ((hour (third (decode-time
11893 (org-current-time))))
11894 (org-extend-today-until (1+ hour)))
11895 (org-todo arg))))
11897 (defvar org-block-entry-blocking ""
11898 "First entry preventing the TODO state change.")
11900 (defun org-todo (&optional arg)
11901 "Change the TODO state of an item.
11902 The state of an item is given by a keyword at the start of the heading,
11903 like
11904 *** TODO Write paper
11905 *** DONE Call mom
11907 The different keywords are specified in the variable `org-todo-keywords'.
11908 By default the available states are \"TODO\" and \"DONE\".
11909 So for this example: when the item starts with TODO, it is changed to DONE.
11910 When it starts with DONE, the DONE is removed. And when neither TODO nor
11911 DONE are present, add TODO at the beginning of the heading.
11913 With \\[universal-argument] prefix arg, use completion to determine the new \
11914 state.
11915 With numeric prefix arg, switch to that state.
11916 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11917 keywords (nextset).
11918 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11919 With a numeric prefix arg of 0, inhibit note taking for the change.
11921 For calling through lisp, arg is also interpreted in the following way:
11922 'none -> empty state
11923 \"\"(empty string) -> switch to empty state
11924 'done -> switch to DONE
11925 'nextset -> switch to the next set of keywords
11926 'previousset -> switch to the previous set of keywords
11927 \"WAITING\" -> switch to the specified keyword, but only if it
11928 really is a member of `org-todo-keywords'."
11929 (interactive "P")
11930 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11931 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11932 'region-start-level 'region))
11933 org-loop-over-headlines-in-active-region)
11934 (org-map-entries
11935 `(org-todo ,arg)
11936 org-loop-over-headlines-in-active-region
11937 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11938 (if (equal arg '(16)) (setq arg 'nextset))
11939 (let ((org-blocker-hook org-blocker-hook)
11940 commentp
11941 case-fold-search)
11942 (when (equal arg '(64))
11943 (setq arg nil org-blocker-hook nil))
11944 (when (and org-blocker-hook
11945 (or org-inhibit-blocking
11946 (org-entry-get nil "NOBLOCKING")))
11947 (setq org-blocker-hook nil))
11948 (save-excursion
11949 (catch 'exit
11950 (org-back-to-heading t)
11951 (when (looking-at (concat "^\\*+ " org-comment-string))
11952 (org-toggle-comment)
11953 (setq commentp t))
11954 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11955 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11956 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11957 (let* ((match-data (match-data))
11958 (startpos (point-at-bol))
11959 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11960 (org-log-done org-log-done)
11961 (org-log-repeat org-log-repeat)
11962 (org-todo-log-states org-todo-log-states)
11963 (org-inhibit-logging
11964 (if (equal arg 0)
11965 (progn (setq arg nil) 'note) org-inhibit-logging))
11966 (this (match-string 1))
11967 (hl-pos (match-beginning 0))
11968 (head (org-get-todo-sequence-head this))
11969 (ass (assoc head org-todo-kwd-alist))
11970 (interpret (nth 1 ass))
11971 (done-word (nth 3 ass))
11972 (final-done-word (nth 4 ass))
11973 (org-last-state (or this ""))
11974 (completion-ignore-case t)
11975 (member (member this org-todo-keywords-1))
11976 (tail (cdr member))
11977 (org-state (cond
11978 ((and org-todo-key-trigger
11979 (or (and (equal arg '(4))
11980 (eq org-use-fast-todo-selection 'prefix))
11981 (and (not arg) org-use-fast-todo-selection
11982 (not (eq org-use-fast-todo-selection
11983 'prefix)))))
11984 ;; Use fast selection
11985 (org-fast-todo-selection))
11986 ((and (equal arg '(4))
11987 (or (not org-use-fast-todo-selection)
11988 (not org-todo-key-trigger)))
11989 ;; Read a state with completion
11990 (org-icompleting-read
11991 "State: " (mapcar (lambda(x) (list x))
11992 org-todo-keywords-1)
11993 nil t))
11994 ((eq arg 'right)
11995 (if this
11996 (if tail (car tail) nil)
11997 (car org-todo-keywords-1)))
11998 ((eq arg 'left)
11999 (if (equal member org-todo-keywords-1)
12001 (if this
12002 (nth (- (length org-todo-keywords-1)
12003 (length tail) 2)
12004 org-todo-keywords-1)
12005 (org-last org-todo-keywords-1))))
12006 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12007 (setq arg nil))) ; hack to fall back to cycling
12008 (arg
12009 ;; user or caller requests a specific state
12010 (cond
12011 ((equal arg "") nil)
12012 ((eq arg 'none) nil)
12013 ((eq arg 'done) (or done-word (car org-done-keywords)))
12014 ((eq arg 'nextset)
12015 (or (car (cdr (member head org-todo-heads)))
12016 (car org-todo-heads)))
12017 ((eq arg 'previousset)
12018 (let ((org-todo-heads (reverse org-todo-heads)))
12019 (or (car (cdr (member head org-todo-heads)))
12020 (car org-todo-heads))))
12021 ((car (member arg org-todo-keywords-1)))
12022 ((stringp arg)
12023 (error "State `%s' not valid in this file" arg))
12024 ((nth (1- (prefix-numeric-value arg))
12025 org-todo-keywords-1))))
12026 ((null member) (or head (car org-todo-keywords-1)))
12027 ((equal this final-done-word) nil) ;; -> make empty
12028 ((null tail) nil) ;; -> first entry
12029 ((memq interpret '(type priority))
12030 (if (eq this-command last-command)
12031 (car tail)
12032 (if (> (length tail) 0)
12033 (or done-word (car org-done-keywords))
12034 nil)))
12036 (car tail))))
12037 (org-state (or
12038 (run-hook-with-args-until-success
12039 'org-todo-get-default-hook org-state org-last-state)
12040 org-state))
12041 (next (if org-state (concat " " org-state " ") " "))
12042 (change-plist (list :type 'todo-state-change :from this :to org-state
12043 :position startpos))
12044 dolog now-done-p)
12045 (when org-blocker-hook
12046 (setq org-last-todo-state-is-todo
12047 (not (member this org-done-keywords)))
12048 (unless (save-excursion
12049 (save-match-data
12050 (org-with-wide-buffer
12051 (run-hook-with-args-until-failure
12052 'org-blocker-hook change-plist))))
12053 (if (org-called-interactively-p 'interactive)
12054 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12055 this org-state org-block-entry-blocking)
12056 ;; fail silently
12057 (message "TODO state change from %s to %s blocked (by \"%s\")"
12058 this org-state org-block-entry-blocking)
12059 (throw 'exit nil))))
12060 (store-match-data match-data)
12061 (replace-match next t t)
12062 (unless (pos-visible-in-window-p hl-pos)
12063 (message "TODO state changed to %s" (org-trim next)))
12064 (unless head
12065 (setq head (org-get-todo-sequence-head org-state)
12066 ass (assoc head org-todo-kwd-alist)
12067 interpret (nth 1 ass)
12068 done-word (nth 3 ass)
12069 final-done-word (nth 4 ass)))
12070 (when (memq arg '(nextset previousset))
12071 (message "Keyword-Set %d/%d: %s"
12072 (- (length org-todo-sets) -1
12073 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12074 (length org-todo-sets)
12075 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12076 (setq org-last-todo-state-is-todo
12077 (not (member org-state org-done-keywords)))
12078 (setq now-done-p (and (member org-state org-done-keywords)
12079 (not (member this org-done-keywords))))
12080 (and logging (org-local-logging logging))
12081 (when (and (or org-todo-log-states org-log-done)
12082 (not (eq org-inhibit-logging t))
12083 (not (memq arg '(nextset previousset))))
12084 ;; we need to look at recording a time and note
12085 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12086 (nth 2 (assoc this org-todo-log-states))))
12087 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12088 (setq dolog 'time))
12089 (when (and org-state
12090 (member org-state org-not-done-keywords)
12091 (not (member this org-not-done-keywords)))
12092 ;; This is now a todo state and was not one before
12093 ;; If there was a CLOSED time stamp, get rid of it.
12094 (org-add-planning-info nil nil 'closed))
12095 (when (and now-done-p org-log-done)
12096 ;; It is now done, and it was not done before
12097 (org-add-planning-info 'closed (org-current-effective-time))
12098 (if (and (not dolog) (eq 'note org-log-done))
12099 (org-add-log-setup 'done org-state this 'findpos 'note)))
12100 (when (and org-state dolog)
12101 ;; This is a non-nil state, and we need to log it
12102 (org-add-log-setup 'state org-state this 'findpos dolog)))
12103 ;; Fixup tag positioning
12104 (org-todo-trigger-tag-changes org-state)
12105 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12106 (when org-provide-todo-statistics
12107 (org-update-parent-todo-statistics))
12108 (run-hooks 'org-after-todo-state-change-hook)
12109 (if (and arg (not (member org-state org-done-keywords)))
12110 (setq head (org-get-todo-sequence-head org-state)))
12111 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12112 ;; Do we need to trigger a repeat?
12113 (when now-done-p
12114 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12115 ;; This is for the agenda, take a snapshot of the headline.
12116 (save-match-data
12117 (setq org-agenda-headline-snapshot-before-repeat
12118 (org-get-heading))))
12119 (org-auto-repeat-maybe org-state))
12120 ;; Fixup cursor location if close to the keyword
12121 (if (and (outline-on-heading-p)
12122 (not (bolp))
12123 (save-excursion (beginning-of-line 1)
12124 (looking-at org-todo-line-regexp))
12125 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12126 (progn
12127 (goto-char (or (match-end 2) (match-end 1)))
12128 (and (looking-at " ") (just-one-space))))
12129 (when org-trigger-hook
12130 (save-excursion
12131 (run-hook-with-args 'org-trigger-hook change-plist)))
12132 (when commentp (org-toggle-comment))))))))
12134 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12135 "Block turning an entry into a TODO, using the hierarchy.
12136 This checks whether the current task should be blocked from state
12137 changes. Such blocking occurs when:
12139 1. The task has children which are not all in a completed state.
12141 2. A task has a parent with the property :ORDERED:, and there
12142 are siblings prior to the current task with incomplete
12143 status.
12145 3. The parent of the task is blocked because it has siblings that should
12146 be done first, or is child of a block grandparent TODO entry."
12148 (if (not org-enforce-todo-dependencies)
12149 t ; if locally turned off don't block
12150 (catch 'dont-block
12151 ;; If this is not a todo state change, or if this entry is already DONE,
12152 ;; do not block
12153 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12154 (member (plist-get change-plist :from)
12155 (cons 'done org-done-keywords))
12156 (member (plist-get change-plist :to)
12157 (cons 'todo org-not-done-keywords))
12158 (not (plist-get change-plist :to)))
12159 (throw 'dont-block t))
12160 ;; If this task has children, and any are undone, it's blocked
12161 (save-excursion
12162 (org-back-to-heading t)
12163 (let ((this-level (funcall outline-level)))
12164 (outline-next-heading)
12165 (let ((child-level (funcall outline-level)))
12166 (while (and (not (eobp))
12167 (> child-level this-level))
12168 ;; this todo has children, check whether they are all
12169 ;; completed
12170 (if (and (not (org-entry-is-done-p))
12171 (org-entry-is-todo-p))
12172 (progn (setq org-block-entry-blocking (org-get-heading))
12173 (throw 'dont-block nil)))
12174 (outline-next-heading)
12175 (setq child-level (funcall outline-level))))))
12176 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12177 ;; any previous siblings are undone, it's blocked
12178 (save-excursion
12179 (org-back-to-heading t)
12180 (let* ((pos (point))
12181 (parent-pos (and (org-up-heading-safe) (point))))
12182 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12183 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12184 (forward-line 1)
12185 (re-search-forward org-not-done-heading-regexp pos t))
12186 (setq org-block-entry-blocking (match-string 0))
12187 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12188 ;; Search further up the hierarchy, to see if an ancestor is blocked
12189 (while t
12190 (goto-char parent-pos)
12191 (if (not (looking-at org-not-done-heading-regexp))
12192 (throw 'dont-block t)) ; do not block, parent is not a TODO
12193 (setq pos (point))
12194 (setq parent-pos (and (org-up-heading-safe) (point)))
12195 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12196 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12197 (forward-line 1)
12198 (re-search-forward org-not-done-heading-regexp pos t)
12199 (setq org-block-entry-blocking (org-get-heading)))
12200 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12202 (defcustom org-track-ordered-property-with-tag nil
12203 "Should the ORDERED property also be shown as a tag?
12204 The ORDERED property decides if an entry should require subtasks to be
12205 completed in sequence. Since a property is not very visible, setting
12206 this option means that toggling the ORDERED property with the command
12207 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12208 not relevant for the behavior, but it makes things more visible.
12210 Note that toggling the tag with tags commands will not change the property
12211 and therefore not influence behavior!
12213 This can be t, meaning the tag ORDERED should be used, It can also be a
12214 string to select a different tag for this task."
12215 :group 'org-todo
12216 :type '(choice
12217 (const :tag "No tracking" nil)
12218 (const :tag "Track with ORDERED tag" t)
12219 (string :tag "Use other tag")))
12221 (defun org-toggle-ordered-property ()
12222 "Toggle the ORDERED property of the current entry.
12223 For better visibility, you can track the value of this property with a tag.
12224 See variable `org-track-ordered-property-with-tag'."
12225 (interactive)
12226 (let* ((t1 org-track-ordered-property-with-tag)
12227 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12228 (save-excursion
12229 (org-back-to-heading)
12230 (if (org-entry-get nil "ORDERED")
12231 (progn
12232 (org-delete-property "ORDERED" "PROPERTIES")
12233 (and tag (org-toggle-tag tag 'off))
12234 (message "Subtasks can be completed in arbitrary order"))
12235 (org-entry-put nil "ORDERED" "t")
12236 (and tag (org-toggle-tag tag 'on))
12237 (message "Subtasks must be completed in sequence")))))
12239 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12240 (defun org-block-todo-from-checkboxes (change-plist)
12241 "Block turning an entry into a TODO, using checkboxes.
12242 This checks whether the current task should be blocked from state
12243 changes because there are unchecked boxes in this entry."
12244 (if (not org-enforce-todo-checkbox-dependencies)
12245 t ; if locally turned off don't block
12246 (catch 'dont-block
12247 ;; If this is not a todo state change, or if this entry is already DONE,
12248 ;; do not block
12249 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12250 (member (plist-get change-plist :from)
12251 (cons 'done org-done-keywords))
12252 (member (plist-get change-plist :to)
12253 (cons 'todo org-not-done-keywords))
12254 (not (plist-get change-plist :to)))
12255 (throw 'dont-block t))
12256 ;; If this task has checkboxes that are not checked, it's blocked
12257 (save-excursion
12258 (org-back-to-heading t)
12259 (let ((beg (point)) end)
12260 (outline-next-heading)
12261 (setq end (point))
12262 (goto-char beg)
12263 (if (org-list-search-forward
12264 (concat (org-item-beginning-re)
12265 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12266 "\\[[- ]\\]")
12267 end t)
12268 (progn
12269 (if (boundp 'org-blocked-by-checkboxes)
12270 (setq org-blocked-by-checkboxes t))
12271 (throw 'dont-block nil)))))
12272 t))) ; do not block
12274 (defun org-entry-blocked-p ()
12275 "Is the current entry blocked?"
12276 (org-with-silent-modifications
12277 (if (org-entry-get nil "NOBLOCKING")
12278 nil ;; Never block this entry
12279 (not (run-hook-with-args-until-failure
12280 'org-blocker-hook
12281 (list :type 'todo-state-change
12282 :position (point)
12283 :from 'todo
12284 :to 'done))))))
12286 (defun org-update-statistics-cookies (all)
12287 "Update the statistics cookie, either from TODO or from checkboxes.
12288 This should be called with the cursor in a line with a statistics cookie."
12289 (interactive "P")
12290 (if all
12291 (progn
12292 (org-update-checkbox-count 'all)
12293 (org-map-entries 'org-update-parent-todo-statistics))
12294 (if (not (org-at-heading-p))
12295 (org-update-checkbox-count)
12296 (let ((pos (point-marker))
12297 end l1 l2)
12298 (ignore-errors (org-back-to-heading t))
12299 (if (not (org-at-heading-p))
12300 (org-update-checkbox-count)
12301 (setq l1 (org-outline-level))
12302 (setq end (save-excursion
12303 (outline-next-heading)
12304 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12305 (point)))
12306 (if (and (save-excursion
12307 (re-search-forward
12308 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12309 (not (save-excursion (re-search-forward
12310 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12311 (org-update-checkbox-count)
12312 (if (and l2 (> l2 l1))
12313 (progn
12314 (goto-char end)
12315 (org-update-parent-todo-statistics))
12316 (goto-char pos)
12317 (beginning-of-line 1)
12318 (while (re-search-forward
12319 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12320 (point-at-eol) t)
12321 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12322 (goto-char pos)
12323 (move-marker pos nil)))))
12325 (defvar org-entry-property-inherited-from) ;; defined below
12326 (defun org-update-parent-todo-statistics ()
12327 "Update any statistics cookie in the parent of the current headline.
12328 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12329 the entire subtree and this will travel up the hierarchy and update
12330 statistics everywhere."
12331 (let* ((prop (save-excursion (org-up-heading-safe)
12332 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12333 (recursive (or (not org-hierarchical-todo-statistics)
12334 (and prop (string-match "\\<recursive\\>" prop))))
12335 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12337 (first t)
12338 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12339 level ltoggle l1 new ndel
12340 (cnt-all 0) (cnt-done 0) is-percent kwd
12341 checkbox-beg ov ovs ove cookie-present)
12342 (catch 'exit
12343 (save-excursion
12344 (beginning-of-line 1)
12345 (setq ltoggle (funcall outline-level))
12346 ;; Three situations are to consider:
12348 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12349 ;; to the top-level ancestor on the headline;
12351 ;; 2. If parent has "recursive" property, repeat up to the
12352 ;; headline setting that property, taking inheritance into
12353 ;; account;
12355 ;; 3. Else, move up to direct parent and proceed only once.
12356 (while (and (setq level (org-up-heading-safe))
12357 (or recursive first)
12358 (>= (point) lim))
12359 (setq first nil cookie-present nil)
12360 (unless (and level
12361 (not (string-match
12362 "\\<checkbox\\>"
12363 (downcase (or (org-entry-get nil "COOKIE_DATA")
12364 "")))))
12365 (throw 'exit nil))
12366 (while (re-search-forward box-re (point-at-eol) t)
12367 (setq cnt-all 0 cnt-done 0 cookie-present t)
12368 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12369 (save-match-data
12370 (unless (outline-next-heading) (throw 'exit nil))
12371 (while (and (looking-at org-complex-heading-regexp)
12372 (> (setq l1 (length (match-string 1))) level))
12373 (setq kwd (and (or recursive (= l1 ltoggle))
12374 (match-string 2)))
12375 (if (or (eq org-provide-todo-statistics 'all-headlines)
12376 (and (listp org-provide-todo-statistics)
12377 (or (member kwd org-provide-todo-statistics)
12378 (member kwd org-done-keywords))))
12379 (setq cnt-all (1+ cnt-all))
12380 (if (eq org-provide-todo-statistics t)
12381 (and kwd (setq cnt-all (1+ cnt-all)))))
12382 (and (member kwd org-done-keywords)
12383 (setq cnt-done (1+ cnt-done)))
12384 (outline-next-heading)))
12385 (setq new
12386 (if is-percent
12387 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12388 (format "[%d/%d]" cnt-done cnt-all))
12389 ndel (- (match-end 0) checkbox-beg))
12390 ;; handle overlays when updating cookie from column view
12391 (when (setq ov (car (overlays-at checkbox-beg)))
12392 (setq ovs (overlay-start ov) ove (overlay-end ov))
12393 (delete-overlay ov))
12394 (goto-char checkbox-beg)
12395 (insert new)
12396 (delete-region (point) (+ (point) ndel))
12397 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12398 (when ov (move-overlay ov ovs ove)))
12399 (when cookie-present
12400 (run-hook-with-args 'org-after-todo-statistics-hook
12401 cnt-done (- cnt-all cnt-done))))))
12402 (run-hooks 'org-todo-statistics-hook)))
12404 (defvar org-after-todo-statistics-hook nil
12405 "Hook that is called after a TODO statistics cookie has been updated.
12406 Each function is called with two arguments: the number of not-done entries
12407 and the number of done entries.
12409 For example, the following function, when added to this hook, will switch
12410 an entry to DONE when all children are done, and back to TODO when new
12411 entries are set to a TODO status. Note that this hook is only called
12412 when there is a statistics cookie in the headline!
12414 (defun org-summary-todo (n-done n-not-done)
12415 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12416 (let (org-log-done org-log-states) ; turn off logging
12417 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12420 (defvar org-todo-statistics-hook nil
12421 "Hook that is run whenever Org thinks TODO statistics should be updated.
12422 This hook runs even if there is no statistics cookie present, in which case
12423 `org-after-todo-statistics-hook' would not run.")
12425 (defun org-todo-trigger-tag-changes (state)
12426 "Apply the changes defined in `org-todo-state-tags-triggers'."
12427 (let ((l org-todo-state-tags-triggers)
12428 changes)
12429 (when (or (not state) (equal state ""))
12430 (setq changes (append changes (cdr (assoc "" l)))))
12431 (when (and (stringp state) (> (length state) 0))
12432 (setq changes (append changes (cdr (assoc state l)))))
12433 (when (member state org-not-done-keywords)
12434 (setq changes (append changes (cdr (assoc 'todo l)))))
12435 (when (member state org-done-keywords)
12436 (setq changes (append changes (cdr (assoc 'done l)))))
12437 (dolist (c changes)
12438 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12440 (defun org-local-logging (value)
12441 "Get logging settings from a property VALUE."
12442 (let* (words w a)
12443 ;; directly set the variables, they are already local.
12444 (setq org-log-done nil
12445 org-log-repeat nil
12446 org-todo-log-states nil)
12447 (setq words (org-split-string value))
12448 (while (setq w (pop words))
12449 (cond
12450 ((setq a (assoc w org-startup-options))
12451 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12452 (set (nth 1 a) (nth 2 a))))
12453 ((setq a (org-extract-log-state-settings w))
12454 (and (member (car a) org-todo-keywords-1)
12455 (push a org-todo-log-states)))))))
12457 (defun org-get-todo-sequence-head (kwd)
12458 "Return the head of the TODO sequence to which KWD belongs.
12459 If KWD is not set, check if there is a text property remembering the
12460 right sequence."
12461 (let (p)
12462 (cond
12463 ((not kwd)
12464 (or (get-text-property (point-at-bol) 'org-todo-head)
12465 (progn
12466 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12467 nil (point-at-eol)))
12468 (get-text-property p 'org-todo-head))))
12469 ((not (member kwd org-todo-keywords-1))
12470 (car org-todo-keywords-1))
12471 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12473 (defun org-fast-todo-selection ()
12474 "Fast TODO keyword selection with single keys.
12475 Returns the new TODO keyword, or nil if no state change should occur."
12476 (let* ((fulltable org-todo-key-alist)
12477 (done-keywords org-done-keywords) ;; needed for the faces.
12478 (maxlen (apply 'max (mapcar
12479 (lambda (x)
12480 (if (stringp (car x)) (string-width (car x)) 0))
12481 fulltable)))
12482 (expert nil)
12483 (fwidth (+ maxlen 3 1 3))
12484 (ncol (/ (- (window-width) 4) fwidth))
12485 tg cnt e c tbl
12486 groups ingroup)
12487 (save-excursion
12488 (save-window-excursion
12489 (if expert
12490 (set-buffer (get-buffer-create " *Org todo*"))
12491 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12492 (erase-buffer)
12493 (org-set-local 'org-done-keywords done-keywords)
12494 (setq tbl fulltable cnt 0)
12495 (while (setq e (pop tbl))
12496 (cond
12497 ((equal e '(:startgroup))
12498 (push '() groups) (setq ingroup t)
12499 (when (not (= cnt 0))
12500 (setq cnt 0)
12501 (insert "\n"))
12502 (insert "{ "))
12503 ((equal e '(:endgroup))
12504 (setq ingroup nil cnt 0)
12505 (insert "}\n"))
12506 ((equal e '(:newline))
12507 (when (not (= cnt 0))
12508 (setq cnt 0)
12509 (insert "\n")
12510 (setq e (car tbl))
12511 (while (equal (car tbl) '(:newline))
12512 (insert "\n")
12513 (setq tbl (cdr tbl)))))
12515 (setq tg (car e) c (cdr e))
12516 (if ingroup (push tg (car groups)))
12517 (setq tg (org-add-props tg nil 'face
12518 (org-get-todo-face tg)))
12519 (if (and (= cnt 0) (not ingroup)) (insert " "))
12520 (insert "[" c "] " tg (make-string
12521 (- fwidth 4 (length tg)) ?\ ))
12522 (when (= (setq cnt (1+ cnt)) ncol)
12523 (insert "\n")
12524 (if ingroup (insert " "))
12525 (setq cnt 0)))))
12526 (insert "\n")
12527 (goto-char (point-min))
12528 (if (not expert) (org-fit-window-to-buffer))
12529 (message "[a-z..]:Set [SPC]:clear")
12530 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12531 (cond
12532 ((or (= c ?\C-g)
12533 (and (= c ?q) (not (rassoc c fulltable))))
12534 (setq quit-flag t))
12535 ((= c ?\ ) nil)
12536 ((setq e (rassoc c fulltable) tg (car e))
12538 (t (setq quit-flag t)))))))
12540 (defun org-entry-is-todo-p ()
12541 (member (org-get-todo-state) org-not-done-keywords))
12543 (defun org-entry-is-done-p ()
12544 (member (org-get-todo-state) org-done-keywords))
12546 (defun org-get-todo-state ()
12547 (save-excursion
12548 (org-back-to-heading t)
12549 (and (looking-at org-todo-line-regexp)
12550 (match-end 2)
12551 (match-string 2))))
12553 (defun org-at-date-range-p (&optional inactive-ok)
12554 "Is the cursor inside a date range?"
12555 (interactive)
12556 (save-excursion
12557 (catch 'exit
12558 (let ((pos (point)))
12559 (skip-chars-backward "^[<\r\n")
12560 (skip-chars-backward "<[")
12561 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12562 (>= (match-end 0) pos)
12563 (throw 'exit t))
12564 (skip-chars-backward "^<[\r\n")
12565 (skip-chars-backward "<[")
12566 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12567 (>= (match-end 0) pos)
12568 (throw 'exit t)))
12569 nil)))
12571 (defun org-get-repeat (&optional tagline)
12572 "Check if there is a deadline/schedule with repeater in this entry."
12573 (save-match-data
12574 (save-excursion
12575 (org-back-to-heading t)
12576 (and (re-search-forward (if tagline
12577 (concat tagline "\\s-*" org-repeat-re)
12578 org-repeat-re)
12579 (org-entry-end-position) t)
12580 (match-string-no-properties 1)))))
12582 (defvar org-last-changed-timestamp)
12583 (defvar org-last-inserted-timestamp)
12584 (defvar org-log-post-message)
12585 (defvar org-log-note-purpose)
12586 (defvar org-log-note-how)
12587 (defvar org-log-note-extra)
12588 (defun org-auto-repeat-maybe (done-word)
12589 "Check if the current headline contains a repeated deadline/schedule.
12590 If yes, set TODO state back to what it was and change the base date
12591 of repeating deadline/scheduled time stamps to new date.
12592 This function is run automatically after each state change to a DONE state."
12593 ;; last-state is dynamically scoped into this function
12594 (let* ((repeat (org-get-repeat))
12595 (aa (assoc org-last-state org-todo-kwd-alist))
12596 (interpret (nth 1 aa))
12597 (head (nth 2 aa))
12598 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12599 (msg "Entry repeats: ")
12600 (org-log-done nil)
12601 (org-todo-log-states nil)
12602 re type n what ts time to-state)
12603 (when repeat
12604 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12605 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12606 org-todo-repeat-to-state))
12607 (unless (and to-state (member to-state org-todo-keywords-1))
12608 (setq to-state (if (eq interpret 'type) org-last-state head)))
12609 (org-todo to-state)
12610 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12611 (org-entry-put nil "LAST_REPEAT" (format-time-string
12612 (org-time-stamp-format t t))))
12613 (when org-log-repeat
12614 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12615 (memq 'org-add-log-note post-command-hook))
12616 ;; OK, we are already setup for some record
12617 (if (eq org-log-repeat 'note)
12618 ;; make sure we take a note, not only a time stamp
12619 (setq org-log-note-how 'note))
12620 ;; Set up for taking a record
12621 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12622 org-last-state
12623 'findpos org-log-repeat)))
12624 (org-back-to-heading t)
12625 (org-add-planning-info nil nil 'closed)
12626 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12627 org-deadline-time-regexp "\\)\\|\\("
12628 org-ts-regexp "\\)"))
12629 (while (re-search-forward
12630 re (save-excursion (outline-next-heading) (point)) t)
12631 (setq type (if (match-end 1) org-scheduled-string
12632 (if (match-end 3) org-deadline-string "Plain:"))
12633 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12634 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12635 (setq n (string-to-number (match-string 2 ts))
12636 what (match-string 3 ts))
12637 (if (equal what "w") (setq n (* n 7) what "d"))
12638 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12639 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12640 ;; Preparation, see if we need to modify the start date for the change
12641 (when (match-end 1)
12642 (setq time (save-match-data (org-time-string-to-time ts)))
12643 (cond
12644 ((equal (match-string 1 ts) ".")
12645 ;; Shift starting date to today
12646 (org-timestamp-change
12647 (- (org-today) (time-to-days time))
12648 'day))
12649 ((equal (match-string 1 ts) "+")
12650 (let ((nshiftmax 10) (nshift 0))
12651 (while (or (= nshift 0)
12652 (<= (time-to-days time)
12653 (time-to-days (current-time))))
12654 (when (= (incf nshift) nshiftmax)
12655 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12656 (error "Abort")))
12657 (org-timestamp-change n (cdr (assoc what whata)))
12658 (org-at-timestamp-p t)
12659 (setq ts (match-string 1))
12660 (setq time (save-match-data (org-time-string-to-time ts)))))
12661 (org-timestamp-change (- n) (cdr (assoc what whata)))
12662 ;; rematch, so that we have everything in place for the real shift
12663 (org-at-timestamp-p t)
12664 (setq ts (match-string 1))
12665 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12666 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12667 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12668 (setq org-log-post-message msg)
12669 (message "%s" msg))))
12671 (defun org-show-todo-tree (arg)
12672 "Make a compact tree which shows all headlines marked with TODO.
12673 The tree will show the lines where the regexp matches, and all higher
12674 headlines above the match.
12675 With a \\[universal-argument] prefix, prompt for a regexp to match.
12676 With a numeric prefix N, construct a sparse tree for the Nth element
12677 of `org-todo-keywords-1'."
12678 (interactive "P")
12679 (let ((case-fold-search nil)
12680 (kwd-re
12681 (cond ((null arg) org-not-done-regexp)
12682 ((equal arg '(4))
12683 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12684 (mapcar 'list org-todo-keywords-1))))
12685 (concat "\\("
12686 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12687 "\\)\\>")))
12688 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12689 (regexp-quote (nth (1- (prefix-numeric-value arg))
12690 org-todo-keywords-1)))
12691 (t (error "Invalid prefix argument: %s" arg)))))
12692 (message "%d TODO entries found"
12693 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12695 (defun org-deadline (arg &optional time)
12696 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12697 With one universal prefix argument, remove any deadline from the item.
12698 With two universal prefix arguments, prompt for a warning delay.
12699 With argument TIME, set the deadline at the corresponding date. TIME
12700 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12701 (interactive "P")
12702 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12703 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12704 'region-start-level 'region))
12705 org-loop-over-headlines-in-active-region)
12706 (org-map-entries
12707 `(org-deadline ',arg ,time)
12708 org-loop-over-headlines-in-active-region
12709 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12710 (let* ((old-date (org-entry-get nil "DEADLINE"))
12711 (old-date-time (if old-date (org-time-string-to-time old-date)))
12712 (repeater (and old-date
12713 (string-match
12714 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12715 old-date)
12716 (match-string 1 old-date))))
12717 (cond
12718 ((equal arg '(4))
12719 (when (and old-date org-log-redeadline)
12720 (org-add-log-setup 'deldeadline nil old-date 'findpos
12721 org-log-redeadline))
12722 (org-remove-timestamp-with-keyword org-deadline-string)
12723 (message "Item no longer has a deadline."))
12724 ((equal arg '(16))
12725 (save-excursion
12726 (if (re-search-forward
12727 org-deadline-time-regexp
12728 (save-excursion (outline-next-heading) (point)) t)
12729 (let* ((rpl0 (match-string 1))
12730 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12731 (replace-match
12732 (concat org-deadline-string
12733 " <" rpl
12734 (format " -%dd"
12735 (abs
12736 (- (time-to-days
12737 (save-match-data
12738 (org-read-date nil t nil "Warn starting from" old-date-time)))
12739 (time-to-days old-date-time))))
12740 ">") t t))
12741 (user-error "No deadline information to update"))))
12743 (org-add-planning-info 'deadline time 'closed)
12744 (when (and old-date org-log-redeadline
12745 (not (equal old-date
12746 (substring org-last-inserted-timestamp 1 -1))))
12747 (org-add-log-setup 'redeadline nil old-date 'findpos
12748 org-log-redeadline))
12749 (when repeater
12750 (save-excursion
12751 (org-back-to-heading t)
12752 (when (re-search-forward (concat org-deadline-string " "
12753 org-last-inserted-timestamp)
12754 (save-excursion
12755 (outline-next-heading) (point)) t)
12756 (goto-char (1- (match-end 0)))
12757 (insert " " repeater)
12758 (setq org-last-inserted-timestamp
12759 (concat (substring org-last-inserted-timestamp 0 -1)
12760 " " repeater
12761 (substring org-last-inserted-timestamp -1))))))
12762 (message "Deadline on %s" org-last-inserted-timestamp))))))
12764 (defun org-schedule (arg &optional time)
12765 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12766 With one universal prefix argument, remove any scheduling date from the item.
12767 With two universal prefix arguments, prompt for a delay cookie.
12768 With argument TIME, scheduled at the corresponding date. TIME can
12769 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12770 (interactive "P")
12771 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12772 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12773 'region-start-level 'region))
12774 org-loop-over-headlines-in-active-region)
12775 (org-map-entries
12776 `(org-schedule ',arg ,time)
12777 org-loop-over-headlines-in-active-region
12778 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12779 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12780 (old-date-time (if old-date (org-time-string-to-time old-date)))
12781 (repeater (and old-date
12782 (string-match
12783 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12784 old-date)
12785 (match-string 1 old-date))))
12786 (cond
12787 ((equal arg '(4))
12788 (progn
12789 (when (and old-date org-log-reschedule)
12790 (org-add-log-setup 'delschedule nil old-date 'findpos
12791 org-log-reschedule))
12792 (org-remove-timestamp-with-keyword org-scheduled-string)
12793 (message "Item is no longer scheduled.")))
12794 ((equal arg '(16))
12795 (save-excursion
12796 (if (re-search-forward
12797 org-scheduled-time-regexp
12798 (save-excursion (outline-next-heading) (point)) t)
12799 (let* ((rpl0 (match-string 1))
12800 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12801 (replace-match
12802 (concat org-scheduled-string
12803 " <" rpl
12804 (format " -%dd"
12805 (abs
12806 (- (time-to-days
12807 (save-match-data
12808 (org-read-date nil t nil "Delay until" old-date-time)))
12809 (time-to-days old-date-time))))
12810 ">") t t))
12811 (user-error "No scheduled information to update"))))
12813 (org-add-planning-info 'scheduled time 'closed)
12814 (when (and old-date org-log-reschedule
12815 (not (equal old-date
12816 (substring org-last-inserted-timestamp 1 -1))))
12817 (org-add-log-setup 'reschedule nil old-date 'findpos
12818 org-log-reschedule))
12819 (when repeater
12820 (save-excursion
12821 (org-back-to-heading t)
12822 (when (re-search-forward (concat org-scheduled-string " "
12823 org-last-inserted-timestamp)
12824 (save-excursion
12825 (outline-next-heading) (point)) t)
12826 (goto-char (1- (match-end 0)))
12827 (insert " " repeater)
12828 (setq org-last-inserted-timestamp
12829 (concat (substring org-last-inserted-timestamp 0 -1)
12830 " " repeater
12831 (substring org-last-inserted-timestamp -1))))))
12832 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12834 (defun org-get-scheduled-time (pom &optional inherit)
12835 "Get the scheduled time as a time tuple, of a format suitable
12836 for calling org-schedule with, or if there is no scheduling,
12837 returns nil."
12838 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12839 (when time
12840 (apply 'encode-time (org-parse-time-string time)))))
12842 (defun org-get-deadline-time (pom &optional inherit)
12843 "Get the deadline as a time tuple, of a format suitable for
12844 calling org-deadline with, or if there is no scheduling, returns
12845 nil."
12846 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12847 (when time
12848 (apply 'encode-time (org-parse-time-string time)))))
12850 (defun org-remove-timestamp-with-keyword (keyword)
12851 "Remove all time stamps with KEYWORD in the current entry."
12852 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12853 beg)
12854 (save-excursion
12855 (org-back-to-heading t)
12856 (setq beg (point))
12857 (outline-next-heading)
12858 (while (re-search-backward re beg t)
12859 (replace-match "")
12860 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12861 (equal (char-before) ?\ ))
12862 (backward-delete-char 1)
12863 (if (string-match "^[ \t]*$" (buffer-substring
12864 (point-at-bol) (point-at-eol)))
12865 (delete-region (point-at-bol)
12866 (min (point-max) (1+ (point-at-eol))))))))))
12868 (defun org-add-planning-info (what &optional time &rest remove)
12869 "Insert new timestamp with keyword in the line directly after the headline.
12870 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12871 If non is given, the user is prompted for a date.
12872 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12873 be removed."
12874 (interactive)
12875 (let (org-time-was-given org-end-time-was-given ts
12876 end default-time default-input)
12878 (catch 'exit
12879 (when (and (memq what '(scheduled deadline))
12880 (or (not time)
12881 (and (stringp time)
12882 (string-match "^[-+]+[0-9]" time))))
12883 ;; Try to get a default date/time from existing timestamp
12884 (save-excursion
12885 (org-back-to-heading t)
12886 (setq end (save-excursion (outline-next-heading) (point)))
12887 (when (re-search-forward (if (eq what 'scheduled)
12888 org-scheduled-time-regexp
12889 org-deadline-time-regexp)
12890 end t)
12891 (setq ts (match-string 1)
12892 default-time
12893 (apply 'encode-time (org-parse-time-string ts))
12894 default-input (and ts (org-get-compact-tod ts))))))
12895 (when what
12896 (setq time
12897 (if (stringp time)
12898 ;; This is a string (relative or absolute), set proper date
12899 (apply 'encode-time
12900 (org-read-date-analyze
12901 time default-time (decode-time default-time)))
12902 ;; If necessary, get the time from the user
12903 (or time (org-read-date nil 'to-time nil nil
12904 default-time default-input)))))
12906 (when (and org-insert-labeled-timestamps-at-point
12907 (member what '(scheduled deadline)))
12908 (insert
12909 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12910 (org-insert-time-stamp time org-time-was-given
12911 nil nil nil (list org-end-time-was-given))
12912 (setq what nil))
12913 (save-excursion
12914 (save-restriction
12915 (let (col list elt ts buffer-invisibility-spec)
12916 (org-back-to-heading t)
12917 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12918 (goto-char (match-end 1))
12919 (setq col (current-column))
12920 (goto-char (match-end 0))
12921 (if (eobp) (insert "\n") (forward-char 1))
12922 (when (and (not what)
12923 (not (looking-at
12924 (concat "[ \t]*"
12925 org-keyword-time-not-clock-regexp))))
12926 ;; Nothing to add, nothing to remove...... :-)
12927 (throw 'exit nil))
12928 (if (and (not (looking-at org-outline-regexp))
12929 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12930 "[^\r\n]*"))
12931 (not (equal (match-string 1) org-clock-string)))
12932 (narrow-to-region (match-beginning 0) (match-end 0))
12933 (insert-before-markers "\n")
12934 (backward-char 1)
12935 (narrow-to-region (point) (point))
12936 (and org-adapt-indentation (org-indent-to-column col)))
12937 ;; Check if we have to remove something.
12938 (setq list (cons what remove))
12939 (while list
12940 (setq elt (pop list))
12941 (when (or (and (eq elt 'scheduled)
12942 (re-search-forward org-scheduled-time-regexp nil t))
12943 (and (eq elt 'deadline)
12944 (re-search-forward org-deadline-time-regexp nil t))
12945 (and (eq elt 'closed)
12946 (re-search-forward org-closed-time-regexp nil t)))
12947 (replace-match "")
12948 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12949 (and (looking-at "[ \t]+") (replace-match ""))
12950 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12951 (when what
12952 (insert
12953 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12954 (cond ((eq what 'scheduled) org-scheduled-string)
12955 ((eq what 'deadline) org-deadline-string)
12956 ((eq what 'closed) org-closed-string))
12957 " ")
12958 (setq ts (org-insert-time-stamp
12959 time
12960 (or org-time-was-given
12961 (and (eq what 'closed) org-log-done-with-time))
12962 (eq what 'closed)
12963 nil nil (list org-end-time-was-given)))
12964 (insert
12965 (if (not (or (bolp) (eq (char-before) ?\ )
12966 (memq (char-after) '(32 10))
12967 (eobp))) " " ""))
12968 (end-of-line 1))
12969 (goto-char (point-min))
12970 (widen)
12971 (if (and (looking-at "[ \t]*\n")
12972 (equal (char-before) ?\n))
12973 (delete-region (1- (point)) (point-at-eol)))
12974 ts))))))
12976 (defvar org-log-note-marker (make-marker))
12977 (defvar org-log-note-purpose nil)
12978 (defvar org-log-note-state nil)
12979 (defvar org-log-note-previous-state nil)
12980 (defvar org-log-note-how nil)
12981 (defvar org-log-note-extra nil)
12982 (defvar org-log-note-window-configuration nil)
12983 (defvar org-log-note-return-to (make-marker))
12984 (defvar org-log-note-effective-time nil
12985 "Remembered current time so that dynamically scoped
12986 `org-extend-today-until' affects tha timestamps in state change
12987 log")
12989 (defvar org-log-post-message nil
12990 "Message to be displayed after a log note has been stored.
12991 The auto-repeater uses this.")
12993 (defun org-add-note ()
12994 "Add a note to the current entry.
12995 This is done in the same way as adding a state change note."
12996 (interactive)
12997 (org-add-log-setup 'note nil nil 'findpos nil))
12999 (defvar org-property-end-re)
13000 (defun org-add-log-setup (&optional purpose state prev-state
13001 findpos how extra)
13002 "Set up the post command hook to take a note.
13003 If this is about to TODO state change, the new state is expected in STATE.
13004 When FINDPOS is non-nil, find the correct position for the note in
13005 the current entry. If not, assume that it can be inserted at point.
13006 HOW is an indicator what kind of note should be created.
13007 EXTRA is additional text that will be inserted into the notes buffer."
13008 (let* ((org-log-into-drawer (org-log-into-drawer))
13009 (drawer (cond ((stringp org-log-into-drawer)
13010 org-log-into-drawer)
13011 (org-log-into-drawer "LOGBOOK"))))
13012 (save-restriction
13013 (save-excursion
13014 (when findpos
13015 (org-back-to-heading t)
13016 (narrow-to-region (point) (save-excursion
13017 (outline-next-heading) (point)))
13018 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13019 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13020 "[^\r\n]*\\)?"))
13021 (goto-char (match-end 0))
13022 (cond
13023 (drawer
13024 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13025 nil t)
13026 (progn
13027 (goto-char (match-end 0))
13028 (or org-log-states-order-reversed
13029 (and (re-search-forward org-property-end-re nil t)
13030 (goto-char (1- (match-beginning 0))))))
13031 (insert "\n:" drawer ":\n:END:")
13032 (beginning-of-line 0)
13033 (org-indent-line)
13034 (beginning-of-line 2)
13035 (org-indent-line)
13036 (end-of-line 0)))
13037 ((and org-log-state-notes-insert-after-drawers
13038 (save-excursion
13039 (forward-line) (looking-at org-drawer-regexp)))
13040 (forward-line)
13041 (while (looking-at org-drawer-regexp)
13042 (goto-char (match-end 0))
13043 (re-search-forward org-property-end-re (point-max) t)
13044 (forward-line))
13045 (forward-line -1)))
13046 (unless org-log-states-order-reversed
13047 (and (= (char-after) ?\n) (forward-char 1))
13048 (org-skip-over-state-notes)
13049 (skip-chars-backward " \t\n\r")))
13050 (move-marker org-log-note-marker (point))
13051 (setq org-log-note-purpose purpose
13052 org-log-note-state state
13053 org-log-note-previous-state prev-state
13054 org-log-note-how how
13055 org-log-note-extra extra
13056 org-log-note-effective-time (org-current-effective-time))
13057 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13059 (defun org-skip-over-state-notes ()
13060 "Skip past the list of State notes in an entry."
13061 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13062 (when (ignore-errors (goto-char (org-in-item-p)))
13063 (let* ((struct (org-list-struct))
13064 (prevs (org-list-prevs-alist struct)))
13065 (while (looking-at "[ \t]*- State")
13066 (goto-char (or (org-list-get-next-item (point) struct prevs)
13067 (org-list-get-item-end (point) struct)))))))
13069 (defun org-add-log-note (&optional purpose)
13070 "Pop up a window for taking a note, and add this note later at point."
13071 (remove-hook 'post-command-hook 'org-add-log-note)
13072 (setq org-log-note-window-configuration (current-window-configuration))
13073 (delete-other-windows)
13074 (move-marker org-log-note-return-to (point))
13075 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13076 (goto-char org-log-note-marker)
13077 (org-switch-to-buffer-other-window "*Org Note*")
13078 (erase-buffer)
13079 (if (memq org-log-note-how '(time state))
13080 (let (current-prefix-arg) (org-store-log-note))
13081 (let ((org-inhibit-startup t)) (org-mode))
13082 (insert (format "# Insert note for %s.
13083 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13084 (cond
13085 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13086 ((eq org-log-note-purpose 'done) "closed todo item")
13087 ((eq org-log-note-purpose 'state)
13088 (format "state change from \"%s\" to \"%s\""
13089 (or org-log-note-previous-state "")
13090 (or org-log-note-state "")))
13091 ((eq org-log-note-purpose 'reschedule)
13092 "rescheduling")
13093 ((eq org-log-note-purpose 'delschedule)
13094 "no longer scheduled")
13095 ((eq org-log-note-purpose 'redeadline)
13096 "changing deadline")
13097 ((eq org-log-note-purpose 'deldeadline)
13098 "removing deadline")
13099 ((eq org-log-note-purpose 'refile)
13100 "refiling")
13101 ((eq org-log-note-purpose 'note)
13102 "this entry")
13103 (t (error "This should not happen")))))
13104 (if org-log-note-extra (insert org-log-note-extra))
13105 (org-set-local 'org-finish-function 'org-store-log-note)
13106 (run-hooks 'org-log-buffer-setup-hook)))
13108 (defvar org-note-abort nil) ; dynamically scoped
13109 (defun org-store-log-note ()
13110 "Finish taking a log note, and insert it to where it belongs."
13111 (let ((txt (buffer-string)))
13112 (kill-buffer (current-buffer))
13113 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13114 lines ind bul)
13115 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13116 (setq txt (replace-match "" t t txt)))
13117 (if (string-match "\\s-+\\'" txt)
13118 (setq txt (replace-match "" t t txt)))
13119 (setq lines (org-split-string txt "\n"))
13120 (when (and note (string-match "\\S-" note))
13121 (setq note
13122 (org-replace-escapes
13123 note
13124 (list (cons "%u" (user-login-name))
13125 (cons "%U" user-full-name)
13126 (cons "%t" (format-time-string
13127 (org-time-stamp-format 'long 'inactive)
13128 org-log-note-effective-time))
13129 (cons "%T" (format-time-string
13130 (org-time-stamp-format 'long nil)
13131 org-log-note-effective-time))
13132 (cons "%d" (format-time-string
13133 (org-time-stamp-format nil 'inactive)
13134 org-log-note-effective-time))
13135 (cons "%D" (format-time-string
13136 (org-time-stamp-format nil nil)
13137 org-log-note-effective-time))
13138 (cons "%s" (if org-log-note-state
13139 (concat "\"" org-log-note-state "\"")
13140 ""))
13141 (cons "%S" (if org-log-note-previous-state
13142 (concat "\"" org-log-note-previous-state "\"")
13143 "\"\"")))))
13144 (if lines (setq note (concat note " \\\\")))
13145 (push note lines))
13146 (when (or current-prefix-arg org-note-abort)
13147 (when org-log-into-drawer
13148 (org-remove-empty-drawer-at
13149 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13150 org-log-note-marker))
13151 (setq lines nil))
13152 (when lines
13153 (with-current-buffer (marker-buffer org-log-note-marker)
13154 (save-excursion
13155 (goto-char org-log-note-marker)
13156 (move-marker org-log-note-marker nil)
13157 (end-of-line 1)
13158 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13159 (setq ind (save-excursion
13160 (if (ignore-errors (goto-char (org-in-item-p)))
13161 (let ((struct (org-list-struct)))
13162 (org-list-get-ind
13163 (org-list-get-top-point struct) struct))
13164 (skip-chars-backward " \r\t\n")
13165 (cond
13166 ((and (org-at-heading-p)
13167 org-adapt-indentation)
13168 (1+ (org-current-level)))
13169 ((org-at-heading-p) 0)
13170 (t (org-get-indentation))))))
13171 (setq bul (org-list-bullet-string "-"))
13172 (org-indent-line-to ind)
13173 (insert bul (pop lines))
13174 (let ((ind-body (+ (length bul) ind)))
13175 (while lines
13176 (insert "\n")
13177 (org-indent-line-to ind-body)
13178 (insert (pop lines))))
13179 (message "Note stored")
13180 (org-back-to-heading t)
13181 (org-cycle-hide-drawers 'children))))))
13182 (set-window-configuration org-log-note-window-configuration)
13183 (with-current-buffer (marker-buffer org-log-note-return-to)
13184 (goto-char org-log-note-return-to))
13185 (move-marker org-log-note-return-to nil)
13186 (and org-log-post-message (message "%s" org-log-post-message)))
13188 (defun org-remove-empty-drawer-at (drawer pos)
13189 "Remove an empty drawer DRAWER at position POS.
13190 POS may also be a marker."
13191 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13192 (save-excursion
13193 (save-restriction
13194 (widen)
13195 (goto-char pos)
13196 (if (org-in-regexp
13197 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13198 (replace-match ""))))))
13200 (defvar org-ts-type nil)
13201 (defun org-sparse-tree (&optional arg type)
13202 "Create a sparse tree, prompt for the details.
13203 This command can create sparse trees. You first need to select the type
13204 of match used to create the tree:
13206 t Show all TODO entries.
13207 T Show entries with a specific TODO keyword.
13208 m Show entries selected by a tags/property match.
13209 p Enter a property name and its value (both with completion on existing
13210 names/values) and show entries with that property.
13211 r Show entries matching a regular expression (`/' can be used as well).
13212 b Show deadlines and scheduled items before a date.
13213 a Show deadlines and scheduled items after a date.
13214 d Show deadlines due within `org-deadline-warning-days'.
13215 D Show deadlines and scheduled items between a date range."
13216 (interactive "P")
13217 (let (ans kwd value ts-type)
13218 (setq type (or type org-sparse-tree-default-date-type))
13219 (setq org-ts-type type)
13220 (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"
13221 (cond ((eq type 'all) "all timestamps")
13222 ((eq type 'scheduled) "only scheduled")
13223 ((eq type 'deadline) "only deadline")
13224 ((eq type 'active) "only active timestamps")
13225 ((eq type 'inactive) "only inactive timestamps")
13226 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13227 (t "scheduled/deadline")))
13228 (setq ans (read-char-exclusive))
13229 (cond
13230 ((equal ans ?c)
13231 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13232 ((equal ans ?d)
13233 (call-interactively 'org-check-deadlines))
13234 ((equal ans ?b)
13235 (call-interactively 'org-check-before-date))
13236 ((equal ans ?a)
13237 (call-interactively 'org-check-after-date))
13238 ((equal ans ?D)
13239 (call-interactively 'org-check-dates-range))
13240 ((equal ans ?t)
13241 (call-interactively 'org-show-todo-tree))
13242 ((equal ans ?T)
13243 (org-show-todo-tree '(4)))
13244 ((member ans '(?T ?m))
13245 (call-interactively 'org-match-sparse-tree))
13246 ((member ans '(?p ?P))
13247 (setq kwd (org-icompleting-read "Property: "
13248 (mapcar 'list (org-buffer-property-keys))))
13249 (setq value (org-icompleting-read "Value: "
13250 (mapcar 'list (org-property-values kwd))))
13251 (unless (string-match "\\`{.*}\\'" value)
13252 (setq value (concat "\"" value "\"")))
13253 (org-match-sparse-tree arg (concat kwd "=" value)))
13254 ((member ans '(?r ?R ?/))
13255 (call-interactively 'org-occur))
13256 (t (error "No such sparse tree command \"%c\"" ans)))))
13258 (defvar org-occur-highlights nil
13259 "List of overlays used for occur matches.")
13260 (make-variable-buffer-local 'org-occur-highlights)
13261 (defvar org-occur-parameters nil
13262 "Parameters of the active org-occur calls.
13263 This is a list, each call to org-occur pushes as cons cell,
13264 containing the regular expression and the callback, onto the list.
13265 The list can contain several entries if `org-occur' has been called
13266 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13267 will only contain one set of parameters. When the highlights are
13268 removed (for example with `C-c C-c', or with the next edit (depending
13269 on `org-remove-highlights-with-change'), this variable is emptied
13270 as well.")
13271 (make-variable-buffer-local 'org-occur-parameters)
13273 (defun org-occur (regexp &optional keep-previous callback)
13274 "Make a compact tree which shows all matches of REGEXP.
13275 The tree will show the lines where the regexp matches, and all higher
13276 headlines above the match. It will also show the heading after the match,
13277 to make sure editing the matching entry is easy.
13278 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13279 call to `org-occur' will be kept, to allow stacking of calls to this
13280 command.
13281 If CALLBACK is non-nil, it is a function which is called to confirm
13282 that the match should indeed be shown."
13283 (interactive "sRegexp: \nP")
13284 (when (equal regexp "")
13285 (error "Regexp cannot be empty"))
13286 (unless keep-previous
13287 (org-remove-occur-highlights nil nil t))
13288 (push (cons regexp callback) org-occur-parameters)
13289 (let ((cnt 0))
13290 (save-excursion
13291 (goto-char (point-min))
13292 (if (or (not keep-previous) ; do not want to keep
13293 (not org-occur-highlights)) ; no previous matches
13294 ;; hide everything
13295 (org-overview))
13296 (while (re-search-forward regexp nil t)
13297 (when (or (not callback)
13298 (save-match-data (funcall callback)))
13299 (setq cnt (1+ cnt))
13300 (when org-highlight-sparse-tree-matches
13301 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13302 (org-show-context 'occur-tree))))
13303 (when org-remove-highlights-with-change
13304 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13305 nil 'local))
13306 (unless org-sparse-tree-open-archived-trees
13307 (org-hide-archived-subtrees (point-min) (point-max)))
13308 (run-hooks 'org-occur-hook)
13309 (if (org-called-interactively-p 'interactive)
13310 (message "%d match(es) for regexp %s" cnt regexp))
13311 cnt))
13313 (defun org-occur-next-match (&optional n reset)
13314 "Function for `next-error-function' to find sparse tree matches.
13315 N is the number of matches to move, when negative move backwards.
13316 RESET is entirely ignored - this function always goes back to the
13317 starting point when no match is found."
13318 (let* ((limit (if (< n 0) (point-min) (point-max)))
13319 (search-func (if (< n 0)
13320 'previous-single-char-property-change
13321 'next-single-char-property-change))
13322 (n (abs n))
13323 (pos (point))
13325 (catch 'exit
13326 (while (setq p1 (funcall search-func (point) 'org-type))
13327 (when (equal p1 limit)
13328 (goto-char pos)
13329 (error "No more matches"))
13330 (when (equal (get-char-property p1 'org-type) 'org-occur)
13331 (setq n (1- n))
13332 (when (= n 0)
13333 (goto-char p1)
13334 (throw 'exit (point))))
13335 (goto-char p1))
13336 (goto-char p1)
13337 (error "No more matches"))))
13339 (defun org-show-context (&optional key)
13340 "Make sure point and context are visible.
13341 How much context is shown depends upon the variables
13342 `org-show-hierarchy-above', `org-show-following-heading',
13343 `org-show-entry-below' and `org-show-siblings'."
13344 (let ((heading-p (org-at-heading-p t))
13345 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13346 (following-p (org-get-alist-option org-show-following-heading key))
13347 (entry-p (org-get-alist-option org-show-entry-below key))
13348 (siblings-p (org-get-alist-option org-show-siblings key)))
13349 ;; Show heading or entry text
13350 (if (and heading-p (not entry-p))
13351 (org-flag-heading nil) ; only show the heading
13352 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13353 (org-show-hidden-entry))) ; show entire entry
13354 (when following-p
13355 ;; Show next sibling, or heading below text
13356 (save-excursion
13357 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13358 (org-flag-heading nil))))
13359 (when siblings-p (org-show-siblings))
13360 (when hierarchy-p
13361 ;; show all higher headings, possibly with siblings
13362 (save-excursion
13363 (while (and (condition-case nil
13364 (progn (org-up-heading-all 1) t)
13365 (error nil))
13366 (not (bobp)))
13367 (org-flag-heading nil)
13368 (when siblings-p (org-show-siblings)))))
13369 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13371 (defvar org-reveal-start-hook nil
13372 "Hook run before revealing a location.")
13374 (defun org-reveal (&optional siblings)
13375 "Show current entry, hierarchy above it, and the following headline.
13376 This can be used to show a consistent set of context around locations
13377 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13378 not t for the search context.
13380 With optional argument SIBLINGS, on each level of the hierarchy all
13381 siblings are shown. This repairs the tree structure to what it would
13382 look like when opened with hierarchical calls to `org-cycle'.
13383 With double optional argument \\[universal-argument] \\[universal-argument], \
13384 go to the parent and show the
13385 entire tree."
13386 (interactive "P")
13387 (run-hooks 'org-reveal-start-hook)
13388 (let ((org-show-hierarchy-above t)
13389 (org-show-following-heading t)
13390 (org-show-siblings (if siblings t org-show-siblings)))
13391 (org-show-context nil))
13392 (when (equal siblings '(16))
13393 (save-excursion
13394 (when (org-up-heading-safe)
13395 (org-show-subtree)
13396 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13398 (defun org-highlight-new-match (beg end)
13399 "Highlight from BEG to END and mark the highlight is an occur headline."
13400 (let ((ov (make-overlay beg end)))
13401 (overlay-put ov 'face 'secondary-selection)
13402 (overlay-put ov 'org-type 'org-occur)
13403 (push ov org-occur-highlights)))
13405 (defun org-remove-occur-highlights (&optional beg end noremove)
13406 "Remove the occur highlights from the buffer.
13407 BEG and END are ignored. If NOREMOVE is nil, remove this function
13408 from the `before-change-functions' in the current buffer."
13409 (interactive)
13410 (unless org-inhibit-highlight-removal
13411 (mapc 'delete-overlay org-occur-highlights)
13412 (setq org-occur-highlights nil)
13413 (setq org-occur-parameters nil)
13414 (unless noremove
13415 (remove-hook 'before-change-functions
13416 'org-remove-occur-highlights 'local))))
13418 ;;;; Priorities
13420 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13421 "Regular expression matching the priority indicator.")
13423 (defvar org-remove-priority-next-time nil)
13425 (defun org-priority-up ()
13426 "Increase the priority of the current item."
13427 (interactive)
13428 (org-priority 'up))
13430 (defun org-priority-down ()
13431 "Decrease the priority of the current item."
13432 (interactive)
13433 (org-priority 'down))
13435 (defun org-priority (&optional action show)
13436 "Change the priority of an item.
13437 ACTION can be `set', `up', `down', or a character."
13438 (interactive "P")
13439 (if (equal action '(4))
13440 (org-show-priority)
13441 (unless org-enable-priority-commands
13442 (error "Priority commands are disabled"))
13443 (setq action (or action 'set))
13444 (let (current new news have remove)
13445 (save-excursion
13446 (org-back-to-heading t)
13447 (if (looking-at org-priority-regexp)
13448 (setq current (string-to-char (match-string 2))
13449 have t))
13450 (cond
13451 ((eq action 'remove)
13452 (setq remove t new ?\ ))
13453 ((or (eq action 'set)
13454 (if (featurep 'xemacs) (characterp action) (integerp action)))
13455 (if (not (eq action 'set))
13456 (setq new action)
13457 (message "Priority %c-%c, SPC to remove: "
13458 org-highest-priority org-lowest-priority)
13459 (save-match-data
13460 (setq new (read-char-exclusive))))
13461 (if (and (= (upcase org-highest-priority) org-highest-priority)
13462 (= (upcase org-lowest-priority) org-lowest-priority))
13463 (setq new (upcase new)))
13464 (cond ((equal new ?\ ) (setq remove t))
13465 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13466 (error "Priority must be between `%c' and `%c'"
13467 org-highest-priority org-lowest-priority))))
13468 ((eq action 'up)
13469 (setq new (if have
13470 (1- current) ; normal cycling
13471 ;; last priority was empty
13472 (if (eq last-command this-command)
13473 org-lowest-priority ; wrap around empty to lowest
13474 ;; default
13475 (if org-priority-start-cycle-with-default
13476 org-default-priority
13477 (1- org-default-priority))))))
13478 ((eq action 'down)
13479 (setq new (if have
13480 (1+ current) ; normal cycling
13481 ;; last priority was empty
13482 (if (eq last-command this-command)
13483 org-highest-priority ; wrap around empty to highest
13484 ;; default
13485 (if org-priority-start-cycle-with-default
13486 org-default-priority
13487 (1+ org-default-priority))))))
13488 (t (error "Invalid action")))
13489 (if (or (< (upcase new) org-highest-priority)
13490 (> (upcase new) org-lowest-priority))
13491 (if (and (memq action '(up down))
13492 (not have) (not (eq last-command this-command)))
13493 ;; `new' is from default priority
13494 (error
13495 "The default can not be set, see `org-default-priority' why")
13496 ;; normal cycling: `new' is beyond highest/lowest priority
13497 ;; and is wrapped around to the empty priority
13498 (setq remove t)))
13499 (setq news (format "%c" new))
13500 (if have
13501 (if remove
13502 (replace-match "" t t nil 1)
13503 (replace-match news t t nil 2))
13504 (if remove
13505 (error "No priority cookie found in line")
13506 (let ((case-fold-search nil))
13507 (looking-at org-todo-line-regexp))
13508 (if (match-end 2)
13509 (progn
13510 (goto-char (match-end 2))
13511 (insert " [#" news "]"))
13512 (goto-char (match-beginning 3))
13513 (insert "[#" news "] "))))
13514 (org-preserve-lc (org-set-tags nil 'align)))
13515 (if remove
13516 (message "Priority removed")
13517 (message "Priority of current item set to %s" news)))))
13519 (defun org-show-priority ()
13520 "Show the priority of the current item.
13521 This priority is composed of the main priority given with the [#A] cookies,
13522 and by additional input from the age of a schedules or deadline entry."
13523 (interactive)
13524 (let ((pri (if (eq major-mode 'org-agenda-mode)
13525 (org-get-at-bol 'priority)
13526 (save-excursion
13527 (save-match-data
13528 (beginning-of-line)
13529 (and (looking-at org-heading-regexp)
13530 (org-get-priority (match-string 0))))))))
13531 (message "Priority is %d" (if pri pri -1000))))
13533 (defun org-get-priority (s)
13534 "Find priority cookie and return priority."
13535 (save-match-data
13536 (if (functionp org-get-priority-function)
13537 (funcall org-get-priority-function)
13538 (if (not (string-match org-priority-regexp s))
13539 (* 1000 (- org-lowest-priority org-default-priority))
13540 (* 1000 (- org-lowest-priority
13541 (string-to-char (match-string 2 s))))))))
13543 ;;;; Tags
13545 (defvar org-agenda-archives-mode)
13546 (defvar org-map-continue-from nil
13547 "Position from where mapping should continue.
13548 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13550 (defvar org-scanner-tags nil
13551 "The current tag list while the tags scanner is running.")
13552 (defvar org-trust-scanner-tags nil
13553 "Should `org-get-tags-at' use the tags for the scanner.
13554 This is for internal dynamical scoping only.
13555 When this is non-nil, the function `org-get-tags-at' will return the value
13556 of `org-scanner-tags' instead of building the list by itself. This
13557 can lead to large speed-ups when the tags scanner is used in a file with
13558 many entries, and when the list of tags is retrieved, for example to
13559 obtain a list of properties. Building the tags list for each entry in such
13560 a file becomes an N^2 operation - but with this variable set, it scales
13561 as N.")
13563 (defun org-scan-tags (action matcher todo-only &optional start-level)
13564 "Sca headline tags with inheritance and produce output ACTION.
13566 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13567 or `agenda' to produce an entry list for an agenda view. It can also be
13568 a Lisp form or a function that should be called at each matched headline, in
13569 this case the return value is a list of all return values from these calls.
13571 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13572 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13573 only lines with a not-done TODO keyword are included in the output.
13574 This should be the same variable that was scoped into
13575 and set by `org-make-tags-matcher' when it constructed MATCHER.
13577 START-LEVEL can be a string with asterisks, reducing the scope to
13578 headlines matching this string."
13579 (require 'org-agenda)
13580 (let* ((re (concat "^"
13581 (if start-level
13582 ;; Get the correct level to match
13583 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13584 org-outline-regexp)
13585 " *\\(\\<\\("
13586 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13587 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13588 (props (list 'face 'default
13589 'done-face 'org-agenda-done
13590 'undone-face 'default
13591 'mouse-face 'highlight
13592 'org-not-done-regexp org-not-done-regexp
13593 'org-todo-regexp org-todo-regexp
13594 'org-complex-heading-regexp org-complex-heading-regexp
13595 'help-echo
13596 (format "mouse-2 or RET jump to org file %s"
13597 (abbreviate-file-name
13598 (or (buffer-file-name (buffer-base-buffer))
13599 (buffer-name (buffer-base-buffer)))))))
13600 (case-fold-search nil)
13601 (org-map-continue-from nil)
13602 lspos tags tags-list
13603 (tags-alist (list (cons 0 org-file-tags)))
13604 (llast 0) rtn rtn1 level category i txt
13605 todo marker entry priority)
13606 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13607 (setq action (list 'lambda nil action)))
13608 (save-excursion
13609 (goto-char (point-min))
13610 (when (eq action 'sparse-tree)
13611 (org-overview)
13612 (org-remove-occur-highlights))
13613 (while (re-search-forward re nil t)
13614 (setq org-map-continue-from nil)
13615 (catch :skip
13616 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13617 tags (if (match-end 4) (org-match-string-no-properties 4)))
13618 (goto-char (setq lspos (match-beginning 0)))
13619 (setq level (org-reduced-level (org-outline-level))
13620 category (org-get-category))
13621 (setq i llast llast level)
13622 ;; remove tag lists from same and sublevels
13623 (while (>= i level)
13624 (when (setq entry (assoc i tags-alist))
13625 (setq tags-alist (delete entry tags-alist)))
13626 (setq i (1- i)))
13627 ;; add the next tags
13628 (when tags
13629 (setq tags (org-split-string tags ":")
13630 tags-alist
13631 (cons (cons level tags) tags-alist)))
13632 ;; compile tags for current headline
13633 (setq tags-list
13634 (if org-use-tag-inheritance
13635 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13636 tags)
13637 org-scanner-tags tags-list)
13638 (when org-use-tag-inheritance
13639 (setcdr (car tags-alist)
13640 (mapcar (lambda (x)
13641 (setq x (copy-sequence x))
13642 (org-add-prop-inherited x))
13643 (cdar tags-alist))))
13644 (when (and tags org-use-tag-inheritance
13645 (or (not (eq t org-use-tag-inheritance))
13646 org-tags-exclude-from-inheritance))
13647 ;; selective inheritance, remove uninherited ones
13648 (setcdr (car tags-alist)
13649 (org-remove-uninherited-tags (cdar tags-alist))))
13650 (when (and
13652 ;; eval matcher only when the todo condition is OK
13653 (and (or (not todo-only) (member todo org-not-done-keywords))
13654 (let ((case-fold-search t) (org-trust-scanner-tags t))
13655 (eval matcher)))
13657 ;; Call the skipper, but return t if it does not skip,
13658 ;; so that the `and' form continues evaluating
13659 (progn
13660 (unless (eq action 'sparse-tree) (org-agenda-skip))
13663 ;; Check if timestamps are deselecting this entry
13664 (or (not todo-only)
13665 (and (member todo org-not-done-keywords)
13666 (or (not org-agenda-tags-todo-honor-ignore-options)
13667 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13669 ;; select this headline
13670 (cond
13671 ((eq action 'sparse-tree)
13672 (and org-highlight-sparse-tree-matches
13673 (org-get-heading) (match-end 0)
13674 (org-highlight-new-match
13675 (match-beginning 1) (match-end 1)))
13676 (org-show-context 'tags-tree))
13677 ((eq action 'agenda)
13678 (setq txt (org-agenda-format-item
13680 (concat
13681 (if (eq org-tags-match-list-sublevels 'indented)
13682 (make-string (1- level) ?.) "")
13683 (org-get-heading))
13684 level category
13685 tags-list)
13686 priority (org-get-priority txt))
13687 (goto-char lspos)
13688 (setq marker (org-agenda-new-marker))
13689 (org-add-props txt props
13690 'org-marker marker 'org-hd-marker marker 'org-category category
13691 'todo-state todo
13692 'priority priority 'type "tagsmatch")
13693 (push txt rtn))
13694 ((functionp action)
13695 (setq org-map-continue-from nil)
13696 (save-excursion
13697 (setq rtn1 (funcall action))
13698 (push rtn1 rtn)))
13699 (t (error "Invalid action")))
13701 ;; if we are to skip sublevels, jump to end of subtree
13702 (unless org-tags-match-list-sublevels
13703 (org-end-of-subtree t)
13704 (backward-char 1))))
13705 ;; Get the correct position from where to continue
13706 (if org-map-continue-from
13707 (goto-char org-map-continue-from)
13708 (and (= (point) lspos) (end-of-line 1)))))
13709 (when (and (eq action 'sparse-tree)
13710 (not org-sparse-tree-open-archived-trees))
13711 (org-hide-archived-subtrees (point-min) (point-max)))
13712 (nreverse rtn)))
13714 (defun org-remove-uninherited-tags (tags)
13715 "Remove all tags that are not inherited from the list TAGS."
13716 (cond
13717 ((eq org-use-tag-inheritance t)
13718 (if org-tags-exclude-from-inheritance
13719 (org-delete-all org-tags-exclude-from-inheritance tags)
13720 tags))
13721 ((not org-use-tag-inheritance) nil)
13722 ((stringp org-use-tag-inheritance)
13723 (delq nil (mapcar
13724 (lambda (x)
13725 (if (and (string-match org-use-tag-inheritance x)
13726 (not (member x org-tags-exclude-from-inheritance)))
13727 x nil))
13728 tags)))
13729 ((listp org-use-tag-inheritance)
13730 (delq nil (mapcar
13731 (lambda (x)
13732 (if (member x org-use-tag-inheritance) x nil))
13733 tags)))))
13735 (defun org-match-sparse-tree (&optional todo-only match)
13736 "Create a sparse tree according to tags string MATCH.
13737 MATCH can contain positive and negative selection of tags, like
13738 \"+WORK+URGENT-WITHBOSS\".
13739 If optional argument TODO-ONLY is non-nil, only select lines that are
13740 also TODO lines."
13741 (interactive "P")
13742 (org-agenda-prepare-buffers (list (current-buffer)))
13743 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13745 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13747 (defvar org-cached-props nil)
13748 (defun org-cached-entry-get (pom property)
13749 (if (or (eq t org-use-property-inheritance)
13750 (and (stringp org-use-property-inheritance)
13751 (string-match org-use-property-inheritance property))
13752 (and (listp org-use-property-inheritance)
13753 (member property org-use-property-inheritance)))
13754 ;; Caching is not possible, check it directly
13755 (org-entry-get pom property 'inherit)
13756 ;; Get all properties, so that we can do complicated checks easily
13757 (cdr (assoc property (or org-cached-props
13758 (setq org-cached-props
13759 (org-entry-properties pom)))))))
13761 (defun org-global-tags-completion-table (&optional files)
13762 "Return the list of all tags in all agenda buffer/files.
13763 Optional FILES argument is a list of files which can be used
13764 instead of the agenda files."
13765 (save-excursion
13766 (org-uniquify
13767 (delq nil
13768 (apply 'append
13769 (mapcar
13770 (lambda (file)
13771 (set-buffer (find-file-noselect file))
13772 (append (org-get-buffer-tags)
13773 (mapcar (lambda (x) (if (stringp (car-safe x))
13774 (list (car-safe x)) nil))
13775 org-tag-alist)))
13776 (if (and files (car files))
13777 files
13778 (org-agenda-files))))))))
13780 (defun org-make-tags-matcher (match)
13781 "Create the TAGS/TODO matcher form for the selection string MATCH.
13783 The variable `todo-only' is scoped dynamically into this function.
13784 It will be set to t if the matcher restricts matching to TODO entries,
13785 otherwise will not be touched.
13787 Returns a cons of the selection string MATCH and the constructed
13788 lisp form implementing the matcher. The matcher is to be evaluated
13789 at an Org entry, with point on the headline, and returns t if the
13790 entry matches the selection string MATCH. The returned lisp form
13791 references two variables with information about the entry, which
13792 must be bound around the form's evaluation: todo, the TODO keyword
13793 at the entry (or nil of none); and tags-list, the list of all tags
13794 at the entry including inherited ones. Additionally, the category
13795 of the entry (if any) must be specified as the text property
13796 'org-category on the headline.
13798 See also `org-scan-tags'.
13800 (declare (special todo-only))
13801 (unless (boundp 'todo-only)
13802 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13803 (unless match
13804 ;; Get a new match request, with completion
13805 (let ((org-last-tags-completion-table
13806 (org-global-tags-completion-table)))
13807 (setq match (org-completing-read-no-i
13808 "Match: " 'org-tags-completion-function nil nil nil
13809 'org-tags-history))))
13811 ;; Parse the string and create a lisp form
13812 (let ((match0 match)
13813 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13814 minus tag mm
13815 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13816 orterms term orlist re-p str-p level-p level-op time-p
13817 prop-p pn pv po gv rest)
13818 (if (string-match "/+" match)
13819 ;; match contains also a todo-matching request
13820 (progn
13821 (setq tagsmatch (substring match 0 (match-beginning 0))
13822 todomatch (substring match (match-end 0)))
13823 (if (string-match "^!" todomatch)
13824 (setq todo-only t todomatch (substring todomatch 1)))
13825 (if (string-match "^\\s-*$" todomatch)
13826 (setq todomatch nil)))
13827 ;; only matching tags
13828 (setq tagsmatch match todomatch nil))
13830 ;; Make the tags matcher
13831 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13832 (setq tagsmatcher t)
13833 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13834 (while (setq term (pop orterms))
13835 (while (and (equal (substring term -1) "\\") orterms)
13836 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13837 (while (string-match re term)
13838 (setq rest (substring term (match-end 0))
13839 minus (and (match-end 1)
13840 (equal (match-string 1 term) "-"))
13841 tag (save-match-data (replace-regexp-in-string
13842 "\\\\-" "-"
13843 (match-string 2 term)))
13844 re-p (equal (string-to-char tag) ?{)
13845 level-p (match-end 4)
13846 prop-p (match-end 5)
13847 mm (cond
13848 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13849 (level-p
13850 (setq level-op (org-op-to-function (match-string 3 term)))
13851 `(,level-op level ,(string-to-number
13852 (match-string 4 term))))
13853 (prop-p
13854 (setq pn (match-string 5 term)
13855 po (match-string 6 term)
13856 pv (match-string 7 term)
13857 re-p (equal (string-to-char pv) ?{)
13858 str-p (equal (string-to-char pv) ?\")
13859 time-p (save-match-data
13860 (string-match "^\"[[<].*[]>]\"$" pv))
13861 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13862 (if time-p (setq pv (org-matcher-time pv)))
13863 (setq po (org-op-to-function po (if time-p 'time str-p)))
13864 (cond
13865 ((equal pn "CATEGORY")
13866 (setq gv '(get-text-property (point) 'org-category)))
13867 ((equal pn "TODO")
13868 (setq gv 'todo))
13870 (setq gv `(org-cached-entry-get nil ,pn))))
13871 (if re-p
13872 (if (eq po 'org<>)
13873 `(not (string-match ,pv (or ,gv "")))
13874 `(string-match ,pv (or ,gv "")))
13875 (if str-p
13876 `(,po (or ,gv "") ,pv)
13877 `(,po (string-to-number (or ,gv ""))
13878 ,(string-to-number pv) ))))
13879 (t `(member ,tag tags-list)))
13880 mm (if minus (list 'not mm) mm)
13881 term rest)
13882 (push mm tagsmatcher))
13883 (push (if (> (length tagsmatcher) 1)
13884 (cons 'and tagsmatcher)
13885 (car tagsmatcher))
13886 orlist)
13887 (setq tagsmatcher nil))
13888 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13889 (setq tagsmatcher
13890 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13891 ;; Make the todo matcher
13892 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13893 (setq todomatcher t)
13894 (setq orterms (org-split-string todomatch "|") orlist nil)
13895 (while (setq term (pop orterms))
13896 (while (string-match re term)
13897 (setq minus (and (match-end 1)
13898 (equal (match-string 1 term) "-"))
13899 kwd (match-string 2 term)
13900 re-p (equal (string-to-char kwd) ?{)
13901 term (substring term (match-end 0))
13902 mm (if re-p
13903 `(string-match ,(substring kwd 1 -1) todo)
13904 (list 'equal 'todo kwd))
13905 mm (if minus (list 'not mm) mm))
13906 (push mm todomatcher))
13907 (push (if (> (length todomatcher) 1)
13908 (cons 'and todomatcher)
13909 (car todomatcher))
13910 orlist)
13911 (setq todomatcher nil))
13912 (setq todomatcher (if (> (length orlist) 1)
13913 (cons 'or orlist) (car orlist))))
13915 ;; Return the string and lisp forms of the matcher
13916 (setq matcher (if todomatcher
13917 (list 'and tagsmatcher todomatcher)
13918 tagsmatcher))
13919 (when todo-only
13920 (setq matcher (list 'and '(member todo org-not-done-keywords)
13921 matcher)))
13922 (cons match0 matcher)))
13924 (defun org-op-to-function (op &optional stringp)
13925 "Turn an operator into the appropriate function."
13926 (setq op
13927 (cond
13928 ((equal op "<" ) '(< string< org-time<))
13929 ((equal op ">" ) '(> org-string> org-time>))
13930 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13931 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13932 ((member op '("=" "==")) '(= string= org-time=))
13933 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13934 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13936 (defun org<> (a b) (not (= a b)))
13937 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13938 (defun org-string>= (a b) (not (string< a b)))
13939 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13940 (defun org-string<> (a b) (not (string= a b)))
13941 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13942 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13943 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13944 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13945 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13946 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13947 (defun org-2ft (s)
13948 "Convert S to a floating point time.
13949 If S is already a number, just return it. If it is a string, parse
13950 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13951 (cond
13952 ((numberp s) s)
13953 ((stringp s)
13954 (condition-case nil
13955 (float-time (apply 'encode-time (org-parse-time-string s)))
13956 (error 0.)))
13957 (t 0.)))
13959 (defun org-time-today ()
13960 "Time in seconds today at 0:00.
13961 Returns the float number of seconds since the beginning of the
13962 epoch to the beginning of today (00:00)."
13963 (float-time (apply 'encode-time
13964 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13966 (defun org-matcher-time (s)
13967 "Interpret a time comparison value."
13968 (save-match-data
13969 (cond
13970 ((string= s "<now>") (float-time))
13971 ((string= s "<today>") (org-time-today))
13972 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13973 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13974 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13975 (+ (org-time-today)
13976 (* (string-to-number (match-string 1 s))
13977 (cdr (assoc (match-string 2 s)
13978 '(("d" . 86400.0) ("w" . 604800.0)
13979 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13980 (t (org-2ft s)))))
13982 (defun org-match-any-p (re list)
13983 "Does re match any element of list?"
13984 (setq list (mapcar (lambda (x) (string-match re x)) list))
13985 (delq nil list))
13987 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13988 (defvar org-tags-overlay (make-overlay 1 1))
13989 (org-detach-overlay org-tags-overlay)
13991 (defun org-get-local-tags-at (&optional pos)
13992 "Get a list of tags defined in the current headline."
13993 (org-get-tags-at pos 'local))
13995 (defun org-get-local-tags ()
13996 "Get a list of tags defined in the current headline."
13997 (org-get-tags-at nil 'local))
13999 (defun org-get-tags-at (&optional pos local)
14000 "Get a list of all headline tags applicable at POS.
14001 POS defaults to point. If tags are inherited, the list contains
14002 the targets in the same sequence as the headlines appear, i.e.
14003 the tags of the current headline come last.
14004 When LOCAL is non-nil, only return tags from the current headline,
14005 ignore inherited ones."
14006 (interactive)
14007 (if (and org-trust-scanner-tags
14008 (or (not pos) (equal pos (point)))
14009 (not local))
14010 org-scanner-tags
14011 (let (tags ltags lastpos parent)
14012 (save-excursion
14013 (save-restriction
14014 (widen)
14015 (goto-char (or pos (point)))
14016 (save-match-data
14017 (catch 'done
14018 (condition-case nil
14019 (progn
14020 (org-back-to-heading t)
14021 (while (not (equal lastpos (point)))
14022 (setq lastpos (point))
14023 (when (looking-at
14024 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14025 (setq ltags (org-split-string
14026 (org-match-string-no-properties 1) ":"))
14027 (when parent
14028 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14029 (setq tags (append
14030 (if parent
14031 (org-remove-uninherited-tags ltags)
14032 ltags)
14033 tags)))
14034 (or org-use-tag-inheritance (throw 'done t))
14035 (if local (throw 'done t))
14036 (or (org-up-heading-safe) (error nil))
14037 (setq parent t)))
14038 (error nil)))))
14039 (if local
14040 tags
14041 (reverse (delete-dups
14042 (reverse (append
14043 (org-remove-uninherited-tags
14044 org-file-tags) tags)))))))))
14046 (defun org-add-prop-inherited (s)
14047 (add-text-properties 0 (length s) '(inherited t) s)
14050 (defun org-toggle-tag (tag &optional onoff)
14051 "Toggle the tag TAG for the current line.
14052 If ONOFF is `on' or `off', don't toggle but set to this state."
14053 (let (res current)
14054 (save-excursion
14055 (org-back-to-heading t)
14056 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14057 (point-at-eol) t)
14058 (progn
14059 (setq current (match-string 1))
14060 (replace-match ""))
14061 (setq current ""))
14062 (setq current (nreverse (org-split-string current ":")))
14063 (cond
14064 ((eq onoff 'on)
14065 (setq res t)
14066 (or (member tag current) (push tag current)))
14067 ((eq onoff 'off)
14068 (or (not (member tag current)) (setq current (delete tag current))))
14069 (t (if (member tag current)
14070 (setq current (delete tag current))
14071 (setq res t)
14072 (push tag current))))
14073 (end-of-line 1)
14074 (if current
14075 (progn
14076 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14077 (org-set-tags nil t))
14078 (delete-horizontal-space))
14079 (run-hooks 'org-after-tags-change-hook))
14080 res))
14082 (defun org-align-tags-here (to-col)
14083 ;; Assumes that this is a headline
14084 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14085 (beginning-of-line 1)
14086 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14087 (< pos (match-beginning 2)))
14088 (progn
14089 (setq tags-l (- (match-end 2) (match-beginning 2)))
14090 (goto-char (match-beginning 1))
14091 (insert " ")
14092 (delete-region (point) (1+ (match-beginning 2)))
14093 (setq ncol (max (current-column)
14094 (1+ col)
14095 (if (> to-col 0)
14096 to-col
14097 (- (abs to-col) tags-l))))
14098 (setq p (point))
14099 (insert (make-string (- ncol (current-column)) ?\ ))
14100 (setq ncol (current-column))
14101 (when indent-tabs-mode (tabify p (point-at-eol)))
14102 (org-move-to-column (min ncol col) t))
14103 (goto-char pos))))
14105 (defun org-set-tags-command (&optional arg just-align)
14106 "Call the set-tags command for the current entry."
14107 (interactive "P")
14108 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14109 (org-set-tags arg just-align)
14110 (save-excursion
14111 (unless (and (org-region-active-p)
14112 org-loop-over-headlines-in-active-region)
14113 (org-back-to-heading t))
14114 (org-set-tags arg just-align))))
14116 (defun org-set-tags-to (data)
14117 "Set the tags of the current entry to DATA, replacing the current tags.
14118 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14119 If DATA is nil or the empty string, any tags will be removed."
14120 (interactive "sTags: ")
14121 (setq data
14122 (cond
14123 ((eq data nil) "")
14124 ((equal data "") "")
14125 ((stringp data)
14126 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14127 ":"))
14128 ((listp data)
14129 (concat ":" (mapconcat 'identity data ":") ":"))))
14130 (when data
14131 (save-excursion
14132 (org-back-to-heading t)
14133 (when (looking-at org-complex-heading-regexp)
14134 (if (match-end 5)
14135 (progn
14136 (goto-char (match-beginning 5))
14137 (insert data)
14138 (delete-region (point) (point-at-eol))
14139 (org-set-tags nil 'align))
14140 (goto-char (point-at-eol))
14141 (insert " " data)
14142 (org-set-tags nil 'align)))
14143 (beginning-of-line 1)
14144 (if (looking-at ".*?\\([ \t]+\\)$")
14145 (delete-region (match-beginning 1) (match-end 1))))))
14147 (defun org-align-all-tags ()
14148 "Align the tags i all headings."
14149 (interactive)
14150 (save-excursion
14151 (or (ignore-errors (org-back-to-heading t))
14152 (outline-next-heading))
14153 (if (org-at-heading-p)
14154 (org-set-tags t)
14155 (message "No headings"))))
14157 (defvar org-indent-indentation-per-level)
14158 (defun org-set-tags (&optional arg just-align)
14159 "Set the tags for the current headline.
14160 With prefix ARG, realign all tags in headings in the current buffer."
14161 (interactive "P")
14162 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14163 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14164 'region-start-level 'region))
14165 org-loop-over-headlines-in-active-region)
14166 (org-map-entries
14167 ;; We don't use ARG and JUST-ALIGN here these args are not
14168 ;; useful when looping over headlines
14169 `(org-set-tags)
14170 org-loop-over-headlines-in-active-region
14171 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14172 (let* ((re org-outline-regexp-bol)
14173 (current (unless arg (org-get-tags-string)))
14174 (col (current-column))
14175 (org-setting-tags t)
14176 table current-tags inherited-tags ; computed below when needed
14177 tags p0 c0 c1 rpl di tc level)
14178 (if arg
14179 (save-excursion
14180 (goto-char (point-min))
14181 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14182 (while (re-search-forward re nil t)
14183 (org-set-tags nil t)
14184 (end-of-line 1)))
14185 (message "All tags realigned to column %d" org-tags-column))
14186 (if just-align
14187 (setq tags current)
14188 ;; Get a new set of tags from the user
14189 (save-excursion
14190 (setq table (append org-tag-persistent-alist
14191 (or org-tag-alist (org-get-buffer-tags))
14192 (and
14193 org-complete-tags-always-offer-all-agenda-tags
14194 (org-global-tags-completion-table
14195 (org-agenda-files))))
14196 org-last-tags-completion-table table
14197 current-tags (org-split-string current ":")
14198 inherited-tags (nreverse
14199 (nthcdr (length current-tags)
14200 (nreverse (org-get-tags-at))))
14201 tags
14202 (if (or (eq t org-use-fast-tag-selection)
14203 (and org-use-fast-tag-selection
14204 (delq nil (mapcar 'cdr table))))
14205 (org-fast-tag-selection
14206 current-tags inherited-tags table
14207 (if org-fast-tag-selection-include-todo
14208 org-todo-key-alist))
14209 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14210 (org-trim
14211 (org-icompleting-read "Tags: "
14212 'org-tags-completion-function
14213 nil nil current 'org-tags-history))))))
14214 (while (string-match "[-+&]+" tags)
14215 ;; No boolean logic, just a list
14216 (setq tags (replace-match ":" t t tags))))
14218 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14220 (if org-tags-sort-function
14221 (setq tags (mapconcat 'identity
14222 (sort (org-split-string
14223 tags (org-re "[^[:alnum:]_@#%]+"))
14224 org-tags-sort-function) ":")))
14226 (if (string-match "\\`[\t ]*\\'" tags)
14227 (setq tags "")
14228 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14229 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14231 ;; Insert new tags at the correct column
14232 (beginning-of-line 1)
14233 (setq level (or (and (looking-at org-outline-regexp)
14234 (- (match-end 0) (point) 1))
14236 (cond
14237 ((and (equal current "") (equal tags "")))
14238 ((re-search-forward
14239 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14240 (point-at-eol) t)
14241 (if (equal tags "")
14242 (setq rpl "")
14243 (goto-char (match-beginning 0))
14244 (setq c0 (current-column)
14245 ;; compute offset for the case of org-indent-mode active
14246 di (if org-indent-mode
14247 (* (1- org-indent-indentation-per-level) (1- level))
14249 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14250 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14251 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14252 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14253 (replace-match rpl t t)
14254 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14255 tags)
14256 (t (error "Tags alignment failed")))
14257 (org-move-to-column col)
14258 (unless just-align
14259 (run-hooks 'org-after-tags-change-hook))))))
14261 (defun org-change-tag-in-region (beg end tag off)
14262 "Add or remove TAG for each entry in the region.
14263 This works in the agenda, and also in an org-mode buffer."
14264 (interactive
14265 (list (region-beginning) (region-end)
14266 (let ((org-last-tags-completion-table
14267 (if (derived-mode-p 'org-mode)
14268 (org-get-buffer-tags)
14269 (org-global-tags-completion-table))))
14270 (org-icompleting-read
14271 "Tag: " 'org-tags-completion-function nil nil nil
14272 'org-tags-history))
14273 (progn
14274 (message "[s]et or [r]emove? ")
14275 (equal (read-char-exclusive) ?r))))
14276 (if (fboundp 'deactivate-mark) (deactivate-mark))
14277 (let ((agendap (equal major-mode 'org-agenda-mode))
14278 l1 l2 m buf pos newhead (cnt 0))
14279 (goto-char end)
14280 (setq l2 (1- (org-current-line)))
14281 (goto-char beg)
14282 (setq l1 (org-current-line))
14283 (loop for l from l1 to l2 do
14284 (org-goto-line l)
14285 (setq m (get-text-property (point) 'org-hd-marker))
14286 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14287 (and agendap m))
14288 (setq buf (if agendap (marker-buffer m) (current-buffer))
14289 pos (if agendap m (point)))
14290 (with-current-buffer buf
14291 (save-excursion
14292 (save-restriction
14293 (goto-char pos)
14294 (setq cnt (1+ cnt))
14295 (org-toggle-tag tag (if off 'off 'on))
14296 (setq newhead (org-get-heading)))))
14297 (and agendap (org-agenda-change-all-lines newhead m))))
14298 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14300 (defun org-tags-completion-function (string predicate &optional flag)
14301 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14302 (confirm (lambda (x) (stringp (car x)))))
14303 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14304 (setq s1 (match-string 1 string)
14305 s2 (match-string 2 string))
14306 (setq s1 "" s2 string))
14307 (cond
14308 ((eq flag nil)
14309 ;; try completion
14310 (setq rtn (try-completion s2 ctable confirm))
14311 (if (stringp rtn)
14312 (setq rtn
14313 (concat s1 s2 (substring rtn (length s2))
14314 (if (and org-add-colon-after-tag-completion
14315 (assoc rtn ctable))
14316 ":" ""))))
14317 rtn)
14318 ((eq flag t)
14319 ;; all-completions
14320 (all-completions s2 ctable confirm)
14322 ((eq flag 'lambda)
14323 ;; exact match?
14324 (assoc s2 ctable)))
14327 (defun org-fast-tag-insert (kwd tags face &optional end)
14328 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14329 (insert (format "%-12s" (concat kwd ":"))
14330 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14331 (or end "")))
14333 (defun org-fast-tag-show-exit (flag)
14334 (save-excursion
14335 (org-goto-line 3)
14336 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14337 (replace-match ""))
14338 (when flag
14339 (end-of-line 1)
14340 (org-move-to-column (- (window-width) 19) t)
14341 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14343 (defun org-set-current-tags-overlay (current prefix)
14344 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14345 (if (featurep 'xemacs)
14346 (org-overlay-display org-tags-overlay (concat prefix s)
14347 'secondary-selection)
14348 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14349 (org-overlay-display org-tags-overlay (concat prefix s)))))
14351 (defvar org-last-tag-selection-key nil)
14352 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14353 "Fast tag selection with single keys.
14354 CURRENT is the current list of tags in the headline, INHERITED is the
14355 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14356 possibly with grouping information. TODO-TABLE is a similar table with
14357 TODO keywords, should these have keys assigned to them.
14358 If the keys are nil, a-z are automatically assigned.
14359 Returns the new tags string, or nil to not change the current settings."
14360 (let* ((fulltable (append table todo-table))
14361 (maxlen (apply 'max (mapcar
14362 (lambda (x)
14363 (if (stringp (car x)) (string-width (car x)) 0))
14364 fulltable)))
14365 (buf (current-buffer))
14366 (expert (eq org-fast-tag-selection-single-key 'expert))
14367 (buffer-tags nil)
14368 (fwidth (+ maxlen 3 1 3))
14369 (ncol (/ (- (window-width) 4) fwidth))
14370 (i-face 'org-done)
14371 (c-face 'org-todo)
14372 tg cnt e c char c1 c2 ntable tbl rtn
14373 ov-start ov-end ov-prefix
14374 (exit-after-next org-fast-tag-selection-single-key)
14375 (done-keywords org-done-keywords)
14376 groups ingroup)
14377 (save-excursion
14378 (beginning-of-line 1)
14379 (if (looking-at
14380 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14381 (setq ov-start (match-beginning 1)
14382 ov-end (match-end 1)
14383 ov-prefix "")
14384 (setq ov-start (1- (point-at-eol))
14385 ov-end (1+ ov-start))
14386 (skip-chars-forward "^\n\r")
14387 (setq ov-prefix
14388 (concat
14389 (buffer-substring (1- (point)) (point))
14390 (if (> (current-column) org-tags-column)
14392 (make-string (- org-tags-column (current-column)) ?\ ))))))
14393 (move-overlay org-tags-overlay ov-start ov-end)
14394 (save-window-excursion
14395 (if expert
14396 (set-buffer (get-buffer-create " *Org tags*"))
14397 (delete-other-windows)
14398 (split-window-vertically)
14399 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14400 (erase-buffer)
14401 (org-set-local 'org-done-keywords done-keywords)
14402 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14403 (org-fast-tag-insert "Current" current c-face "\n\n")
14404 (org-fast-tag-show-exit exit-after-next)
14405 (org-set-current-tags-overlay current ov-prefix)
14406 (setq tbl fulltable char ?a cnt 0)
14407 (while (setq e (pop tbl))
14408 (cond
14409 ((equal (car e) :startgroup)
14410 (push '() groups) (setq ingroup t)
14411 (when (not (= cnt 0))
14412 (setq cnt 0)
14413 (insert "\n"))
14414 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14415 ((equal (car e) :endgroup)
14416 (setq ingroup nil cnt 0)
14417 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14418 ((equal e '(:newline))
14419 (when (not (= cnt 0))
14420 (setq cnt 0)
14421 (insert "\n")
14422 (setq e (car tbl))
14423 (while (equal (car tbl) '(:newline))
14424 (insert "\n")
14425 (setq tbl (cdr tbl)))))
14427 (setq tg (copy-sequence (car e)) c2 nil)
14428 (if (cdr e)
14429 (setq c (cdr e))
14430 ;; automatically assign a character.
14431 (setq c1 (string-to-char
14432 (downcase (substring
14433 tg (if (= (string-to-char tg) ?@) 1 0)))))
14434 (if (or (rassoc c1 ntable) (rassoc c1 table))
14435 (while (or (rassoc char ntable) (rassoc char table))
14436 (setq char (1+ char)))
14437 (setq c2 c1))
14438 (setq c (or c2 char)))
14439 (if ingroup (push tg (car groups)))
14440 (setq tg (org-add-props tg nil 'face
14441 (cond
14442 ((not (assoc tg table))
14443 (org-get-todo-face tg))
14444 ((member tg current) c-face)
14445 ((member tg inherited) i-face))))
14446 (if (and (= cnt 0) (not ingroup)) (insert " "))
14447 (insert "[" c "] " tg (make-string
14448 (- fwidth 4 (length tg)) ?\ ))
14449 (push (cons tg c) ntable)
14450 (when (= (setq cnt (1+ cnt)) ncol)
14451 (insert "\n")
14452 (if ingroup (insert " "))
14453 (setq cnt 0)))))
14454 (setq ntable (nreverse ntable))
14455 (insert "\n")
14456 (goto-char (point-min))
14457 (if (not expert) (org-fit-window-to-buffer))
14458 (setq rtn
14459 (catch 'exit
14460 (while t
14461 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14462 (if (not groups) "no " "")
14463 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14464 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14465 (setq org-last-tag-selection-key c)
14466 (cond
14467 ((= c ?\r) (throw 'exit t))
14468 ((= c ?!)
14469 (setq groups (not groups))
14470 (goto-char (point-min))
14471 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14472 ((= c ?\C-c)
14473 (if (not expert)
14474 (org-fast-tag-show-exit
14475 (setq exit-after-next (not exit-after-next)))
14476 (setq expert nil)
14477 (delete-other-windows)
14478 (set-window-buffer (split-window-vertically) " *Org tags*")
14479 (org-switch-to-buffer-other-window " *Org tags*")
14480 (org-fit-window-to-buffer)))
14481 ((or (= c ?\C-g)
14482 (and (= c ?q) (not (rassoc c ntable))))
14483 (org-detach-overlay org-tags-overlay)
14484 (setq quit-flag t))
14485 ((= c ?\ )
14486 (setq current nil)
14487 (if exit-after-next (setq exit-after-next 'now)))
14488 ((= c ?\t)
14489 (condition-case nil
14490 (setq tg (org-icompleting-read
14491 "Tag: "
14492 (or buffer-tags
14493 (with-current-buffer buf
14494 (org-get-buffer-tags)))))
14495 (quit (setq tg "")))
14496 (when (string-match "\\S-" tg)
14497 (add-to-list 'buffer-tags (list tg))
14498 (if (member tg current)
14499 (setq current (delete tg current))
14500 (push tg current)))
14501 (if exit-after-next (setq exit-after-next 'now)))
14502 ((setq e (rassoc c todo-table) tg (car e))
14503 (with-current-buffer buf
14504 (save-excursion (org-todo tg)))
14505 (if exit-after-next (setq exit-after-next 'now)))
14506 ((setq e (rassoc c ntable) tg (car e))
14507 (if (member tg current)
14508 (setq current (delete tg current))
14509 (loop for g in groups do
14510 (if (member tg g)
14511 (mapc (lambda (x)
14512 (setq current (delete x current)))
14513 g)))
14514 (push tg current))
14515 (if exit-after-next (setq exit-after-next 'now))))
14517 ;; Create a sorted list
14518 (setq current
14519 (sort current
14520 (lambda (a b)
14521 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14522 (if (eq exit-after-next 'now) (throw 'exit t))
14523 (goto-char (point-min))
14524 (beginning-of-line 2)
14525 (delete-region (point) (point-at-eol))
14526 (org-fast-tag-insert "Current" current c-face)
14527 (org-set-current-tags-overlay current ov-prefix)
14528 (while (re-search-forward
14529 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14530 (setq tg (match-string 1))
14531 (add-text-properties
14532 (match-beginning 1) (match-end 1)
14533 (list 'face
14534 (cond
14535 ((member tg current) c-face)
14536 ((member tg inherited) i-face)
14537 (t (get-text-property (match-beginning 1) 'face))))))
14538 (goto-char (point-min)))))
14539 (org-detach-overlay org-tags-overlay)
14540 (if rtn
14541 (mapconcat 'identity current ":")
14542 nil))))
14544 (defun org-get-tags-string ()
14545 "Get the TAGS string in the current headline."
14546 (unless (org-at-heading-p t)
14547 (error "Not on a heading"))
14548 (save-excursion
14549 (beginning-of-line 1)
14550 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14551 (org-match-string-no-properties 1)
14552 "")))
14554 (defun org-get-tags ()
14555 "Get the list of tags specified in the current headline."
14556 (org-split-string (org-get-tags-string) ":"))
14558 (defun org-get-buffer-tags ()
14559 "Get a table of all tags used in the buffer, for completion."
14560 (let (tags)
14561 (save-excursion
14562 (goto-char (point-min))
14563 (while (re-search-forward
14564 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14565 (when (equal (char-after (point-at-bol 0)) ?*)
14566 (mapc (lambda (x) (add-to-list 'tags x))
14567 (org-split-string (org-match-string-no-properties 1) ":")))))
14568 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14569 (mapcar 'list tags)))
14571 ;;;; The mapping API
14573 (defun org-map-entries (func &optional match scope &rest skip)
14574 "Call FUNC at each headline selected by MATCH in SCOPE.
14576 FUNC is a function or a lisp form. The function will be called without
14577 arguments, with the cursor positioned at the beginning of the headline.
14578 The return values of all calls to the function will be collected and
14579 returned as a list.
14581 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14582 does not need to preserve point. After evaluation, the cursor will be
14583 moved to the end of the line (presumably of the headline of the
14584 processed entry) and search continues from there. Under some
14585 circumstances, this may not produce the wanted results. For example,
14586 if you have removed (e.g. archived) the current (sub)tree it could
14587 mean that the next entry will be skipped entirely. In such cases, you
14588 can specify the position from where search should continue by making
14589 FUNC set the variable `org-map-continue-from' to the desired buffer
14590 position.
14592 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14593 Only headlines that are matched by this query will be considered during
14594 the iteration. When MATCH is nil or t, all headlines will be
14595 visited by the iteration.
14597 SCOPE determines the scope of this command. It can be any of:
14599 nil The current buffer, respecting the restriction if any
14600 tree The subtree started with the entry at point
14601 region The entries within the active region, if any
14602 region-start-level
14603 The entries within the active region, but only those at
14604 the same level than the first one.
14605 file The current buffer, without restriction
14606 file-with-archives
14607 The current buffer, and any archives associated with it
14608 agenda All agenda files
14609 agenda-with-archives
14610 All agenda files with any archive files associated with them
14611 \(file1 file2 ...)
14612 If this is a list, all files in the list will be scanned
14614 The remaining args are treated as settings for the skipping facilities of
14615 the scanner. The following items can be given here:
14617 archive skip trees with the archive tag
14618 comment skip trees with the COMMENT keyword
14619 function or Emacs Lisp form:
14620 will be used as value for `org-agenda-skip-function', so
14621 whenever the function returns a position, FUNC will not be
14622 called for that entry and search will continue from the
14623 position returned
14625 If your function needs to retrieve the tags including inherited tags
14626 at the *current* entry, you can use the value of the variable
14627 `org-scanner-tags' which will be much faster than getting the value
14628 with `org-get-tags-at'. If your function gets properties with
14629 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14630 to t around the call to `org-entry-properties' to get the same speedup.
14631 Note that if your function moves around to retrieve tags and properties at
14632 a *different* entry, you cannot use these techniques."
14633 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14634 (not (org-region-active-p)))
14635 (let* ((org-agenda-archives-mode nil) ; just to make sure
14636 (org-agenda-skip-archived-trees (memq 'archive skip))
14637 (org-agenda-skip-comment-trees (memq 'comment skip))
14638 (org-agenda-skip-function
14639 (car (org-delete-all '(comment archive) skip)))
14640 (org-tags-match-list-sublevels t)
14641 (start-level (eq scope 'region-start-level))
14642 matcher file res
14643 org-todo-keywords-for-agenda
14644 org-done-keywords-for-agenda
14645 org-todo-keyword-alist-for-agenda
14646 org-drawers-for-agenda
14647 org-tag-alist-for-agenda
14648 todo-only)
14650 (cond
14651 ((eq match t) (setq matcher t))
14652 ((eq match nil) (setq matcher t))
14653 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14655 (save-window-excursion
14656 (save-restriction
14657 (cond ((eq scope 'tree)
14658 (org-back-to-heading t)
14659 (org-narrow-to-subtree)
14660 (setq scope nil))
14661 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14662 (org-region-active-p))
14663 ;; If needed, set start-level to a string like "2"
14664 (when start-level
14665 (save-excursion
14666 (goto-char (region-beginning))
14667 (unless (org-at-heading-p) (outline-next-heading))
14668 (setq start-level (org-current-level))))
14669 (narrow-to-region (region-beginning)
14670 (save-excursion
14671 (goto-char (region-end))
14672 (unless (and (bolp) (org-at-heading-p))
14673 (outline-next-heading))
14674 (point)))
14675 (setq scope nil)))
14677 (if (not scope)
14678 (progn
14679 (org-agenda-prepare-buffers
14680 (list (buffer-file-name (current-buffer))))
14681 (setq res (org-scan-tags func matcher todo-only start-level)))
14682 ;; Get the right scope
14683 (cond
14684 ((and scope (listp scope) (symbolp (car scope)))
14685 (setq scope (eval scope)))
14686 ((eq scope 'agenda)
14687 (setq scope (org-agenda-files t)))
14688 ((eq scope 'agenda-with-archives)
14689 (setq scope (org-agenda-files t))
14690 (setq scope (org-add-archive-files scope)))
14691 ((eq scope 'file)
14692 (setq scope (list (buffer-file-name))))
14693 ((eq scope 'file-with-archives)
14694 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14695 (org-agenda-prepare-buffers scope)
14696 (while (setq file (pop scope))
14697 (with-current-buffer (org-find-base-buffer-visiting file)
14698 (save-excursion
14699 (save-restriction
14700 (widen)
14701 (goto-char (point-min))
14702 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14703 res)))
14705 ;;;; Properties
14707 ;;; Setting and retrieving properties
14709 (defconst org-special-properties
14710 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14711 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14712 "The special properties valid in Org-mode.
14714 These are properties that are not defined in the property drawer,
14715 but in some other way.")
14717 (defconst org-default-properties
14718 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14719 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14720 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14721 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14722 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14723 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14724 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14725 "Some properties that are used by Org-mode for various purposes.
14726 Being in this list makes sure that they are offered for completion.")
14728 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14729 "Regular expression matching the first line of a property drawer.")
14731 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14732 "Regular expression matching the last line of a property drawer.")
14734 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14735 "Regular expression matching the first line of a property drawer.")
14737 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14738 "Regular expression matching the first line of a property drawer.")
14740 (defconst org-property-drawer-re
14741 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14742 org-property-end-re "\\)\n?")
14743 "Matches an entire property drawer.")
14745 (defconst org-clock-drawer-re
14746 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14747 org-property-end-re "\\)\n?")
14748 "Matches an entire clock drawer.")
14750 (defsubst org-re-property (property)
14751 "Return a regexp matching a PROPERTY line.
14752 Match group 1 will be set to the value."
14753 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14755 (defsubst org-re-property-keyword (property)
14756 "Return a regexp matching a PROPERTY line, possibly with no
14757 value for the property."
14758 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14760 (defun org-property-action ()
14761 "Do an action on properties."
14762 (interactive)
14763 (let (c)
14764 (org-at-property-p)
14765 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14766 (setq c (read-char-exclusive))
14767 (cond
14768 ((equal c ?s)
14769 (call-interactively 'org-set-property))
14770 ((equal c ?d)
14771 (call-interactively 'org-delete-property))
14772 ((equal c ?D)
14773 (call-interactively 'org-delete-property-globally))
14774 ((equal c ?c)
14775 (call-interactively 'org-compute-property-at-point))
14776 (t (error "No such property action %c" c)))))
14778 (defun org-inc-effort ()
14779 "Increment the value of the effort property in the current entry."
14780 (interactive)
14781 (org-set-effort nil t))
14783 (defvar org-clock-effort) ;; Defined in org-clock.el
14784 (defvar org-clock-current-task) ;; Defined in org-clock.el
14785 (defun org-set-effort (&optional value increment)
14786 "Set the effort property of the current entry.
14787 With numerical prefix arg, use the nth allowed value, 0 stands for the
14788 10th allowed value.
14790 When INCREMENT is non-nil, set the property to the next allowed value."
14791 (interactive "P")
14792 (if (equal value 0) (setq value 10))
14793 (let* ((completion-ignore-case t)
14794 (prop org-effort-property)
14795 (cur (org-entry-get nil prop))
14796 (allowed (org-property-get-allowed-values nil prop 'table))
14797 (existing (mapcar 'list (org-property-values prop)))
14798 (heading (nth 4 (org-heading-components)))
14800 (val (cond
14801 ((stringp value) value)
14802 ((and allowed (integerp value))
14803 (or (car (nth (1- value) allowed))
14804 (car (org-last allowed))))
14805 ((and allowed increment)
14806 (or (caadr (member (list cur) allowed))
14807 (error "Allowed effort values are not set")))
14808 (allowed
14809 (message "Select 1-9,0, [RET%s]: %s"
14810 (if cur (concat "=" cur) "")
14811 (mapconcat 'car allowed " "))
14812 (setq rpl (read-char-exclusive))
14813 (if (equal rpl ?\r)
14815 (setq rpl (- rpl ?0))
14816 (if (equal rpl 0) (setq rpl 10))
14817 (if (and (> rpl 0) (<= rpl (length allowed)))
14818 (car (nth (1- rpl) allowed))
14819 (org-completing-read "Effort: " allowed nil))))
14821 (let (org-completion-use-ido org-completion-use-iswitchb)
14822 (org-completing-read
14823 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14824 (concat "[" cur "]") "")
14825 ": ")
14826 existing nil nil "" nil cur))))))
14827 (unless (equal (org-entry-get nil prop) val)
14828 (org-entry-put nil prop val))
14829 (save-excursion
14830 (org-back-to-heading t)
14831 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14832 (when (string= heading org-clock-current-task)
14833 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
14834 (org-clock-update-mode-line))
14835 (message "%s is now %s" prop val)))
14837 (defun org-at-property-p ()
14838 "Is cursor inside a property drawer?"
14839 (save-excursion
14840 (beginning-of-line 1)
14841 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14842 (save-match-data ;; Used by calling procedures
14843 (let ((p (point))
14844 (range (unless (org-before-first-heading-p)
14845 (org-get-property-block))))
14846 (and range (<= (car range) p) (< p (cdr range))))))))
14848 (defun org-get-property-block (&optional beg end force)
14849 "Return the (beg . end) range of the body of the property drawer.
14850 BEG and END are the beginning and end of the current subtree, or of
14851 the part before the first headline. If they are not given, they will
14852 be found. If the drawer does not exist and FORCE is non-nil, create
14853 the drawer."
14854 (catch 'exit
14855 (save-excursion
14856 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14857 (progn (org-back-to-heading t) (point))))
14858 (end (or end (and (not (outline-next-heading)) (point-max))
14859 (point))))
14860 (goto-char beg)
14861 (if (re-search-forward org-property-start-re end t)
14862 (setq beg (1+ (match-end 0)))
14863 (if force
14864 (save-excursion
14865 (org-insert-property-drawer)
14866 (setq end (progn (outline-next-heading) (point))))
14867 (throw 'exit nil))
14868 (goto-char beg)
14869 (if (re-search-forward org-property-start-re end t)
14870 (setq beg (1+ (match-end 0)))))
14871 (if (re-search-forward org-property-end-re end t)
14872 (setq end (match-beginning 0))
14873 (or force (throw 'exit nil))
14874 (goto-char beg)
14875 (setq end beg)
14876 (org-indent-line)
14877 (insert ":END:\n"))
14878 (cons beg end)))))
14880 (defun org-entry-properties (&optional pom which specific)
14881 "Get all properties of the entry at point-or-marker POM.
14882 This includes the TODO keyword, the tags, time strings for deadline,
14883 scheduled, and clocking, and any additional properties defined in the
14884 entry. The return value is an alist, keys may occur multiple times
14885 if the property key was used several times.
14886 POM may also be nil, in which case the current entry is used.
14887 If WHICH is nil or `all', get all properties. If WHICH is
14888 `special' or `standard', only get that subclass. If WHICH
14889 is a string only get exactly this property. SPECIFIC can be a string, the
14890 specific property we are interested in. Specifying it can speed
14891 things up because then unnecessary parsing is avoided."
14892 (setq which (or which 'all))
14893 (org-with-point-at pom
14894 (let ((clockstr (substring org-clock-string 0 -1))
14895 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14896 (case-fold-search nil)
14897 beg end range props sum-props key key1 value string clocksum clocksumt)
14898 (save-excursion
14899 (when (condition-case nil
14900 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14901 (error nil))
14902 (setq beg (point))
14903 (setq sum-props (get-text-property (point) 'org-summaries))
14904 (setq clocksum (get-text-property (point) :org-clock-minutes)
14905 clocksumt (get-text-property (point) :org-clock-minutes-today))
14906 (outline-next-heading)
14907 (setq end (point))
14908 (when (memq which '(all special))
14909 ;; Get the special properties, like TODO and tags
14910 (goto-char beg)
14911 (when (and (or (not specific) (string= specific "TODO"))
14912 (looking-at org-todo-line-regexp) (match-end 2))
14913 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14914 (when (and (or (not specific) (string= specific "PRIORITY"))
14915 (looking-at org-priority-regexp))
14916 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14917 (when (or (not specific) (string= specific "FILE"))
14918 (push (cons "FILE" buffer-file-name) props))
14919 (when (and (or (not specific) (string= specific "TAGS"))
14920 (setq value (org-get-tags-string))
14921 (string-match "\\S-" value))
14922 (push (cons "TAGS" value) props))
14923 (when (and (or (not specific) (string= specific "ALLTAGS"))
14924 (setq value (org-get-tags-at)))
14925 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14926 ":"))
14927 props))
14928 (when (or (not specific) (string= specific "BLOCKED"))
14929 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14930 (when (or (not specific)
14931 (member specific
14932 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14933 "TIMESTAMP" "TIMESTAMP_IA")))
14934 (catch 'match
14935 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14936 (setq key (if (match-end 1)
14937 (substring (org-match-string-no-properties 1)
14938 0 -1))
14939 string (if (equal key clockstr)
14940 (org-trim
14941 (buffer-substring-no-properties
14942 (match-beginning 3) (goto-char
14943 (point-at-eol))))
14944 (substring (org-match-string-no-properties 3)
14945 1 -1)))
14946 ;; Get the correct property name from the key. This is
14947 ;; necessary if the user has configured time keywords.
14948 (setq key1 (concat key ":"))
14949 (cond
14950 ((not key)
14951 (setq key
14952 (if (= (char-after (match-beginning 3)) ?\[)
14953 "TIMESTAMP_IA" "TIMESTAMP")))
14954 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14955 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14956 ((equal key1 org-closed-string) (setq key "CLOSED"))
14957 ((equal key1 org-clock-string) (setq key "CLOCK")))
14958 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14959 (progn
14960 (push (cons key string) props)
14961 ;; no need to search further if match is found
14962 (throw 'match t))
14963 (when (or (equal key "CLOCK") (not (assoc key props)))
14964 (push (cons key string) props)))))))
14966 (when (memq which '(all standard))
14967 ;; Get the standard properties, like :PROP: ...
14968 (setq range (org-get-property-block beg end))
14969 (when range
14970 (goto-char (car range))
14971 (while (re-search-forward
14972 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14973 (cdr range) t)
14974 (setq key (org-match-string-no-properties 1)
14975 value (org-trim (or (org-match-string-no-properties 2) "")))
14976 (unless (member key excluded)
14977 (push (cons key (or value "")) props)))))
14978 (if clocksum
14979 (push (cons "CLOCKSUM"
14980 (org-columns-number-to-string (/ (float clocksum) 60.)
14981 'add_times))
14982 props))
14983 (if clocksumt
14984 (push (cons "CLOCKSUM_T"
14985 (org-columns-number-to-string (/ (float clocksumt) 60.)
14986 'add_times))
14987 props))
14988 (unless (assoc "CATEGORY" props)
14989 (push (cons "CATEGORY" (org-get-category)) props))
14990 (append sum-props (nreverse props)))))))
14992 (defun org-entry-get (pom property &optional inherit literal-nil)
14993 "Get value of PROPERTY for entry or content at point-or-marker POM.
14994 If INHERIT is non-nil and the entry does not have the property,
14995 then also check higher levels of the hierarchy.
14996 If INHERIT is the symbol `selective', use inheritance only if the setting
14997 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14998 If the property is present but empty, the return value is the empty string.
14999 If the property is not present at all, nil is returned.
15001 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15002 do not interpret it as the list atom nil. This is used for inheritance
15003 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15004 (org-with-point-at pom
15005 (if (and inherit (if (eq inherit 'selective)
15006 (org-property-inherit-p property)
15008 (org-entry-get-with-inheritance property literal-nil)
15009 (if (member property org-special-properties)
15010 ;; We need a special property. Use `org-entry-properties' to
15011 ;; retrieve it, but specify the wanted property
15012 (cdr (assoc property (org-entry-properties nil 'special property)))
15013 (let ((range (org-get-property-block)))
15014 (when (and range (not (eq (car range) (cdr range))))
15015 (let* ((props (list (or (assoc property org-file-properties)
15016 (assoc property org-global-properties)
15017 (assoc property org-global-properties-fixed))))
15018 (ap (lambda (key)
15019 (when (re-search-forward
15020 (org-re-property key) (cdr range) t)
15021 (setq props
15022 (org-update-property-plist
15024 (if (match-end 1)
15025 (org-match-string-no-properties 1) "")
15026 props)))))
15027 val)
15028 (goto-char (car range))
15029 (funcall ap property)
15030 (goto-char (car range))
15031 (while (funcall ap (concat property "+")))
15032 (setq val (cdr (assoc property props)))
15033 (when val (if literal-nil val (org-not-nil val))))))))))
15035 (defun org-property-or-variable-value (var &optional inherit)
15036 "Check if there is a property fixing the value of VAR.
15037 If yes, return this value. If not, return the current value of the variable."
15038 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15039 (if (and prop (stringp prop) (string-match "\\S-" prop))
15040 (read prop)
15041 (symbol-value var))))
15043 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15044 "Delete the property PROPERTY from entry at point-or-marker POM.
15045 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15046 an empty drawer to delete."
15047 (org-with-point-at pom
15048 (if (member property org-special-properties)
15049 nil ; cannot delete these properties.
15050 (let ((range (org-get-property-block)))
15051 (if (and range
15052 (goto-char (car range))
15053 (re-search-forward
15054 (org-re-property property)
15055 (cdr range) t))
15056 (progn
15057 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15058 (and delete-empty-drawer
15059 (org-remove-empty-drawer-at
15060 delete-empty-drawer (car range)))
15062 nil)))))
15064 ;; Multi-values properties are properties that contain multiple values
15065 ;; These values are assumed to be single words, separated by whitespace.
15066 (defun org-entry-add-to-multivalued-property (pom property value)
15067 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15068 (let* ((old (org-entry-get pom property))
15069 (values (and old (org-split-string old "[ \t]"))))
15070 (setq value (org-entry-protect-space value))
15071 (unless (member value values)
15072 (setq values (cons value values))
15073 (org-entry-put pom property
15074 (mapconcat 'identity values " ")))))
15076 (defun org-entry-remove-from-multivalued-property (pom property value)
15077 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15078 (let* ((old (org-entry-get pom property))
15079 (values (and old (org-split-string old "[ \t]"))))
15080 (setq value (org-entry-protect-space value))
15081 (when (member value values)
15082 (setq values (delete value values))
15083 (org-entry-put pom property
15084 (mapconcat 'identity values " ")))))
15086 (defun org-entry-member-in-multivalued-property (pom property value)
15087 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15088 (let* ((old (org-entry-get pom property))
15089 (values (and old (org-split-string old "[ \t]"))))
15090 (setq value (org-entry-protect-space value))
15091 (member value values)))
15093 (defun org-entry-get-multivalued-property (pom property)
15094 "Return a list of values in a multivalued property."
15095 (let* ((value (org-entry-get pom property))
15096 (values (and value (org-split-string value "[ \t]"))))
15097 (mapcar 'org-entry-restore-space values)))
15099 (defun org-entry-put-multivalued-property (pom property &rest values)
15100 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15101 VALUES should be a list of strings. Spaces will be protected."
15102 (org-entry-put pom property
15103 (mapconcat 'org-entry-protect-space values " "))
15104 (let* ((value (org-entry-get pom property))
15105 (values (and value (org-split-string value "[ \t]"))))
15106 (mapcar 'org-entry-restore-space values)))
15108 (defun org-entry-protect-space (s)
15109 "Protect spaces and newline in string S."
15110 (while (string-match " " s)
15111 (setq s (replace-match "%20" t t s)))
15112 (while (string-match "\n" s)
15113 (setq s (replace-match "%0A" t t s)))
15116 (defun org-entry-restore-space (s)
15117 "Restore spaces and newline in string S."
15118 (while (string-match "%20" s)
15119 (setq s (replace-match " " t t s)))
15120 (while (string-match "%0A" s)
15121 (setq s (replace-match "\n" t t s)))
15124 (defvar org-entry-property-inherited-from (make-marker)
15125 "Marker pointing to the entry from where a property was inherited.
15126 Each call to `org-entry-get-with-inheritance' will set this marker to the
15127 location of the entry where the inheritance search matched. If there was
15128 no match, the marker will point nowhere.
15129 Note that also `org-entry-get' calls this function, if the INHERIT flag
15130 is set.")
15132 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15133 "Get PROPERTY of entry or content at point, search higher levels if needed.
15134 The search will stop at the first ancestor which has the property defined.
15135 If the value found is \"nil\", return nil to show that the property
15136 should be considered as undefined (this is the meaning of nil here).
15137 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15138 (move-marker org-entry-property-inherited-from nil)
15139 (let (tmp)
15140 (save-excursion
15141 (save-restriction
15142 (widen)
15143 (catch 'ex
15144 (while t
15145 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15146 (or (ignore-errors (org-back-to-heading t))
15147 (goto-char (point-min)))
15148 (move-marker org-entry-property-inherited-from (point))
15149 (throw 'ex tmp))
15150 (or (ignore-errors (org-up-heading-safe))
15151 (throw 'ex nil))))))
15152 (setq tmp (or tmp
15153 (cdr (assoc property org-file-properties))
15154 (cdr (assoc property org-global-properties))
15155 (cdr (assoc property org-global-properties-fixed))))
15156 (if literal-nil tmp (org-not-nil tmp))))
15158 (defvar org-property-changed-functions nil
15159 "Hook called when the value of a property has changed.
15160 Each hook function should accept two arguments, the name of the property
15161 and the new value.")
15163 (defun org-entry-put (pom property value)
15164 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15165 (org-with-point-at pom
15166 (org-back-to-heading t)
15167 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15168 range)
15169 (cond
15170 ((equal property "TODO")
15171 (when (and (stringp value) (string-match "\\S-" value)
15172 (not (member value org-todo-keywords-1)))
15173 (error "\"%s\" is not a valid TODO state" value))
15174 (if (or (not value)
15175 (not (string-match "\\S-" value)))
15176 (setq value 'none))
15177 (org-todo value)
15178 (org-set-tags nil 'align))
15179 ((equal property "PRIORITY")
15180 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15181 (string-to-char value) ?\ ))
15182 (org-set-tags nil 'align))
15183 ((equal property "CLOCKSUM")
15184 (if (not (re-search-forward
15185 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15186 (error "Cannot find a clock log")
15187 (goto-char (- (match-end 1) 2))
15188 (cond
15189 ((eq value 'earlier) (org-timestamp-down))
15190 ((eq value 'later) (org-timestamp-up)))
15191 (org-clock-sum-current-item)))
15192 ((equal property "SCHEDULED")
15193 (if (re-search-forward org-scheduled-time-regexp end t)
15194 (cond
15195 ((eq value 'earlier) (org-timestamp-change -1 'day))
15196 ((eq value 'later) (org-timestamp-change 1 'day))
15197 (t (call-interactively 'org-schedule)))
15198 (call-interactively 'org-schedule)))
15199 ((equal property "DEADLINE")
15200 (if (re-search-forward org-deadline-time-regexp end t)
15201 (cond
15202 ((eq value 'earlier) (org-timestamp-change -1 'day))
15203 ((eq value 'later) (org-timestamp-change 1 'day))
15204 (t (call-interactively 'org-deadline)))
15205 (call-interactively 'org-deadline)))
15206 ((member property org-special-properties)
15207 (error "The %s property can not yet be set with `org-entry-put'"
15208 property))
15209 (t ; a non-special property
15210 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15211 (setq range (org-get-property-block beg end 'force))
15212 (goto-char (car range))
15213 (if (re-search-forward
15214 (org-re-property-keyword property) (cdr range) t)
15215 (progn
15216 (delete-region (match-beginning 0) (match-end 0))
15217 (goto-char (match-beginning 0)))
15218 (goto-char (cdr range))
15219 (insert "\n")
15220 (backward-char 1)
15221 (org-indent-line))
15222 (insert ":" property ":")
15223 (and value (insert " " value))
15224 (org-indent-line)))))
15225 (run-hook-with-args 'org-property-changed-functions property value)))
15227 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15228 "Get all property keys in the current buffer.
15229 With INCLUDE-SPECIALS, also list the special properties that reflect things
15230 like tags and TODO state.
15231 With INCLUDE-DEFAULTS, also include properties that has special meaning
15232 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15233 and others.
15234 With INCLUDE-COLUMNS, also include property names given in COLUMN
15235 formats in the current buffer."
15236 (let (rtn range cfmt s p)
15237 (save-excursion
15238 (save-restriction
15239 (widen)
15240 (goto-char (point-min))
15241 (while (re-search-forward org-property-start-re nil t)
15242 (setq range (org-get-property-block))
15243 (goto-char (car range))
15244 (while (re-search-forward
15245 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15246 (cdr range) t)
15247 (add-to-list 'rtn (org-match-string-no-properties 1)))
15248 (outline-next-heading))))
15250 (when include-specials
15251 (setq rtn (append org-special-properties rtn)))
15253 (when include-defaults
15254 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15255 (add-to-list 'rtn org-effort-property))
15257 (when include-columns
15258 (save-excursion
15259 (save-restriction
15260 (widen)
15261 (goto-char (point-min))
15262 (while (re-search-forward
15263 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15264 nil t)
15265 (setq cfmt (match-string 2) s 0)
15266 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15267 cfmt s)
15268 (setq s (match-end 0)
15269 p (match-string 1 cfmt))
15270 (unless (or (equal p "ITEM")
15271 (member p org-special-properties))
15272 (add-to-list 'rtn (match-string 1 cfmt))))))))
15274 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15276 (defun org-property-values (key)
15277 "Return a list of all values of property KEY in the current buffer."
15278 (save-excursion
15279 (save-restriction
15280 (widen)
15281 (goto-char (point-min))
15282 (let ((re (org-re-property key))
15283 values)
15284 (while (re-search-forward re nil t)
15285 (add-to-list 'values (org-trim (match-string 1))))
15286 (delete "" values)))))
15288 (defun org-insert-property-drawer ()
15289 "Insert a property drawer into the current entry."
15290 (org-back-to-heading t)
15291 (looking-at org-outline-regexp)
15292 (let ((indent (if org-adapt-indentation
15293 (- (match-end 0) (match-beginning 0))
15295 (beg (point))
15296 (re (concat "^[ \t]*" org-keyword-time-regexp))
15297 end hiddenp)
15298 (outline-next-heading)
15299 (setq end (point))
15300 (goto-char beg)
15301 (while (re-search-forward re end t))
15302 (setq hiddenp (outline-invisible-p))
15303 (end-of-line 1)
15304 (and (equal (char-after) ?\n) (forward-char 1))
15305 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15306 (if (member (match-string 1) '("CLOCK:" ":END:"))
15307 ;; just skip this line
15308 (beginning-of-line 2)
15309 ;; Drawer start, find the end
15310 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15311 (beginning-of-line 1)))
15312 (org-skip-over-state-notes)
15313 (skip-chars-backward " \t\n\r")
15314 (if (eq (char-before) ?*) (forward-char 1))
15315 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15316 (beginning-of-line 0)
15317 (org-indent-to-column indent)
15318 (beginning-of-line 2)
15319 (org-indent-to-column indent)
15320 (beginning-of-line 0)
15321 (if hiddenp
15322 (save-excursion
15323 (org-back-to-heading t)
15324 (hide-entry))
15325 (org-flag-drawer t))))
15327 (defun org-insert-drawer (&optional arg drawer)
15328 "Insert a drawer at point.
15330 Optional argument DRAWER, when non-nil, is a string representing
15331 drawer's name. Otherwise, the user is prompted for a name.
15333 If a region is active, insert the drawer around that region
15334 instead.
15336 Point is left between drawer's boundaries."
15337 (interactive "P")
15338 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15339 "LOGBOOK"))
15340 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15341 ;; internally by Org. They are meant to be inserted
15342 ;; automatically.
15343 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15344 ;; Remove system drawers from list. Note: For some reason,
15345 ;; `org-completing-read' ignores the predicate while
15346 ;; `completing-read' handles it fine.
15347 (drawer (if arg "PROPERTIES"
15348 (or drawer
15349 (completing-read
15350 "Drawer: " org-drawers
15351 (lambda (d) (not (member d system-drawers))))))))
15352 (cond
15353 ;; With C-u, fall back on `org-insert-property-drawer'
15354 (arg (org-insert-property-drawer))
15355 ;; With an active region, insert a drawer at point.
15356 ((not (org-region-active-p))
15357 (progn
15358 (unless (bolp) (insert "\n"))
15359 (insert (format ":%s:\n\n:END:\n" drawer))
15360 (forward-line -2)))
15361 ;; Otherwise, insert the drawer at point
15363 (let ((rbeg (region-beginning))
15364 (rend (copy-marker (region-end))))
15365 (unwind-protect
15366 (progn
15367 (goto-char rbeg)
15368 (beginning-of-line)
15369 (when (save-excursion
15370 (re-search-forward org-outline-regexp-bol rend t))
15371 (error "Drawers cannot contain headlines"))
15372 ;; Position point at the beginning of the first
15373 ;; non-blank line in region. Insert drawer's opening
15374 ;; there, then indent it.
15375 (org-skip-whitespace)
15376 (beginning-of-line)
15377 (insert ":" drawer ":\n")
15378 (forward-line -1)
15379 (indent-for-tab-command)
15380 ;; Move point to the beginning of the first blank line
15381 ;; after the last non-blank line in region. Insert
15382 ;; drawer's closing, then indent it.
15383 (goto-char rend)
15384 (skip-chars-backward " \r\t\n")
15385 (insert "\n:END:")
15386 (deactivate-mark t)
15387 (indent-for-tab-command)
15388 (unless (eolp) (insert "\n")))
15389 ;; Clear marker, whatever the outcome of insertion is.
15390 (set-marker rend nil)))))))
15392 (defvar org-property-set-functions-alist nil
15393 "Property set function alist.
15394 Each entry should have the following format:
15396 (PROPERTY . READ-FUNCTION)
15398 The read function will be called with the same argument as
15399 `org-completing-read'.")
15401 (defun org-set-property-function (property)
15402 "Get the function that should be used to set PROPERTY.
15403 This is computed according to `org-property-set-functions-alist'."
15404 (or (cdr (assoc property org-property-set-functions-alist))
15405 'org-completing-read))
15407 (defun org-read-property-value (property)
15408 "Read PROPERTY value from user."
15409 (let* ((completion-ignore-case t)
15410 (allowed (org-property-get-allowed-values nil property 'table))
15411 (cur (org-entry-get nil property))
15412 (prompt (concat property " value"
15413 (if (and cur (string-match "\\S-" cur))
15414 (concat " [" cur "]") "") ": "))
15415 (set-function (org-set-property-function property))
15416 (val (if allowed
15417 (funcall set-function prompt allowed nil
15418 (not (get-text-property 0 'org-unrestricted
15419 (caar allowed))))
15420 (let (org-completion-use-ido org-completion-use-iswitchb)
15421 (funcall set-function prompt
15422 (mapcar 'list (org-property-values property))
15423 nil nil "" nil cur)))))
15424 (if (equal val "")
15426 val)))
15428 (defvar org-last-set-property nil)
15429 (defvar org-last-set-property-value nil)
15430 (defun org-read-property-name ()
15431 "Read a property name."
15432 (let* ((completion-ignore-case t)
15433 (keys (org-buffer-property-keys nil t t))
15434 (default-prop (or (save-excursion
15435 (save-match-data
15436 (beginning-of-line)
15437 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15438 (null (string= (match-string 1) "END"))
15439 (match-string 1))))
15440 org-last-set-property))
15441 (property (org-icompleting-read
15442 (concat "Property"
15443 (if default-prop (concat " [" default-prop "]") "")
15444 ": ")
15445 (mapcar 'list keys)
15446 nil nil nil nil
15447 default-prop)))
15448 (if (member property keys)
15449 property
15450 (or (cdr (assoc (downcase property)
15451 (mapcar (lambda (x) (cons (downcase x) x))
15452 keys)))
15453 property))))
15455 (defun org-set-property-and-value (use-last)
15456 "Allow to set [PROPERTY]: [value] direction from prompt.
15457 When use-default, don't even ask, just use the last
15458 \"[PROPERTY]: [value]\" string from the history."
15459 (interactive "P")
15460 (let* ((completion-ignore-case t)
15461 (pv (or (and use-last org-last-set-property-value)
15462 (org-completing-read
15463 "Enter a \"[Property]: [value]\" pair: "
15464 nil nil nil nil nil
15465 org-last-set-property-value)))
15466 prop val)
15467 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15468 (setq prop (match-string 1 pv)
15469 val (match-string 2 pv))
15470 (org-set-property prop val))))
15472 (defun org-set-property (property value)
15473 "In the current entry, set PROPERTY to VALUE.
15474 When called interactively, this will prompt for a property name, offering
15475 completion on existing and default properties. And then it will prompt
15476 for a value, offering completion either on allowed values (via an inherited
15477 xxx_ALL property) or on existing values in other instances of this property
15478 in the current file."
15479 (interactive (list nil nil))
15480 (let* ((property (or property (org-read-property-name)))
15481 (value (or value (org-read-property-value property)))
15482 (fn (cdr (assoc property org-properties-postprocess-alist))))
15483 (setq org-last-set-property property)
15484 (setq org-last-set-property-value (concat property ": " value))
15485 ;; Possibly postprocess the inserted value:
15486 (when fn (setq value (funcall fn value)))
15487 (unless (equal (org-entry-get nil property) value)
15488 (org-entry-put nil property value))))
15490 (defun org-delete-property (property &optional delete-empty-drawer)
15491 "In the current entry, delete PROPERTY.
15492 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15493 an empty drawer to delete."
15494 (interactive
15495 (let* ((completion-ignore-case t)
15496 (prop (org-icompleting-read "Property: "
15497 (org-entry-properties nil 'standard))))
15498 (list prop)))
15499 (message "Property %s %s" property
15500 (if (org-entry-delete nil property delete-empty-drawer)
15501 "deleted"
15502 "was not present in the entry")))
15504 (defun org-delete-property-globally (property)
15505 "Remove PROPERTY globally, from all entries."
15506 (interactive
15507 (let* ((completion-ignore-case t)
15508 (prop (org-icompleting-read
15509 "Globally remove property: "
15510 (mapcar 'list (org-buffer-property-keys)))))
15511 (list prop)))
15512 (save-excursion
15513 (save-restriction
15514 (widen)
15515 (goto-char (point-min))
15516 (let ((cnt 0))
15517 (while (re-search-forward
15518 (org-re-property property)
15519 nil t)
15520 (setq cnt (1+ cnt))
15521 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15522 (message "Property \"%s\" removed from %d entries" property cnt)))))
15524 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15526 (defun org-compute-property-at-point ()
15527 "Compute the property at point.
15528 This looks for an enclosing column format, extracts the operator and
15529 then applies it to the property in the column format's scope."
15530 (interactive)
15531 (unless (org-at-property-p)
15532 (error "Not at a property"))
15533 (let ((prop (org-match-string-no-properties 2)))
15534 (org-columns-get-format-and-top-level)
15535 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15536 (error "No operator defined for property %s" prop))
15537 (org-columns-compute prop)))
15539 (defvar org-property-allowed-value-functions nil
15540 "Hook for functions supplying allowed values for a specific property.
15541 The functions must take a single argument, the name of the property, and
15542 return a flat list of allowed values. If \":ETC\" is one of
15543 the values, this means that these values are intended as defaults for
15544 completion, but that other values should be allowed too.
15545 The functions must return nil if they are not responsible for this
15546 property.")
15548 (defun org-property-get-allowed-values (pom property &optional table)
15549 "Get allowed values for the property PROPERTY.
15550 When TABLE is non-nil, return an alist that can directly be used for
15551 completion."
15552 (let (vals)
15553 (cond
15554 ((equal property "TODO")
15555 (setq vals (org-with-point-at pom
15556 (append org-todo-keywords-1 '("")))))
15557 ((equal property "PRIORITY")
15558 (let ((n org-lowest-priority))
15559 (while (>= n org-highest-priority)
15560 (push (char-to-string n) vals)
15561 (setq n (1- n)))))
15562 ((member property org-special-properties))
15563 ((setq vals (run-hook-with-args-until-success
15564 'org-property-allowed-value-functions property)))
15566 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15567 (when (and vals (string-match "\\S-" vals))
15568 (setq vals (car (read-from-string (concat "(" vals ")"))))
15569 (setq vals (mapcar (lambda (x)
15570 (cond ((stringp x) x)
15571 ((numberp x) (number-to-string x))
15572 ((symbolp x) (symbol-name x))
15573 (t "???")))
15574 vals)))))
15575 (when (member ":ETC" vals)
15576 (setq vals (remove ":ETC" vals))
15577 (org-add-props (car vals) '(org-unrestricted t)))
15578 (if table (mapcar 'list vals) vals)))
15580 (defun org-property-previous-allowed-value (&optional previous)
15581 "Switch to the next allowed value for this property."
15582 (interactive)
15583 (org-property-next-allowed-value t))
15585 (defun org-property-next-allowed-value (&optional previous)
15586 "Switch to the next allowed value for this property."
15587 (interactive)
15588 (unless (org-at-property-p)
15589 (error "Not at a property"))
15590 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15591 (key (match-string 2))
15592 (value (match-string 3))
15593 (allowed (or (org-property-get-allowed-values (point) key)
15594 (and (member value '("[ ]" "[-]" "[X]"))
15595 '("[ ]" "[X]"))))
15596 (heading (save-match-data (nth 4 (org-heading-components))))
15597 nval)
15598 (unless allowed
15599 (error "Allowed values for this property have not been defined"))
15600 (if previous (setq allowed (reverse allowed)))
15601 (if (member value allowed)
15602 (setq nval (car (cdr (member value allowed)))))
15603 (setq nval (or nval (car allowed)))
15604 (if (equal nval value)
15605 (error "Only one allowed value for this property"))
15606 (org-at-property-p)
15607 (replace-match (concat " :" key ": " nval) t t)
15608 (org-indent-line)
15609 (beginning-of-line 1)
15610 (skip-chars-forward " \t")
15611 (when (equal prop org-effort-property)
15612 (save-excursion
15613 (org-back-to-heading t)
15614 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15615 (when (string= org-clock-current-task heading)
15616 (setq org-clock-effort nval)
15617 (org-clock-update-mode-line)))
15618 (run-hook-with-args 'org-property-changed-functions key nval)))
15620 (defun org-find-olp (path &optional this-buffer)
15621 "Return a marker pointing to the entry at outline path OLP.
15622 If anything goes wrong, throw an error.
15623 You can wrap this call to catch the error like this:
15625 (condition-case msg
15626 (org-mobile-locate-entry (match-string 4))
15627 (error (nth 1 msg)))
15629 The return value will then be either a string with the error message,
15630 or a marker if everything is OK.
15632 If THIS-BUFFER is set, the outline path does not contain a file,
15633 only headings."
15634 (let* ((file (if this-buffer buffer-file-name (pop path)))
15635 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15636 (level 1)
15637 (lmin 1)
15638 (lmax 1)
15639 limit re end found pos heading cnt flevel)
15640 (unless buffer (error "File not found :%s" file))
15641 (with-current-buffer buffer
15642 (save-excursion
15643 (save-restriction
15644 (widen)
15645 (setq limit (point-max))
15646 (goto-char (point-min))
15647 (while (setq heading (pop path))
15648 (setq re (format org-complex-heading-regexp-format
15649 (regexp-quote heading)))
15650 (setq cnt 0 pos (point))
15651 (while (re-search-forward re end t)
15652 (setq level (- (match-end 1) (match-beginning 1)))
15653 (if (and (>= level lmin) (<= level lmax))
15654 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15655 (when (= cnt 0) (error "Heading not found on level %d: %s"
15656 lmax heading))
15657 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15658 lmax heading))
15659 (goto-char found)
15660 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15661 (setq end (save-excursion (org-end-of-subtree t t))))
15662 (when (org-at-heading-p)
15663 (point-marker)))))))
15665 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15666 "Find node HEADING in BUFFER.
15667 Return a marker to the heading if it was found, or nil if not.
15668 If POS-ONLY is set, return just the position instead of a marker.
15670 The heading text must match exact, but it may have a TODO keyword,
15671 a priority cookie and tags in the standard locations."
15672 (with-current-buffer (or buffer (current-buffer))
15673 (save-excursion
15674 (save-restriction
15675 (widen)
15676 (goto-char (point-min))
15677 (let (case-fold-search)
15678 (if (re-search-forward
15679 (format org-complex-heading-regexp-format
15680 (regexp-quote heading)) nil t)
15681 (if pos-only
15682 (match-beginning 0)
15683 (move-marker (make-marker) (match-beginning 0)))))))))
15685 (defun org-find-exact-heading-in-directory (heading &optional dir)
15686 "Find Org node headline HEADING in all .org files in directory DIR.
15687 When the target headline is found, return a marker to this location."
15688 (let ((files (directory-files (or dir default-directory)
15689 nil "\\`[^.#].*\\.org\\'"))
15690 file visiting m buffer)
15691 (catch 'found
15692 (while (setq file (pop files))
15693 (message "trying %s" file)
15694 (setq visiting (org-find-base-buffer-visiting file))
15695 (setq buffer (or visiting (find-file-noselect file)))
15696 (setq m (org-find-exact-headline-in-buffer
15697 heading buffer))
15698 (when (and (not m) (not visiting)) (kill-buffer buffer))
15699 (and m (throw 'found m))))))
15701 (defun org-find-entry-with-id (ident)
15702 "Locate the entry that contains the ID property with exact value IDENT.
15703 IDENT can be a string, a symbol or a number, this function will search for
15704 the string representation of it.
15705 Return the position where this entry starts, or nil if there is no such entry."
15706 (interactive "sID: ")
15707 (let ((id (cond
15708 ((stringp ident) ident)
15709 ((symbol-name ident) (symbol-name ident))
15710 ((numberp ident) (number-to-string ident))
15711 (t (error "IDENT %s must be a string, symbol or number" ident))))
15712 (case-fold-search nil))
15713 (save-excursion
15714 (save-restriction
15715 (widen)
15716 (goto-char (point-min))
15717 (when (re-search-forward
15718 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15719 nil t)
15720 (org-back-to-heading t)
15721 (point))))))
15723 ;;;; Timestamps
15725 (defvar org-last-changed-timestamp nil)
15726 (defvar org-last-inserted-timestamp nil
15727 "The last time stamp inserted with `org-insert-time-stamp'.")
15728 (defvar org-time-was-given) ; dynamically scoped parameter
15729 (defvar org-end-time-was-given) ; dynamically scoped parameter
15730 (defvar org-ts-what) ; dynamically scoped parameter
15732 (defun org-time-stamp (arg &optional inactive)
15733 "Prompt for a date/time and insert a time stamp.
15734 If the user specifies a time like HH:MM or if this command is
15735 called with at least one prefix argument, the time stamp contains
15736 the date and the time. Otherwise, only the date is be included.
15738 All parts of a date not specified by the user is filled in from
15739 the current date/time. So if you just press return without
15740 typing anything, the time stamp will represent the current
15741 date/time.
15743 If there is already a timestamp at the cursor, it will be
15744 modified.
15746 With two universal prefix arguments, insert an active timestamp
15747 with the current time without prompting the user."
15748 (interactive "P")
15749 (let* ((ts nil)
15750 (default-time
15751 ;; Default time is either today, or, when entering a range,
15752 ;; the range start.
15753 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15754 (save-excursion
15755 (re-search-backward
15756 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15757 (- (point) 20) t)))
15758 (apply 'encode-time (org-parse-time-string (match-string 1)))
15759 (current-time)))
15760 (default-input (and ts (org-get-compact-tod ts)))
15761 (repeater (save-excursion
15762 (save-match-data
15763 (beginning-of-line)
15764 (when (re-search-forward
15765 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15766 (save-excursion (progn (end-of-line) (point))) t)
15767 (match-string 0)))))
15768 org-time-was-given org-end-time-was-given time)
15769 (cond
15770 ((and (org-at-timestamp-p t)
15771 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15772 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15773 (insert "--")
15774 (setq time (let ((this-command this-command))
15775 (org-read-date arg 'totime nil nil
15776 default-time default-input inactive)))
15777 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15778 ((org-at-timestamp-p t)
15779 (setq time (let ((this-command this-command))
15780 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15781 (when (org-at-timestamp-p t) ; just to get the match data
15782 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15783 (replace-match "")
15784 (setq org-last-changed-timestamp
15785 (org-insert-time-stamp
15786 time (or org-time-was-given arg)
15787 inactive nil nil (list org-end-time-was-given)))
15788 (when repeater (goto-char (1- (point))) (insert " " repeater)
15789 (setq org-last-changed-timestamp
15790 (concat (substring org-last-inserted-timestamp 0 -1)
15791 " " repeater ">"))))
15792 (message "Timestamp updated"))
15793 ((equal arg '(16))
15794 (org-insert-time-stamp (current-time) t))
15796 (setq time (let ((this-command this-command))
15797 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15798 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15799 nil nil (list org-end-time-was-given))))))
15801 ;; FIXME: can we use this for something else, like computing time differences?
15802 (defun org-get-compact-tod (s)
15803 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15804 (let* ((t1 (match-string 1 s))
15805 (h1 (string-to-number (match-string 2 s)))
15806 (m1 (string-to-number (match-string 3 s)))
15807 (t2 (and (match-end 4) (match-string 5 s)))
15808 (h2 (and t2 (string-to-number (match-string 6 s))))
15809 (m2 (and t2 (string-to-number (match-string 7 s))))
15810 dh dm)
15811 (if (not t2)
15813 (setq dh (- h2 h1) dm (- m2 m1))
15814 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15815 (concat t1 "+" (number-to-string dh)
15816 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15818 (defun org-time-stamp-inactive (&optional arg)
15819 "Insert an inactive time stamp.
15820 An inactive time stamp is enclosed in square brackets instead of angle
15821 brackets. It is inactive in the sense that it does not trigger agenda entries,
15822 does not link to the calendar and cannot be changed with the S-cursor keys.
15823 So these are more for recording a certain time/date."
15824 (interactive "P")
15825 (org-time-stamp arg 'inactive))
15827 (defvar org-date-ovl (make-overlay 1 1))
15828 (overlay-put org-date-ovl 'face 'org-date-selected)
15829 (org-detach-overlay org-date-ovl)
15831 (defvar org-ans1) ; dynamically scoped parameter
15832 (defvar org-ans2) ; dynamically scoped parameter
15834 (defvar org-plain-time-of-day-regexp) ; defined below
15836 (defvar org-overriding-default-time nil) ; dynamically scoped
15837 (defvar org-read-date-overlay nil)
15838 (defvar org-dcst nil) ; dynamically scoped
15839 (defvar org-read-date-history nil)
15840 (defvar org-read-date-final-answer nil)
15841 (defvar org-read-date-analyze-futurep nil)
15842 (defvar org-read-date-analyze-forced-year nil)
15843 (defvar org-read-date-inactive)
15845 (defvar org-read-date-minibuffer-local-map
15846 (let ((map (make-sparse-keymap)))
15847 (set-keymap-parent map minibuffer-local-map)
15848 (org-defkey map (kbd ".")
15849 (lambda () (interactive)
15850 (org-eval-in-calendar '(calendar-goto-today))))
15851 (org-defkey map [(meta shift left)]
15852 (lambda () (interactive)
15853 (org-eval-in-calendar '(calendar-backward-month 1))))
15854 (org-defkey map [(meta shift right)]
15855 (lambda () (interactive)
15856 (org-eval-in-calendar '(calendar-forward-month 1))))
15857 (org-defkey map [(meta shift up)]
15858 (lambda () (interactive)
15859 (org-eval-in-calendar '(calendar-backward-year 1))))
15860 (org-defkey map [(meta shift down)]
15861 (lambda () (interactive)
15862 (org-eval-in-calendar '(calendar-forward-year 1))))
15863 (org-defkey map [?\e (shift left)]
15864 (lambda () (interactive)
15865 (org-eval-in-calendar '(calendar-backward-month 1))))
15866 (org-defkey map [?\e (shift right)]
15867 (lambda () (interactive)
15868 (org-eval-in-calendar '(calendar-forward-month 1))))
15869 (org-defkey map [?\e (shift up)]
15870 (lambda () (interactive)
15871 (org-eval-in-calendar '(calendar-backward-year 1))))
15872 (org-defkey map [?\e (shift down)]
15873 (lambda () (interactive)
15874 (org-eval-in-calendar '(calendar-forward-year 1))))
15875 (org-defkey map [(shift up)]
15876 (lambda () (interactive)
15877 (org-eval-in-calendar '(calendar-backward-week 1))))
15878 (org-defkey map [(shift down)]
15879 (lambda () (interactive)
15880 (org-eval-in-calendar '(calendar-forward-week 1))))
15881 (org-defkey map [(shift left)]
15882 (lambda () (interactive)
15883 (org-eval-in-calendar '(calendar-backward-day 1))))
15884 (org-defkey map [(shift right)]
15885 (lambda () (interactive)
15886 (org-eval-in-calendar '(calendar-forward-day 1))))
15887 (org-defkey map "!"
15888 (lambda () (interactive)
15889 (org-eval-in-calendar '(diary-view-entries))
15890 (message "")))
15891 (org-defkey map ">"
15892 (lambda () (interactive)
15893 (org-eval-in-calendar '(scroll-calendar-left 1))))
15894 (org-defkey map "<"
15895 (lambda () (interactive)
15896 (org-eval-in-calendar '(scroll-calendar-right 1))))
15897 (org-defkey map "\C-v"
15898 (lambda () (interactive)
15899 (org-eval-in-calendar
15900 '(calendar-scroll-left-three-months 1))))
15901 (org-defkey map "\M-v"
15902 (lambda () (interactive)
15903 (org-eval-in-calendar
15904 '(calendar-scroll-right-three-months 1))))
15905 map)
15906 "Keymap for minibuffer commands when using `org-read-date'.")
15908 (defun org-read-date (&optional org-with-time to-time from-string prompt
15909 default-time default-input inactive)
15910 "Read a date, possibly a time, and make things smooth for the user.
15911 The prompt will suggest to enter an ISO date, but you can also enter anything
15912 which will at least partially be understood by `parse-time-string'.
15913 Unrecognized parts of the date will default to the current day, month, year,
15914 hour and minute. If this command is called to replace a timestamp at point,
15915 or to enter the second timestamp of a range, the default time is taken
15916 from the existing stamp. Furthermore, the command prefers the future,
15917 so if you are giving a date where the year is not given, and the day-month
15918 combination is already past in the current year, it will assume you
15919 mean next year. For details, see the manual. A few examples:
15921 3-2-5 --> 2003-02-05
15922 feb 15 --> currentyear-02-15
15923 2/15 --> currentyear-02-15
15924 sep 12 9 --> 2009-09-12
15925 12:45 --> today 12:45
15926 22 sept 0:34 --> currentyear-09-22 0:34
15927 12 --> currentyear-currentmonth-12
15928 Fri --> nearest Friday (today or later)
15929 etc.
15931 Furthermore you can specify a relative date by giving, as the *first* thing
15932 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15933 change in days weeks, months, years.
15934 With a single plus or minus, the date is relative to today. With a double
15935 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15936 +4d --> four days from today
15937 +4 --> same as above
15938 +2w --> two weeks from today
15939 ++5 --> five days from default date
15941 The function understands only English month and weekday abbreviations.
15943 While prompting, a calendar is popped up - you can also select the
15944 date with the mouse (button 1). The calendar shows a period of three
15945 months. To scroll it to other months, use the keys `>' and `<'.
15946 If you don't like the calendar, turn it off with
15947 \(setq org-read-date-popup-calendar nil)
15949 With optional argument TO-TIME, the date will immediately be converted
15950 to an internal time.
15951 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15952 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15953 still enter a time, and this function will inform the calling routine
15954 about this change. The calling routine may then choose to change the
15955 format used to insert the time stamp into the buffer to include the time.
15956 With optional argument FROM-STRING, read from this string instead from
15957 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15958 the time/date that is used for everything that is not specified by the
15959 user."
15960 (require 'parse-time)
15961 (let* ((org-time-stamp-rounding-minutes
15962 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15963 (org-dcst org-display-custom-times)
15964 (ct (org-current-time))
15965 (org-def (or org-overriding-default-time default-time ct))
15966 (org-defdecode (decode-time org-def))
15967 (dummy (progn
15968 (when (< (nth 2 org-defdecode) org-extend-today-until)
15969 (setcar (nthcdr 2 org-defdecode) -1)
15970 (setcar (nthcdr 1 org-defdecode) 59)
15971 (setq org-def (apply 'encode-time org-defdecode)
15972 org-defdecode (decode-time org-def)))))
15973 (mouse-autoselect-window nil) ; Don't let the mouse jump
15974 (calendar-frame-setup nil)
15975 (calendar-setup nil)
15976 (calendar-move-hook nil)
15977 (calendar-view-diary-initially-flag nil)
15978 (calendar-view-holidays-initially-flag nil)
15979 (timestr (format-time-string
15980 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15981 (prompt (concat (if prompt (concat prompt " ") "")
15982 (format "Date+time [%s]: " timestr)))
15983 ans (org-ans0 "") org-ans1 org-ans2 final)
15985 (cond
15986 (from-string (setq ans from-string))
15987 (org-read-date-popup-calendar
15988 (save-excursion
15989 (save-window-excursion
15990 (calendar)
15991 (org-eval-in-calendar '(setq cursor-type nil) t)
15992 (unwind-protect
15993 (progn
15994 (calendar-forward-day (- (time-to-days org-def)
15995 (calendar-absolute-from-gregorian
15996 (calendar-current-date))))
15997 (org-eval-in-calendar nil t)
15998 (let* ((old-map (current-local-map))
15999 (map (copy-keymap calendar-mode-map))
16000 (minibuffer-local-map
16001 (copy-keymap org-read-date-minibuffer-local-map)))
16002 (org-defkey map (kbd "RET") 'org-calendar-select)
16003 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16004 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16005 (unwind-protect
16006 (progn
16007 (use-local-map map)
16008 (setq org-read-date-inactive inactive)
16009 (add-hook 'post-command-hook 'org-read-date-display)
16010 (setq org-ans0 (read-string prompt default-input
16011 'org-read-date-history nil))
16012 ;; org-ans0: from prompt
16013 ;; org-ans1: from mouse click
16014 ;; org-ans2: from calendar motion
16015 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16016 (remove-hook 'post-command-hook 'org-read-date-display)
16017 (use-local-map old-map)
16018 (when org-read-date-overlay
16019 (delete-overlay org-read-date-overlay)
16020 (setq org-read-date-overlay nil)))))
16021 (bury-buffer "*Calendar*")))))
16023 (t ; Naked prompt only
16024 (unwind-protect
16025 (setq ans (read-string prompt default-input
16026 'org-read-date-history timestr))
16027 (when org-read-date-overlay
16028 (delete-overlay org-read-date-overlay)
16029 (setq org-read-date-overlay nil)))))
16031 (setq final (org-read-date-analyze ans org-def org-defdecode))
16033 (when org-read-date-analyze-forced-year
16034 (message "Year was forced into %s"
16035 (if org-read-date-force-compatible-dates
16036 "compatible range (1970-2037)"
16037 "range representable on this machine"))
16038 (ding))
16040 ;; One round trip to get rid of 34th of August and stuff like that....
16041 (setq final (decode-time (apply 'encode-time final)))
16043 (setq org-read-date-final-answer ans)
16045 (if to-time
16046 (apply 'encode-time final)
16047 (if (and (boundp 'org-time-was-given) org-time-was-given)
16048 (format "%04d-%02d-%02d %02d:%02d"
16049 (nth 5 final) (nth 4 final) (nth 3 final)
16050 (nth 2 final) (nth 1 final))
16051 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16053 (defvar org-def)
16054 (defvar org-defdecode)
16055 (defvar org-with-time)
16056 (defun org-read-date-display ()
16057 "Display the current date prompt interpretation in the minibuffer."
16058 (when org-read-date-display-live
16059 (when org-read-date-overlay
16060 (delete-overlay org-read-date-overlay))
16061 (when (minibufferp (current-buffer))
16062 (save-excursion
16063 (end-of-line 1)
16064 (while (not (equal (buffer-substring
16065 (max (point-min) (- (point) 4)) (point))
16066 " "))
16067 (insert " ")))
16068 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16069 " " (or org-ans1 org-ans2)))
16070 (org-end-time-was-given nil)
16071 (f (org-read-date-analyze ans org-def org-defdecode))
16072 (fmts (if org-dcst
16073 org-time-stamp-custom-formats
16074 org-time-stamp-formats))
16075 (fmt (if (or org-with-time
16076 (and (boundp 'org-time-was-given) org-time-was-given))
16077 (cdr fmts)
16078 (car fmts)))
16079 (txt (format-time-string fmt (apply 'encode-time f)))
16080 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16081 (txt (concat "=> " txt)))
16082 (when (and org-end-time-was-given
16083 (string-match org-plain-time-of-day-regexp txt))
16084 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16085 org-end-time-was-given
16086 (substring txt (match-end 0)))))
16087 (when org-read-date-analyze-futurep
16088 (setq txt (concat txt " (=>F)")))
16089 (setq org-read-date-overlay
16090 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16091 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16093 (defun org-read-date-analyze (ans org-def org-defdecode)
16094 "Analyze the combined answer of the date prompt."
16095 ;; FIXME: cleanup and comment
16096 (let ((nowdecode (decode-time (current-time)))
16097 delta deltan deltaw deltadef year month day
16098 hour minute second wday pm h2 m2 tl wday1
16099 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16100 (setq org-read-date-analyze-futurep nil
16101 org-read-date-analyze-forced-year nil)
16102 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16103 (setq ans "+0"))
16105 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16106 (setq ans (replace-match "" t t ans)
16107 deltan (car delta)
16108 deltaw (nth 1 delta)
16109 deltadef (nth 2 delta)))
16111 ;; Check if there is an iso week date in there. If yes, store the
16112 ;; info and postpone interpreting it until the rest of the parsing
16113 ;; is done.
16114 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16115 (setq iso-year (if (match-end 1)
16116 (org-small-year-to-year
16117 (string-to-number (match-string 1 ans))))
16118 iso-weekday (if (match-end 3)
16119 (string-to-number (match-string 3 ans)))
16120 iso-week (string-to-number (match-string 2 ans)))
16121 (setq ans (replace-match "" t t ans)))
16123 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16124 (when (string-match
16125 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16126 (setq year (if (match-end 2)
16127 (string-to-number (match-string 2 ans))
16128 (progn (setq kill-year t)
16129 (string-to-number (format-time-string "%Y"))))
16130 month (string-to-number (match-string 3 ans))
16131 day (string-to-number (match-string 4 ans)))
16132 (if (< year 100) (setq year (+ 2000 year)))
16133 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16134 t nil ans)))
16136 ;; Help matching dotted european dates
16137 (when (string-match
16138 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16139 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16140 (setq kill-year t)
16141 (string-to-number (format-time-string "%Y")))
16142 day (string-to-number (match-string 1 ans))
16143 month (string-to-number (match-string 2 ans))
16144 ans (replace-match (format "%04d-%02d-%02d" year month day)
16145 t nil ans)))
16147 ;; Help matching american dates, like 5/30 or 5/30/7
16148 (when (string-match
16149 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16150 (setq year (if (match-end 4)
16151 (string-to-number (match-string 4 ans))
16152 (progn (setq kill-year t)
16153 (string-to-number (format-time-string "%Y"))))
16154 month (string-to-number (match-string 1 ans))
16155 day (string-to-number (match-string 2 ans)))
16156 (if (< year 100) (setq year (+ 2000 year)))
16157 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16158 t nil ans)))
16159 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16160 ;; If there is a time with am/pm, and *no* time without it, we convert
16161 ;; so that matching will be successful.
16162 (loop for i from 1 to 2 do ; twice, for end time as well
16163 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16164 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16165 (setq hour (string-to-number (match-string 1 ans))
16166 minute (if (match-end 3)
16167 (string-to-number (match-string 3 ans))
16169 pm (equal ?p
16170 (string-to-char (downcase (match-string 4 ans)))))
16171 (if (and (= hour 12) (not pm))
16172 (setq hour 0)
16173 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16174 (setq ans (replace-match (format "%02d:%02d" hour minute)
16175 t t ans))))
16177 ;; Check if a time range is given as a duration
16178 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16179 (setq hour (string-to-number (match-string 1 ans))
16180 h2 (+ hour (string-to-number (match-string 3 ans)))
16181 minute (string-to-number (match-string 2 ans))
16182 m2 (+ minute (if (match-end 5) (string-to-number
16183 (match-string 5 ans))0)))
16184 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16185 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16186 t t ans)))
16188 ;; Check if there is a time range
16189 (when (boundp 'org-end-time-was-given)
16190 (setq org-time-was-given nil)
16191 (when (and (string-match org-plain-time-of-day-regexp ans)
16192 (match-end 8))
16193 (setq org-end-time-was-given (match-string 8 ans))
16194 (setq ans (concat (substring ans 0 (match-beginning 7))
16195 (substring ans (match-end 7))))))
16197 (setq tl (parse-time-string ans)
16198 day (or (nth 3 tl) (nth 3 org-defdecode))
16199 month (or (nth 4 tl)
16200 (if (and org-read-date-prefer-future
16201 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16202 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16203 (nth 4 org-defdecode)))
16204 year (or (and (not kill-year) (nth 5 tl))
16205 (if (and org-read-date-prefer-future
16206 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16207 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16208 (nth 5 org-defdecode)))
16209 hour (or (nth 2 tl) (nth 2 org-defdecode))
16210 minute (or (nth 1 tl) (nth 1 org-defdecode))
16211 second (or (nth 0 tl) 0)
16212 wday (nth 6 tl))
16214 (when (and (eq org-read-date-prefer-future 'time)
16215 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16216 (equal day (nth 3 nowdecode))
16217 (equal month (nth 4 nowdecode))
16218 (equal year (nth 5 nowdecode))
16219 (nth 2 tl)
16220 (or (< (nth 2 tl) (nth 2 nowdecode))
16221 (and (= (nth 2 tl) (nth 2 nowdecode))
16222 (nth 1 tl)
16223 (< (nth 1 tl) (nth 1 nowdecode)))))
16224 (setq day (1+ day)
16225 futurep t))
16227 ;; Special date definitions below
16228 (cond
16229 (iso-week
16230 ;; There was an iso week
16231 (require 'cal-iso)
16232 (setq futurep nil)
16233 (setq year (or iso-year year)
16234 day (or iso-weekday wday 1)
16235 wday nil ; to make sure that the trigger below does not match
16236 iso-date (calendar-gregorian-from-absolute
16237 (calendar-absolute-from-iso
16238 (list iso-week day year))))
16239 ; FIXME: Should we also push ISO weeks into the future?
16240 ; (when (and org-read-date-prefer-future
16241 ; (not iso-year)
16242 ; (< (calendar-absolute-from-gregorian iso-date)
16243 ; (time-to-days (current-time))))
16244 ; (setq year (1+ year)
16245 ; iso-date (calendar-gregorian-from-absolute
16246 ; (calendar-absolute-from-iso
16247 ; (list iso-week day year)))))
16248 (setq month (car iso-date)
16249 year (nth 2 iso-date)
16250 day (nth 1 iso-date)))
16251 (deltan
16252 (setq futurep nil)
16253 (unless deltadef
16254 (let ((now (decode-time (current-time))))
16255 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16256 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16257 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16258 ((equal deltaw "m") (setq month (+ month deltan)))
16259 ((equal deltaw "y") (setq year (+ year deltan)))))
16260 ((and wday (not (nth 3 tl)))
16261 ;; Weekday was given, but no day, so pick that day in the week
16262 ;; on or after the derived date.
16263 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16264 (unless (equal wday wday1)
16265 (setq day (+ day (% (- wday wday1 -7) 7))))))
16266 (if (and (boundp 'org-time-was-given)
16267 (nth 2 tl))
16268 (setq org-time-was-given t))
16269 (if (< year 100) (setq year (+ 2000 year)))
16270 ;; Check of the date is representable
16271 (if org-read-date-force-compatible-dates
16272 (progn
16273 (if (< year 1970)
16274 (setq year 1970 org-read-date-analyze-forced-year t))
16275 (if (> year 2037)
16276 (setq year 2037 org-read-date-analyze-forced-year t)))
16277 (condition-case nil
16278 (ignore (encode-time second minute hour day month year))
16279 (error
16280 (setq year (nth 5 org-defdecode))
16281 (setq org-read-date-analyze-forced-year t))))
16282 (setq org-read-date-analyze-futurep futurep)
16283 (list second minute hour day month year)))
16285 (defvar parse-time-weekdays)
16286 (defun org-read-date-get-relative (s today default)
16287 "Check string S for special relative date string.
16288 TODAY and DEFAULT are internal times, for today and for a default.
16289 Return shift list (N what def-flag)
16290 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16291 N is the number of WHATs to shift.
16292 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16293 the DEFAULT date rather than TODAY."
16294 (require 'parse-time)
16295 (when (and
16296 (string-match
16297 (concat
16298 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16299 "\\([0-9]+\\)?"
16300 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16301 "\\([ \t]\\|$\\)") s)
16302 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16303 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16304 (string-to-char (substring (match-string 1 s) -1))
16305 ?+))
16306 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16307 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16308 (what (if (match-end 3) (match-string 3 s) "d"))
16309 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16310 (date (if rel default today))
16311 (wday (nth 6 (decode-time date)))
16312 delta)
16313 (if wday1
16314 (progn
16315 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16316 (if (= dir ?-) (setq delta (- delta 7)))
16317 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16318 (list delta "d" rel))
16319 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16321 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16322 "Turn a user-specified date into the internal representation.
16323 The internal representation needed by the calendar is (month day year).
16324 This is a wrapper to handle the brain-dead convention in calendar that
16325 user function argument order change dependent on argument order."
16326 (if (boundp 'calendar-date-style)
16327 (cond
16328 ((eq calendar-date-style 'american)
16329 (list arg1 arg2 arg3))
16330 ((eq calendar-date-style 'european)
16331 (list arg2 arg1 arg3))
16332 ((eq calendar-date-style 'iso)
16333 (list arg2 arg3 arg1)))
16334 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16335 (if (org-bound-and-true-p european-calendar-style)
16336 (list arg2 arg1 arg3)
16337 (list arg1 arg2 arg3)))))
16339 (defun org-eval-in-calendar (form &optional keepdate)
16340 "Eval FORM in the calendar window and return to current window.
16341 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16342 otherwise stick to the current value of `org-ans2'."
16343 (let ((sf (selected-frame))
16344 (sw (selected-window)))
16345 (select-window (get-buffer-window "*Calendar*" t))
16346 (eval form)
16347 (when (and (not keepdate) (calendar-cursor-to-date))
16348 (let* ((date (calendar-cursor-to-date))
16349 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16350 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16351 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16352 (select-window sw)
16353 (org-select-frame-set-input-focus sf)))
16355 (defun org-calendar-select ()
16356 "Return to `org-read-date' with the date currently selected.
16357 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16358 (interactive)
16359 (when (calendar-cursor-to-date)
16360 (let* ((date (calendar-cursor-to-date))
16361 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16362 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16363 (if (active-minibuffer-window) (exit-minibuffer))))
16365 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16366 "Insert a date stamp for the date given by the internal TIME.
16367 WITH-HM means use the stamp format that includes the time of the day.
16368 INACTIVE means use square brackets instead of angular ones, so that the
16369 stamp will not contribute to the agenda.
16370 PRE and POST are optional strings to be inserted before and after the
16371 stamp.
16372 The command returns the inserted time stamp."
16373 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16374 stamp)
16375 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16376 (insert-before-markers (or pre ""))
16377 (when (listp extra)
16378 (setq extra (car extra))
16379 (if (and (stringp extra)
16380 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16381 (setq extra (format "-%02d:%02d"
16382 (string-to-number (match-string 1 extra))
16383 (string-to-number (match-string 2 extra))))
16384 (setq extra nil)))
16385 (when extra
16386 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16387 (insert-before-markers (setq stamp (format-time-string fmt time)))
16388 (insert-before-markers (or post ""))
16389 (setq org-last-inserted-timestamp stamp)))
16391 (defun org-toggle-time-stamp-overlays ()
16392 "Toggle the use of custom time stamp formats."
16393 (interactive)
16394 (setq org-display-custom-times (not org-display-custom-times))
16395 (unless org-display-custom-times
16396 (let ((p (point-min)) (bmp (buffer-modified-p)))
16397 (while (setq p (next-single-property-change p 'display))
16398 (if (and (get-text-property p 'display)
16399 (eq (get-text-property p 'face) 'org-date))
16400 (remove-text-properties
16401 p (setq p (next-single-property-change p 'display))
16402 '(display t))))
16403 (set-buffer-modified-p bmp)))
16404 (if (featurep 'xemacs)
16405 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16406 (org-restart-font-lock)
16407 (setq org-table-may-need-update t)
16408 (if org-display-custom-times
16409 (message "Time stamps are overlaid with custom format")
16410 (message "Time stamp overlays removed")))
16412 (defun org-display-custom-time (beg end)
16413 "Overlay modified time stamp format over timestamp between BEG and END."
16414 (let* ((ts (buffer-substring beg end))
16415 t1 w1 with-hm tf time str w2 (off 0))
16416 (save-match-data
16417 (setq t1 (org-parse-time-string ts t))
16418 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16419 (setq off (- (match-end 0) (match-beginning 0)))))
16420 (setq end (- end off))
16421 (setq w1 (- end beg)
16422 with-hm (and (nth 1 t1) (nth 2 t1))
16423 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16424 time (org-fix-decoded-time t1)
16425 str (org-add-props
16426 (format-time-string
16427 (substring tf 1 -1) (apply 'encode-time time))
16428 nil 'mouse-face 'highlight)
16429 w2 (length str))
16430 (if (not (= w2 w1))
16431 (add-text-properties (1+ beg) (+ 2 beg)
16432 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16433 (if (featurep 'xemacs)
16434 (progn
16435 (put-text-property beg end 'invisible t)
16436 (put-text-property beg end 'end-glyph (make-glyph str)))
16437 (put-text-property beg end 'display str))))
16439 (defun org-translate-time (string)
16440 "Translate all timestamps in STRING to custom format.
16441 But do this only if the variable `org-display-custom-times' is set."
16442 (when org-display-custom-times
16443 (save-match-data
16444 (let* ((start 0)
16445 (re org-ts-regexp-both)
16446 t1 with-hm inactive tf time str beg end)
16447 (while (setq start (string-match re string start))
16448 (setq beg (match-beginning 0)
16449 end (match-end 0)
16450 t1 (save-match-data
16451 (org-parse-time-string (substring string beg end) t))
16452 with-hm (and (nth 1 t1) (nth 2 t1))
16453 inactive (equal (substring string beg (1+ beg)) "[")
16454 tf (funcall (if with-hm 'cdr 'car)
16455 org-time-stamp-custom-formats)
16456 time (org-fix-decoded-time t1)
16457 str (format-time-string
16458 (concat
16459 (if inactive "[" "<") (substring tf 1 -1)
16460 (if inactive "]" ">"))
16461 (apply 'encode-time time))
16462 string (replace-match str t t string)
16463 start (+ start (length str)))))))
16464 string)
16466 (defun org-fix-decoded-time (time)
16467 "Set 0 instead of nil for the first 6 elements of time.
16468 Don't touch the rest."
16469 (let ((n 0))
16470 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16472 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16474 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16475 "Difference between TIMESTAMP-STRING and now in days.
16476 If SECONDS is non-nil, return the difference in seconds."
16477 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16478 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16479 (funcall fdiff (current-time)))))
16481 (defun org-deadline-close (timestamp-string &optional ndays)
16482 "Is the time in TIMESTAMP-STRING close to the current date?"
16483 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16484 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16485 (not (org-entry-is-done-p))))
16487 (defun org-get-wdays (ts &optional delay zero-delay)
16488 "Get the deadline lead time appropriate for timestring TS.
16489 When DELAY is non-nil, get the delay time for scheduled items
16490 instead of the deadline lead time. When ZERO-DELAY is non-nil
16491 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16492 don't try to find the delay cookie in the scheduled timestamp."
16493 (let ((tv (if delay org-scheduled-delay-days
16494 org-deadline-warning-days)))
16495 (cond
16496 ((or (and delay (< tv 0))
16497 (and delay zero-delay (<= tv 0))
16498 (and (not delay) (<= tv 0)))
16499 ;; Enforce this value no matter what
16500 (- tv))
16501 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16502 ;; lead time is specified.
16503 (floor (* (string-to-number (match-string 1 ts))
16504 (cdr (assoc (match-string 2 ts)
16505 '(("d" . 1) ("w" . 7)
16506 ("m" . 30.4) ("y" . 365.25)
16507 ("h" . 0.041667)))))))
16508 ;; go for the default.
16509 (t tv))))
16511 (defun org-calendar-select-mouse (ev)
16512 "Return to `org-read-date' with the date currently selected.
16513 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16514 (interactive "e")
16515 (mouse-set-point ev)
16516 (when (calendar-cursor-to-date)
16517 (let* ((date (calendar-cursor-to-date))
16518 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16519 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16520 (if (active-minibuffer-window) (exit-minibuffer))))
16522 (defun org-check-deadlines (ndays)
16523 "Check if there are any deadlines due or past due.
16524 A deadline is considered due if it happens within `org-deadline-warning-days'
16525 days from today's date. If the deadline appears in an entry marked DONE,
16526 it is not shown. The prefix arg NDAYS can be used to test that many
16527 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16528 (interactive "P")
16529 (let* ((org-warn-days
16530 (cond
16531 ((equal ndays '(4)) 100000)
16532 (ndays (prefix-numeric-value ndays))
16533 (t (abs org-deadline-warning-days))))
16534 (case-fold-search nil)
16535 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16536 (callback
16537 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16539 (message "%d deadlines past-due or due within %d days"
16540 (org-occur regexp nil callback)
16541 org-warn-days)))
16543 (defsubst org-re-timestamp (type)
16544 "Return a regexp for timestamp TYPE.
16545 Allowed values for TYPE are:
16547 all: all timestamps
16548 active: only active timestamps (<...>)
16549 inactive: only inactive timestamps ([...])
16550 scheduled: only scheduled timestamps
16551 deadline: only deadline timestamps
16553 When TYPE is nil, fall back on returning a regexp that matches
16554 both scheduled and deadline timestamps."
16555 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16556 ((eq type 'active) org-ts-regexp)
16557 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16558 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16559 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16560 ((eq type 'scheduled-or-deadline)
16561 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16563 (defun org-check-before-date (date)
16564 "Check if there are deadlines or scheduled entries before DATE."
16565 (interactive (list (org-read-date)))
16566 (let ((case-fold-search nil)
16567 (regexp (org-re-timestamp org-ts-type))
16568 (callback
16569 (lambda () (time-less-p
16570 (org-time-string-to-time (match-string 1))
16571 (org-time-string-to-time date)))))
16572 (message "%d entries before %s"
16573 (org-occur regexp nil callback) date)))
16575 (defun org-check-after-date (date)
16576 "Check if there are deadlines or scheduled entries after DATE."
16577 (interactive (list (org-read-date)))
16578 (let ((case-fold-search nil)
16579 (regexp (org-re-timestamp org-ts-type))
16580 (callback
16581 (lambda () (not
16582 (time-less-p
16583 (org-time-string-to-time (match-string 1))
16584 (org-time-string-to-time date))))))
16585 (message "%d entries after %s"
16586 (org-occur regexp nil callback) date)))
16588 (defun org-check-dates-range (start-date end-date)
16589 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16590 (interactive (list (org-read-date nil nil nil "Range starts")
16591 (org-read-date nil nil nil "Range end")))
16592 (let ((case-fold-search nil)
16593 (regexp (org-re-timestamp org-ts-type))
16594 (callback
16595 (lambda ()
16596 (let ((match (match-string 1)))
16597 (and
16598 (not (time-less-p
16599 (org-time-string-to-time match)
16600 (org-time-string-to-time start-date)))
16601 (time-less-p
16602 (org-time-string-to-time match)
16603 (org-time-string-to-time end-date)))))))
16604 (message "%d entries between %s and %s"
16605 (org-occur regexp nil callback) start-date end-date)))
16607 (defun org-evaluate-time-range (&optional to-buffer)
16608 "Evaluate a time range by computing the difference between start and end.
16609 Normally the result is just printed in the echo area, but with prefix arg
16610 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16611 If the time range is actually in a table, the result is inserted into the
16612 next column.
16613 For time difference computation, a year is assumed to be exactly 365
16614 days in order to avoid rounding problems."
16615 (interactive "P")
16617 (org-clock-update-time-maybe)
16618 (save-excursion
16619 (unless (org-at-date-range-p t)
16620 (goto-char (point-at-bol))
16621 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16622 (if (not (org-at-date-range-p t))
16623 (error "Not at a time-stamp range, and none found in current line")))
16624 (let* ((ts1 (match-string 1))
16625 (ts2 (match-string 2))
16626 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16627 (match-end (match-end 0))
16628 (time1 (org-time-string-to-time ts1))
16629 (time2 (org-time-string-to-time ts2))
16630 (t1 (org-float-time time1))
16631 (t2 (org-float-time time2))
16632 (diff (abs (- t2 t1)))
16633 (negative (< (- t2 t1) 0))
16634 ;; (ys (floor (* 365 24 60 60)))
16635 (ds (* 24 60 60))
16636 (hs (* 60 60))
16637 (fy "%dy %dd %02d:%02d")
16638 (fy1 "%dy %dd")
16639 (fd "%dd %02d:%02d")
16640 (fd1 "%dd")
16641 (fh "%02d:%02d")
16642 y d h m align)
16643 (if havetime
16644 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16646 d (floor (/ diff ds)) diff (mod diff ds)
16647 h (floor (/ diff hs)) diff (mod diff hs)
16648 m (floor (/ diff 60)))
16649 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16651 d (floor (+ (/ diff ds) 0.5))
16652 h 0 m 0))
16653 (if (not to-buffer)
16654 (message "%s" (org-make-tdiff-string y d h m))
16655 (if (org-at-table-p)
16656 (progn
16657 (goto-char match-end)
16658 (setq align t)
16659 (and (looking-at " *|") (goto-char (match-end 0))))
16660 (goto-char match-end))
16661 (if (looking-at
16662 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16663 (replace-match ""))
16664 (if negative (insert " -"))
16665 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16666 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16667 (insert " " (format fh h m))))
16668 (if align (org-table-align))
16669 (message "Time difference inserted")))))
16671 (defun org-make-tdiff-string (y d h m)
16672 (let ((fmt "")
16673 (l nil))
16674 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16675 l (push y l)))
16676 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16677 l (push d l)))
16678 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16679 l (push h l)))
16680 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16681 l (push m l)))
16682 (apply 'format fmt (nreverse l))))
16684 (defun org-time-string-to-time (s &optional buffer pos)
16685 "Convert a timestamp string into internal time."
16686 (condition-case errdata
16687 (apply 'encode-time (org-parse-time-string s))
16688 (error (error "Bad timestamp `%s'%s\nError was: %s"
16689 s (if (not (and buffer pos))
16691 (format " at %d in buffer `%s'" pos buffer))
16692 (cdr errdata)))))
16694 (defun org-time-string-to-seconds (s)
16695 "Convert a timestamp string to a number of seconds."
16696 (org-float-time (org-time-string-to-time s)))
16698 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16699 "Convert a time stamp to an absolute day number.
16700 If there is a specifier for a cyclic time stamp, get the closest
16701 date to DAYNR.
16702 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16703 The variable `date' is bound by the calendar when this is called."
16704 (cond
16705 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16706 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16707 daynr
16708 (+ daynr 1000)))
16709 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16710 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16711 (time-to-days (current-time))) (match-string 0 s)
16712 prefer show-all))
16713 (t (time-to-days
16714 (condition-case errdata
16715 (apply 'encode-time (org-parse-time-string s))
16716 (error (error "Bad timestamp `%s'%s\nError was: %s"
16717 s (if (not (and buffer pos))
16719 (format " at %d in buffer `%s'" pos buffer))
16720 (cdr errdata))))))))
16722 (defun org-days-to-iso-week (days)
16723 "Return the iso week number."
16724 (require 'cal-iso)
16725 (car (calendar-iso-from-absolute days)))
16727 (defun org-small-year-to-year (year)
16728 "Convert 2-digit years into 4-digit years.
16729 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16730 The year 2000 cannot be abbreviated. Any year larger than 99
16731 is returned unchanged."
16732 (if (< year 38)
16733 (setq year (+ 2000 year))
16734 (if (< year 100)
16735 (setq year (+ 1900 year))))
16736 year)
16738 (defun org-time-from-absolute (d)
16739 "Return the time corresponding to date D.
16740 D may be an absolute day number, or a calendar-type list (month day year)."
16741 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16742 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16744 (defun org-calendar-holiday ()
16745 "List of holidays, for Diary display in Org-mode."
16746 (require 'holidays)
16747 (let ((hl (funcall
16748 (if (fboundp 'calendar-check-holidays)
16749 'calendar-check-holidays 'check-calendar-holidays) date)))
16750 (if hl (mapconcat 'identity hl "; "))))
16752 (defun org-diary-sexp-entry (sexp entry date)
16753 "Process a SEXP diary ENTRY for DATE."
16754 (require 'diary-lib)
16755 (let ((result (if calendar-debug-sexp
16756 (let ((stack-trace-on-error t))
16757 (eval (car (read-from-string sexp))))
16758 (condition-case nil
16759 (eval (car (read-from-string sexp)))
16760 (error
16761 (beep)
16762 (message "Bad sexp at line %d in %s: %s"
16763 (org-current-line)
16764 (buffer-file-name) sexp)
16765 (sleep-for 2))))))
16766 (cond ((stringp result) (split-string result "; "))
16767 ((and (consp result)
16768 (not (consp (cdr result)))
16769 (stringp (cdr result))) (cdr result))
16770 ((and (consp result)
16771 (stringp (car result))) result)
16772 (result entry))))
16774 (defun org-diary-to-ical-string (frombuf)
16775 "Get iCalendar entries from diary entries in buffer FROMBUF.
16776 This uses the icalendar.el library."
16777 (let* ((tmpdir (if (featurep 'xemacs)
16778 (temp-directory)
16779 temporary-file-directory))
16780 (tmpfile (make-temp-name
16781 (expand-file-name "orgics" tmpdir)))
16782 buf rtn b e)
16783 (with-current-buffer frombuf
16784 (icalendar-export-region (point-min) (point-max) tmpfile)
16785 (setq buf (find-buffer-visiting tmpfile))
16786 (set-buffer buf)
16787 (goto-char (point-min))
16788 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16789 (setq b (match-beginning 0)))
16790 (goto-char (point-max))
16791 (if (re-search-backward "^END:VEVENT" nil t)
16792 (setq e (match-end 0)))
16793 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16794 (kill-buffer buf)
16795 (delete-file tmpfile)
16796 rtn))
16798 (defun org-closest-date (start current change prefer show-all)
16799 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16800 When PREFER is `past', return a date that is either CURRENT or past.
16801 When PREFER is `future', return a date that is either CURRENT or future.
16802 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16803 ;; Make the proper lists from the dates
16804 (catch 'exit
16805 (let ((a1 '(("h" . hour)
16806 ("d" . day)
16807 ("w" . week)
16808 ("m" . month)
16809 ("y" . year)))
16810 (shour (nth 2 (org-parse-time-string start)))
16811 dn dw sday cday n1 n2 n0
16812 d m y y1 y2 date1 date2 nmonths nm ny m2)
16814 (setq start (org-date-to-gregorian start)
16815 current (org-date-to-gregorian
16816 (if show-all
16817 current
16818 (time-to-days (current-time))))
16819 sday (calendar-absolute-from-gregorian start)
16820 cday (calendar-absolute-from-gregorian current))
16822 (if (<= cday sday) (throw 'exit sday))
16824 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16825 (setq dn (string-to-number (match-string 1 change))
16826 dw (cdr (assoc (match-string 2 change) a1)))
16827 (error "Invalid change specifier: %s" change))
16828 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16829 (cond
16830 ((eq dw 'hour)
16831 (let ((missing-hours
16832 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16833 dn)))
16834 (setq n1 (if (zerop missing-hours) cday
16835 (- cday (1+ (floor (/ missing-hours 24)))))
16836 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16837 ((eq dw 'day)
16838 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16839 n2 (+ n1 dn)))
16840 ((eq dw 'year)
16841 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16842 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16843 (setq date1 (list m d y1)
16844 n1 (calendar-absolute-from-gregorian date1)
16845 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16846 n2 (calendar-absolute-from-gregorian date2)))
16847 ((eq dw 'month)
16848 ;; approx number of month between the two dates
16849 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16850 ;; How often does dn fit in there?
16851 (setq d (nth 1 start) m (car start) y (nth 2 start)
16852 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16853 m (+ m nm)
16854 ny (floor (/ m 12))
16855 y (+ y ny)
16856 m (- m (* ny 12)))
16857 (while (> m 12) (setq m (- m 12) y (1+ y)))
16858 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16859 (setq m2 (+ m dn) y2 y)
16860 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16861 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16862 (while (<= n2 cday)
16863 (setq n1 n2 m m2 y y2)
16864 (setq m2 (+ m dn) y2 y)
16865 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16866 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16867 ;; Make sure n1 is the earlier date
16868 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16869 (if show-all
16870 (cond
16871 ((eq prefer 'past) (if (= cday n2) n2 n1))
16872 ((eq prefer 'future) (if (= cday n1) n1 n2))
16873 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16874 (cond
16875 ((eq prefer 'past) (if (= cday n2) n2 n1))
16876 ((eq prefer 'future) (if (= cday n1) n1 n2))
16877 (t (if (= cday n1) n1 n2)))))))
16879 (defun org-date-to-gregorian (date)
16880 "Turn any specification of DATE into a Gregorian date for the calendar."
16881 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16882 ((and (listp date) (= (length date) 3)) date)
16883 ((stringp date)
16884 (setq date (org-parse-time-string date))
16885 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16886 ((listp date)
16887 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16889 (defun org-parse-time-string (s &optional nodefault)
16890 "Parse the standard Org-mode time string.
16891 This should be a lot faster than the normal `parse-time-string'.
16892 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16893 hour and minute fields will be nil if not given."
16894 (cond ((string-match org-ts-regexp0 s)
16895 (list 0
16896 (if (or (match-beginning 8) (not nodefault))
16897 (string-to-number (or (match-string 8 s) "0")))
16898 (if (or (match-beginning 7) (not nodefault))
16899 (string-to-number (or (match-string 7 s) "0")))
16900 (string-to-number (match-string 4 s))
16901 (string-to-number (match-string 3 s))
16902 (string-to-number (match-string 2 s))
16903 nil nil nil))
16904 ((string-match "^<[^>]+>$" s)
16905 (decode-time (seconds-to-time (org-matcher-time s))))
16906 (t (error "Not a standard Org-mode time string: %s" s))))
16908 (defun org-timestamp-up (&optional arg)
16909 "Increase the date item at the cursor by one.
16910 If the cursor is on the year, change the year. If it is on the month,
16911 the day or the time, change that.
16912 With prefix ARG, change by that many units."
16913 (interactive "p")
16914 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16916 (defun org-timestamp-down (&optional arg)
16917 "Decrease the date item at the cursor by one.
16918 If the cursor is on the year, change the year. If it is on the month,
16919 the day or the time, change that.
16920 With prefix ARG, change by that many units."
16921 (interactive "p")
16922 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16924 (defun org-timestamp-up-day (&optional arg)
16925 "Increase the date in the time stamp by one day.
16926 With prefix ARG, change that many days."
16927 (interactive "p")
16928 (if (and (not (org-at-timestamp-p t))
16929 (org-at-heading-p))
16930 (org-todo 'up)
16931 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16933 (defun org-timestamp-down-day (&optional arg)
16934 "Decrease the date in the time stamp by one day.
16935 With prefix ARG, change that many days."
16936 (interactive "p")
16937 (if (and (not (org-at-timestamp-p t))
16938 (org-at-heading-p))
16939 (org-todo 'down)
16940 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16942 (defun org-at-timestamp-p (&optional inactive-ok)
16943 "Determine if the cursor is in or at a timestamp."
16944 (interactive)
16945 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16946 (pos (point))
16947 (ans (or (looking-at tsr)
16948 (save-excursion
16949 (skip-chars-backward "^[<\n\r\t")
16950 (if (> (point) (point-min)) (backward-char 1))
16951 (and (looking-at tsr)
16952 (> (- (match-end 0) pos) -1))))))
16953 (and ans
16954 (boundp 'org-ts-what)
16955 (setq org-ts-what
16956 (cond
16957 ((= pos (match-beginning 0)) 'bracket)
16958 ;; Point is considered to be "on the bracket" whether
16959 ;; it's really on it or right after it.
16960 ((= pos (1- (match-end 0))) 'bracket)
16961 ((= pos (match-end 0)) 'after)
16962 ((org-pos-in-match-range pos 2) 'year)
16963 ((org-pos-in-match-range pos 3) 'month)
16964 ((org-pos-in-match-range pos 7) 'hour)
16965 ((org-pos-in-match-range pos 8) 'minute)
16966 ((or (org-pos-in-match-range pos 4)
16967 (org-pos-in-match-range pos 5)) 'day)
16968 ((and (> pos (or (match-end 8) (match-end 5)))
16969 (< pos (match-end 0)))
16970 (- pos (or (match-end 8) (match-end 5))))
16971 (t 'day))))
16972 ans))
16974 (defun org-toggle-timestamp-type ()
16975 "Toggle the type (<active> or [inactive]) of a time stamp."
16976 (interactive)
16977 (when (org-at-timestamp-p t)
16978 (let ((beg (match-beginning 0)) (end (match-end 0))
16979 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16980 (save-excursion
16981 (goto-char beg)
16982 (while (re-search-forward "[][<>]" end t)
16983 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16984 t t)))
16985 (message "Timestamp is now %sactive"
16986 (if (equal (char-after beg) ?<) "" "in")))))
16988 (defun org-at-clock-log-p nil
16989 "Is the cursor on the clock log line?"
16990 (save-excursion
16991 (move-beginning-of-line 1)
16992 (looking-at "^[ \t]*CLOCK:")))
16994 (defvar org-clock-history) ; defined in org-clock.el
16995 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16996 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16997 "Change the date in the time stamp at point.
16998 The date will be changed by N times WHAT. WHAT can be `day', `month',
16999 `year', `minute', `second'. If WHAT is not given, the cursor position
17000 in the timestamp determines what will be changed.
17001 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17002 (let ((origin (point)) origin-cat
17003 with-hm inactive
17004 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17005 org-ts-what
17006 extra rem
17007 ts time time0 fixnext clrgx)
17008 (if (not (org-at-timestamp-p t))
17009 (error "Not at a timestamp"))
17010 (if (and (not what) (eq org-ts-what 'bracket))
17011 (org-toggle-timestamp-type)
17012 ;; Point isn't on brackets. Remember the part of the time-stamp
17013 ;; the point was in. Indeed, size of time-stamps may change,
17014 ;; but point must be kept in the same category nonetheless.
17015 (setq origin-cat org-ts-what)
17016 (if (and (not what) (not (eq org-ts-what 'day))
17017 org-display-custom-times
17018 (get-text-property (point) 'display)
17019 (not (get-text-property (1- (point)) 'display)))
17020 (setq org-ts-what 'day))
17021 (setq org-ts-what (or what org-ts-what)
17022 inactive (= (char-after (match-beginning 0)) ?\[)
17023 ts (match-string 0))
17024 (replace-match "")
17025 (when (string-match
17026 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17028 (setq extra (match-string 1 ts))
17029 (if suppress-tmp-delay
17030 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17031 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17032 (setq with-hm t))
17033 (setq time0 (org-parse-time-string ts))
17034 (when (and updown
17035 (eq org-ts-what 'minute)
17036 (not current-prefix-arg))
17037 ;; This looks like s-up and s-down. Change by one rounding step.
17038 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17039 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17040 (setcar (cdr time0) (+ (nth 1 time0)
17041 (if (> n 0) (- rem) (- dm rem))))))
17042 (setq time
17043 (encode-time (or (car time0) 0)
17044 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17045 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17046 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17047 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17048 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17049 (nthcdr 6 time0)))
17050 (when (and (member org-ts-what '(hour minute))
17051 extra
17052 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17053 (setq extra (org-modify-ts-extra
17054 extra
17055 (if (eq org-ts-what 'hour) 2 5)
17056 n dm)))
17057 (when (integerp org-ts-what)
17058 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17059 (if (eq what 'calendar)
17060 (let ((cal-date (org-get-date-from-calendar)))
17061 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17062 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17063 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17064 (setcar time0 (or (car time0) 0))
17065 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17066 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17067 (setq time (apply 'encode-time time0))))
17068 ;; Insert the new time-stamp, and ensure point stays in the same
17069 ;; category as before (i.e. not after the last position in that
17070 ;; category).
17071 (let ((pos (point)))
17072 ;; Stay before inserted string. `save-excursion' is of no use.
17073 (setq org-last-changed-timestamp
17074 (org-insert-time-stamp time with-hm inactive nil nil extra))
17075 (goto-char pos))
17076 (save-match-data
17077 (looking-at org-ts-regexp3)
17078 (goto-char (cond
17079 ;; `day' category ends before `hour' if any, or at
17080 ;; the end of the day name.
17081 ((eq origin-cat 'day)
17082 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17083 ((eq origin-cat 'hour) (min (match-end 7) origin))
17084 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17085 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17086 ;; `year' and `month' have both fixed size: point
17087 ;; couldn't have moved into another part.
17088 (t origin))))
17089 ;; Update clock if on a CLOCK line.
17090 (org-clock-update-time-maybe)
17091 ;; Maybe adjust the closest clock in `org-clock-history'
17092 (when org-clock-adjust-closest
17093 (if (not (and (org-at-clock-log-p)
17094 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
17095 org-clock-history))))))
17096 (message "No clock to adjust")
17097 (cond ((save-excursion ; fix previous clock?
17098 (re-search-backward org-ts-regexp0 nil t)
17099 (org-looking-back (concat org-clock-string " \\[")))
17100 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17101 ((save-excursion ; fix next clock?
17102 (re-search-backward org-ts-regexp0 nil t)
17103 (looking-at (concat org-ts-regexp0 "\\] =>")))
17104 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17105 (save-window-excursion
17106 ;; Find closest clock to point, adjust the previous/next one in history
17107 (let* ((p (save-excursion (org-back-to-heading t)))
17108 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17109 (clfixnth
17110 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17111 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17112 (if (not clfixpos)
17113 (message "No clock to adjust")
17114 (save-excursion
17115 (org-goto-marker-or-bmk clfixpos)
17116 (org-show-subtree)
17117 (when (re-search-forward clrgx nil t)
17118 (goto-char (match-beginning 1))
17119 (let (org-clock-adjust-closest)
17120 (org-timestamp-change n org-ts-what updown))
17121 (message "Clock adjusted in %s for heading: %s"
17122 (file-name-nondirectory (buffer-file-name))
17123 (org-get-heading t t)))))))))
17124 ;; Try to recenter the calendar window, if any.
17125 (if (and org-calendar-follow-timestamp-change
17126 (get-buffer-window "*Calendar*" t)
17127 (memq org-ts-what '(day month year)))
17128 (org-recenter-calendar (time-to-days time))))))
17130 (defun org-modify-ts-extra (s pos n dm)
17131 "Change the different parts of the lead-time and repeat fields in timestamp."
17132 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17133 ng h m new rem)
17134 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17135 (cond
17136 ((or (org-pos-in-match-range pos 2)
17137 (org-pos-in-match-range pos 3))
17138 (setq m (string-to-number (match-string 3 s))
17139 h (string-to-number (match-string 2 s)))
17140 (if (org-pos-in-match-range pos 2)
17141 (setq h (+ h n))
17142 (setq n (* dm (org-no-warnings (signum n))))
17143 (when (not (= 0 (setq rem (% m dm))))
17144 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17145 (setq m (+ m n)))
17146 (if (< m 0) (setq m (+ m 60) h (1- h)))
17147 (if (> m 59) (setq m (- m 60) h (1+ h)))
17148 (setq h (min 24 (max 0 h)))
17149 (setq ng 1 new (format "-%02d:%02d" h m)))
17150 ((org-pos-in-match-range pos 6)
17151 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17152 ((org-pos-in-match-range pos 5)
17153 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17155 ((org-pos-in-match-range pos 9)
17156 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17157 ((org-pos-in-match-range pos 8)
17158 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17160 (when ng
17161 (setq s (concat
17162 (substring s 0 (match-beginning ng))
17164 (substring s (match-end ng))))))
17167 (defun org-recenter-calendar (date)
17168 "If the calendar is visible, recenter it to DATE."
17169 (let ((cwin (get-buffer-window "*Calendar*" t)))
17170 (when cwin
17171 (let ((calendar-move-hook nil))
17172 (with-selected-window cwin
17173 (calendar-goto-date (if (listp date) date
17174 (calendar-gregorian-from-absolute date))))))))
17176 (defun org-goto-calendar (&optional arg)
17177 "Go to the Emacs calendar at the current date.
17178 If there is a time stamp in the current line, go to that date.
17179 A prefix ARG can be used to force the current date."
17180 (interactive "P")
17181 (let ((tsr org-ts-regexp) diff
17182 (calendar-move-hook nil)
17183 (calendar-view-holidays-initially-flag nil)
17184 (calendar-view-diary-initially-flag nil))
17185 (if (or (org-at-timestamp-p)
17186 (save-excursion
17187 (beginning-of-line 1)
17188 (looking-at (concat ".*" tsr))))
17189 (let ((d1 (time-to-days (current-time)))
17190 (d2 (time-to-days
17191 (org-time-string-to-time (match-string 1)))))
17192 (setq diff (- d2 d1))))
17193 (calendar)
17194 (calendar-goto-today)
17195 (if (and diff (not arg)) (calendar-forward-day diff))))
17197 (defun org-get-date-from-calendar ()
17198 "Return a list (month day year) of date at point in calendar."
17199 (with-current-buffer "*Calendar*"
17200 (save-match-data
17201 (calendar-cursor-to-date))))
17203 (defun org-date-from-calendar ()
17204 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17205 If there is already a time stamp at the cursor position, update it."
17206 (interactive)
17207 (if (org-at-timestamp-p t)
17208 (org-timestamp-change 0 'calendar)
17209 (let ((cal-date (org-get-date-from-calendar)))
17210 (org-insert-time-stamp
17211 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17213 (defcustom org-effort-durations
17214 `(("h" . 60)
17215 ("d" . ,(* 60 8))
17216 ("w" . ,(* 60 8 5))
17217 ("m" . ,(* 60 8 5 4))
17218 ("y" . ,(* 60 8 5 40)))
17219 "Conversion factor to minutes for an effort modifier.
17221 Each entry has the form (MODIFIER . MINUTES).
17223 In an effort string, a number followed by MODIFIER is multiplied
17224 by the specified number of MINUTES to obtain an effort in
17225 minutes.
17227 For example, if the value of this variable is ((\"hours\" . 60)), then an
17228 effort string \"2hours\" is equivalent to 120 minutes."
17229 :group 'org-agenda
17230 :version "24.1"
17231 :type '(alist :key-type (string :tag "Modifier")
17232 :value-type (number :tag "Minutes")))
17234 (defun org-minutes-to-clocksum-string (m)
17235 "Format number of minutes as a clocksum string.
17236 The format is determined by `org-time-clocksum-format',
17237 `org-time-clocksum-use-fractional' and
17238 `org-time-clocksum-fractional-format' and
17239 `org-time-clocksum-use-effort-durations'."
17240 (let ((clocksum "") h d w mo y fmt n)
17241 (setq h (if org-time-clocksum-use-effort-durations
17242 (cdr (assoc "h" org-effort-durations)) 60)
17243 d (if org-time-clocksum-use-effort-durations
17244 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17245 w (if org-time-clocksum-use-effort-durations
17246 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17247 mo (if org-time-clocksum-use-effort-durations
17248 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17249 y (if org-time-clocksum-use-effort-durations
17250 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17251 ;; fractional format
17252 (if org-time-clocksum-use-fractional
17253 (cond
17254 ;; single format string
17255 ((stringp org-time-clocksum-fractional-format)
17256 (format org-time-clocksum-fractional-format (/ m (float h))))
17257 ;; choice of fractional formats for different time units
17258 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17259 (> (/ (truncate m) (* y d h)) 0))
17260 (format fmt (/ m (* y d (float h)))))
17261 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17262 (> (/ (truncate m) (* mo d h)) 0))
17263 (format fmt (/ m (* mo d (float h)))))
17264 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17265 (> (/ (truncate m) (* w d h)) 0))
17266 (format fmt (/ m (* w d (float h)))))
17267 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17268 (> (/ (truncate m) (* d h)) 0))
17269 (format fmt (/ m (* d (float h)))))
17270 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17271 (> (/ (truncate m) h) 0))
17272 (format fmt (/ m (float h))))
17273 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17274 (format fmt m))
17275 ;; fall back to smallest time unit with a format
17276 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17277 (format fmt (/ m (float h))))
17278 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17279 (format fmt (/ m (* d (float h)))))
17280 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17281 (format fmt (/ m (* w d (float h)))))
17282 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17283 (format fmt (/ m (* mo d (float h)))))
17284 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17285 (format fmt (/ m (* y d (float h))))))
17286 ;; standard (non-fractional) format, with single format string
17287 (if (stringp org-time-clocksum-format)
17288 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17289 ;; separate formats components
17290 (and (setq fmt (plist-get org-time-clocksum-format :years))
17291 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17292 (plist-get org-time-clocksum-format :require-years))
17293 (setq clocksum (concat clocksum (format fmt n))
17294 m (- m (* n y d h))))
17295 (and (setq fmt (plist-get org-time-clocksum-format :months))
17296 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17297 (plist-get org-time-clocksum-format :require-months))
17298 (setq clocksum (concat clocksum (format fmt n))
17299 m (- m (* n mo d h))))
17300 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17301 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17302 (plist-get org-time-clocksum-format :require-weeks))
17303 (setq clocksum (concat clocksum (format fmt n))
17304 m (- m (* n w d h))))
17305 (and (setq fmt (plist-get org-time-clocksum-format :days))
17306 (or (> (setq n (/ (truncate m) (* d h))) 0)
17307 (plist-get org-time-clocksum-format :require-days))
17308 (setq clocksum (concat clocksum (format fmt n))
17309 m (- m (* n d h))))
17310 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17311 (or (> (setq n (/ (truncate m) h)) 0)
17312 (plist-get org-time-clocksum-format :require-hours))
17313 (setq clocksum (concat clocksum (format fmt n))
17314 m (- m (* n h))))
17315 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17316 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17317 (setq clocksum (concat clocksum (format fmt m))))
17318 ;; return formatted time duration
17319 clocksum))))
17321 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17322 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17323 "Org mode version 8.0")
17325 (defun org-hours-to-clocksum-string (n)
17326 (org-minutes-to-clocksum-string (* n 60)))
17328 (defun org-hh:mm-string-to-minutes (s)
17329 "Convert a string H:MM to a number of minutes.
17330 If the string is just a number, interpret it as minutes.
17331 In fact, the first hh:mm or number in the string will be taken,
17332 there can be extra stuff in the string.
17333 If no number is found, the return value is 0."
17334 (cond
17335 ((integerp s) s)
17336 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17337 (+ (* (string-to-number (match-string 1 s)) 60)
17338 (string-to-number (match-string 2 s))))
17339 ((string-match "\\([0-9]+\\)" s)
17340 (string-to-number (match-string 1 s)))
17341 (t 0)))
17343 (defcustom org-image-actual-width t
17344 "Should we use the actual width of images when inlining them?
17346 When set to `t', always use the image width.
17348 When set to a number, use imagemagick (when available) to set
17349 the image's width to this value.
17351 When set to a number in a list, try to get the width from the
17352 #+ATTR.* keyword if it matches a width specification like
17353 width=\"[0-9]+\", and fall back on that number if none is found.
17355 When set to nil, try to get the width from an #+ATTR.* keyword
17356 and fall back on the original width if none is found.
17358 This requires Emacs >= 24.1, build with imagemagick support."
17359 :group 'org-appearance
17360 :version "24.4"
17361 :package-version '(Org . "8.0")
17362 :type '(choice
17363 (const :tag "Use the image width" t)
17364 (integer :tag "Use a number of pixels")
17365 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17366 (const :tag "Use #+ATTR* or don't resize" nil)))
17368 (defcustom org-agenda-inhibit-startup nil
17369 "Inhibit startup when preparing agenda buffers.
17370 When this variable is `t' (the default), the initialization of
17371 the Org agenda buffers is inhibited: e.g. the visibility state
17372 is not set, the tables are not re-aligned, etc."
17373 :type 'boolean
17374 :version "24.3"
17375 :group 'org-agenda)
17377 (defun org-duration-string-to-minutes (s &optional output-to-string)
17378 "Convert a duration string S to minutes.
17380 A bare number is interpreted as minutes, modifiers can be set by
17381 customizing `org-effort-durations' (which see).
17383 Entries containing a colon are interpreted as H:MM by
17384 `org-hh:mm-string-to-minutes'."
17385 (let ((result 0)
17386 (re (concat "\\([0-9.]+\\) *\\("
17387 (regexp-opt (mapcar 'car org-effort-durations))
17388 "\\)")))
17389 (while (string-match re s)
17390 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17391 (string-to-number (match-string 1 s))))
17392 (setq s (replace-match "" nil t s)))
17393 (setq result (floor result))
17394 (incf result (org-hh:mm-string-to-minutes s))
17395 (if output-to-string (number-to-string result) result)))
17397 ;;;; Files
17399 (defun org-save-all-org-buffers ()
17400 "Save all Org-mode buffers without user confirmation."
17401 (interactive)
17402 (message "Saving all Org-mode buffers...")
17403 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17404 (when (featurep 'org-id) (org-id-locations-save))
17405 (message "Saving all Org-mode buffers... done"))
17407 (defun org-revert-all-org-buffers ()
17408 "Revert all Org-mode buffers.
17409 Prompt for confirmation when there are unsaved changes.
17410 Be sure you know what you are doing before letting this function
17411 overwrite your changes.
17413 This function is useful in a setup where one tracks org files
17414 with a version control system, to revert on one machine after pulling
17415 changes from another. I believe the procedure must be like this:
17417 1. M-x org-save-all-org-buffers
17418 2. Pull changes from the other machine, resolve conflicts
17419 3. M-x org-revert-all-org-buffers"
17420 (interactive)
17421 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17422 (error "Abort"))
17423 (save-excursion
17424 (save-window-excursion
17425 (mapc
17426 (lambda (b)
17427 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17428 (with-current-buffer b buffer-file-name))
17429 (org-pop-to-buffer-same-window b)
17430 (revert-buffer t 'no-confirm)))
17431 (buffer-list))
17432 (when (and (featurep 'org-id) org-id-track-globally)
17433 (org-id-locations-load)))))
17435 ;;;; Agenda files
17437 ;;;###autoload
17438 (defun org-switchb (&optional arg)
17439 "Switch between Org buffers.
17440 With one prefix argument, restrict available buffers to files.
17441 With two prefix arguments, restrict available buffers to agenda files.
17443 Defaults to `iswitchb' for buffer name completion.
17444 Set `org-completion-use-ido' to make it use ido instead."
17445 (interactive "P")
17446 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17447 ((equal arg '(16)) (org-buffer-list 'agenda))
17448 (t (org-buffer-list))))
17449 (org-completion-use-iswitchb org-completion-use-iswitchb)
17450 (org-completion-use-ido org-completion-use-ido))
17451 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17452 (setq org-completion-use-iswitchb t))
17453 (org-pop-to-buffer-same-window
17454 (org-icompleting-read "Org buffer: "
17455 (mapcar 'list (mapcar 'buffer-name blist))
17456 nil t))))
17458 ;;; Define some older names previously used for this functionality
17459 ;;;###autoload
17460 (defalias 'org-ido-switchb 'org-switchb)
17461 ;;;###autoload
17462 (defalias 'org-iswitchb 'org-switchb)
17464 (defun org-buffer-list (&optional predicate exclude-tmp)
17465 "Return a list of Org buffers.
17466 PREDICATE can be `export', `files' or `agenda'.
17468 export restrict the list to Export buffers.
17469 files restrict the list to buffers visiting Org files.
17470 agenda restrict the list to buffers visiting agenda files.
17472 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17473 (let* ((bfn nil)
17474 (agenda-files (and (eq predicate 'agenda)
17475 (mapcar 'file-truename (org-agenda-files t))))
17476 (filter
17477 (cond
17478 ((eq predicate 'files)
17479 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17480 ((eq predicate 'export)
17481 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17482 ((eq predicate 'agenda)
17483 (lambda (b)
17484 (with-current-buffer b
17485 (and (derived-mode-p 'org-mode)
17486 (setq bfn (buffer-file-name b))
17487 (member (file-truename bfn) agenda-files)))))
17488 (t (lambda (b) (with-current-buffer b
17489 (or (derived-mode-p 'org-mode)
17490 (string-match "\*Org .*Export"
17491 (buffer-name b)))))))))
17492 (delq nil
17493 (mapcar
17494 (lambda(b)
17495 (if (and (funcall filter b)
17496 (or (not exclude-tmp)
17497 (not (string-match "tmp" (buffer-name b)))))
17499 nil))
17500 (buffer-list)))))
17502 (defun org-agenda-files (&optional unrestricted archives)
17503 "Get the list of agenda files.
17504 Optional UNRESTRICTED means return the full list even if a restriction
17505 is currently in place.
17506 When ARCHIVES is t, include all archive files that are really being
17507 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17508 `org-agenda-archives-mode' is t."
17509 (let ((files
17510 (cond
17511 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17512 ((stringp org-agenda-files) (org-read-agenda-file-list))
17513 ((listp org-agenda-files) org-agenda-files)
17514 (t (error "Invalid value of `org-agenda-files'")))))
17515 (setq files (apply 'append
17516 (mapcar (lambda (f)
17517 (if (file-directory-p f)
17518 (directory-files
17519 f t org-agenda-file-regexp)
17520 (list f)))
17521 files)))
17522 (when org-agenda-skip-unavailable-files
17523 (setq files (delq nil
17524 (mapcar (function
17525 (lambda (file)
17526 (and (file-readable-p file) file)))
17527 files))))
17528 (when (or (eq archives t)
17529 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17530 (setq files (org-add-archive-files files)))
17531 files))
17533 (defun org-agenda-file-p (&optional file)
17534 "Return non-nil, if FILE is an agenda file.
17535 If FILE is omitted, use the file associated with the current
17536 buffer."
17537 (member (or file (buffer-file-name))
17538 (org-agenda-files t)))
17540 (defun org-edit-agenda-file-list ()
17541 "Edit the list of agenda files.
17542 Depending on setup, this either uses customize to edit the variable
17543 `org-agenda-files', or it visits the file that is holding the list. In the
17544 latter case, the buffer is set up in a way that saving it automatically kills
17545 the buffer and restores the previous window configuration."
17546 (interactive)
17547 (if (stringp org-agenda-files)
17548 (let ((cw (current-window-configuration)))
17549 (find-file org-agenda-files)
17550 (org-set-local 'org-window-configuration cw)
17551 (org-add-hook 'after-save-hook
17552 (lambda ()
17553 (set-window-configuration
17554 (prog1 org-window-configuration
17555 (kill-buffer (current-buffer))))
17556 (org-install-agenda-files-menu)
17557 (message "New agenda file list installed"))
17558 nil 'local)
17559 (message "%s" (substitute-command-keys
17560 "Edit list and finish with \\[save-buffer]")))
17561 (customize-variable 'org-agenda-files)))
17563 (defun org-store-new-agenda-file-list (list)
17564 "Set new value for the agenda file list and save it correctly."
17565 (if (stringp org-agenda-files)
17566 (let ((fe (org-read-agenda-file-list t)) b u)
17567 (while (setq b (find-buffer-visiting org-agenda-files))
17568 (kill-buffer b))
17569 (with-temp-file org-agenda-files
17570 (insert
17571 (mapconcat
17572 (lambda (f) ;; Keep un-expanded entries.
17573 (if (setq u (assoc f fe))
17574 (cdr u)
17576 list "\n")
17577 "\n")))
17578 (let ((org-mode-hook nil) (org-inhibit-startup t)
17579 (org-insert-mode-line-in-empty-file nil))
17580 (setq org-agenda-files list)
17581 (customize-save-variable 'org-agenda-files org-agenda-files))))
17583 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17584 "Read the list of agenda files from a file.
17585 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17586 filenames, used by `org-store-new-agenda-file-list' to write back
17587 un-expanded file names."
17588 (when (file-directory-p org-agenda-files)
17589 (error "`org-agenda-files' cannot be a single directory"))
17590 (when (stringp org-agenda-files)
17591 (with-temp-buffer
17592 (insert-file-contents org-agenda-files)
17593 (mapcar
17594 (lambda (f)
17595 (let ((e (expand-file-name (substitute-in-file-name f)
17596 org-directory)))
17597 (if pair-with-expansion
17598 (cons e f)
17599 e)))
17600 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17602 ;;;###autoload
17603 (defun org-cycle-agenda-files ()
17604 "Cycle through the files in `org-agenda-files'.
17605 If the current buffer visits an agenda file, find the next one in the list.
17606 If the current buffer does not, find the first agenda file."
17607 (interactive)
17608 (let* ((fs (org-agenda-files t))
17609 (files (append fs (list (car fs))))
17610 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17611 file)
17612 (unless files (error "No agenda files"))
17613 (catch 'exit
17614 (while (setq file (pop files))
17615 (if (equal (file-truename file) tcf)
17616 (when (car files)
17617 (find-file (car files))
17618 (throw 'exit t))))
17619 (find-file (car fs)))
17620 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17622 (defun org-agenda-file-to-front (&optional to-end)
17623 "Move/add the current file to the top of the agenda file list.
17624 If the file is not present in the list, it is added to the front. If it is
17625 present, it is moved there. With optional argument TO-END, add/move to the
17626 end of the list."
17627 (interactive "P")
17628 (let ((org-agenda-skip-unavailable-files nil)
17629 (file-alist (mapcar (lambda (x)
17630 (cons (file-truename x) x))
17631 (org-agenda-files t)))
17632 (ctf (file-truename
17633 (or buffer-file-name
17634 (error "Please save the current buffer to a file"))))
17635 x had)
17636 (setq x (assoc ctf file-alist) had x)
17638 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17639 (if to-end
17640 (setq file-alist (append (delq x file-alist) (list x)))
17641 (setq file-alist (cons x (delq x file-alist))))
17642 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17643 (org-install-agenda-files-menu)
17644 (message "File %s to %s of agenda file list"
17645 (if had "moved" "added") (if to-end "end" "front"))))
17647 (defun org-remove-file (&optional file)
17648 "Remove current file from the list of files in variable `org-agenda-files'.
17649 These are the files which are being checked for agenda entries.
17650 Optional argument FILE means use this file instead of the current."
17651 (interactive)
17652 (let* ((org-agenda-skip-unavailable-files nil)
17653 (file (or file buffer-file-name
17654 (error "Current buffer does not visit a file")))
17655 (true-file (file-truename file))
17656 (afile (abbreviate-file-name file))
17657 (files (delq nil (mapcar
17658 (lambda (x)
17659 (if (equal true-file
17660 (file-truename x))
17661 nil x))
17662 (org-agenda-files t)))))
17663 (if (not (= (length files) (length (org-agenda-files t))))
17664 (progn
17665 (org-store-new-agenda-file-list files)
17666 (org-install-agenda-files-menu)
17667 (message "Removed file: %s" afile))
17668 (message "File was not in list: %s (not removed)" afile))))
17670 (defun org-file-menu-entry (file)
17671 (vector file (list 'find-file file) t))
17673 (defun org-check-agenda-file (file)
17674 "Make sure FILE exists. If not, ask user what to do."
17675 (when (not (file-exists-p file))
17676 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17677 (abbreviate-file-name file))
17678 (let ((r (downcase (read-char-exclusive))))
17679 (cond
17680 ((equal r ?r)
17681 (org-remove-file file)
17682 (throw 'nextfile t))
17683 (t (error "Abort"))))))
17685 (defun org-get-agenda-file-buffer (file)
17686 "Get a buffer visiting FILE. If the buffer needs to be created, add
17687 it to the list of buffers which might be released later."
17688 (let ((buf (org-find-base-buffer-visiting file)))
17689 (if buf
17690 buf ; just return it
17691 ;; Make a new buffer and remember it
17692 (setq buf (find-file-noselect file))
17693 (if buf (push buf org-agenda-new-buffers))
17694 buf)))
17696 (defun org-release-buffers (blist)
17697 "Release all buffers in list, asking the user for confirmation when needed.
17698 When a buffer is unmodified, it is just killed. When modified, it is saved
17699 \(if the user agrees) and then killed."
17700 (let (buf file)
17701 (while (setq buf (pop blist))
17702 (setq file (buffer-file-name buf))
17703 (when (and (buffer-modified-p buf)
17704 file
17705 (y-or-n-p (format "Save file %s? " file)))
17706 (with-current-buffer buf (save-buffer)))
17707 (kill-buffer buf))))
17709 (defun org-agenda-prepare-buffers (files)
17710 "Create buffers for all agenda files, protect archived trees and comments."
17711 (interactive)
17712 (let ((pa '(:org-archived t))
17713 (pc '(:org-comment t))
17714 (pall '(:org-archived t :org-comment t))
17715 (inhibit-read-only t)
17716 (org-inhibit-startup org-agenda-inhibit-startup)
17717 (rea (concat ":" org-archive-tag ":"))
17718 file re)
17719 (save-excursion
17720 (save-restriction
17721 (while (setq file (pop files))
17722 (catch 'nextfile
17723 (if (bufferp file)
17724 (set-buffer file)
17725 (org-check-agenda-file file)
17726 (set-buffer (org-get-agenda-file-buffer file)))
17727 (widen)
17728 (org-refresh-category-properties)
17729 (org-refresh-properties org-effort-property 'org-effort)
17730 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17731 (setq org-todo-keywords-for-agenda
17732 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17733 (setq org-done-keywords-for-agenda
17734 (append org-done-keywords-for-agenda org-done-keywords))
17735 (setq org-todo-keyword-alist-for-agenda
17736 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17737 (setq org-drawers-for-agenda
17738 (append org-drawers-for-agenda org-drawers))
17739 (setq org-tag-alist-for-agenda
17740 (append org-tag-alist-for-agenda org-tag-alist))
17741 (org-with-silent-modifications
17742 (save-excursion
17743 (remove-text-properties (point-min) (point-max) pall)
17744 (when org-agenda-skip-archived-trees
17745 (goto-char (point-min))
17746 (while (re-search-forward rea nil t)
17747 (if (org-at-heading-p t)
17748 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17749 (goto-char (point-min))
17750 (setq re (format org-heading-keyword-regexp-format
17751 org-comment-string))
17752 (while (re-search-forward re nil t)
17753 (add-text-properties
17754 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17755 (setq org-todo-keywords-for-agenda
17756 (org-uniquify org-todo-keywords-for-agenda))
17757 (setq org-todo-keyword-alist-for-agenda
17758 (org-uniquify org-todo-keyword-alist-for-agenda)
17759 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17762 ;;;; CDLaTeX minor mode
17764 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17765 "Keymap for the minor `org-cdlatex-mode'.")
17767 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17768 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17769 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17770 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17771 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17773 (defvar org-cdlatex-texmathp-advice-is-done nil
17774 "Flag remembering if we have applied the advice to texmathp already.")
17776 (define-minor-mode org-cdlatex-mode
17777 "Toggle the minor `org-cdlatex-mode'.
17778 This mode supports entering LaTeX environment and math in LaTeX fragments
17779 in Org-mode.
17780 \\{org-cdlatex-mode-map}"
17781 nil " OCDL" nil
17782 (when org-cdlatex-mode
17783 (require 'cdlatex)
17784 (run-hooks 'cdlatex-mode-hook)
17785 (cdlatex-compute-tables))
17786 (unless org-cdlatex-texmathp-advice-is-done
17787 (setq org-cdlatex-texmathp-advice-is-done t)
17788 (defadvice texmathp (around org-math-always-on activate)
17789 "Always return t in org-mode buffers.
17790 This is because we want to insert math symbols without dollars even outside
17791 the LaTeX math segments. If Orgmode thinks that point is actually inside
17792 an embedded LaTeX fragment, let texmathp do its job.
17793 \\[org-cdlatex-mode-map]"
17794 (interactive)
17795 (let (p)
17796 (cond
17797 ((not (derived-mode-p 'org-mode)) ad-do-it)
17798 ((eq this-command 'cdlatex-math-symbol)
17799 (setq ad-return-value t
17800 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17802 (let ((p (org-inside-LaTeX-fragment-p)))
17803 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17804 (setq ad-return-value t
17805 texmathp-why '("Org-mode embedded math" . 0))
17806 (if p ad-do-it)))))))))
17808 (defun turn-on-org-cdlatex ()
17809 "Unconditionally turn on `org-cdlatex-mode'."
17810 (org-cdlatex-mode 1))
17812 (defun org-try-cdlatex-tab ()
17813 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17814 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17815 - inside a LaTeX fragment, or
17816 - after the first word in a line, where an abbreviation expansion could
17817 insert a LaTeX environment."
17818 (when org-cdlatex-mode
17819 (cond
17820 ;; Before any word on the line: No expansion possible.
17821 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17822 ;; Just after first word on the line: Expand it. Make sure it
17823 ;; cannot happen on headlines, though.
17824 ((save-excursion
17825 (skip-chars-backward "a-zA-Z0-9*")
17826 (skip-chars-backward " \t")
17827 (and (bolp) (not (org-at-heading-p))))
17828 (cdlatex-tab) t)
17829 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17831 (defun org-cdlatex-underscore-caret (&optional arg)
17832 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17833 Revert to the normal definition outside of these fragments."
17834 (interactive "P")
17835 (if (org-inside-LaTeX-fragment-p)
17836 (call-interactively 'cdlatex-sub-superscript)
17837 (let (org-cdlatex-mode)
17838 (call-interactively (key-binding (vector last-input-event))))))
17840 (defun org-cdlatex-math-modify (&optional arg)
17841 "Execute `cdlatex-math-modify' in LaTeX fragments.
17842 Revert to the normal definition outside of these fragments."
17843 (interactive "P")
17844 (if (org-inside-LaTeX-fragment-p)
17845 (call-interactively 'cdlatex-math-modify)
17846 (let (org-cdlatex-mode)
17847 (call-interactively (key-binding (vector last-input-event))))))
17851 ;;;; LaTeX fragments
17853 (defvar org-latex-regexps
17854 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17855 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17856 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17857 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17858 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17859 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17860 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17861 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17862 "Regular expressions for matching embedded LaTeX.")
17864 (defun org-inside-LaTeX-fragment-p ()
17865 "Test if point is inside a LaTeX fragment.
17866 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17867 sequence appearing also before point.
17868 Even though the matchers for math are configurable, this function assumes
17869 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17870 delimiters are skipped when they have been removed by customization.
17871 The return value is nil, or a cons cell with the delimiter and the
17872 position of this delimiter.
17874 This function does a reasonably good job, but can locally be fooled by
17875 for example currency specifications. For example it will assume being in
17876 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17877 fragments that are properly closed, but during editing, we have to live
17878 with the uncertainty caused by missing closing delimiters. This function
17879 looks only before point, not after."
17880 (catch 'exit
17881 (let ((pos (point))
17882 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17883 (lim (progn
17884 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17885 (point)))
17886 dd-on str (start 0) m re)
17887 (goto-char pos)
17888 (when dodollar
17889 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17890 re (nth 1 (assoc "$" org-latex-regexps)))
17891 (while (string-match re str start)
17892 (cond
17893 ((= (match-end 0) (length str))
17894 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17895 ((= (match-end 0) (- (length str) 5))
17896 (throw 'exit nil))
17897 (t (setq start (match-end 0))))))
17898 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17899 (goto-char pos)
17900 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17901 (and (match-beginning 2) (throw 'exit nil))
17902 ;; count $$
17903 (while (re-search-backward "\\$\\$" lim t)
17904 (setq dd-on (not dd-on)))
17905 (goto-char pos)
17906 (if dd-on (cons "$$" m))))))
17908 (defun org-inside-latex-macro-p ()
17909 "Is point inside a LaTeX macro or its arguments?"
17910 (save-match-data
17911 (org-in-regexp
17912 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17914 (defvar org-latex-fragment-image-overlays nil
17915 "List of overlays carrying the images of latex fragments.")
17916 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17918 (defun org-remove-latex-fragment-image-overlays ()
17919 "Remove all overlays with LaTeX fragment images in current buffer."
17920 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17921 (setq org-latex-fragment-image-overlays nil))
17923 (defun org-preview-latex-fragment (&optional subtree)
17924 "Preview the LaTeX fragment at point, or all locally or globally.
17925 If the cursor is in a LaTeX fragment, create the image and overlay
17926 it over the source code. If there is no fragment at point, display
17927 all fragments in the current text, from one headline to the next. With
17928 prefix SUBTREE, display all fragments in the current subtree. With a
17929 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17930 the cursor is before the first headline,
17931 display all fragments in the buffer.
17932 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17933 (interactive "P")
17934 (unless buffer-file-name
17935 (error "Can't preview LaTeX fragment in a non-file buffer"))
17936 (org-remove-latex-fragment-image-overlays)
17937 (save-excursion
17938 (save-restriction
17939 (let (beg end at msg)
17940 (cond
17941 ((or (equal subtree '(16))
17942 (not (save-excursion
17943 (re-search-backward org-outline-regexp-bol nil t))))
17944 (setq beg (point-min) end (point-max)
17945 msg "Creating images for buffer...%s"))
17946 ((equal subtree '(4))
17947 (org-back-to-heading)
17948 (setq beg (point) end (org-end-of-subtree t)
17949 msg "Creating images for subtree...%s"))
17951 (if (setq at (org-inside-LaTeX-fragment-p))
17952 (goto-char (max (point-min) (- (cdr at) 2)))
17953 (org-back-to-heading))
17954 (setq beg (point) end (progn (outline-next-heading) (point))
17955 msg (if at "Creating image...%s"
17956 "Creating images for entry...%s"))))
17957 (message msg "")
17958 (narrow-to-region beg end)
17959 (goto-char beg)
17960 (org-format-latex
17961 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17962 (file-name-nondirectory
17963 buffer-file-name)))
17964 default-directory 'overlays msg at 'forbuffer
17965 org-latex-create-formula-image-program)
17966 (message msg "done. Use `C-c C-c' to remove images.")))))
17968 (defun org-format-latex (prefix &optional dir overlays msg at
17969 forbuffer processing-type)
17970 "Replace LaTeX fragments with links to an image, and produce images.
17971 Some of the options can be changed using the variable
17972 `org-format-latex-options'."
17973 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17974 (let* ((prefixnodir (file-name-nondirectory prefix))
17975 (absprefix (expand-file-name prefix dir))
17976 (todir (file-name-directory absprefix))
17977 (opt org-format-latex-options)
17978 (optnew org-format-latex-options)
17979 (matchers (plist-get opt :matchers))
17980 (re-list org-latex-regexps)
17981 (cnt 0) txt hash link beg end re e checkdir
17982 string
17983 m n block-type block linkfile movefile ov)
17984 ;; Check the different regular expressions
17985 (while (setq e (pop re-list))
17986 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17987 block (if block-type "\n\n" ""))
17988 (when (member m matchers)
17989 (goto-char (point-min))
17990 (while (re-search-forward re nil t)
17991 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17992 (or (not overlays)
17993 (not (eq (get-char-property (match-beginning n)
17994 'org-overlay-type)
17995 'org-latex-overlay))))
17996 (cond
17997 ((eq processing-type 'verbatim))
17998 ((eq processing-type 'mathjax)
17999 ;; Prepare for MathJax processing.
18000 (setq string (match-string n))
18001 (when (member m '("$" "$1"))
18002 (save-excursion
18003 (delete-region (match-beginning n) (match-end n))
18004 (goto-char (match-beginning n))
18005 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18006 ((or (eq processing-type 'dvipng)
18007 (eq processing-type 'imagemagick))
18008 ;; Process to an image.
18009 (setq txt (match-string n)
18010 beg (match-beginning n) end (match-end n)
18011 cnt (1+ cnt))
18012 (let ((face (face-at-point))
18013 (fg (plist-get opt :foreground))
18014 (bg (plist-get opt :background))
18015 ;; Ensure full list is printed.
18016 print-length print-level)
18017 (when forbuffer
18018 ;; Get the colors from the face at point.
18019 (goto-char beg)
18020 (when (eq fg 'auto)
18021 (setq fg (face-attribute face :foreground nil 'default)))
18022 (when (eq bg 'auto)
18023 (setq bg (face-attribute face :background nil 'default)))
18024 (setq optnew (copy-sequence opt))
18025 (plist-put optnew :foreground fg)
18026 (plist-put optnew :background bg))
18027 (setq hash (sha1 (prin1-to-string
18028 (list org-format-latex-header
18029 org-latex-default-packages-alist
18030 org-latex-packages-alist
18031 org-format-latex-options
18032 forbuffer txt fg bg)))
18033 linkfile (format "%s_%s.png" prefix hash)
18034 movefile (format "%s_%s.png" absprefix hash)))
18035 (setq link (concat block "[[file:" linkfile "]]" block))
18036 (if msg (message msg cnt))
18037 (goto-char beg)
18038 (unless checkdir ; Ensure the directory exists.
18039 (setq checkdir t)
18040 (or (file-directory-p todir) (make-directory todir t)))
18041 (unless (file-exists-p movefile)
18042 (org-create-formula-image
18043 txt movefile optnew forbuffer processing-type))
18044 (if overlays
18045 (progn
18046 (mapc (lambda (o)
18047 (if (eq (overlay-get o 'org-overlay-type)
18048 'org-latex-overlay)
18049 (delete-overlay o)))
18050 (overlays-in beg end))
18051 (setq ov (make-overlay beg end))
18052 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18053 (if (featurep 'xemacs)
18054 (progn
18055 (overlay-put ov 'invisible t)
18056 (overlay-put
18057 ov 'end-glyph
18058 (make-glyph (vector 'png :file movefile))))
18059 (overlay-put
18060 ov 'display
18061 (list 'image :type 'png :file movefile :ascent 'center)))
18062 (push ov org-latex-fragment-image-overlays)
18063 (goto-char end))
18064 (delete-region beg end)
18065 (insert (org-add-props link
18066 (list 'org-latex-src
18067 (replace-regexp-in-string
18068 "\"" "" txt)
18069 'org-latex-src-embed-type
18070 (if block-type 'paragraph 'character))))))
18071 ((eq processing-type 'mathml)
18072 ;; Process to MathML
18073 (unless (save-match-data (org-format-latex-mathml-available-p))
18074 (error "LaTeX to MathML converter not configured"))
18075 (setq txt (match-string n)
18076 beg (match-beginning n) end (match-end n)
18077 cnt (1+ cnt))
18078 (if msg (message msg cnt))
18079 (goto-char beg)
18080 (delete-region beg end)
18081 (insert (org-format-latex-as-mathml
18082 txt block-type prefix dir)))
18084 (error "Unknown conversion type %s for latex fragments"
18085 processing-type)))))))))
18087 (defun org-create-math-formula (latex-frag &optional mathml-file)
18088 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18089 Use `org-latex-to-mathml-convert-command'. If the conversion is
18090 sucessful, return the portion between \"<math...> </math>\"
18091 elements otherwise return nil. When MATHML-FILE is specified,
18092 write the results in to that file. When invoked as an
18093 interactive command, prompt for LATEX-FRAG, with initial value
18094 set to the current active region and echo the results for user
18095 inspection."
18096 (interactive (list (let ((frag (when (org-region-active-p)
18097 (buffer-substring-no-properties
18098 (region-beginning) (region-end)))))
18099 (read-string "LaTeX Fragment: " frag nil frag))))
18100 (unless latex-frag (error "Invalid latex-frag"))
18101 (let* ((tmp-in-file (file-relative-name
18102 (make-temp-name (expand-file-name "ltxmathml-in"))))
18103 (ignore (write-region latex-frag nil tmp-in-file))
18104 (tmp-out-file (file-relative-name
18105 (make-temp-name (expand-file-name "ltxmathml-out"))))
18106 (cmd (format-spec
18107 org-latex-to-mathml-convert-command
18108 `((?j . ,(shell-quote-argument
18109 (expand-file-name org-latex-to-mathml-jar-file)))
18110 (?I . ,(shell-quote-argument tmp-in-file))
18111 (?o . ,(shell-quote-argument tmp-out-file)))))
18112 mathml shell-command-output)
18113 (when (org-called-interactively-p 'any)
18114 (unless (org-format-latex-mathml-available-p)
18115 (error "LaTeX to MathML converter not configured")))
18116 (message "Running %s" cmd)
18117 (setq shell-command-output (shell-command-to-string cmd))
18118 (setq mathml
18119 (when (file-readable-p tmp-out-file)
18120 (with-current-buffer (find-file-noselect tmp-out-file t)
18121 (goto-char (point-min))
18122 (when (re-search-forward
18123 (concat
18124 (regexp-quote
18125 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18126 "\\(.\\|\n\\)*"
18127 (regexp-quote "</math>")) nil t)
18128 (prog1 (match-string 0) (kill-buffer))))))
18129 (cond
18130 (mathml
18131 (setq mathml
18132 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18133 (when mathml-file
18134 (write-region mathml nil mathml-file))
18135 (when (org-called-interactively-p 'any)
18136 (message mathml)))
18137 ((message "LaTeX to MathML conversion failed")
18138 (message shell-command-output)))
18139 (delete-file tmp-in-file)
18140 (when (file-exists-p tmp-out-file)
18141 (delete-file tmp-out-file))
18142 mathml))
18144 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18145 prefix &optional dir)
18146 "Use `org-create-math-formula' but check local cache first."
18147 (let* ((absprefix (expand-file-name prefix dir))
18148 (print-length nil) (print-level nil)
18149 (formula-id (concat
18150 "formula-"
18151 (sha1
18152 (prin1-to-string
18153 (list latex-frag
18154 org-latex-to-mathml-convert-command)))))
18155 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18156 (formula-cache-dir (file-name-directory formula-cache)))
18158 (unless (file-directory-p formula-cache-dir)
18159 (make-directory formula-cache-dir t))
18161 (unless (file-exists-p formula-cache)
18162 (org-create-math-formula latex-frag formula-cache))
18164 (if (file-exists-p formula-cache)
18165 ;; Successful conversion. Return the link to MathML file.
18166 (org-add-props
18167 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18168 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18169 'org-latex-src-embed-type (if latex-frag-type
18170 'paragraph 'character)))
18171 ;; Failed conversion. Return the LaTeX fragment verbatim
18172 latex-frag)))
18174 (defun org-create-formula-image (string tofile options buffer &optional type)
18175 "Create an image from LaTeX source using dvipng or convert.
18176 This function calls either `org-create-formula-image-with-dvipng'
18177 or `org-create-formula-image-with-imagemagick' depending on the
18178 value of `org-latex-create-formula-image-program' or on the value
18179 of the optional TYPE variable.
18181 Note: ultimately these two function should be combined as they
18182 share a good deal of logic."
18183 (org-check-external-command
18184 "latex" "needed to convert LaTeX fragments to images")
18185 (funcall
18186 (case (or type org-latex-create-formula-image-program)
18187 ('dvipng
18188 (org-check-external-command
18189 "dvipng" "needed to convert LaTeX fragments to images")
18190 #'org-create-formula-image-with-dvipng)
18191 ('imagemagick
18192 (org-check-external-command
18193 "convert" "you need to install imagemagick")
18194 #'org-create-formula-image-with-imagemagick)
18195 (t (error
18196 "invalid value of `org-latex-create-formula-image-program'")))
18197 string tofile options buffer))
18199 (declare-function org-export--get-global-options "ox" (&optional backend))
18200 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18201 (defun org-create-formula--latex-header ()
18202 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18203 (org-latex-guess-inputenc
18204 (org-splice-latex-header
18205 org-format-latex-header
18206 org-latex-default-packages-alist
18207 org-latex-packages-alist t
18208 (plist-get
18209 (org-combine-plists
18210 (org-export--get-global-options 'latex)
18211 (org-export--get-inbuffer-options 'latex))
18212 :latex-header))))
18214 ;; This function borrows from Ganesh Swami's latex2png.el
18215 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18216 "This calls dvipng."
18217 (require 'ox-latex)
18218 (let* ((tmpdir (if (featurep 'xemacs)
18219 (temp-directory)
18220 temporary-file-directory))
18221 (texfilebase (make-temp-name
18222 (expand-file-name "orgtex" tmpdir)))
18223 (texfile (concat texfilebase ".tex"))
18224 (dvifile (concat texfilebase ".dvi"))
18225 (pngfile (concat texfilebase ".png"))
18226 (fnh (if (featurep 'xemacs)
18227 (font-height (face-font 'default))
18228 (face-attribute 'default :height nil)))
18229 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18230 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18231 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18232 "Black"))
18233 (bg (or (plist-get options (if buffer :background :html-background))
18234 "Transparent")))
18235 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18236 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18237 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18238 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18239 (let ((latex-header (org-create-formula--latex-header)))
18240 (with-temp-file texfile
18241 (insert latex-header)
18242 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18243 (let ((dir default-directory))
18244 (condition-case nil
18245 (progn
18246 (cd tmpdir)
18247 (call-process "latex" nil nil nil texfile))
18248 (error nil))
18249 (cd dir))
18250 (if (not (file-exists-p dvifile))
18251 (progn (message "Failed to create dvi file from %s" texfile) nil)
18252 (condition-case nil
18253 (if (featurep 'xemacs)
18254 (call-process "dvipng" nil nil nil
18255 "-fg" fg "-bg" bg
18256 "-T" "tight"
18257 "-o" pngfile
18258 dvifile)
18259 (call-process "dvipng" nil nil nil
18260 "-fg" fg "-bg" bg
18261 "-D" dpi
18262 ;;"-x" scale "-y" scale
18263 "-T" "tight"
18264 "-o" pngfile
18265 dvifile))
18266 (error nil))
18267 (if (not (file-exists-p pngfile))
18268 (if org-format-latex-signal-error
18269 (error "Failed to create png file from %s" texfile)
18270 (message "Failed to create png file from %s" texfile)
18271 nil)
18272 ;; Use the requested file name and clean up
18273 (copy-file pngfile tofile 'replace)
18274 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18275 (if (file-exists-p (concat texfilebase e))
18276 (delete-file (concat texfilebase e))))
18277 pngfile))))
18279 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18280 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18281 "This calls convert, which is included into imagemagick."
18282 (require 'ox-latex)
18283 (let* ((tmpdir (if (featurep 'xemacs)
18284 (temp-directory)
18285 temporary-file-directory))
18286 (texfilebase (make-temp-name
18287 (expand-file-name "orgtex" tmpdir)))
18288 (texfile (concat texfilebase ".tex"))
18289 (pdffile (concat texfilebase ".pdf"))
18290 (pngfile (concat texfilebase ".png"))
18291 (fnh (if (featurep 'xemacs)
18292 (font-height (face-font 'default))
18293 (face-attribute 'default :height nil)))
18294 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18295 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18296 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18297 "black"))
18298 (bg (or (plist-get options (if buffer :background :html-background))
18299 "white")))
18300 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18301 (setq fg (org-latex-color-format fg)))
18302 (if (eq bg 'default) (setq bg (org-latex-color :background))
18303 (setq bg (org-latex-color-format
18304 (if (string= bg "Transparent") "white" bg))))
18305 (let ((latex-header (org-create-formula--latex-header)))
18306 (with-temp-file texfile
18307 (insert latex-header)
18308 (insert "\n\\begin{document}\n"
18309 "\\definecolor{fg}{rgb}{" fg "}\n"
18310 "\\definecolor{bg}{rgb}{" bg "}\n"
18311 "\n\\pagecolor{bg}\n"
18312 "\n{\\color{fg}\n"
18313 string
18314 "\n}\n"
18315 "\n\\end{document}\n")))
18316 (org-latex-compile texfile t)
18317 (if (not (file-exists-p pdffile))
18318 (progn (message "Failed to create pdf file from %s" texfile) nil)
18319 (condition-case nil
18320 (if (featurep 'xemacs)
18321 (call-process "convert" nil nil nil
18322 "-density" "96"
18323 "-trim"
18324 "-antialias"
18325 pdffile
18326 "-quality" "100"
18327 ;; "-sharpen" "0x1.0"
18328 pngfile)
18329 (call-process "convert" nil nil nil
18330 "-density" dpi
18331 "-trim"
18332 "-antialias"
18333 pdffile
18334 "-quality" "100"
18335 ;; "-sharpen" "0x1.0"
18336 pngfile))
18337 (error nil))
18338 (if (not (file-exists-p pngfile))
18339 (if org-format-latex-signal-error
18340 (error "Failed to create png file from %s" texfile)
18341 (message "Failed to create png file from %s" texfile)
18342 nil)
18343 ;; Use the requested file name and clean up
18344 (copy-file pngfile tofile 'replace)
18345 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18346 (if (file-exists-p (concat texfilebase e))
18347 (delete-file (concat texfilebase e))))
18348 pngfile))))
18350 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18351 "Fill a LaTeX header template TPL.
18352 In the template, the following place holders will be recognized:
18354 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18355 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18356 [PACKAGES] \\usepackage statements for PKG
18357 [NO-PACKAGES] do not include PKG
18358 [EXTRA] the string EXTRA
18359 [NO-EXTRA] do not include EXTRA
18361 For backward compatibility, if both the positive and the negative place
18362 holder is missing, the positive one (without the \"NO-\") will be
18363 assumed to be present at the end of the template.
18364 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18365 EXTRA is a string.
18366 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18367 (let (rpl (end ""))
18368 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18369 (setq rpl (if (or (match-end 1) (not def-pkg))
18370 "" (org-latex-packages-to-string def-pkg snippets-p t))
18371 tpl (replace-match rpl t t tpl))
18372 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18374 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18375 (setq rpl (if (or (match-end 1) (not pkg))
18376 "" (org-latex-packages-to-string pkg snippets-p t))
18377 tpl (replace-match rpl t t tpl))
18378 (if pkg (setq end
18379 (concat end "\n"
18380 (org-latex-packages-to-string pkg snippets-p)))))
18382 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18383 (setq rpl (if (or (match-end 1) (not extra))
18384 "" (concat extra "\n"))
18385 tpl (replace-match rpl t t tpl))
18386 (if (and extra (string-match "\\S-" extra))
18387 (setq end (concat end "\n" extra))))
18389 (if (string-match "\\S-" end)
18390 (concat tpl "\n" end)
18391 tpl)))
18393 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18394 "Turn an alist of packages into a string with the \\usepackage macros."
18395 (setq pkg (mapconcat (lambda(p)
18396 (cond
18397 ((stringp p) p)
18398 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18399 (format "%% Package %s omitted" (cadr p)))
18400 ((equal "" (car p))
18401 (format "\\usepackage{%s}" (cadr p)))
18403 (format "\\usepackage[%s]{%s}"
18404 (car p) (cadr p)))))
18406 "\n"))
18407 (if newline (concat pkg "\n") pkg))
18409 (defun org-dvipng-color (attr)
18410 "Return a RGB color specification for dvipng."
18411 (apply 'format "rgb %s %s %s"
18412 (mapcar 'org-normalize-color
18413 (if (featurep 'xemacs)
18414 (color-rgb-components
18415 (face-property 'default
18416 (cond ((eq attr :foreground) 'foreground)
18417 ((eq attr :background) 'background))))
18418 (color-values (face-attribute 'default attr nil))))))
18420 (defun org-dvipng-color-format (color-name)
18421 "Convert COLOR-NAME to a RGB color value for dvipng."
18422 (apply 'format "rgb %s %s %s"
18423 (mapcar 'org-normalize-color
18424 (color-values color-name))))
18426 (defun org-latex-color (attr)
18427 "Return a RGB color for the LaTeX color package."
18428 (apply 'format "%s,%s,%s"
18429 (mapcar 'org-normalize-color
18430 (if (featurep 'xemacs)
18431 (color-rgb-components
18432 (face-property 'default
18433 (cond ((eq attr :foreground) 'foreground)
18434 ((eq attr :background) 'background))))
18435 (color-values (face-attribute 'default attr nil))))))
18437 (defun org-latex-color-format (color-name)
18438 "Convert COLOR-NAME to a RGB color value."
18439 (apply 'format "%s,%s,%s"
18440 (mapcar 'org-normalize-color
18441 (color-values color-name))))
18443 (defun org-normalize-color (value)
18444 "Return string to be used as color value for an RGB component."
18445 (format "%g" (/ value 65535.0)))
18449 ;; Image display
18451 (defvar org-inline-image-overlays nil)
18452 (make-variable-buffer-local 'org-inline-image-overlays)
18454 (defun org-toggle-inline-images (&optional include-linked)
18455 "Toggle the display of inline images.
18456 INCLUDE-LINKED is passed to `org-display-inline-images'."
18457 (interactive "P")
18458 (if org-inline-image-overlays
18459 (progn
18460 (org-remove-inline-images)
18461 (message "Inline image display turned off"))
18462 (org-display-inline-images include-linked)
18463 (if (and (org-called-interactively-p)
18464 org-inline-image-overlays)
18465 (message "%d images displayed inline"
18466 (length org-inline-image-overlays))
18467 (message "No images to display inline"))))
18469 (defun org-redisplay-inline-images ()
18470 "Refresh the display of inline images."
18471 (interactive)
18472 (if (not org-inline-image-overlays)
18473 (org-toggle-inline-images)
18474 (org-toggle-inline-images)
18475 (org-toggle-inline-images)))
18477 (defun org-display-inline-images (&optional include-linked refresh beg end)
18478 "Display inline images.
18479 Normally only links without a description part are inlined, because this
18480 is how it will work for export. When INCLUDE-LINKED is set, also links
18481 with a description part will be inlined. This can be nice for a quick
18482 look at those images, but it does not reflect what exported files will look
18483 like.
18484 When REFRESH is set, refresh existing images between BEG and END.
18485 This will create new image displays only if necessary.
18486 BEG and END default to the buffer boundaries."
18487 (interactive "P")
18488 (unless refresh
18489 (org-remove-inline-images)
18490 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18491 (save-excursion
18492 (save-restriction
18493 (widen)
18494 (setq beg (or beg (point-min)) end (or end (point-max)))
18495 (goto-char beg)
18496 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18497 (substring (org-image-file-name-regexp) 0 -2)
18498 "\\)\\]" (if include-linked "" "\\]")))
18499 old file ov img type attrwidth width)
18500 (while (re-search-forward re end t)
18501 (setq old (get-char-property-and-overlay (match-beginning 1)
18502 'org-image-overlay)
18503 file (expand-file-name
18504 (concat (or (match-string 3) "") (match-string 4))))
18505 (when (image-type-available-p 'imagemagick)
18506 (setq attrwidth (if (or (listp org-image-actual-width)
18507 (null org-image-actual-width))
18508 (save-excursion
18509 (save-match-data
18510 (when (re-search-backward
18511 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18512 (save-excursion
18513 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18514 (string-to-number (match-string 1))))))
18515 width (cond ((eq org-image-actual-width t) nil)
18516 ((null org-image-actual-width) attrwidth)
18517 ((numberp org-image-actual-width)
18518 org-image-actual-width)
18519 ((listp org-image-actual-width)
18520 (or attrwidth (car org-image-actual-width))))
18521 type (if width 'imagemagick)))
18522 (when (file-exists-p file)
18523 (if (and (car-safe old) refresh)
18524 (image-refresh (overlay-get (cdr old) 'display))
18525 (setq img (save-match-data (create-image file type nil :width width)))
18526 (when img
18527 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18528 (overlay-put ov 'display img)
18529 (overlay-put ov 'face 'default)
18530 (overlay-put ov 'org-image-overlay t)
18531 (overlay-put ov 'modification-hooks
18532 (list 'org-display-inline-remove-overlay))
18533 (push ov org-inline-image-overlays)))))))))
18535 (define-obsolete-function-alias
18536 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18538 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18539 "Remove inline-display overlay if a corresponding region is modified."
18540 (let ((inhibit-modification-hooks t))
18541 (when (and ov after)
18542 (delete ov org-inline-image-overlays)
18543 (delete-overlay ov))))
18545 (defun org-remove-inline-images ()
18546 "Remove inline display of images."
18547 (interactive)
18548 (mapc 'delete-overlay org-inline-image-overlays)
18549 (setq org-inline-image-overlays nil))
18551 ;;;; Key bindings
18553 ;; Outline functions from `outline-mode-prefix-map'
18554 ;; that can be remapped in Org:
18555 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18556 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18557 (define-key org-mode-map [remap outline-forward-same-level]
18558 'org-forward-heading-same-level)
18559 (define-key org-mode-map [remap outline-backward-same-level]
18560 'org-backward-heading-same-level)
18561 (define-key org-mode-map [remap show-branches]
18562 'org-kill-note-or-show-branches)
18563 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18564 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18565 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18567 ;; Outline functions from `outline-mode-prefix-map' that can not
18568 ;; be remapped in Org:
18570 ;; - the column "key binding" shows whether the Outline function is still
18571 ;; available in Org mode on the same key that it has been bound to in
18572 ;; Outline mode:
18573 ;; - "overridden": key used for a different functionality in Org mode
18574 ;; - else: key still bound to the same Outline function in Org mode
18576 ;; | Outline function | key binding | Org replacement |
18577 ;; |------------------------------------+-------------+-----------------------|
18578 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18579 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18580 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18581 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18582 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18583 ;; | `show-entry' | overridden | no replacement |
18584 ;; | `show-children' | `C-c C-i' | visibility cycling |
18585 ;; | `show-branches' | `C-c C-k' | still same function |
18586 ;; | `show-subtree' | overridden | visibility cycling |
18587 ;; | `show-all' | overridden | no replacement |
18588 ;; | `hide-subtree' | overridden | visibility cycling |
18589 ;; | `hide-body' | overridden | no replacement |
18590 ;; | `hide-entry' | overridden | visibility cycling |
18591 ;; | `hide-leaves' | overridden | no replacement |
18592 ;; | `hide-sublevels' | overridden | no replacement |
18593 ;; | `hide-other' | overridden | no replacement |
18595 ;; Make `C-c C-x' a prefix key
18596 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18598 ;; TAB key with modifiers
18599 (org-defkey org-mode-map "\C-i" 'org-cycle)
18600 (org-defkey org-mode-map [(tab)] 'org-cycle)
18601 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18602 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18603 ;; The following line is necessary under Suse GNU/Linux
18604 (unless (featurep 'xemacs)
18605 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18606 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18607 (define-key org-mode-map [backtab] 'org-shifttab)
18609 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18610 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18611 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18613 ;; Cursor keys with modifiers
18614 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18615 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18616 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18617 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18619 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18620 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18621 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18622 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18624 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18625 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18626 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18627 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18629 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18630 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18631 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18632 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18634 ;; Babel keys
18635 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18636 (mapc (lambda (pair)
18637 (define-key org-babel-map (car pair) (cdr pair)))
18638 org-babel-key-bindings)
18640 ;;; Extra keys for tty access.
18641 ;; We only set them when really needed because otherwise the
18642 ;; menus don't show the simple keys
18644 (when (or org-use-extra-keys
18645 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18646 (not window-system))
18647 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18648 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18649 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18650 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18651 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18652 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18653 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18654 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18655 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18656 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18657 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18658 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18659 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18660 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18661 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18662 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18663 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18664 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18665 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18666 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18667 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18668 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18669 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18670 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18671 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18672 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18673 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18674 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18676 ;; All the other keys
18678 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18679 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18680 (if (boundp 'narrow-map)
18681 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18682 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18683 (if (boundp 'narrow-map)
18684 (org-defkey narrow-map "b" 'org-narrow-to-block)
18685 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18686 (if (boundp 'narrow-map)
18687 (org-defkey narrow-map "e" 'org-narrow-to-element)
18688 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18689 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18690 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18691 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18692 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18693 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18694 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18695 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18696 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18697 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18698 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18699 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18700 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18701 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18702 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18703 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18704 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18705 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18706 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18707 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18708 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18709 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18710 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18711 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18712 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18713 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18714 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18715 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18716 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18717 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18718 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18719 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18720 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18721 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18722 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18723 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18724 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18725 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18726 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18727 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18728 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18729 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18730 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18731 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18732 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18733 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18734 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18735 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18736 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18737 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18738 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18739 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18740 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18741 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18742 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18743 (org-defkey org-mode-map "\C-c^" 'org-sort)
18744 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18745 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18746 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18747 (org-defkey org-mode-map "\C-m" 'org-return)
18748 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18749 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18750 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18751 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18752 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18753 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18754 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18755 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18756 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18757 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18758 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18759 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18760 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18761 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18762 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18763 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18764 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18765 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18766 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18767 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18768 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18769 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18770 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18772 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18773 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18774 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18776 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18777 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18778 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18779 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18780 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18781 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18782 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18783 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18784 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18785 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18786 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18787 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18788 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18789 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18790 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18791 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18792 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18793 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18794 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18795 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18796 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18797 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18798 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18800 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18801 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18802 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18803 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18804 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18806 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18808 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18810 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18811 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18813 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18816 (when (featurep 'xemacs)
18817 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18820 (defconst org-speed-commands-default
18822 ("Outline Navigation")
18823 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18824 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18825 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18826 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18827 ("F" . org-next-block)
18828 ("B" . org-previous-block)
18829 ("u" . (org-speed-move-safe 'outline-up-heading))
18830 ("j" . org-goto)
18831 ("g" . (org-refile t))
18832 ("Outline Visibility")
18833 ("c" . org-cycle)
18834 ("C" . org-shifttab)
18835 (" " . org-display-outline-path)
18836 ("=" . org-columns)
18837 ("Outline Structure Editing")
18838 ("U" . org-shiftmetaup)
18839 ("D" . org-shiftmetadown)
18840 ("r" . org-metaright)
18841 ("l" . org-metaleft)
18842 ("R" . org-shiftmetaright)
18843 ("L" . org-shiftmetaleft)
18844 ("i" . (progn (forward-char 1) (call-interactively
18845 'org-insert-heading-respect-content)))
18846 ("^" . org-sort)
18847 ("w" . org-refile)
18848 ("a" . org-archive-subtree-default-with-confirmation)
18849 ("@" . org-mark-subtree)
18850 ("#" . org-toggle-comment)
18851 ("Clock Commands")
18852 ("I" . org-clock-in)
18853 ("O" . org-clock-out)
18854 ("Meta Data Editing")
18855 ("t" . org-todo)
18856 ("," . (org-priority))
18857 ("0" . (org-priority ?\ ))
18858 ("1" . (org-priority ?A))
18859 ("2" . (org-priority ?B))
18860 ("3" . (org-priority ?C))
18861 (":" . org-set-tags-command)
18862 ("e" . org-set-effort)
18863 ("E" . org-inc-effort)
18864 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18865 (org-entry-put (point) "APPT_WARNTIME" m)))
18866 ("Agenda Views etc")
18867 ("v" . org-agenda)
18868 ("/" . org-sparse-tree)
18869 ("Misc")
18870 ("o" . org-open-at-point)
18871 ("?" . org-speed-command-help)
18872 ("<" . (org-agenda-set-restriction-lock 'subtree))
18873 (">" . (org-agenda-remove-restriction-lock))
18875 "The default speed commands.")
18877 (defun org-print-speed-command (e)
18878 (if (> (length (car e)) 1)
18879 (progn
18880 (princ "\n")
18881 (princ (car e))
18882 (princ "\n")
18883 (princ (make-string (length (car e)) ?-))
18884 (princ "\n"))
18885 (princ (car e))
18886 (princ " ")
18887 (if (symbolp (cdr e))
18888 (princ (symbol-name (cdr e)))
18889 (prin1 (cdr e)))
18890 (princ "\n")))
18892 (defun org-speed-command-help ()
18893 "Show the available speed commands."
18894 (interactive)
18895 (if (not org-use-speed-commands)
18896 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18897 (with-output-to-temp-buffer "*Help*"
18898 (princ "User-defined Speed commands\n===========================\n")
18899 (mapc 'org-print-speed-command org-speed-commands-user)
18900 (princ "\n")
18901 (princ "Built-in Speed commands\n=======================\n")
18902 (mapc 'org-print-speed-command org-speed-commands-default))
18903 (with-current-buffer "*Help*"
18904 (setq truncate-lines t))))
18906 (defun org-speed-move-safe (cmd)
18907 "Execute CMD, but make sure that the cursor always ends up in a headline.
18908 If not, return to the original position and throw an error."
18909 (interactive)
18910 (let ((pos (point)))
18911 (call-interactively cmd)
18912 (unless (and (bolp) (org-at-heading-p))
18913 (goto-char pos)
18914 (error "Boundary reached while executing %s" cmd))))
18916 (defvar org-self-insert-command-undo-counter 0)
18918 (defvar org-table-auto-blank-field) ; defined in org-table.el
18919 (defvar org-speed-command nil)
18921 (define-obsolete-function-alias
18922 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18924 (defun org-speed-command-activate (keys)
18925 "Hook for activating single-letter speed commands.
18926 `org-speed-commands-default' specifies a minimal command set.
18927 Use `org-speed-commands-user' for further customization."
18928 (when (or (and (bolp) (looking-at org-outline-regexp))
18929 (and (functionp org-use-speed-commands)
18930 (funcall org-use-speed-commands)))
18931 (cdr (assoc keys (append org-speed-commands-user
18932 org-speed-commands-default)))))
18934 (define-obsolete-function-alias
18935 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18937 (defun org-babel-speed-command-activate (keys)
18938 "Hook for activating single-letter code block commands."
18939 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18940 (cdr (assoc keys org-babel-key-bindings))))
18942 (defcustom org-speed-command-hook
18943 '(org-speed-command-default-hook org-babel-speed-command-hook)
18944 "Hook for activating speed commands at strategic locations.
18945 Hook functions are called in sequence until a valid handler is
18946 found.
18948 Each hook takes a single argument, a user-pressed command key
18949 which is also a `self-insert-command' from the global map.
18951 Within the hook, examine the cursor position and the command key
18952 and return nil or a valid handler as appropriate. Handler could
18953 be one of an interactive command, a function, or a form.
18955 Set `org-use-speed-commands' to non-nil value to enable this
18956 hook. The default setting is `org-speed-command-activate'."
18957 :group 'org-structure
18958 :version "24.1"
18959 :type 'hook)
18961 (defun org-self-insert-command (N)
18962 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18963 If the cursor is in a table looking at whitespace, the whitespace is
18964 overwritten, and the table is not marked as requiring realignment."
18965 (interactive "p")
18966 (org-check-before-invisible-edit 'insert)
18967 (cond
18968 ((and org-use-speed-commands
18969 (setq org-speed-command
18970 (run-hook-with-args-until-success
18971 'org-speed-command-hook (this-command-keys))))
18972 (cond
18973 ((commandp org-speed-command)
18974 (setq this-command org-speed-command)
18975 (call-interactively org-speed-command))
18976 ((functionp org-speed-command)
18977 (funcall org-speed-command))
18978 ((and org-speed-command (listp org-speed-command))
18979 (eval org-speed-command))
18980 (t (let (org-use-speed-commands)
18981 (call-interactively 'org-self-insert-command)))))
18982 ((and
18983 (org-table-p)
18984 (progn
18985 ;; check if we blank the field, and if that triggers align
18986 (and (featurep 'org-table) org-table-auto-blank-field
18987 (member last-command
18988 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18989 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18990 ;; got extra space, this field does not determine column width
18991 (let (org-table-may-need-update) (org-table-blank-field))
18992 ;; no extra space, this field may determine column width
18993 (org-table-blank-field)))
18995 (eq N 1)
18996 (looking-at "[^|\n]* |"))
18997 (let (org-table-may-need-update)
18998 (goto-char (1- (match-end 0)))
18999 (backward-delete-char 1)
19000 (goto-char (match-beginning 0))
19001 (self-insert-command N)))
19003 (setq org-table-may-need-update t)
19004 (self-insert-command N)
19005 (org-fix-tags-on-the-fly)
19006 (if org-self-insert-cluster-for-undo
19007 (if (not (eq last-command 'org-self-insert-command))
19008 (setq org-self-insert-command-undo-counter 1)
19009 (if (>= org-self-insert-command-undo-counter 20)
19010 (setq org-self-insert-command-undo-counter 1)
19011 (and (> org-self-insert-command-undo-counter 0)
19012 buffer-undo-list (listp buffer-undo-list)
19013 (not (cadr buffer-undo-list)) ; remove nil entry
19014 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19015 (setq org-self-insert-command-undo-counter
19016 (1+ org-self-insert-command-undo-counter))))))))
19018 (defun org-check-before-invisible-edit (kind)
19019 "Check is editing if kind KIND would be dangerous with invisible text around.
19020 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19021 ;; First, try to get out of here as quickly as possible, to reduce overhead
19022 (if (and org-catch-invisible-edits
19023 (or (not (boundp 'visible-mode)) (not visible-mode))
19024 (or (get-char-property (point) 'invisible)
19025 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19026 ;; OK, we need to take a closer look
19027 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19028 (invisible-before-point (if (bobp) nil (get-char-property
19029 (1- (point)) 'invisible)))
19030 (border-and-ok-direction
19032 ;; Check if we are acting predictably before invisible text
19033 (and invisible-at-point (not invisible-before-point)
19034 (memq kind '(insert delete-backward)))
19035 ;; Check if we are acting predictably after invisible text
19036 ;; This works not well, and I have turned it off. It seems
19037 ;; better to always show and stop after invisible text.
19038 ;; (and (not invisible-at-point) invisible-before-point
19039 ;; (memq kind '(insert delete)))
19041 (when (or (memq invisible-at-point '(outline org-hide-block t))
19042 (memq invisible-before-point '(outline org-hide-block t)))
19043 (if (eq org-catch-invisible-edits 'error)
19044 (error "Editing in invisible areas is prohibited - make visible first"))
19045 (if (and org-custom-properties-overlays
19046 (y-or-n-p "Display invisible properties in this buffer? "))
19047 (org-toggle-custom-properties-visibility)
19048 ;; Make the area visible
19049 (save-excursion
19050 (if invisible-before-point
19051 (goto-char (previous-single-char-property-change
19052 (point) 'invisible)))
19053 (org-cycle))
19054 (cond
19055 ((eq org-catch-invisible-edits 'show)
19056 ;; That's it, we do the edit after showing
19057 (message
19058 "Unfolding invisible region around point before editing")
19059 (sit-for 1))
19060 ((and (eq org-catch-invisible-edits 'smart)
19061 border-and-ok-direction)
19062 (message "Unfolding invisible region around point before editing"))
19064 ;; Don't do the edit, make the user repeat it in full visibility
19065 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19067 (defun org-fix-tags-on-the-fly ()
19068 (when (and (equal (char-after (point-at-bol)) ?*)
19069 (org-at-heading-p))
19070 (org-align-tags-here org-tags-column)))
19072 (defun org-delete-backward-char (N)
19073 "Like `delete-backward-char', insert whitespace at field end in tables.
19074 When deleting backwards, in tables this function will insert whitespace in
19075 front of the next \"|\" separator, to keep the table aligned. The table will
19076 still be marked for re-alignment if the field did fill the entire column,
19077 because, in this case the deletion might narrow the column."
19078 (interactive "p")
19079 (save-match-data
19080 (org-check-before-invisible-edit 'delete-backward)
19081 (if (and (org-table-p)
19082 (eq N 1)
19083 (string-match "|" (buffer-substring (point-at-bol) (point)))
19084 (looking-at ".*?|"))
19085 (let ((pos (point))
19086 (noalign (looking-at "[^|\n\r]* |"))
19087 (c org-table-may-need-update))
19088 (backward-delete-char N)
19089 (if (not overwrite-mode)
19090 (progn
19091 (skip-chars-forward "^|")
19092 (insert " ")
19093 (goto-char (1- pos))))
19094 ;; noalign: if there were two spaces at the end, this field
19095 ;; does not determine the width of the column.
19096 (if noalign (setq org-table-may-need-update c)))
19097 (backward-delete-char N)
19098 (org-fix-tags-on-the-fly))))
19100 (defun org-delete-char (N)
19101 "Like `delete-char', but insert whitespace at field end in tables.
19102 When deleting characters, in tables this function will insert whitespace in
19103 front of the next \"|\" separator, to keep the table aligned. The table will
19104 still be marked for re-alignment if the field did fill the entire column,
19105 because, in this case the deletion might narrow the column."
19106 (interactive "p")
19107 (save-match-data
19108 (org-check-before-invisible-edit 'delete)
19109 (if (and (org-table-p)
19110 (not (bolp))
19111 (not (= (char-after) ?|))
19112 (eq N 1))
19113 (if (looking-at ".*?|")
19114 (let ((pos (point))
19115 (noalign (looking-at "[^|\n\r]* |"))
19116 (c org-table-may-need-update))
19117 (replace-match (concat
19118 (substring (match-string 0) 1 -1)
19119 " |"))
19120 (goto-char pos)
19121 ;; noalign: if there were two spaces at the end, this field
19122 ;; does not determine the width of the column.
19123 (if noalign (setq org-table-may-need-update c)))
19124 (delete-char N))
19125 (delete-char N)
19126 (org-fix-tags-on-the-fly))))
19128 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19129 (put 'org-self-insert-command 'delete-selection t)
19130 (put 'orgtbl-self-insert-command 'delete-selection t)
19131 (put 'org-delete-char 'delete-selection 'supersede)
19132 (put 'org-delete-backward-char 'delete-selection 'supersede)
19133 (put 'org-yank 'delete-selection 'yank)
19135 ;; Make `flyspell-mode' delay after some commands
19136 (put 'org-self-insert-command 'flyspell-delayed t)
19137 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19138 (put 'org-delete-char 'flyspell-delayed t)
19139 (put 'org-delete-backward-char 'flyspell-delayed t)
19141 ;; Make pabbrev-mode expand after org-mode commands
19142 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19143 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19145 ;; How to do this: Measure non-white length of current string
19146 ;; If equal to column width, we should realign.
19148 (defun org-remap (map &rest commands)
19149 "In MAP, remap the functions given in COMMANDS.
19150 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19151 (let (new old)
19152 (while commands
19153 (setq old (pop commands) new (pop commands))
19154 (if (fboundp 'command-remapping)
19155 (org-defkey map (vector 'remap old) new)
19156 (substitute-key-definition old new map global-map)))))
19158 (defun org-transpose-words ()
19159 "Transpose words for Org.
19160 This uses the `org-mode-transpose-word-syntax-table' syntax
19161 table, which interprets characters in `org-emphasis-alist' as
19162 word constituants."
19163 (interactive)
19164 (with-syntax-table org-mode-transpose-word-syntax-table
19165 (call-interactively 'transpose-words)))
19166 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19168 (when (eq org-enable-table-editor 'optimized)
19169 ;; If the user wants maximum table support, we need to hijack
19170 ;; some standard editing functions
19171 (org-remap org-mode-map
19172 'self-insert-command 'org-self-insert-command
19173 'delete-char 'org-delete-char
19174 'delete-backward-char 'org-delete-backward-char)
19175 (org-defkey org-mode-map "|" 'org-force-self-insert))
19177 (defvar org-ctrl-c-ctrl-c-hook nil
19178 "Hook for functions attaching themselves to `C-c C-c'.
19180 This can be used to add additional functionality to the C-c C-c
19181 key which executes context-dependent commands. This hook is run
19182 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19183 run after the last test.
19185 Each function will be called with no arguments. The function
19186 must check if the context is appropriate for it to act. If yes,
19187 it should do its thing and then return a non-nil value. If the
19188 context is wrong, just do nothing and return nil.")
19190 (defvar org-ctrl-c-ctrl-c-final-hook nil
19191 "Hook for functions attaching themselves to `C-c C-c'.
19193 This can be used to add additional functionality to the C-c C-c
19194 key which executes context-dependent commands. This hook is run
19195 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19196 before the first test.
19198 Each function will be called with no arguments. The function
19199 must check if the context is appropriate for it to act. If yes,
19200 it should do its thing and then return a non-nil value. If the
19201 context is wrong, just do nothing and return nil.")
19203 (defvar org-tab-first-hook nil
19204 "Hook for functions to attach themselves to TAB.
19205 See `org-ctrl-c-ctrl-c-hook' for more information.
19206 This hook runs as the first action when TAB is pressed, even before
19207 `org-cycle' messes around with the `outline-regexp' to cater for
19208 inline tasks and plain list item folding.
19209 If any function in this hook returns t, any other actions that
19210 would have been caused by TAB (such as table field motion or visibility
19211 cycling) will not occur.")
19213 (defvar org-tab-after-check-for-table-hook nil
19214 "Hook for functions to attach themselves to TAB.
19215 See `org-ctrl-c-ctrl-c-hook' for more information.
19216 This hook runs after it has been established that the cursor is not in a
19217 table, but before checking if the cursor is in a headline or if global cycling
19218 should be done.
19219 If any function in this hook returns t, not other actions like visibility
19220 cycling will be done.")
19222 (defvar org-tab-after-check-for-cycling-hook nil
19223 "Hook for functions to attach themselves to TAB.
19224 See `org-ctrl-c-ctrl-c-hook' for more information.
19225 This hook runs after it has been established that not table field motion and
19226 not visibility should be done because of current context. This is probably
19227 the place where a package like yasnippets can hook in.")
19229 (defvar org-tab-before-tab-emulation-hook nil
19230 "Hook for functions to attach themselves to TAB.
19231 See `org-ctrl-c-ctrl-c-hook' for more information.
19232 This hook runs after every other options for TAB have been exhausted, but
19233 before indentation and \t insertion takes place.")
19235 (defvar org-metaleft-hook nil
19236 "Hook for functions attaching themselves to `M-left'.
19237 See `org-ctrl-c-ctrl-c-hook' for more information.")
19238 (defvar org-metaright-hook nil
19239 "Hook for functions attaching themselves to `M-right'.
19240 See `org-ctrl-c-ctrl-c-hook' for more information.")
19241 (defvar org-metaup-hook nil
19242 "Hook for functions attaching themselves to `M-up'.
19243 See `org-ctrl-c-ctrl-c-hook' for more information.")
19244 (defvar org-metadown-hook nil
19245 "Hook for functions attaching themselves to `M-down'.
19246 See `org-ctrl-c-ctrl-c-hook' for more information.")
19247 (defvar org-shiftmetaleft-hook nil
19248 "Hook for functions attaching themselves to `M-S-left'.
19249 See `org-ctrl-c-ctrl-c-hook' for more information.")
19250 (defvar org-shiftmetaright-hook nil
19251 "Hook for functions attaching themselves to `M-S-right'.
19252 See `org-ctrl-c-ctrl-c-hook' for more information.")
19253 (defvar org-shiftmetaup-hook nil
19254 "Hook for functions attaching themselves to `M-S-up'.
19255 See `org-ctrl-c-ctrl-c-hook' for more information.")
19256 (defvar org-shiftmetadown-hook nil
19257 "Hook for functions attaching themselves to `M-S-down'.
19258 See `org-ctrl-c-ctrl-c-hook' for more information.")
19259 (defvar org-metareturn-hook nil
19260 "Hook for functions attaching themselves to `M-RET'.
19261 See `org-ctrl-c-ctrl-c-hook' for more information.")
19262 (defvar org-shiftup-hook nil
19263 "Hook for functions attaching themselves to `S-up'.
19264 See `org-ctrl-c-ctrl-c-hook' for more information.")
19265 (defvar org-shiftup-final-hook nil
19266 "Hook for functions attaching themselves to `S-up'.
19267 This one runs after all other options except shift-select have been excluded.
19268 See `org-ctrl-c-ctrl-c-hook' for more information.")
19269 (defvar org-shiftdown-hook nil
19270 "Hook for functions attaching themselves to `S-down'.
19271 See `org-ctrl-c-ctrl-c-hook' for more information.")
19272 (defvar org-shiftdown-final-hook nil
19273 "Hook for functions attaching themselves to `S-down'.
19274 This one runs after all other options except shift-select have been excluded.
19275 See `org-ctrl-c-ctrl-c-hook' for more information.")
19276 (defvar org-shiftleft-hook nil
19277 "Hook for functions attaching themselves to `S-left'.
19278 See `org-ctrl-c-ctrl-c-hook' for more information.")
19279 (defvar org-shiftleft-final-hook nil
19280 "Hook for functions attaching themselves to `S-left'.
19281 This one runs after all other options except shift-select have been excluded.
19282 See `org-ctrl-c-ctrl-c-hook' for more information.")
19283 (defvar org-shiftright-hook nil
19284 "Hook for functions attaching themselves to `S-right'.
19285 See `org-ctrl-c-ctrl-c-hook' for more information.")
19286 (defvar org-shiftright-final-hook nil
19287 "Hook for functions attaching themselves to `S-right'.
19288 This one runs after all other options except shift-select have been excluded.
19289 See `org-ctrl-c-ctrl-c-hook' for more information.")
19291 (defun org-modifier-cursor-error ()
19292 "Throw an error, a modified cursor command was applied in wrong context."
19293 (error "This command is active in special context like tables, headlines or items"))
19295 (defun org-shiftselect-error ()
19296 "Throw an error because Shift-Cursor command was applied in wrong context."
19297 (if (and (boundp 'shift-select-mode) shift-select-mode)
19298 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19299 (error "This command works only in special context like headlines or timestamps")))
19301 (defun org-call-for-shift-select (cmd)
19302 (let ((this-command-keys-shift-translated t))
19303 (call-interactively cmd)))
19305 (defun org-shifttab (&optional arg)
19306 "Global visibility cycling or move to previous table field.
19307 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19308 on context.
19309 See the individual commands for more information."
19310 (interactive "P")
19311 (cond
19312 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19313 ((integerp arg)
19314 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19315 (message "Content view to level: %d" arg)
19316 (org-content (prefix-numeric-value arg2))
19317 (setq org-cycle-global-status 'overview)))
19318 (t (call-interactively 'org-global-cycle))))
19320 (defun org-shiftmetaleft ()
19321 "Promote subtree or delete table column.
19322 Calls `org-promote-subtree', `org-outdent-item-tree', or
19323 `org-table-delete-column', depending on context. See the
19324 individual commands for more information."
19325 (interactive)
19326 (cond
19327 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19328 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19329 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19330 ((if (not (org-region-active-p)) (org-at-item-p)
19331 (save-excursion (goto-char (region-beginning))
19332 (org-at-item-p)))
19333 (call-interactively 'org-outdent-item-tree))
19334 (t (org-modifier-cursor-error))))
19336 (defun org-shiftmetaright ()
19337 "Demote subtree or insert table column.
19338 Calls `org-demote-subtree', `org-indent-item-tree', or
19339 `org-table-insert-column', depending on context. See the
19340 individual commands for more information."
19341 (interactive)
19342 (cond
19343 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19344 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19345 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19346 ((if (not (org-region-active-p)) (org-at-item-p)
19347 (save-excursion (goto-char (region-beginning))
19348 (org-at-item-p)))
19349 (call-interactively 'org-indent-item-tree))
19350 (t (org-modifier-cursor-error))))
19352 (defun org-shiftmetaup (&optional arg)
19353 "Move subtree up or kill table row.
19354 Calls `org-move-subtree-up' or `org-table-kill-row' or
19355 `org-move-item-up' or `org-timestamp-up', depending on context.
19356 See the individual commands for more information."
19357 (interactive "P")
19358 (cond
19359 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19360 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19361 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19362 ((org-at-item-p) (call-interactively 'org-move-item-up))
19363 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19364 (call-interactively 'org-timestamp-up)))
19365 (t (call-interactively 'org-drag-line-backward))))
19367 (defun org-shiftmetadown (&optional arg)
19368 "Move subtree down or insert table row.
19369 Calls `org-move-subtree-down' or `org-table-insert-row' or
19370 `org-move-item-down' or `org-timestamp-up', depending on context.
19371 See the individual commands for more information."
19372 (interactive "P")
19373 (cond
19374 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19375 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19376 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19377 ((org-at-item-p) (call-interactively 'org-move-item-down))
19378 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19379 (call-interactively 'org-timestamp-down)))
19380 (t (call-interactively 'org-drag-line-forward))))
19382 (defsubst org-hidden-tree-error ()
19383 (error
19384 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19386 (defun org-metaleft (&optional arg)
19387 "Promote heading or move table column to left.
19388 Calls `org-do-promote' or `org-table-move-column', depending on context.
19389 With no specific context, calls the Emacs default `backward-word'.
19390 See the individual commands for more information."
19391 (interactive "P")
19392 (cond
19393 ((run-hook-with-args-until-success 'org-metaleft-hook))
19394 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19395 ((org-with-limited-levels
19396 (or (org-at-heading-p)
19397 (and (org-region-active-p)
19398 (save-excursion
19399 (goto-char (region-beginning))
19400 (org-at-heading-p)))))
19401 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19402 (call-interactively 'org-do-promote))
19403 ;; At an inline task.
19404 ((org-at-heading-p)
19405 (call-interactively 'org-inlinetask-promote))
19406 ((or (org-at-item-p)
19407 (and (org-region-active-p)
19408 (save-excursion
19409 (goto-char (region-beginning))
19410 (org-at-item-p))))
19411 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19412 (call-interactively 'org-outdent-item))
19413 (t (call-interactively 'backward-word))))
19415 (defun org-metaright (&optional arg)
19416 "Demote a subtree, a list item or move table column to right.
19417 In front of a drawer or a block keyword, indent it correctly.
19418 With no specific context, calls the Emacs default `forward-word'.
19419 See the individual commands for more information."
19420 (interactive "P")
19421 (cond
19422 ((run-hook-with-args-until-success 'org-metaright-hook))
19423 ((org-at-table-p) (call-interactively 'org-table-move-column))
19424 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19425 ((org-at-block-p) (call-interactively 'org-indent-block))
19426 ((org-with-limited-levels
19427 (or (org-at-heading-p)
19428 (and (org-region-active-p)
19429 (save-excursion
19430 (goto-char (region-beginning))
19431 (org-at-heading-p)))))
19432 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19433 (call-interactively 'org-do-demote))
19434 ;; At an inline task.
19435 ((org-at-heading-p)
19436 (call-interactively 'org-inlinetask-demote))
19437 ((or (org-at-item-p)
19438 (and (org-region-active-p)
19439 (save-excursion
19440 (goto-char (region-beginning))
19441 (org-at-item-p))))
19442 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19443 (call-interactively 'org-indent-item))
19444 (t (call-interactively 'forward-word))))
19446 (defun org-check-for-hidden (what)
19447 "Check if there are hidden headlines/items in the current visual line.
19448 WHAT can be either `headlines' or `items'. If the current line is
19449 an outline or item heading and it has a folded subtree below it,
19450 this function returns t, nil otherwise."
19451 (let ((re (cond
19452 ((eq what 'headlines) org-outline-regexp-bol)
19453 ((eq what 'items) (org-item-beginning-re))
19454 (t (error "This should not happen"))))
19455 beg end)
19456 (save-excursion
19457 (catch 'exit
19458 (unless (org-region-active-p)
19459 (setq beg (point-at-bol))
19460 (beginning-of-line 2)
19461 (while (and (not (eobp)) ;; this is like `next-line'
19462 (get-char-property (1- (point)) 'invisible))
19463 (beginning-of-line 2))
19464 (setq end (point))
19465 (goto-char beg)
19466 (goto-char (point-at-eol))
19467 (setq end (max end (point)))
19468 (while (re-search-forward re end t)
19469 (if (get-char-property (match-beginning 0) 'invisible)
19470 (throw 'exit t))))
19471 nil))))
19473 (defun org-metaup (&optional arg)
19474 "Move subtree up or move table row up.
19475 Calls `org-move-subtree-up' or `org-table-move-row' or
19476 `org-move-item-up', depending on context. See the individual commands
19477 for more information."
19478 (interactive "P")
19479 (cond
19480 ((run-hook-with-args-until-success 'org-metaup-hook))
19481 ((org-region-active-p)
19482 (let* ((a (min (region-beginning) (region-end)))
19483 (b (1- (max (region-beginning) (region-end))))
19484 (c (save-excursion (goto-char a)
19485 (move-beginning-of-line 0)))
19486 (d (save-excursion (goto-char a)
19487 (move-end-of-line 0) (point))))
19488 (transpose-regions a b c d)
19489 (goto-char c)))
19490 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19491 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19492 ((org-at-item-p) (call-interactively 'org-move-item-up))
19493 (t (org-drag-element-backward))))
19495 (defun org-metadown (&optional arg)
19496 "Move subtree down or move table row down.
19497 Calls `org-move-subtree-down' or `org-table-move-row' or
19498 `org-move-item-down', depending on context. See the individual
19499 commands for more information."
19500 (interactive "P")
19501 (cond
19502 ((run-hook-with-args-until-success 'org-metadown-hook))
19503 ((org-region-active-p)
19504 (let* ((a (min (region-beginning) (region-end)))
19505 (b (max (region-beginning) (region-end)))
19506 (c (save-excursion (goto-char b)
19507 (move-beginning-of-line 1)))
19508 (d (save-excursion (goto-char b)
19509 (move-end-of-line 1) (1+ (point)))))
19510 (transpose-regions a b c d)
19511 (goto-char d)))
19512 ((org-at-table-p) (call-interactively 'org-table-move-row))
19513 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19514 ((org-at-item-p) (call-interactively 'org-move-item-down))
19515 (t (org-drag-element-forward))))
19517 (defun org-shiftup (&optional arg)
19518 "Increase item in timestamp or increase priority of current headline.
19519 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19520 depending on context. See the individual commands for more information."
19521 (interactive "P")
19522 (cond
19523 ((run-hook-with-args-until-success 'org-shiftup-hook))
19524 ((and org-support-shift-select (org-region-active-p))
19525 (org-call-for-shift-select 'previous-line))
19526 ((org-at-timestamp-p t)
19527 (call-interactively (if org-edit-timestamp-down-means-later
19528 'org-timestamp-down 'org-timestamp-up)))
19529 ((and (not (eq org-support-shift-select 'always))
19530 org-enable-priority-commands
19531 (org-at-heading-p))
19532 (call-interactively 'org-priority-up))
19533 ((and (not org-support-shift-select) (org-at-item-p))
19534 (call-interactively 'org-previous-item))
19535 ((org-clocktable-try-shift 'up arg))
19536 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19537 (org-support-shift-select
19538 (org-call-for-shift-select 'previous-line))
19539 (t (org-shiftselect-error))))
19541 (defun org-shiftdown (&optional arg)
19542 "Decrease item in timestamp or decrease priority of current headline.
19543 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19544 depending on context. See the individual commands for more information."
19545 (interactive "P")
19546 (cond
19547 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19548 ((and org-support-shift-select (org-region-active-p))
19549 (org-call-for-shift-select 'next-line))
19550 ((org-at-timestamp-p t)
19551 (call-interactively (if org-edit-timestamp-down-means-later
19552 'org-timestamp-up 'org-timestamp-down)))
19553 ((and (not (eq org-support-shift-select 'always))
19554 org-enable-priority-commands
19555 (org-at-heading-p))
19556 (call-interactively 'org-priority-down))
19557 ((and (not org-support-shift-select) (org-at-item-p))
19558 (call-interactively 'org-next-item))
19559 ((org-clocktable-try-shift 'down arg))
19560 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19561 (org-support-shift-select
19562 (org-call-for-shift-select 'next-line))
19563 (t (org-shiftselect-error))))
19565 (defun org-shiftright (&optional arg)
19566 "Cycle the thing at point or in the current line, depending on context.
19567 Depending on context, this does one of the following:
19569 - switch a timestamp at point one day into the future
19570 - on a headline, switch to the next TODO keyword.
19571 - on an item, switch entire list to the next bullet type
19572 - on a property line, switch to the next allowed value
19573 - on a clocktable definition line, move time block into the future"
19574 (interactive "P")
19575 (cond
19576 ((run-hook-with-args-until-success 'org-shiftright-hook))
19577 ((and org-support-shift-select (org-region-active-p))
19578 (org-call-for-shift-select 'forward-char))
19579 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19580 ((and (not (eq org-support-shift-select 'always))
19581 (org-at-heading-p))
19582 (let ((org-inhibit-logging
19583 (not org-treat-S-cursor-todo-selection-as-state-change))
19584 (org-inhibit-blocking
19585 (not org-treat-S-cursor-todo-selection-as-state-change)))
19586 (org-call-with-arg 'org-todo 'right)))
19587 ((or (and org-support-shift-select
19588 (not (eq org-support-shift-select 'always))
19589 (org-at-item-bullet-p))
19590 (and (not org-support-shift-select) (org-at-item-p)))
19591 (org-call-with-arg 'org-cycle-list-bullet nil))
19592 ((and (not (eq org-support-shift-select 'always))
19593 (org-at-property-p))
19594 (call-interactively 'org-property-next-allowed-value))
19595 ((org-clocktable-try-shift 'right arg))
19596 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19597 (org-support-shift-select
19598 (org-call-for-shift-select 'forward-char))
19599 (t (org-shiftselect-error))))
19601 (defun org-shiftleft (&optional arg)
19602 "Cycle the thing at point or in the current line, depending on context.
19603 Depending on context, this does one of the following:
19605 - switch a timestamp at point one day into the past
19606 - on a headline, switch to the previous TODO keyword.
19607 - on an item, switch entire list to the previous bullet type
19608 - on a property line, switch to the previous allowed value
19609 - on a clocktable definition line, move time block into the past"
19610 (interactive "P")
19611 (cond
19612 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19613 ((and org-support-shift-select (org-region-active-p))
19614 (org-call-for-shift-select 'backward-char))
19615 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19616 ((and (not (eq org-support-shift-select 'always))
19617 (org-at-heading-p))
19618 (let ((org-inhibit-logging
19619 (not org-treat-S-cursor-todo-selection-as-state-change))
19620 (org-inhibit-blocking
19621 (not org-treat-S-cursor-todo-selection-as-state-change)))
19622 (org-call-with-arg 'org-todo 'left)))
19623 ((or (and org-support-shift-select
19624 (not (eq org-support-shift-select 'always))
19625 (org-at-item-bullet-p))
19626 (and (not org-support-shift-select) (org-at-item-p)))
19627 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19628 ((and (not (eq org-support-shift-select 'always))
19629 (org-at-property-p))
19630 (call-interactively 'org-property-previous-allowed-value))
19631 ((org-clocktable-try-shift 'left arg))
19632 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19633 (org-support-shift-select
19634 (org-call-for-shift-select 'backward-char))
19635 (t (org-shiftselect-error))))
19637 (defun org-shiftcontrolright ()
19638 "Switch to next TODO set."
19639 (interactive)
19640 (cond
19641 ((and org-support-shift-select (org-region-active-p))
19642 (org-call-for-shift-select 'forward-word))
19643 ((and (not (eq org-support-shift-select 'always))
19644 (org-at-heading-p))
19645 (org-call-with-arg 'org-todo 'nextset))
19646 (org-support-shift-select
19647 (org-call-for-shift-select 'forward-word))
19648 (t (org-shiftselect-error))))
19650 (defun org-shiftcontrolleft ()
19651 "Switch to previous TODO set."
19652 (interactive)
19653 (cond
19654 ((and org-support-shift-select (org-region-active-p))
19655 (org-call-for-shift-select 'backward-word))
19656 ((and (not (eq org-support-shift-select 'always))
19657 (org-at-heading-p))
19658 (org-call-with-arg 'org-todo 'previousset))
19659 (org-support-shift-select
19660 (org-call-for-shift-select 'backward-word))
19661 (t (org-shiftselect-error))))
19663 (defun org-shiftcontrolup (&optional n)
19664 "Change timestamps synchronously up in CLOCK log lines.
19665 Optional argument N tells to change by that many units."
19666 (interactive "P")
19667 (cond ((and (not org-support-shift-select)
19668 (org-at-clock-log-p)
19669 (org-at-timestamp-p t))
19670 (org-clock-timestamps-up n))
19671 (t (org-shiftselect-error))))
19673 (defun org-shiftcontroldown (&optional n)
19674 "Change timestamps synchronously down in CLOCK log lines.
19675 Optional argument N tells to change by that many units."
19676 (interactive "P")
19677 (cond ((and (not org-support-shift-select)
19678 (org-at-clock-log-p)
19679 (org-at-timestamp-p t))
19680 (org-clock-timestamps-down n))
19681 (t (org-shiftselect-error))))
19683 (defun org-ctrl-c-ret ()
19684 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19685 (interactive)
19686 (cond
19687 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19688 (t (call-interactively 'org-insert-heading))))
19690 (defun org-find-visible ()
19691 (let ((s (point)))
19692 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19693 (get-char-property s 'invisible)))
19695 (defun org-find-invisible ()
19696 (let ((s (point)))
19697 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19698 (not (get-char-property s 'invisible))))
19701 (defun org-copy-visible (beg end)
19702 "Copy the visible parts of the region."
19703 (interactive "r")
19704 (let (snippets s)
19705 (save-excursion
19706 (save-restriction
19707 (narrow-to-region beg end)
19708 (setq s (goto-char (point-min)))
19709 (while (not (= (point) (point-max)))
19710 (goto-char (org-find-invisible))
19711 (push (buffer-substring s (point)) snippets)
19712 (setq s (goto-char (org-find-visible))))))
19713 (kill-new (apply 'concat (nreverse snippets)))))
19715 (defun org-copy-special ()
19716 "Copy region in table or copy current subtree.
19717 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19718 See the individual commands for more information."
19719 (interactive)
19720 (call-interactively
19721 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19723 (defun org-cut-special ()
19724 "Cut region in table or cut current subtree.
19725 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19726 See the individual commands for more information."
19727 (interactive)
19728 (call-interactively
19729 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19731 (defun org-paste-special (arg)
19732 "Paste rectangular region into table, or past subtree relative to level.
19733 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19734 See the individual commands for more information."
19735 (interactive "P")
19736 (if (org-at-table-p)
19737 (org-table-paste-rectangle)
19738 (org-paste-subtree arg)))
19740 (defsubst org-in-fixed-width-region-p ()
19741 "Is point in a fixed-width region?"
19742 (save-match-data
19743 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19745 (defun org-edit-special (&optional arg)
19746 "Call a special editor for the element at point.
19747 When at a table, call the formula editor with `org-table-edit-formulas'.
19748 When in a source code block, call `org-edit-src-code'.
19749 When in a fixed-width region, call `org-edit-fixed-width-region'.
19750 When at an #+INCLUDE keyword, visit the included file.
19751 On a link, call `ffap' to visit the link at point.
19752 Otherwise, return a user error."
19753 (interactive)
19754 (let ((element (org-element-at-point)))
19755 (assert (not buffer-read-only) nil
19756 "Buffer is read-only: %s" (buffer-name))
19757 (case (org-element-type element)
19758 (src-block
19759 (if (not arg) (org-edit-src-code)
19760 (let* ((info (org-babel-get-src-block-info))
19761 (lang (nth 0 info))
19762 (params (nth 2 info))
19763 (session (cdr (assq :session params))))
19764 (if (not session) (org-edit-src-code)
19765 ;; At a src-block with a session and function called with
19766 ;; an ARG: switch to the buffer related to the inferior
19767 ;; process.
19768 (funcall (intern (concat "org-babel-prep-session:" lang))
19769 session params)))))
19770 (keyword
19771 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19772 (find-file
19773 (org-remove-double-quotes
19774 (car (org-split-string (org-element-property :value element)))))
19775 (user-error "No special environment to edit here")))
19776 (table
19777 (if (eq (org-element-property :type element) 'table.el)
19778 (org-edit-src-code)
19779 (call-interactively 'org-table-edit-formulas)))
19780 ;; Only Org tables contain `table-row' type elements.
19781 (table-row (call-interactively 'org-table-edit-formulas))
19782 ((example-block export-block) (org-edit-src-code))
19783 (fixed-width (org-edit-fixed-width-region))
19784 (otherwise
19785 ;; No notable element at point. Though, we may be at a link,
19786 ;; which is an object. Thus, scan deeper.
19787 (if (eq (org-element-type (org-element-context element)) 'link)
19788 (call-interactively 'ffap)
19789 (user-error "No special environment to edit here"))))))
19791 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19792 (defun org-ctrl-c-ctrl-c (&optional arg)
19793 "Set tags in headline, or update according to changed information at point.
19795 This command does many different things, depending on context:
19797 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19798 this is what we do.
19800 - If the cursor is on a statistics cookie, update it.
19802 - If the cursor is in a headline, prompt for tags and insert them
19803 into the current line, aligned to `org-tags-column'. When called
19804 with prefix arg, realign all tags in the current buffer.
19806 - If the cursor is in one of the special #+KEYWORD lines, this
19807 triggers scanning the buffer for these lines and updating the
19808 information.
19810 - If the cursor is inside a table, realign the table. This command
19811 works even if the automatic table editor has been turned off.
19813 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19814 the entire table.
19816 - If the cursor is at a footnote reference or definition, jump to
19817 the corresponding definition or references, respectively.
19819 - If the cursor is a the beginning of a dynamic block, update it.
19821 - If the current buffer is a capture buffer, close note and file it.
19823 - If the cursor is on a <<<target>>>, update radio targets and
19824 corresponding links in this buffer.
19826 - If the cursor is on a numbered item in a plain list, renumber the
19827 ordered list.
19829 - If the cursor is on a checkbox, toggle it.
19831 - If the cursor is on a code block, evaluate it. The variable
19832 `org-confirm-babel-evaluate' can be used to control prompting
19833 before code block evaluation, by default every code block
19834 evaluation requires confirmation. Code block evaluation can be
19835 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19836 (interactive "P")
19837 (cond
19838 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19839 org-occur-highlights
19840 org-latex-fragment-image-overlays)
19841 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19842 (org-remove-occur-highlights)
19843 (org-remove-latex-fragment-image-overlays)
19844 (message "Temporary highlights/overlays removed from current buffer"))
19845 ((and (local-variable-p 'org-finish-function (current-buffer))
19846 (fboundp org-finish-function))
19847 (funcall org-finish-function))
19848 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19850 (let* ((context (org-element-context)) (type (org-element-type context)))
19851 ;; Test if point is within a blank line.
19852 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
19853 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19854 (user-error "C-c C-c can do nothing useful at this location"))
19855 ;; For convenience: at the first line of a paragraph on the
19856 ;; same line as an item, apply function on that item instead.
19857 (when (eq type 'paragraph)
19858 (let ((parent (org-element-property :parent context)))
19859 (when (and (eq (org-element-type parent) 'item)
19860 (= (point-at-bol) (org-element-property :begin parent)))
19861 (setq context parent type 'item))))
19862 ;; Act according to type of element or object at point.
19863 (case type
19864 (clock (org-clock-update-time-maybe))
19865 (dynamic-block
19866 (save-excursion
19867 (goto-char (org-element-property :post-affiliated context))
19868 (org-update-dblock)))
19869 (footnote-definition
19870 (goto-char (org-element-property :post-affiliated context))
19871 (call-interactively 'org-footnote-action))
19872 (footnote-reference (call-interactively 'org-footnote-action))
19873 ((headline inlinetask)
19874 (save-excursion (goto-char (org-element-property :begin context))
19875 (call-interactively 'org-set-tags)))
19876 (item
19877 ;; At an item: a double C-u set checkbox to "[-]"
19878 ;; unconditionally, whereas a single one will toggle its
19879 ;; presence. Without an universal argument, if the item
19880 ;; has a checkbox, toggle it. Otherwise repair the list.
19881 (let* ((box (org-element-property :checkbox context))
19882 (struct (org-element-property :structure context))
19883 (old-struct (copy-tree struct))
19884 (parents (org-list-parents-alist struct))
19885 (prevs (org-list-prevs-alist struct))
19886 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19887 (org-list-set-checkbox
19888 (org-element-property :begin context) struct
19889 (cond ((equal arg '(16)) "[-]")
19890 ((and (not box) (equal arg '(4))) "[ ]")
19891 ((or (not box) (equal arg '(4))) nil)
19892 ((eq box 'on) "[ ]")
19893 (t "[X]")))
19894 ;; Mimic `org-list-write-struct' but with grabbing
19895 ;; a return value from `org-list-struct-fix-box'.
19896 (org-list-struct-fix-ind struct parents 2)
19897 (org-list-struct-fix-item-end struct)
19898 (org-list-struct-fix-bul struct prevs)
19899 (org-list-struct-fix-ind struct parents)
19900 (let ((block-item
19901 (org-list-struct-fix-box struct parents prevs orderedp)))
19902 (if (and box (equal struct old-struct))
19903 (if (equal arg '(16))
19904 (message "Checkboxes already reset")
19905 (user-error "Cannot toggle this checkbox: %s"
19906 (if (eq box 'on)
19907 "all subitems checked"
19908 "unchecked subitems")))
19909 (org-list-struct-apply-struct struct old-struct)
19910 (org-update-checkbox-count-maybe))
19911 (when block-item
19912 (message "Checkboxes were removed due to empty box at line %d"
19913 (org-current-line block-item))))))
19914 (keyword
19915 (let ((org-inhibit-startup-visibility-stuff t)
19916 (org-startup-align-all-tables nil))
19917 (when (boundp 'org-table-coordinate-overlays)
19918 (mapc 'delete-overlay org-table-coordinate-overlays)
19919 (setq org-table-coordinate-overlays nil))
19920 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19921 (message "Local setup has been refreshed"))
19922 (plain-list
19923 ;; At a plain list, with a double C-u argument, set
19924 ;; checkboxes of each item to "[-]", whereas a single one
19925 ;; will toggle their presence according to the state of the
19926 ;; first item in the list. Without an argument, repair the
19927 ;; list.
19928 (let* ((begin (org-element-property :contents-begin context))
19929 (struct (org-element-property :structure context))
19930 (old-struct (copy-tree struct))
19931 (first-box (save-excursion
19932 (goto-char begin)
19933 (looking-at org-list-full-item-re)
19934 (match-string-no-properties 3)))
19935 (new-box (cond ((equal arg '(16)) "[-]")
19936 ((equal arg '(4)) (unless first-box "[ ]"))
19937 ((equal first-box "[X]") "[ ]")
19938 (t "[X]"))))
19939 (cond
19940 (arg
19941 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19942 (org-list-get-all-items
19943 begin struct (org-list-prevs-alist struct))))
19944 ((and first-box (eq (point) begin))
19945 ;; For convenience, when point is at bol on the first
19946 ;; item of the list and no argument is provided, simply
19947 ;; toggle checkbox of that item, if any.
19948 (org-list-set-checkbox begin struct new-box)))
19949 (org-list-write-struct
19950 struct (org-list-parents-alist struct) old-struct)
19951 (org-update-checkbox-count-maybe)
19952 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19953 ((property-drawer node-property)
19954 (call-interactively 'org-property-action))
19955 ((radio-target target)
19956 (call-interactively 'org-update-radio-target-regexp))
19957 (statistics-cookie
19958 (call-interactively 'org-update-statistics-cookies))
19959 ((table table-cell table-row)
19960 ;; At a table, recalculate every field and align it. Also
19961 ;; send the table if necessary. If the table has
19962 ;; a `table.el' type, just give up. At a table row or
19963 ;; cell, maybe recalculate line but always align table.
19964 (if (eq (org-element-property :type context) 'table.el)
19965 (message "Use C-c ' to edit table.el tables")
19966 (let ((org-enable-table-editor t))
19967 (if (or (eq type 'table)
19968 ;; Check if point is at a TBLFM line.
19969 (and (eq type 'table-row)
19970 (= (point) (org-element-property :end context))))
19971 (save-excursion
19972 (goto-char (org-element-property :contents-begin context))
19973 (org-call-with-arg 'org-table-recalculate (or arg t))
19974 (orgtbl-send-table 'maybe))
19975 (org-table-maybe-eval-formula)
19976 (cond (arg (call-interactively 'org-table-recalculate))
19977 ((org-table-maybe-recalculate-line))
19978 (t (org-table-align)))))))
19979 (timestamp (org-timestamp-change 0 'day))
19980 (otherwise
19981 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19982 (user-error
19983 "C-c C-c can do nothing useful at this location")))))))))
19985 (defun org-mode-restart ()
19986 "Restart Org-mode, to scan again for special lines.
19987 Also updates the keyword regular expressions."
19988 (interactive)
19989 (org-mode)
19990 (message "Org-mode restarted"))
19992 (defun org-kill-note-or-show-branches ()
19993 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19994 (interactive)
19995 (if (not org-finish-function)
19996 (progn
19997 (hide-subtree)
19998 (call-interactively 'show-branches))
19999 (let ((org-note-abort t))
20000 (funcall org-finish-function))))
20002 (defun org-return (&optional indent)
20003 "Goto next table row or insert a newline.
20004 Calls `org-table-next-row' or `newline', depending on context.
20005 See the individual commands for more information."
20006 (interactive)
20007 (let (org-ts-what)
20008 (cond
20009 ((or (bobp) (org-in-src-block-p))
20010 (if indent (newline-and-indent) (newline)))
20011 ((org-at-table-p)
20012 (org-table-justify-field-maybe)
20013 (call-interactively 'org-table-next-row))
20014 ;; when `newline-and-indent' is called within a list, make sure
20015 ;; text moved stays inside the item.
20016 ((and (org-in-item-p) indent)
20017 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20018 (progn
20019 (save-match-data (newline))
20020 (org-indent-line-to (length (match-string 0))))
20021 (let ((ind (org-get-indentation)))
20022 (newline)
20023 (if (org-looking-back org-list-end-re)
20024 (org-indent-line)
20025 (org-indent-line-to ind)))))
20026 ((and org-return-follows-link
20027 (org-at-timestamp-p t)
20028 (not (eq org-ts-what 'after)))
20029 (org-follow-timestamp-link))
20030 ((and org-return-follows-link
20031 (let ((tprop (get-text-property (point) 'face)))
20032 (or (eq tprop 'org-link)
20033 (and (listp tprop) (memq 'org-link tprop)))))
20034 (call-interactively 'org-open-at-point))
20035 ((and (org-at-heading-p)
20036 (looking-at
20037 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20038 (org-show-entry)
20039 (end-of-line 1)
20040 (newline))
20041 (t (if indent (newline-and-indent) (newline))))))
20043 (defun org-return-indent ()
20044 "Goto next table row or insert a newline and indent.
20045 Calls `org-table-next-row' or `newline-and-indent', depending on
20046 context. See the individual commands for more information."
20047 (interactive)
20048 (org-return t))
20050 (defun org-ctrl-c-star ()
20051 "Compute table, or change heading status of lines.
20052 Calls `org-table-recalculate' or `org-toggle-heading',
20053 depending on context."
20054 (interactive)
20055 (cond
20056 ((org-at-table-p)
20057 (call-interactively 'org-table-recalculate))
20059 ;; Convert all lines in region to list items
20060 (call-interactively 'org-toggle-heading))))
20062 (defun org-ctrl-c-minus ()
20063 "Insert separator line in table or modify bullet status of line.
20064 Also turns a plain line or a region of lines into list items.
20065 Calls `org-table-insert-hline', `org-toggle-item', or
20066 `org-cycle-list-bullet', depending on context."
20067 (interactive)
20068 (cond
20069 ((org-at-table-p)
20070 (call-interactively 'org-table-insert-hline))
20071 ((org-region-active-p)
20072 (call-interactively 'org-toggle-item))
20073 ((org-in-item-p)
20074 (call-interactively 'org-cycle-list-bullet))
20076 (call-interactively 'org-toggle-item))))
20078 (defun org-toggle-item (arg)
20079 "Convert headings or normal lines to items, items to normal lines.
20080 If there is no active region, only the current line is considered.
20082 If the first non blank line in the region is a headline, convert
20083 all headlines to items, shifting text accordingly.
20085 If it is an item, convert all items to normal lines.
20087 If it is normal text, change region into a list of items.
20088 With a prefix argument ARG, change the region in a single item."
20089 (interactive "P")
20090 (let ((shift-text
20091 (function
20092 ;; Shift text in current section to IND, from point to END.
20093 ;; The function leaves point to END line.
20094 (lambda (ind end)
20095 (let ((min-i 1000) (end (copy-marker end)))
20096 ;; First determine the minimum indentation (MIN-I) of
20097 ;; the text.
20098 (save-excursion
20099 (catch 'exit
20100 (while (< (point) end)
20101 (let ((i (org-get-indentation)))
20102 (cond
20103 ;; Skip blank lines and inline tasks.
20104 ((looking-at "^[ \t]*$"))
20105 ((looking-at org-outline-regexp-bol))
20106 ;; We can't find less than 0 indentation.
20107 ((zerop i) (throw 'exit (setq min-i 0)))
20108 ((< i min-i) (setq min-i i))))
20109 (forward-line))))
20110 ;; Then indent each line so that a line indented to
20111 ;; MIN-I becomes indented to IND. Ignore blank lines
20112 ;; and inline tasks in the process.
20113 (let ((delta (- ind min-i)))
20114 (while (< (point) end)
20115 (unless (or (looking-at "^[ \t]*$")
20116 (looking-at org-outline-regexp-bol))
20117 (org-indent-line-to (+ (org-get-indentation) delta)))
20118 (forward-line)))))))
20119 (skip-blanks
20120 (function
20121 ;; Return beginning of first non-blank line, starting from
20122 ;; line at POS.
20123 (lambda (pos)
20124 (save-excursion
20125 (goto-char pos)
20126 (skip-chars-forward " \r\t\n")
20127 (point-at-bol)))))
20128 beg end)
20129 ;; Determine boundaries of changes.
20130 (if (org-region-active-p)
20131 (setq beg (funcall skip-blanks (region-beginning))
20132 end (copy-marker (region-end)))
20133 (setq beg (funcall skip-blanks (point-at-bol))
20134 end (copy-marker (point-at-eol))))
20135 ;; Depending on the starting line, choose an action on the text
20136 ;; between BEG and END.
20137 (org-with-limited-levels
20138 (save-excursion
20139 (goto-char beg)
20140 (cond
20141 ;; Case 1. Start at an item: de-itemize. Note that it only
20142 ;; happens when a region is active: `org-ctrl-c-minus'
20143 ;; would call `org-cycle-list-bullet' otherwise.
20144 ((org-at-item-p)
20145 (while (< (point) end)
20146 (when (org-at-item-p)
20147 (skip-chars-forward " \t")
20148 (delete-region (point) (match-end 0)))
20149 (forward-line)))
20150 ;; Case 2. Start at an heading: convert to items.
20151 ((org-at-heading-p)
20152 (let* ((bul (org-list-bullet-string "-"))
20153 (bul-len (length bul))
20154 ;; Indentation of the first heading. It should be
20155 ;; relative to the indentation of its parent, if any.
20156 (start-ind (save-excursion
20157 (cond
20158 ((not org-adapt-indentation) 0)
20159 ((not (outline-previous-heading)) 0)
20160 (t (length (match-string 0))))))
20161 ;; Level of first heading. Further headings will be
20162 ;; compared to it to determine hierarchy in the list.
20163 (ref-level (org-reduced-level (org-outline-level))))
20164 (while (< (point) end)
20165 (let* ((level (org-reduced-level (org-outline-level)))
20166 (delta (max 0 (- level ref-level))))
20167 ;; If current headline is less indented than the first
20168 ;; one, set it as reference, in order to preserve
20169 ;; subtrees.
20170 (when (< level ref-level) (setq ref-level level))
20171 (replace-match bul t t)
20172 (org-indent-line-to (+ start-ind (* delta bul-len)))
20173 ;; Ensure all text down to END (or SECTION-END) belongs
20174 ;; to the newly created item.
20175 (let ((section-end (save-excursion
20176 (or (outline-next-heading) (point)))))
20177 (forward-line)
20178 (funcall shift-text
20179 (+ start-ind (* (1+ delta) bul-len))
20180 (min end section-end)))))))
20181 ;; Case 3. Normal line with ARG: make the first line of region
20182 ;; an item, and shift indentation of others lines to
20183 ;; set them as item's body.
20184 (arg (let* ((bul (org-list-bullet-string "-"))
20185 (bul-len (length bul))
20186 (ref-ind (org-get-indentation)))
20187 (skip-chars-forward " \t")
20188 (insert bul)
20189 (forward-line)
20190 (while (< (point) end)
20191 ;; Ensure that lines less indented than first one
20192 ;; still get included in item body.
20193 (funcall shift-text
20194 (+ ref-ind bul-len)
20195 (min end (save-excursion (or (outline-next-heading)
20196 (point)))))
20197 (forward-line))))
20198 ;; Case 4. Normal line without ARG: turn each non-item line
20199 ;; into an item.
20201 (while (< (point) end)
20202 (unless (or (org-at-heading-p) (org-at-item-p))
20203 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20204 (replace-match
20205 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20206 (forward-line))))))))
20208 (defun org-toggle-heading (&optional nstars)
20209 "Convert headings to normal text, or items or text to headings.
20210 If there is no active region, only convert the current line.
20212 With a \\[universal-argument] prefix, convert the whole list at
20213 point into heading.
20215 In a region:
20217 - If the first non blank line is a headline, remove the stars
20218 from all headlines in the region.
20220 - If it is a normal line, turn each and every normal line (i.e.,
20221 not an heading or an item) in the region into headings. If you
20222 want to convert only the first line of this region, use one
20223 universal prefix argument.
20225 - If it is a plain list item, turn all plain list items into headings.
20227 When converting a line into a heading, the number of stars is chosen
20228 such that the lines become children of the current entry. However,
20229 when a numeric prefix argument is given, its value determines the
20230 number of stars to add."
20231 (interactive "P")
20232 (let ((skip-blanks
20233 (function
20234 ;; Return beginning of first non-blank line, starting from
20235 ;; line at POS.
20236 (lambda (pos)
20237 (save-excursion
20238 (goto-char pos)
20239 (while (org-at-comment-p) (forward-line))
20240 (skip-chars-forward " \r\t\n")
20241 (point-at-bol)))))
20242 beg end toggled)
20243 ;; Determine boundaries of changes. If a universal prefix has
20244 ;; been given, put the list in a region. If region ends at a bol,
20245 ;; do not consider the last line to be in the region.
20247 (when (and current-prefix-arg (org-at-item-p))
20248 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20249 (org-mark-element))
20251 (if (org-region-active-p)
20252 (setq beg (funcall skip-blanks (region-beginning))
20253 end (copy-marker (save-excursion
20254 (goto-char (region-end))
20255 (if (bolp) (point) (point-at-eol)))))
20256 (setq beg (funcall skip-blanks (point-at-bol))
20257 end (copy-marker (point-at-eol))))
20258 ;; Ensure inline tasks don't count as headings.
20259 (org-with-limited-levels
20260 (save-excursion
20261 (goto-char beg)
20262 (cond
20263 ;; Case 1. Started at an heading: de-star headings.
20264 ((org-at-heading-p)
20265 (while (< (point) end)
20266 (when (org-at-heading-p t)
20267 (looking-at org-outline-regexp) (replace-match "")
20268 (setq toggled t))
20269 (forward-line)))
20270 ;; Case 2. Started at an item: change items into headlines.
20271 ;; One star will be added by `org-list-to-subtree'.
20272 ((org-at-item-p)
20273 (let* ((stars (make-string
20274 ;; subtract the star that will be added again by
20275 ;; `org-list-to-subtree'
20276 (if (numberp nstars) (1- nstars)
20277 (or (org-current-level) 0))
20278 ?*))
20279 (add-stars
20280 (cond (nstars "") ; stars from prefix only
20281 ((equal stars "") "") ; before first heading
20282 (org-odd-levels-only "*") ; inside heading, odd
20283 (t "")))) ; inside heading, oddeven
20284 (while (< (point) end)
20285 (when (org-at-item-p)
20286 ;; Pay attention to cases when region ends before list.
20287 (let* ((struct (org-list-struct))
20288 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20289 (save-restriction
20290 (narrow-to-region (point) list-end)
20291 (insert
20292 (org-list-to-subtree
20293 (org-list-parse-list t)
20294 '(:istart (concat stars add-stars (funcall get-stars depth))
20295 :icount (concat stars add-stars (funcall get-stars depth)))))))
20296 (setq toggled t))
20297 (forward-line))))
20298 ;; Case 3. Started at normal text: make every line an heading,
20299 ;; skipping headlines and items.
20300 (t (let* ((stars
20301 (make-string
20302 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20303 (add-stars
20304 (cond (nstars "") ; stars from prefix only
20305 ((equal stars "") "*") ; before first heading
20306 (org-odd-levels-only "**") ; inside heading, odd
20307 (t "*"))) ; inside heading, oddeven
20308 (rpl (concat stars add-stars " "))
20309 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20310 (while (< (point) (if (equal nstars '(4)) lend end))
20311 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20312 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20313 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20314 (forward-line)))))))
20315 (unless toggled (message "Cannot toggle heading from here"))))
20317 (defun org-meta-return (&optional arg)
20318 "Insert a new heading or wrap a region in a table.
20319 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20320 See the individual commands for more information."
20321 (interactive "P")
20322 (cond
20323 ((run-hook-with-args-until-success 'org-metareturn-hook))
20324 ((or (org-at-drawer-p) (org-at-property-p))
20325 (newline-and-indent))
20326 ((org-at-table-p)
20327 (call-interactively 'org-table-wrap-region))
20328 (t (call-interactively 'org-insert-heading))))
20330 ;;; Menu entries
20332 (defsubst org-in-subtree-not-table-p ()
20333 "Are we in a subtree and not in a table?"
20334 (and (not (org-before-first-heading-p))
20335 (not (org-at-table-p))))
20337 ;; Define the Org-mode menus
20338 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20339 '("Tbl"
20340 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20341 ["Next Field" org-cycle (org-at-table-p)]
20342 ["Previous Field" org-shifttab (org-at-table-p)]
20343 ["Next Row" org-return (org-at-table-p)]
20344 "--"
20345 ["Blank Field" org-table-blank-field (org-at-table-p)]
20346 ["Edit Field" org-table-edit-field (org-at-table-p)]
20347 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20348 "--"
20349 ("Column"
20350 ["Move Column Left" org-metaleft (org-at-table-p)]
20351 ["Move Column Right" org-metaright (org-at-table-p)]
20352 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20353 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20354 ("Row"
20355 ["Move Row Up" org-metaup (org-at-table-p)]
20356 ["Move Row Down" org-metadown (org-at-table-p)]
20357 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20358 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20359 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20360 "--"
20361 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20362 ("Rectangle"
20363 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20364 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20365 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20366 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20367 "--"
20368 ("Calculate"
20369 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20370 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20371 ["Edit Formulas" org-edit-special (org-at-table-p)]
20372 "--"
20373 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20374 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20375 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20376 "--"
20377 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20378 "--"
20379 ["Sum Column/Rectangle" org-table-sum
20380 (or (org-at-table-p) (org-region-active-p))]
20381 ["Which Column?" org-table-current-column (org-at-table-p)])
20382 ["Debug Formulas"
20383 org-table-toggle-formula-debugger
20384 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20385 ["Show Col/Row Numbers"
20386 org-table-toggle-coordinate-overlays
20387 :style toggle
20388 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20389 "--"
20390 ["Create" org-table-create (and (not (org-at-table-p))
20391 org-enable-table-editor)]
20392 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20393 ["Import from File" org-table-import (not (org-at-table-p))]
20394 ["Export to File" org-table-export (org-at-table-p)]
20395 "--"
20396 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20398 (easy-menu-define org-org-menu org-mode-map "Org menu"
20399 '("Org"
20400 ("Show/Hide"
20401 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20402 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20403 ["Sparse Tree..." org-sparse-tree t]
20404 ["Reveal Context" org-reveal t]
20405 ["Show All" show-all t]
20406 "--"
20407 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20408 "--"
20409 ["New Heading" org-insert-heading t]
20410 ("Navigate Headings"
20411 ["Up" outline-up-heading t]
20412 ["Next" outline-next-visible-heading t]
20413 ["Previous" outline-previous-visible-heading t]
20414 ["Next Same Level" outline-forward-same-level t]
20415 ["Previous Same Level" outline-backward-same-level t]
20416 "--"
20417 ["Jump" org-goto t])
20418 ("Edit Structure"
20419 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20420 "--"
20421 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20422 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20423 "--"
20424 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20425 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20426 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20427 "--"
20428 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20429 "--"
20430 ["Copy visible text" org-copy-visible t]
20431 "--"
20432 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20433 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20434 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20435 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20436 "--"
20437 ["Sort Region/Children" org-sort t]
20438 "--"
20439 ["Convert to odd levels" org-convert-to-odd-levels t]
20440 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20441 ("Editing"
20442 ["Emphasis..." org-emphasize t]
20443 ["Edit Source Example" org-edit-special t]
20444 "--"
20445 ["Footnote new/jump" org-footnote-action t]
20446 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20447 ("Archive"
20448 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20449 "--"
20450 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20451 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20452 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20454 "--"
20455 ("Hyperlinks"
20456 ["Store Link (Global)" org-store-link t]
20457 ["Find existing link to here" org-occur-link-in-agenda-files t]
20458 ["Insert Link" org-insert-link t]
20459 ["Follow Link" org-open-at-point t]
20460 "--"
20461 ["Next link" org-next-link t]
20462 ["Previous link" org-previous-link t]
20463 "--"
20464 ["Descriptive Links"
20465 org-toggle-link-display
20466 :style radio
20467 :selected org-descriptive-links
20469 ["Literal Links"
20470 org-toggle-link-display
20471 :style radio
20472 :selected (not org-descriptive-links)])
20473 "--"
20474 ("TODO Lists"
20475 ["TODO/DONE/-" org-todo t]
20476 ("Select keyword"
20477 ["Next keyword" org-shiftright (org-at-heading-p)]
20478 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20479 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20480 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20481 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20482 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20483 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20484 "--"
20485 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20486 :selected org-enforce-todo-dependencies :style toggle :active t]
20487 "Settings for tree at point"
20488 ["Do Children sequentially" org-toggle-ordered-property :style radio
20489 :selected (org-entry-get nil "ORDERED")
20490 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20491 ["Do Children parallel" org-toggle-ordered-property :style radio
20492 :selected (not (org-entry-get nil "ORDERED"))
20493 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20494 "--"
20495 ["Set Priority" org-priority t]
20496 ["Priority Up" org-shiftup t]
20497 ["Priority Down" org-shiftdown t]
20498 "--"
20499 ["Get news from all feeds" org-feed-update-all t]
20500 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20501 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20502 ("TAGS and Properties"
20503 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20504 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20505 "--"
20506 ["Set property" org-set-property (not (org-before-first-heading-p))]
20507 ["Column view of properties" org-columns t]
20508 ["Insert Column View DBlock" org-insert-columns-dblock t])
20509 ("Dates and Scheduling"
20510 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20511 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20512 ("Change Date"
20513 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20514 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20515 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20516 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20517 ["Compute Time Range" org-evaluate-time-range t]
20518 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20519 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20520 "--"
20521 ["Custom time format" org-toggle-time-stamp-overlays
20522 :style radio :selected org-display-custom-times]
20523 "--"
20524 ["Goto Calendar" org-goto-calendar t]
20525 ["Date from Calendar" org-date-from-calendar t]
20526 "--"
20527 ["Start/Restart Timer" org-timer-start t]
20528 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20529 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20530 ["Insert Timer String" org-timer t]
20531 ["Insert Timer Item" org-timer-item t])
20532 ("Logging work"
20533 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20534 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20535 ["Clock out" org-clock-out t]
20536 ["Clock cancel" org-clock-cancel t]
20537 "--"
20538 ["Mark as default task" org-clock-mark-default-task t]
20539 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20540 ["Goto running clock" org-clock-goto t]
20541 "--"
20542 ["Display times" org-clock-display t]
20543 ["Create clock table" org-clock-report t]
20544 "--"
20545 ["Record DONE time"
20546 (progn (setq org-log-done (not org-log-done))
20547 (message "Switching to %s will %s record a timestamp"
20548 (car org-done-keywords)
20549 (if org-log-done "automatically" "not")))
20550 :style toggle :selected org-log-done])
20551 "--"
20552 ["Agenda Command..." org-agenda t]
20553 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20554 ("File List for Agenda")
20555 ("Special views current file"
20556 ["TODO Tree" org-show-todo-tree t]
20557 ["Check Deadlines" org-check-deadlines t]
20558 ["Timeline" org-timeline t]
20559 ["Tags/Property tree" org-match-sparse-tree t])
20560 "--"
20561 ["Export/Publish..." org-export-dispatch t]
20562 ("LaTeX"
20563 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20564 :selected org-cdlatex-mode]
20565 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20566 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20567 ["Modify math symbol" org-cdlatex-math-modify
20568 (org-inside-LaTeX-fragment-p)]
20569 ["Insert citation" org-reftex-citation t]
20570 "--"
20571 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20572 "--"
20573 ("MobileOrg"
20574 ["Push Files and Views" org-mobile-push t]
20575 ["Get Captured and Flagged" org-mobile-pull t]
20576 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20577 "--"
20578 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20579 "--"
20580 ("Documentation"
20581 ["Show Version" org-version t]
20582 ["Info Documentation" org-info t])
20583 ("Customize"
20584 ["Browse Org Group" org-customize t]
20585 "--"
20586 ["Expand This Menu" org-create-customize-menu
20587 (fboundp 'customize-menu-create)])
20588 ["Send bug report" org-submit-bug-report t]
20589 "--"
20590 ("Refresh/Reload"
20591 ["Refresh setup current buffer" org-mode-restart t]
20592 ["Reload Org (after update)" org-reload t]
20593 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20596 (defun org-info (&optional node)
20597 "Read documentation for Org-mode in the info system.
20598 With optional NODE, go directly to that node."
20599 (interactive)
20600 (info (format "(org)%s" (or node ""))))
20602 ;;;###autoload
20603 (defun org-submit-bug-report ()
20604 "Submit a bug report on Org-mode via mail.
20606 Don't hesitate to report any problems or inaccurate documentation.
20608 If you don't have setup sending mail from (X)Emacs, please copy the
20609 output buffer into your mail program, as it gives us important
20610 information about your Org-mode version and configuration."
20611 (interactive)
20612 (require 'reporter)
20613 (org-load-modules-maybe)
20614 (org-require-autoloaded-modules)
20615 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20616 (reporter-submit-bug-report
20617 "emacs-orgmode@gnu.org"
20618 (org-version nil 'full)
20619 (let (list)
20620 (save-window-excursion
20621 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20622 (delete-other-windows)
20623 (erase-buffer)
20624 (insert "You are about to submit a bug report to the Org-mode mailing list.
20626 We would like to add your full Org-mode and Outline configuration to the
20627 bug report. This greatly simplifies the work of the maintainer and
20628 other experts on the mailing list.
20630 HOWEVER, some variables you have customized may contain private
20631 information. The names of customers, colleagues, or friends, might
20632 appear in the form of file names, tags, todo states, or search strings.
20633 If you answer yes to the prompt, you might want to check and remove
20634 such private information before sending the email.")
20635 (add-text-properties (point-min) (point-max) '(face org-warning))
20636 (when (yes-or-no-p "Include your Org-mode configuration ")
20637 (mapatoms
20638 (lambda (v)
20639 (and (boundp v)
20640 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20641 (or (and (symbol-value v)
20642 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20643 (and
20644 (get v 'custom-type) (get v 'standard-value)
20645 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20646 (push v list)))))
20647 (kill-buffer (get-buffer "*Warn about privacy*"))
20648 list))
20649 nil nil
20650 "Remember to cover the basics, that is, what you expected to happen and
20651 what in fact did happen. You don't know how to make a good report? See
20653 http://orgmode.org/manual/Feedback.html#Feedback
20655 Your bug report will be posted to the Org-mode mailing list.
20656 ------------------------------------------------------------------------")
20657 (save-excursion
20658 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20659 (replace-match "\\1Bug: \\3 [\\2]")))))
20662 (defun org-install-agenda-files-menu ()
20663 (let ((bl (buffer-list)))
20664 (save-excursion
20665 (while bl
20666 (set-buffer (pop bl))
20667 (if (derived-mode-p 'org-mode) (setq bl nil)))
20668 (when (derived-mode-p 'org-mode)
20669 (easy-menu-change
20670 '("Org") "File List for Agenda"
20671 (append
20672 (list
20673 ["Edit File List" (org-edit-agenda-file-list) t]
20674 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20675 ["Remove Current File from List" org-remove-file t]
20676 ["Cycle through agenda files" org-cycle-agenda-files t]
20677 ["Occur in all agenda files" org-occur-in-agenda-files t]
20678 "--")
20679 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20681 ;;;; Documentation
20683 (defun org-require-autoloaded-modules ()
20684 (interactive)
20685 (mapc 'require
20686 '(org-agenda org-archive org-attach org-clock org-colview org-id
20687 org-remember org-table org-timer)))
20689 ;;;###autoload
20690 (defun org-reload (&optional uncompiled)
20691 "Reload all org lisp files.
20692 With prefix arg UNCOMPILED, load the uncompiled versions."
20693 (interactive "P")
20694 (require 'loadhist)
20695 (let* ((org-dir (org-find-library-dir "org"))
20696 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20697 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20698 (remove-re (mapconcat 'identity
20699 (mapcar (lambda (f) (concat "^" f "$"))
20700 (list (if (featurep 'xemacs)
20701 "org-colview"
20702 "org-colview-xemacs")
20703 "org" "org-loaddefs" "org-version"))
20704 "\\|"))
20705 (feats (delete-dups
20706 (mapcar 'file-name-sans-extension
20707 (mapcar 'file-name-nondirectory
20708 (delq nil
20709 (mapcar 'feature-file
20710 features))))))
20711 (lfeat (append
20712 (sort
20713 (setq feats
20714 (delq nil (mapcar
20715 (lambda (f)
20716 (if (and (string-match feature-re f)
20717 (not (string-match remove-re f)))
20718 f nil))
20719 feats)))
20720 'string-lessp)
20721 (list "org-version" "org")))
20722 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20723 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20724 load-uncore load-misses)
20725 (setq load-misses
20726 (delq 't
20727 (mapcar (lambda (f)
20728 (or (org-load-noerror-mustsuffix (concat org-dir f))
20729 (and (string= org-dir contrib-dir)
20730 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20731 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20732 (add-to-list 'load-uncore f 'append)
20735 lfeat)))
20736 (if load-uncore
20737 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20738 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20739 (if load-misses
20740 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20741 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20742 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20744 ;;;###autoload
20745 (defun org-customize ()
20746 "Call the customize function with org as argument."
20747 (interactive)
20748 (org-load-modules-maybe)
20749 (org-require-autoloaded-modules)
20750 (customize-browse 'org))
20752 (defun org-create-customize-menu ()
20753 "Create a full customization menu for Org-mode, insert it into the menu."
20754 (interactive)
20755 (org-load-modules-maybe)
20756 (org-require-autoloaded-modules)
20757 (if (fboundp 'customize-menu-create)
20758 (progn
20759 (easy-menu-change
20760 '("Org") "Customize"
20761 `(["Browse Org group" org-customize t]
20762 "--"
20763 ,(customize-menu-create 'org)
20764 ["Set" Custom-set t]
20765 ["Save" Custom-save t]
20766 ["Reset to Current" Custom-reset-current t]
20767 ["Reset to Saved" Custom-reset-saved t]
20768 ["Reset to Standard Settings" Custom-reset-standard t]))
20769 (message "\"Org\"-menu now contains full customization menu"))
20770 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20772 ;;;; Miscellaneous stuff
20774 ;;; Generally useful functions
20776 (defun org-get-at-bol (property)
20777 "Get text property PROPERTY at beginning of line."
20778 (get-text-property (point-at-bol) property))
20780 (defun org-find-text-property-in-string (prop s)
20781 "Return the first non-nil value of property PROP in string S."
20782 (or (get-text-property 0 prop s)
20783 (get-text-property (or (next-single-property-change 0 prop s) 0)
20784 prop s)))
20786 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20787 "Display the given MESSAGE as a warning."
20788 (if (fboundp 'display-warning)
20789 (display-warning 'org message
20790 (if (featurep 'xemacs) 'warning :warning))
20791 (let ((buf (get-buffer-create "*Org warnings*")))
20792 (with-current-buffer buf
20793 (goto-char (point-max))
20794 (insert "Warning (Org): " message)
20795 (unless (bolp)
20796 (newline)))
20797 (display-buffer buf)
20798 (sit-for 0))))
20800 (defun org-eval (form)
20801 "Eval FORM and return result."
20802 (condition-case error
20803 (eval form)
20804 (error (format "%%![Error: %s]" error))))
20806 (defun org-in-clocktable-p ()
20807 "Check if the cursor is in a clocktable."
20808 (let ((pos (point)) start)
20809 (save-excursion
20810 (end-of-line 1)
20811 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20812 (setq start (match-beginning 0))
20813 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20814 (>= (match-end 0) pos)
20815 start))))
20817 (defun org-in-commented-line ()
20818 "Is point in a line starting with `#'?"
20819 (equal (char-after (point-at-bol)) ?#))
20821 (defun org-in-indented-comment-line ()
20822 "Is point in a line starting with `#' after some white space?"
20823 (save-excursion
20824 (save-match-data
20825 (goto-char (point-at-bol))
20826 (looking-at "[ \t]*#"))))
20828 (defun org-in-verbatim-emphasis ()
20829 (save-match-data
20830 (and (org-in-regexp org-emph-re 2)
20831 (>= (point) (match-beginning 3))
20832 (<= (point) (match-end 4))
20833 (member (match-string 3) '("=" "~")))))
20835 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20836 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20837 (if (and marker (marker-buffer marker)
20838 (buffer-live-p (marker-buffer marker)))
20839 (progn
20840 (org-pop-to-buffer-same-window (marker-buffer marker))
20841 (if (or (> marker (point-max)) (< marker (point-min)))
20842 (widen))
20843 (goto-char marker)
20844 (org-show-context 'org-goto))
20845 (if bookmark
20846 (bookmark-jump bookmark)
20847 (error "Cannot find location"))))
20849 (defun org-quote-csv-field (s)
20850 "Quote field for inclusion in CSV material."
20851 (if (string-match "[\",]" s)
20852 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20855 (defun org-force-self-insert (N)
20856 "Needed to enforce self-insert under remapping."
20857 (interactive "p")
20858 (self-insert-command N))
20860 (defun org-string-width (s)
20861 "Compute width of string, ignoring invisible characters.
20862 This ignores character with invisibility property `org-link', and also
20863 characters with property `org-cwidth', because these will become invisible
20864 upon the next fontification round."
20865 (let (b l)
20866 (when (or (eq t buffer-invisibility-spec)
20867 (assq 'org-link buffer-invisibility-spec))
20868 (while (setq b (text-property-any 0 (length s)
20869 'invisible 'org-link s))
20870 (setq s (concat (substring s 0 b)
20871 (substring s (or (next-single-property-change
20872 b 'invisible s) (length s)))))))
20873 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20874 (setq s (concat (substring s 0 b)
20875 (substring s (or (next-single-property-change
20876 b 'org-cwidth s) (length s))))))
20877 (setq l (string-width s) b -1)
20878 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20879 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20882 (defun org-shorten-string (s maxlength)
20883 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20884 If the string is shorter or has length MAXLENGTH, just return the
20885 original string. If it is longer, the functions finds a space in the
20886 string, breaks this string off at that locations and adds three dots
20887 as ellipsis. Including the ellipsis, the string will not be longer
20888 than MAXLENGTH. If finding a good breaking point in the string does
20889 not work, the string is just chopped off in the middle of a word
20890 if necessary."
20891 (if (<= (length s) maxlength)
20893 (let* ((n (max (- maxlength 4) 1))
20894 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20895 (if (string-match re s)
20896 (concat (match-string 1 s) "...")
20897 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20899 (defun org-get-indentation (&optional line)
20900 "Get the indentation of the current line, interpreting tabs.
20901 When LINE is given, assume it represents a line and compute its indentation."
20902 (if line
20903 (if (string-match "^ *" (org-remove-tabs line))
20904 (match-end 0))
20905 (save-excursion
20906 (beginning-of-line 1)
20907 (skip-chars-forward " \t")
20908 (current-column))))
20910 (defun org-get-string-indentation (s)
20911 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20912 (let ((n -1) (i 0) (w tab-width) c)
20913 (catch 'exit
20914 (while (< (setq n (1+ n)) (length s))
20915 (setq c (aref s n))
20916 (cond ((= c ?\ ) (setq i (1+ i)))
20917 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20918 (t (throw 'exit t)))))
20921 (defun org-remove-tabs (s &optional width)
20922 "Replace tabulators in S with spaces.
20923 Assumes that s is a single line, starting in column 0."
20924 (setq width (or width tab-width))
20925 (while (string-match "\t" s)
20926 (setq s (replace-match
20927 (make-string
20928 (- (* width (/ (+ (match-beginning 0) width) width))
20929 (match-beginning 0)) ?\ )
20930 t t s)))
20933 (defun org-fix-indentation (line ind)
20934 "Fix indentation in LINE.
20935 IND is a cons cell with target and minimum indentation.
20936 If the current indentation in LINE is smaller than the minimum,
20937 leave it alone. If it is larger than ind, set it to the target."
20938 (let* ((l (org-remove-tabs line))
20939 (i (org-get-indentation l))
20940 (i1 (car ind)) (i2 (cdr ind)))
20941 (if (>= i i2) (setq l (substring line i2)))
20942 (if (> i1 0)
20943 (concat (make-string i1 ?\ ) l)
20944 l)))
20946 (defun org-remove-indentation (code &optional n)
20947 "Remove the maximum common indentation from the lines in CODE.
20948 N may optionally be the number of spaces to remove."
20949 (with-temp-buffer
20950 (insert code)
20951 (org-do-remove-indentation n)
20952 (buffer-string)))
20954 (defun org-do-remove-indentation (&optional n)
20955 "Remove the maximum common indentation from the buffer."
20956 (untabify (point-min) (point-max))
20957 (let ((min 10000) re)
20958 (if n
20959 (setq min n)
20960 (goto-char (point-min))
20961 (while (re-search-forward "^ *[^ \n]" nil t)
20962 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20963 (unless (or (= min 0) (= min 10000))
20964 (setq re (format "^ \\{%d\\}" min))
20965 (goto-char (point-min))
20966 (while (re-search-forward re nil t)
20967 (replace-match "")
20968 (end-of-line 1))
20969 min)))
20971 (defun org-fill-template (template alist)
20972 "Find each %key of ALIST in TEMPLATE and replace it."
20973 (let ((case-fold-search nil)
20974 entry key value)
20975 (setq alist (sort (copy-sequence alist)
20976 (lambda (a b) (< (length (car a)) (length (car b))))))
20977 (while (setq entry (pop alist))
20978 (setq template
20979 (replace-regexp-in-string
20980 (concat "%" (regexp-quote (car entry)))
20981 (or (cdr entry) "") template t t)))
20982 template))
20984 (defun org-base-buffer (buffer)
20985 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20986 (if (not buffer)
20987 buffer
20988 (or (buffer-base-buffer buffer)
20989 buffer)))
20991 (defun org-trim (s)
20992 "Remove whitespace at beginning and end of string."
20993 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20994 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20997 (defun org-wrap (string &optional width lines)
20998 "Wrap string to either a number of lines, or a width in characters.
20999 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21000 that costs. If there is a word longer than WIDTH, the text is actually
21001 wrapped to the length of that word.
21002 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21003 many lines, whatever width that takes.
21004 The return value is a list of lines, without newlines at the end."
21005 (let* ((words (org-split-string string "[ \t\n]+"))
21006 (maxword (apply 'max (mapcar 'org-string-width words)))
21007 w ll)
21008 (cond (width
21009 (org-do-wrap words (max maxword width)))
21010 (lines
21011 (setq w maxword)
21012 (setq ll (org-do-wrap words maxword))
21013 (if (<= (length ll) lines)
21015 (setq ll words)
21016 (while (> (length ll) lines)
21017 (setq w (1+ w))
21018 (setq ll (org-do-wrap words w)))
21019 ll))
21020 (t (error "Cannot wrap this")))))
21022 (defun org-do-wrap (words width)
21023 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21024 (let (lines line)
21025 (while words
21026 (setq line (pop words))
21027 (while (and words (< (+ (length line) (length (car words))) width))
21028 (setq line (concat line " " (pop words))))
21029 (setq lines (push line lines)))
21030 (nreverse lines)))
21032 (defun org-split-string (string &optional separators)
21033 "Splits STRING into substrings at SEPARATORS.
21034 No empty strings are returned if there are matches at the beginning
21035 and end of string."
21036 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21037 (start 0)
21038 notfirst
21039 (list nil))
21040 (while (and (string-match rexp string
21041 (if (and notfirst
21042 (= start (match-beginning 0))
21043 (< start (length string)))
21044 (1+ start) start))
21045 (< (match-beginning 0) (length string)))
21046 (setq notfirst t)
21047 (or (eq (match-beginning 0) 0)
21048 (and (eq (match-beginning 0) (match-end 0))
21049 (eq (match-beginning 0) start))
21050 (setq list
21051 (cons (substring string start (match-beginning 0))
21052 list)))
21053 (setq start (match-end 0)))
21054 (or (eq start (length string))
21055 (setq list
21056 (cons (substring string start)
21057 list)))
21058 (nreverse list)))
21060 (defun org-quote-vert (s)
21061 "Replace \"|\" with \"\\vert\"."
21062 (while (string-match "|" s)
21063 (setq s (replace-match "\\vert" t t s)))
21066 (defun org-uuidgen-p (s)
21067 "Is S an ID created by UUIDGEN?"
21068 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21070 (defun org-in-src-block-p (&optional inside)
21071 "Whether point is in a code source block.
21072 When INSIDE is non-nil, don't consider we are within a src block
21073 when point is at #+BEGIN_SRC or #+END_SRC."
21074 (let ((case-fold-search t) ov)
21075 (or (and (setq ov (overlays-at (point)))
21076 (memq 'org-block-background
21077 (overlay-properties (car ov))))
21078 (and (not inside)
21079 (save-match-data
21080 (save-excursion
21081 (beginning-of-line)
21082 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21084 (defun org-context ()
21085 "Return a list of contexts of the current cursor position.
21086 If several contexts apply, all are returned.
21087 Each context entry is a list with a symbol naming the context, and
21088 two positions indicating start and end of the context. Possible
21089 contexts are:
21091 :headline anywhere in a headline
21092 :headline-stars on the leading stars in a headline
21093 :todo-keyword on a TODO keyword (including DONE) in a headline
21094 :tags on the TAGS in a headline
21095 :priority on the priority cookie in a headline
21096 :item on the first line of a plain list item
21097 :item-bullet on the bullet/number of a plain list item
21098 :checkbox on the checkbox in a plain list item
21099 :table in an org-mode table
21100 :table-special on a special filed in a table
21101 :table-table in a table.el table
21102 :clocktable in a clocktable
21103 :src-block in a source block
21104 :link on a hyperlink
21105 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21106 :target on a <<target>>
21107 :radio-target on a <<<radio-target>>>
21108 :latex-fragment on a LaTeX fragment
21109 :latex-preview on a LaTeX fragment with overlaid preview image
21111 This function expects the position to be visible because it uses font-lock
21112 faces as a help to recognize the following contexts: :table-special, :link,
21113 and :keyword."
21114 (let* ((f (get-text-property (point) 'face))
21115 (faces (if (listp f) f (list f)))
21116 (case-fold-search t)
21117 (p (point)) clist o)
21118 ;; First the large context
21119 (cond
21120 ((org-at-heading-p t)
21121 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21122 (when (progn
21123 (beginning-of-line 1)
21124 (looking-at org-todo-line-tags-regexp))
21125 (push (org-point-in-group p 1 :headline-stars) clist)
21126 (push (org-point-in-group p 2 :todo-keyword) clist)
21127 (push (org-point-in-group p 4 :tags) clist))
21128 (goto-char p)
21129 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21130 (if (looking-at "\\[#[A-Z0-9]\\]")
21131 (push (org-point-in-group p 0 :priority) clist)))
21133 ((org-at-item-p)
21134 (push (org-point-in-group p 2 :item-bullet) clist)
21135 (push (list :item (point-at-bol)
21136 (save-excursion (org-end-of-item) (point)))
21137 clist)
21138 (and (org-at-item-checkbox-p)
21139 (push (org-point-in-group p 0 :checkbox) clist)))
21141 ((org-at-table-p)
21142 (push (list :table (org-table-begin) (org-table-end)) clist)
21143 (if (memq 'org-formula faces)
21144 (push (list :table-special
21145 (previous-single-property-change p 'face)
21146 (next-single-property-change p 'face)) clist)))
21147 ((org-at-table-p 'any)
21148 (push (list :table-table) clist)))
21149 (goto-char p)
21151 (let ((case-fold-search t))
21152 ;; New the "medium" contexts: clocktables, source blocks
21153 (cond ((org-in-clocktable-p)
21154 (push (list :clocktable
21155 (and (or (looking-at "#\\+BEGIN: clocktable")
21156 (search-backward "#+BEGIN: clocktable" nil t))
21157 (match-beginning 0))
21158 (and (re-search-forward "#\\+END:?" nil t)
21159 (match-end 0))) clist))
21160 ((org-in-src-block-p)
21161 (push (list :src-block
21162 (and (or (looking-at "#\\+BEGIN_SRC")
21163 (search-backward "#+BEGIN_SRC" nil t))
21164 (match-beginning 0))
21165 (and (search-forward "#+END_SRC" nil t)
21166 (match-beginning 0))) clist))))
21167 (goto-char p)
21169 ;; Now the small context
21170 (cond
21171 ((org-at-timestamp-p)
21172 (push (org-point-in-group p 0 :timestamp) clist))
21173 ((memq 'org-link faces)
21174 (push (list :link
21175 (previous-single-property-change p 'face)
21176 (next-single-property-change p 'face)) clist))
21177 ((memq 'org-special-keyword faces)
21178 (push (list :keyword
21179 (previous-single-property-change p 'face)
21180 (next-single-property-change p 'face)) clist))
21181 ((org-at-target-p)
21182 (push (org-point-in-group p 0 :target) clist)
21183 (goto-char (1- (match-beginning 0)))
21184 (if (looking-at org-radio-target-regexp)
21185 (push (org-point-in-group p 0 :radio-target) clist))
21186 (goto-char p))
21187 ((setq o (car (delq nil
21188 (mapcar
21189 (lambda (x)
21190 (if (memq x org-latex-fragment-image-overlays) x))
21191 (overlays-at (point))))))
21192 (push (list :latex-fragment
21193 (overlay-start o) (overlay-end o)) clist)
21194 (push (list :latex-preview
21195 (overlay-start o) (overlay-end o)) clist))
21196 ((org-inside-LaTeX-fragment-p)
21197 ;; FIXME: positions wrong.
21198 (push (list :latex-fragment (point) (point)) clist)))
21200 (setq clist (nreverse (delq nil clist)))
21201 clist))
21203 ;; FIXME: Compare with at-regexp-p Do we need both?
21204 (defun org-in-regexp (re &optional nlines visually)
21205 "Check if point is inside a match of regexp.
21206 Normally only the current line is checked, but you can include NLINES extra
21207 lines both before and after point into the search.
21208 If VISUALLY is set, require that the cursor is not after the match but
21209 really on, so that the block visually is on the match."
21210 (catch 'exit
21211 (let ((pos (point))
21212 (eol (point-at-eol (+ 1 (or nlines 0))))
21213 (inc (if visually 1 0)))
21214 (save-excursion
21215 (beginning-of-line (- 1 (or nlines 0)))
21216 (while (re-search-forward re eol t)
21217 (if (and (<= (match-beginning 0) pos)
21218 (>= (+ inc (match-end 0)) pos))
21219 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21221 (defun org-at-regexp-p (regexp)
21222 "Is point inside a match of REGEXP in the current line?"
21223 (catch 'exit
21224 (save-excursion
21225 (let ((pos (point)) (end (point-at-eol)))
21226 (beginning-of-line 1)
21227 (while (re-search-forward regexp end t)
21228 (if (and (<= (match-beginning 0) pos)
21229 (>= (match-end 0) pos))
21230 (throw 'exit t)))
21231 nil))))
21233 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21234 "Non-nil when point is between matches of START-RE and END-RE.
21236 Also return a non-nil value when point is on one of the matches.
21238 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21239 buffer positions. Default values are the positions of headlines
21240 surrounding the point.
21242 The functions returns a cons cell whose car (resp. cdr) is the
21243 position before START-RE (resp. after END-RE)."
21244 (save-match-data
21245 (let ((pos (point))
21246 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21247 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21248 beg end)
21249 (save-excursion
21250 ;; Point is on a block when on START-RE or if START-RE can be
21251 ;; found before it...
21252 (and (or (org-at-regexp-p start-re)
21253 (re-search-backward start-re limit-up t))
21254 (setq beg (match-beginning 0))
21255 ;; ... and END-RE after it...
21256 (goto-char (match-end 0))
21257 (re-search-forward end-re limit-down t)
21258 (> (setq end (match-end 0)) pos)
21259 ;; ... without another START-RE in-between.
21260 (goto-char (match-beginning 0))
21261 (not (re-search-backward start-re (1+ beg) t))
21262 ;; Return value.
21263 (cons beg end))))))
21265 (defun org-in-block-p (names)
21266 "Non-nil when point belongs to a block whose name belongs to NAMES.
21268 NAMES is a list of strings containing names of blocks.
21270 Return first block name matched, or nil. Beware that in case of
21271 nested blocks, the returned name may not belong to the closest
21272 block from point."
21273 (save-match-data
21274 (catch 'exit
21275 (let ((case-fold-search t)
21276 (lim-up (save-excursion (outline-previous-heading)))
21277 (lim-down (save-excursion (outline-next-heading))))
21278 (mapc (lambda (name)
21279 (let ((n (regexp-quote name)))
21280 (when (org-between-regexps-p
21281 (concat "^[ \t]*#\\+begin_" n)
21282 (concat "^[ \t]*#\\+end_" n)
21283 lim-up lim-down)
21284 (throw 'exit n))))
21285 names))
21286 nil)))
21288 (defun org-occur-in-agenda-files (regexp &optional nlines)
21289 "Call `multi-occur' with buffers for all agenda files."
21290 (interactive "sOrg-files matching: \np")
21291 (let* ((files (org-agenda-files))
21292 (tnames (mapcar 'file-truename files))
21293 (extra org-agenda-text-search-extra-files)
21295 (when (eq (car extra) 'agenda-archives)
21296 (setq extra (cdr extra))
21297 (setq files (org-add-archive-files files)))
21298 (while (setq f (pop extra))
21299 (unless (member (file-truename f) tnames)
21300 (add-to-list 'files f 'append)
21301 (add-to-list 'tnames (file-truename f) 'append)))
21302 (multi-occur
21303 (mapcar (lambda (x)
21304 (with-current-buffer
21305 (or (get-file-buffer x) (find-file-noselect x))
21306 (widen)
21307 (current-buffer)))
21308 files)
21309 regexp)))
21311 (if (boundp 'occur-mode-find-occurrence-hook)
21312 ;; Emacs 23
21313 (add-hook 'occur-mode-find-occurrence-hook
21314 (lambda ()
21315 (when (derived-mode-p 'org-mode)
21316 (org-reveal))))
21317 ;; Emacs 22
21318 (defadvice occur-mode-goto-occurrence
21319 (after org-occur-reveal activate)
21320 (and (derived-mode-p 'org-mode) (org-reveal)))
21321 (defadvice occur-mode-goto-occurrence-other-window
21322 (after org-occur-reveal activate)
21323 (and (derived-mode-p 'org-mode) (org-reveal)))
21324 (defadvice occur-mode-display-occurrence
21325 (after org-occur-reveal activate)
21326 (when (derived-mode-p 'org-mode)
21327 (let ((pos (occur-mode-find-occurrence)))
21328 (with-current-buffer (marker-buffer pos)
21329 (save-excursion
21330 (goto-char pos)
21331 (org-reveal)))))))
21333 (defun org-occur-link-in-agenda-files ()
21334 "Create a link and search for it in the agendas.
21335 The link is not stored in `org-stored-links', it is just created
21336 for the search purpose."
21337 (interactive)
21338 (let ((link (condition-case nil
21339 (org-store-link nil)
21340 (error "Unable to create a link to here"))))
21341 (org-occur-in-agenda-files (regexp-quote link))))
21343 (defun org-reverse-string (string)
21344 "Return the reverse of STRING."
21345 (apply 'string (reverse (string-to-list string))))
21347 (defun org-uniquify (list)
21348 "Remove duplicate elements from LIST."
21349 (let (res)
21350 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21351 res))
21353 (defun org-delete-all (elts list)
21354 "Remove all elements in ELTS from LIST."
21355 (while elts
21356 (setq list (delete (pop elts) list)))
21357 list)
21359 (defun org-count (cl-item cl-seq)
21360 "Count the number of occurrences of ITEM in SEQ.
21361 Taken from `count' in cl-seq.el with all keyword arguments removed."
21362 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21363 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21364 (while (< cl-start cl-end)
21365 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21366 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21367 (setq cl-start (1+ cl-start)))
21368 cl-count))
21370 (defun org-remove-if (predicate seq)
21371 "Remove everything from SEQ that fulfills PREDICATE."
21372 (let (res e)
21373 (while seq
21374 (setq e (pop seq))
21375 (if (not (funcall predicate e)) (push e res)))
21376 (nreverse res)))
21378 (defun org-remove-if-not (predicate seq)
21379 "Remove everything from SEQ that does not fulfill PREDICATE."
21380 (let (res e)
21381 (while seq
21382 (setq e (pop seq))
21383 (if (funcall predicate e) (push e res)))
21384 (nreverse res)))
21386 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21387 "Reduce two-argument FUNCTION across SEQ.
21388 Taken from `reduce' in cl-seq.el with all keyword arguments but
21389 \":initial-value\" removed."
21390 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21391 (cadr (memq :initial-value cl-keys)))
21392 (cl-seq (pop cl-seq))
21393 (t (funcall cl-func)))))
21394 (while cl-seq
21395 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21396 cl-accum))
21398 (defun org-back-over-empty-lines ()
21399 "Move backwards over whitespace, to the beginning of the first empty line.
21400 Returns the number of empty lines passed."
21401 (let ((pos (point)))
21402 (if (cdr (assoc 'heading org-blank-before-new-entry))
21403 (skip-chars-backward " \t\n\r")
21404 (unless (eobp)
21405 (forward-line -1)))
21406 (beginning-of-line 2)
21407 (goto-char (min (point) pos))
21408 (count-lines (point) pos)))
21410 (defun org-skip-whitespace ()
21411 (skip-chars-forward " \t\n\r"))
21413 (defun org-point-in-group (point group &optional context)
21414 "Check if POINT is in match-group GROUP.
21415 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21416 match. If the match group does not exist or point is not inside it,
21417 return nil."
21418 (and (match-beginning group)
21419 (>= point (match-beginning group))
21420 (<= point (match-end group))
21421 (if context
21422 (list context (match-beginning group) (match-end group))
21423 t)))
21425 (defun org-switch-to-buffer-other-window (&rest args)
21426 "Switch to buffer in a second window on the current frame.
21427 In particular, do not allow pop-up frames.
21428 Returns the newly created buffer."
21429 (org-no-popups
21430 (apply 'switch-to-buffer-other-window args)))
21432 (defun org-combine-plists (&rest plists)
21433 "Create a single property list from all plists in PLISTS.
21434 The process starts by copying the first list, and then setting properties
21435 from the other lists. Settings in the last list are the most significant
21436 ones and overrule settings in the other lists."
21437 (let ((rtn (copy-sequence (pop plists)))
21438 p v ls)
21439 (while plists
21440 (setq ls (pop plists))
21441 (while ls
21442 (setq p (pop ls) v (pop ls))
21443 (setq rtn (plist-put rtn p v))))
21444 rtn))
21446 (defun org-replace-escapes (string table)
21447 "Replace %-escapes in STRING with values in TABLE.
21448 TABLE is an association list with keys like \"%a\" and string values.
21449 The sequences in STRING may contain normal field width and padding information,
21450 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21451 so values can contain further %-escapes if they are define later in TABLE."
21452 (let ((tbl (copy-alist table))
21453 (case-fold-search nil)
21454 (pchg 0)
21455 e re rpl)
21456 (while (setq e (pop tbl))
21457 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21458 (when (and (cdr e) (string-match re (cdr e)))
21459 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21460 (safe "SREF"))
21461 (add-text-properties 0 3 (list 'sref sref) safe)
21462 (setcdr e (replace-match safe t t (cdr e)))))
21463 (while (string-match re string)
21464 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21465 (cdr e)))
21466 (setq string (replace-match rpl t t string))))
21467 (while (setq pchg (next-property-change pchg string))
21468 (let ((sref (get-text-property pchg 'sref string)))
21469 (when (and sref (string-match "SREF" string pchg))
21470 (setq string (replace-match sref t t string)))))
21471 string))
21473 (defun org-sublist (list start end)
21474 "Return a section of LIST, from START to END.
21475 Counting starts at 1."
21476 (let (rtn (c start))
21477 (setq list (nthcdr (1- start) list))
21478 (while (and list (<= c end))
21479 (push (pop list) rtn)
21480 (setq c (1+ c)))
21481 (nreverse rtn)))
21483 (defun org-find-base-buffer-visiting (file)
21484 "Like `find-buffer-visiting' but always return the base buffer and
21485 not an indirect buffer."
21486 (let ((buf (or (get-file-buffer file)
21487 (find-buffer-visiting file))))
21488 (if buf
21489 (or (buffer-base-buffer buf) buf)
21490 nil)))
21492 (defun org-image-file-name-regexp (&optional extensions)
21493 "Return regexp matching the file names of images.
21494 If EXTENSIONS is given, only match these."
21495 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21496 (image-file-name-regexp)
21497 (let ((image-file-name-extensions
21498 (or extensions
21499 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21500 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21501 (concat "\\."
21502 (regexp-opt (nconc (mapcar 'upcase
21503 image-file-name-extensions)
21504 image-file-name-extensions)
21506 "\\'"))))
21508 (defun org-file-image-p (file &optional extensions)
21509 "Return non-nil if FILE is an image."
21510 (save-match-data
21511 (string-match (org-image-file-name-regexp extensions) file)))
21513 (defun org-get-cursor-date (&optional with-time)
21514 "Return the date at cursor in as a time.
21515 This works in the calendar and in the agenda, anywhere else it just
21516 returns the current time.
21517 If WITH-TIME is non-nil, returns the time of the event at point (in
21518 the agenda) or the current time of the day."
21519 (let (date day defd tp tm hod mod)
21520 (when with-time
21521 (setq tp (get-text-property (point) 'time))
21522 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21523 (setq hod (string-to-number (match-string 1 tp))
21524 mod (string-to-number (match-string 2 tp))))
21525 (or tp (setq hod (nth 2 (decode-time (current-time)))
21526 mod (nth 1 (decode-time (current-time))))))
21527 (cond
21528 ((eq major-mode 'calendar-mode)
21529 (setq date (calendar-cursor-to-date)
21530 defd (encode-time 0 (or mod 0) (or hod 0)
21531 (nth 1 date) (nth 0 date) (nth 2 date))))
21532 ((eq major-mode 'org-agenda-mode)
21533 (setq day (get-text-property (point) 'day))
21534 (if day
21535 (setq date (calendar-gregorian-from-absolute day)
21536 defd (encode-time 0 (or mod 0) (or hod 0)
21537 (nth 1 date) (nth 0 date) (nth 2 date))))))
21538 (or defd (current-time))))
21540 (defun org-mark-subtree (&optional up)
21541 "Mark the current subtree.
21542 This puts point at the start of the current subtree, and mark at
21543 the end. If a numeric prefix UP is given, move up into the
21544 hierarchy of headlines by UP levels before marking the subtree."
21545 (interactive "P")
21546 (org-with-limited-levels
21547 (cond ((org-at-heading-p) (beginning-of-line))
21548 ((org-before-first-heading-p) (error "Not in a subtree"))
21549 (t (outline-previous-visible-heading 1))))
21550 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21551 (if (org-called-interactively-p 'any)
21552 (call-interactively 'org-mark-element)
21553 (org-mark-element)))
21556 ;;; Indentation
21558 (defun org-indent-line ()
21559 "Indent line depending on context."
21560 (interactive)
21561 (let* ((pos (point))
21562 (itemp (org-at-item-p))
21563 (case-fold-search t)
21564 (org-drawer-regexp (or org-drawer-regexp "\000"))
21565 (inline-task-p (and (featurep 'org-inlinetask)
21566 (org-inlinetask-in-task-p)))
21567 (inline-re (and inline-task-p
21568 (org-inlinetask-outline-regexp)))
21569 column)
21570 (if (and orgstruct-is-++ (eq pos (point)))
21571 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21572 (indent-according-to-mode))
21573 (beginning-of-line 1)
21574 (cond
21575 ;; Headings
21576 ((looking-at org-outline-regexp) (setq column 0))
21577 ;; Footnote definition
21578 ((looking-at org-footnote-definition-re) (setq column 0))
21579 ;; Literal examples
21580 ((looking-at "[ \t]*:\\( \\|$\\)")
21581 (setq column (org-get-indentation))) ; do nothing
21582 ;; Lists
21583 ((ignore-errors (goto-char (org-in-item-p)))
21584 (setq column (if itemp
21585 (org-get-indentation)
21586 (org-list-item-body-column (point))))
21587 (goto-char pos))
21588 ;; Drawers
21589 ((and (looking-at "[ \t]*:END:")
21590 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21591 (save-excursion
21592 (goto-char (1- (match-beginning 1)))
21593 (setq column (current-column))))
21594 ;; Special blocks
21595 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21596 (save-excursion
21597 (re-search-backward
21598 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21599 (setq column (org-get-indentation (match-string 0))))
21600 ((and (not (looking-at "[ \t]*#\\+begin_"))
21601 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21602 (save-excursion
21603 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21604 (setq column
21605 (cond ((equal (downcase (match-string 1)) "src")
21606 ;; src blocks: let `org-edit-src-exit' handle them
21607 (org-get-indentation))
21608 ((equal (downcase (match-string 1)) "example")
21609 (max (org-get-indentation)
21610 (org-get-indentation (match-string 0))))
21612 (org-get-indentation (match-string 0))))))
21613 ;; This line has nothing special, look at the previous relevant
21614 ;; line to compute indentation
21616 (beginning-of-line 0)
21617 (while (and (not (bobp))
21618 (not (looking-at org-table-line-regexp))
21619 (not (looking-at org-drawer-regexp))
21620 ;; When point started in an inline task, do not move
21621 ;; above task starting line.
21622 (not (and inline-task-p (looking-at inline-re)))
21623 ;; Skip drawers, blocks, empty lines, verbatim,
21624 ;; comments, tables, footnotes definitions, lists,
21625 ;; inline tasks.
21626 (or (and (looking-at "[ \t]*:END:")
21627 (re-search-backward org-drawer-regexp nil t))
21628 (and (looking-at "[ \t]*#\\+end_")
21629 (re-search-backward "[ \t]*#\\+begin_"nil t))
21630 (looking-at "[ \t]*[\n:#|]")
21631 (looking-at org-footnote-definition-re)
21632 (and (ignore-errors (goto-char (org-in-item-p)))
21633 (goto-char
21634 (org-list-get-top-point (org-list-struct))))
21635 (and (not inline-task-p)
21636 (featurep 'org-inlinetask)
21637 (org-inlinetask-in-task-p)
21638 (or (org-inlinetask-goto-beginning) t))))
21639 (beginning-of-line 0))
21640 (cond
21641 ;; There was an heading above.
21642 ((looking-at "\\*+[ \t]+")
21643 (if (not org-adapt-indentation)
21644 (setq column 0)
21645 (goto-char (match-end 0))
21646 (setq column (current-column))))
21647 ;; A drawer had started and is unfinished
21648 ((looking-at org-drawer-regexp)
21649 (goto-char (1- (match-beginning 1)))
21650 (setq column (current-column)))
21651 ;; Else, nothing noticeable found: get indentation and go on.
21652 (t (setq column (org-get-indentation))))))
21653 ;; Now apply indentation and move cursor accordingly
21654 (goto-char pos)
21655 (if (<= (current-column) (current-indentation))
21656 (org-indent-line-to column)
21657 (save-excursion (org-indent-line-to column)))
21658 ;; Special polishing for properties, see `org-property-format'
21659 (setq column (current-column))
21660 (beginning-of-line 1)
21661 (if (looking-at
21662 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21663 (replace-match (concat (match-string 1)
21664 (format org-property-format
21665 (match-string 2) (match-string 3)))
21666 t t))
21667 (org-move-to-column column))))
21669 (defun org-indent-drawer ()
21670 "Indent the drawer at point."
21671 (interactive)
21672 (let ((p (point))
21673 (e (and (save-excursion (re-search-forward ":END:" nil t))
21674 (match-end 0)))
21675 (folded
21676 (save-excursion
21677 (end-of-line)
21678 (when (overlays-at (point))
21679 (member 'invisible (overlay-properties
21680 (car (overlays-at (point)))))))))
21681 (when folded (org-cycle))
21682 (indent-for-tab-command)
21683 (while (and (move-beginning-of-line 2) (< (point) e))
21684 (indent-for-tab-command))
21685 (goto-char p)
21686 (when folded (org-cycle)))
21687 (message "Drawer at point indented"))
21689 (defun org-indent-block ()
21690 "Indent the block at point."
21691 (interactive)
21692 (let ((p (point))
21693 (case-fold-search t)
21694 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21695 (match-end 0)))
21696 (folded
21697 (save-excursion
21698 (end-of-line)
21699 (when (overlays-at (point))
21700 (member 'invisible (overlay-properties
21701 (car (overlays-at (point)))))))))
21702 (when folded (org-cycle))
21703 (indent-for-tab-command)
21704 (while (and (move-beginning-of-line 2) (< (point) e))
21705 (indent-for-tab-command))
21706 (goto-char p)
21707 (when folded (org-cycle)))
21708 (message "Block at point indented"))
21710 (defun org-indent-region (start end)
21711 "Indent region."
21712 (interactive "r")
21713 (save-excursion
21714 (let ((line-end (org-current-line end)))
21715 (goto-char start)
21716 (while (< (org-current-line) line-end)
21717 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21718 (t (call-interactively 'org-indent-line)))
21719 (move-beginning-of-line 2)))))
21722 ;;; Filling
21724 ;; We use our own fill-paragraph and auto-fill functions.
21726 ;; `org-fill-paragraph' relies on adaptive filling and context
21727 ;; checking. Appropriate `fill-prefix' is computed with
21728 ;; `org-adaptive-fill-function'.
21730 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21731 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21732 ;; `org-adaptive-fill-function' value. Internally,
21733 ;; `org-comment-line-break-function' breaks the line.
21735 ;; `org-setup-filling' installs filling and auto-filling related
21736 ;; variables during `org-mode' initialization.
21738 (defun org-setup-filling ()
21739 (interactive)
21740 ;; Prevent auto-fill from inserting unwanted new items.
21741 (when (boundp 'fill-nobreak-predicate)
21742 (org-set-local
21743 'fill-nobreak-predicate
21744 (org-uniquify
21745 (append fill-nobreak-predicate
21746 '(org-fill-paragraph-separate-nobreak-p
21747 org-fill-line-break-nobreak-p
21748 org-fill-paragraph-with-timestamp-nobreak-p)))))
21749 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21750 (org-set-local 'auto-fill-inhibit-regexp nil)
21751 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21752 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21753 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21755 (defvar org-element-paragraph-separate) ; org-element.el
21756 (defun org-fill-paragraph-separate-nobreak-p ()
21757 "Non-nil when a line break at point would insert a new item."
21758 (looking-at (substring org-element-paragraph-separate 1)))
21760 (defun org-fill-line-break-nobreak-p ()
21761 "Non-nil when a line break at point would create an Org line break."
21762 (save-excursion
21763 (skip-chars-backward "[ \t]")
21764 (skip-chars-backward "\\\\")
21765 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21767 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21768 "Non-nil when a line break at point would insert a new item."
21769 (and (org-at-timestamp-p t)
21770 (not (looking-at org-ts-regexp-both))))
21772 (declare-function message-in-body-p "message" ())
21773 (defvar orgtbl-line-start-regexp) ; From org-table.el
21774 (defun org-adaptive-fill-function ()
21775 "Compute a fill prefix for the current line.
21776 Return fill prefix, as a string, or nil if current line isn't
21777 meant to be filled."
21778 (let (prefix)
21779 (catch 'exit
21780 (when (derived-mode-p 'message-mode)
21781 (save-excursion
21782 (beginning-of-line)
21783 (cond ((or (not (message-in-body-p))
21784 (looking-at orgtbl-line-start-regexp))
21785 (throw 'exit nil))
21786 ((looking-at message-cite-prefix-regexp)
21787 (throw 'exit (match-string-no-properties 0)))
21788 ((looking-at org-outline-regexp)
21789 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21790 (org-with-wide-buffer
21791 (let* ((p (line-beginning-position))
21792 (element (save-excursion (beginning-of-line)
21793 (org-element-at-point)))
21794 (type (org-element-type element))
21795 (post-affiliated (org-element-property :post-affiliated element)))
21796 (unless (and post-affiliated (< p post-affiliated))
21797 (case type
21798 (comment (looking-at "[ \t]*# ?") (match-string 0))
21799 (footnote-definition "")
21800 ((item plain-list)
21801 (make-string (org-list-item-body-column
21802 (or post-affiliated
21803 (org-element-property :begin element)))
21804 ? ))
21805 (paragraph
21806 ;; Fill prefix is usually the same as the current line,
21807 ;; except if the paragraph is at the beginning of an item.
21808 (let ((parent (org-element-property :parent element)))
21809 (cond ((eq (org-element-type parent) 'item)
21810 (make-string (org-list-item-body-column
21811 (org-element-property :begin parent))
21812 ? ))
21813 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21814 (match-string 0))
21815 (t ""))))
21816 (comment-block
21817 ;; Only fill contents if P is within block boundaries.
21818 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21819 (forward-line)
21820 (point)))
21821 (cend (save-excursion
21822 (goto-char (org-element-property :end element))
21823 (skip-chars-backward " \r\t\n")
21824 (line-beginning-position))))
21825 (when (and (>= p cbeg) (< p cend))
21826 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21827 (match-string 0)
21828 "")))))))))))
21830 (declare-function message-goto-body "message" ())
21831 (defvar message-cite-prefix-regexp) ; From message.el
21832 (defun org-fill-paragraph (&optional justify)
21833 "Fill element at point, when applicable.
21835 This function only applies to comment blocks, comments, example
21836 blocks and paragraphs. Also, as a special case, re-align table
21837 when point is at one.
21839 If JUSTIFY is non-nil (interactively, with prefix argument),
21840 justify as well. If `sentence-end-double-space' is non-nil, then
21841 period followed by one space does not end a sentence, so don't
21842 break a line there. The variable `fill-column' controls the
21843 width for filling.
21845 For convenience, when point is at a plain list, an item or
21846 a footnote definition, try to fill the first paragraph within."
21847 (interactive)
21848 (if (and (derived-mode-p 'message-mode)
21849 (or (not (message-in-body-p))
21850 (save-excursion (move-beginning-of-line 1)
21851 (looking-at message-cite-prefix-regexp))))
21852 ;; First ensure filling is correct in message-mode.
21853 (let ((fill-paragraph-function
21854 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21855 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21856 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21857 (paragraph-separate
21858 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21859 (fill-paragraph nil))
21860 (with-syntax-table org-mode-transpose-word-syntax-table
21861 ;; Move to end of line in order to get the first paragraph
21862 ;; within a plain list or a footnote definition.
21863 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
21864 ;; First check if point is in a blank line at the beginning of
21865 ;; the buffer. In that case, ignore filling.
21866 (case (org-element-type element)
21867 ;; Use major mode filling function is src blocks.
21868 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21869 ;; Align Org tables, leave table.el tables as-is.
21870 (table-row (org-table-align) t)
21871 (table
21872 (when (eq (org-element-property :type element) 'org)
21873 (org-table-align))
21875 (paragraph
21876 ;; Paragraphs may contain `line-break' type objects.
21877 (let ((beg (max (point-min)
21878 (org-element-property :contents-begin element)))
21879 (end (min (point-max)
21880 (org-element-property :contents-end element))))
21881 ;; Do nothing if point is at an affiliated keyword.
21882 (if (< (line-end-position) beg) t
21883 (when (derived-mode-p 'message-mode)
21884 ;; In `message-mode', do not fill following citation
21885 ;; in current paragraph nor text before message body.
21886 (let ((body-start (save-excursion (message-goto-body))))
21887 (when body-start (setq beg (max body-start beg))))
21888 (when (save-excursion
21889 (re-search-forward
21890 (concat "^" message-cite-prefix-regexp) end t))
21891 (setq end (match-beginning 0))))
21892 ;; Fill paragraph, taking line breaks into account.
21893 ;; For that, slice the paragraph using line breaks as
21894 ;; separators, and fill the parts in reverse order to
21895 ;; avoid messing with markers.
21896 (save-excursion
21897 (goto-char end)
21898 (mapc
21899 (lambda (pos)
21900 (fill-region-as-paragraph pos (point) justify)
21901 (goto-char pos))
21902 ;; Find the list of ending positions for line breaks
21903 ;; in the current paragraph. Add paragraph
21904 ;; beginning to include first slice.
21905 (nreverse
21906 (cons beg
21907 (org-element-map
21908 (org-element--parse-objects
21909 beg end nil (org-element-restriction 'paragraph))
21910 'line-break
21911 (lambda (lb) (org-element-property :end lb)))))))
21912 t)))
21913 ;; Contents of `comment-block' type elements should be
21914 ;; filled as plain text, but only if point is within block
21915 ;; markers.
21916 (comment-block
21917 (let* ((case-fold-search t)
21918 (beg (save-excursion
21919 (goto-char (org-element-property :begin element))
21920 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21921 (forward-line)
21922 (point)))
21923 (end (save-excursion
21924 (goto-char (org-element-property :end element))
21925 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21926 (line-beginning-position))))
21927 (when (and (>= (point) beg) (< (point) end))
21928 (fill-region-as-paragraph
21929 (save-excursion
21930 (end-of-line)
21931 (re-search-backward "^[ \t]*$" beg 'move)
21932 (line-beginning-position))
21933 (save-excursion
21934 (beginning-of-line)
21935 (re-search-forward "^[ \t]*$" end 'move)
21936 (line-beginning-position))
21937 justify)))
21939 ;; Fill comments.
21940 (comment (fill-comment-paragraph justify))
21941 ;; Ignore every other element.
21942 (otherwise t))))))
21944 (defun org-auto-fill-function ()
21945 "Auto-fill function."
21946 ;; Check if auto-filling is meaningful.
21947 (let ((fc (current-fill-column)))
21948 (when (and fc (> (current-column) fc))
21949 (let* ((fill-prefix (org-adaptive-fill-function))
21950 ;; Enforce empty fill prefix, if required. Otherwise, it
21951 ;; will be computed again.
21952 (adaptive-fill-mode (not (equal fill-prefix ""))))
21953 (when fill-prefix (do-auto-fill))))))
21955 (defun org-comment-line-break-function (&optional soft)
21956 "Break line at point and indent, continuing comment if within one.
21957 The inserted newline is marked hard if variable
21958 `use-hard-newlines' is true, unless optional argument SOFT is
21959 non-nil."
21960 (if soft (insert-and-inherit ?\n) (newline 1))
21961 (save-excursion (forward-char -1) (delete-horizontal-space))
21962 (delete-horizontal-space)
21963 (indent-to-left-margin)
21964 (insert-before-markers-and-inherit fill-prefix))
21967 ;;; Comments
21969 ;; Org comments syntax is quite complex. It requires the entire line
21970 ;; to be just a comment. Also, even with the right syntax at the
21971 ;; beginning of line, some some elements (i.e. verse-block or
21972 ;; example-block) don't accept comments. Usual Emacs comment commands
21973 ;; cannot cope with those requirements. Therefore, Org replaces them.
21975 ;; Org still relies on `comment-dwim', but cannot trust
21976 ;; `comment-only-p'. So, `comment-region-function' and
21977 ;; `uncomment-region-function' both point
21978 ;; to`org-comment-or-uncomment-region'. Eventually,
21979 ;; `org-insert-comment' takes care of insertion of comments at the
21980 ;; beginning of line.
21982 ;; `org-setup-comments-handling' install comments related variables
21983 ;; during `org-mode' initialization.
21985 (defun org-setup-comments-handling ()
21986 (interactive)
21987 (org-set-local 'comment-use-syntax nil)
21988 (org-set-local 'comment-start "# ")
21989 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21990 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21991 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21992 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21994 (defun org-insert-comment ()
21995 "Insert an empty comment above current line.
21996 If the line is empty, insert comment at its beginning."
21997 (beginning-of-line)
21998 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21999 (org-indent-line)
22000 (insert "# "))
22002 (defvar comment-empty-lines) ; From newcomment.el.
22003 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22004 "Comment or uncomment each non-blank line in the region.
22005 Uncomment each non-blank line between BEG and END if it only
22006 contains commented lines. Otherwise, comment them."
22007 (save-restriction
22008 ;; Restrict region
22009 (narrow-to-region (save-excursion (goto-char beg)
22010 (skip-chars-forward " \r\t\n" end)
22011 (line-beginning-position))
22012 (save-excursion (goto-char end)
22013 (skip-chars-backward " \r\t\n" beg)
22014 (line-end-position)))
22015 (let ((uncommentp
22016 ;; UNCOMMENTP is non-nil when every non blank line between
22017 ;; BEG and END is a comment.
22018 (save-excursion
22019 (goto-char (point-min))
22020 (while (and (not (eobp))
22021 (let ((element (org-element-at-point)))
22022 (and (eq (org-element-type element) 'comment)
22023 (goto-char (min (point-max)
22024 (org-element-property
22025 :end element)))))))
22026 (eobp))))
22027 (if uncommentp
22028 ;; Only blank lines and comments in region: uncomment it.
22029 (save-excursion
22030 (goto-char (point-min))
22031 (while (not (eobp))
22032 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22033 (replace-match "" nil nil nil 1))
22034 (forward-line)))
22035 ;; Comment each line in region.
22036 (let ((min-indent (point-max)))
22037 ;; First find the minimum indentation across all lines.
22038 (save-excursion
22039 (goto-char (point-min))
22040 (while (and (not (eobp)) (not (zerop min-indent)))
22041 (unless (looking-at "[ \t]*$")
22042 (setq min-indent (min min-indent (current-indentation))))
22043 (forward-line)))
22044 ;; Then loop over all lines.
22045 (save-excursion
22046 (goto-char (point-min))
22047 (while (not (eobp))
22048 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22049 (org-move-to-column min-indent t)
22050 (insert comment-start))
22051 (forward-line))))))))
22054 ;;; Planning
22056 ;; This section contains tools to operate on timestamp objects, as
22057 ;; returned by, e.g. `org-element-context'.
22059 (defun org-timestamp-has-time-p (timestamp)
22060 "Non-nil when TIMESTAMP has a time specified."
22061 (org-element-property :hour-start timestamp))
22063 (defun org-timestamp-format (timestamp format &optional end utc)
22064 "Format a TIMESTAMP element into a string.
22066 FORMAT is a format specifier to be passed to
22067 `format-time-string'.
22069 When optional argument END is non-nil, use end of date-range or
22070 time-range, if possible.
22072 When optional argument UTC is non-nil, time will be expressed as
22073 Universal Time."
22074 (format-time-string
22075 format
22076 (apply 'encode-time
22077 (cons 0
22078 (mapcar
22079 (lambda (prop) (or (org-element-property prop timestamp) 0))
22080 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22081 '(:minute-start :hour-start :day-start :month-start
22082 :year-start)))))
22083 utc))
22085 (defun org-timestamp-split-range (timestamp &optional end)
22086 "Extract a timestamp object from a date or time range.
22088 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22089 the end of the range. Otherwise, extract its start.
22091 Return a new timestamp object sharing the same parent as
22092 TIMESTAMP."
22093 (let ((type (org-element-property :type timestamp)))
22094 (if (memq type '(active inactive diary)) timestamp
22095 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22096 ;; Set new type.
22097 (org-element-put-property
22098 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22099 ;; Copy start properties over end properties if END is
22100 ;; non-nil. Otherwise, copy end properties over `start' ones.
22101 (let ((p-alist '((:minute-start . :minute-end)
22102 (:hour-start . :hour-end)
22103 (:day-start . :day-end)
22104 (:month-start . :month-end)
22105 (:year-start . :year-end))))
22106 (dolist (p-cell p-alist)
22107 (org-element-put-property
22108 split-ts
22109 (funcall (if end 'car 'cdr) p-cell)
22110 (org-element-property
22111 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22112 ;; Eventually refresh `:raw-value'.
22113 (org-element-put-property split-ts :raw-value nil)
22114 (org-element-put-property
22115 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22117 (defun org-timestamp-translate (timestamp &optional boundary)
22118 "Apply `org-translate-time' on a TIMESTAMP object.
22119 When optional argument BOUNDARY is non-nil, it is either the
22120 symbol `start' or `end'. In this case, only translate the
22121 starting or ending part of TIMESTAMP if it is a date or time
22122 range. Otherwise, translate both parts."
22123 (if (and (not boundary)
22124 (memq (org-element-property :type timestamp)
22125 '(active-range inactive-range)))
22126 (concat
22127 (org-translate-time
22128 (org-element-property :raw-value
22129 (org-timestamp-split-range timestamp)))
22130 "--"
22131 (org-translate-time
22132 (org-element-property :raw-value
22133 (org-timestamp-split-range timestamp t))))
22134 (org-translate-time
22135 (org-element-property
22136 :raw-value
22137 (if (not boundary) timestamp
22138 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22142 ;;; Other stuff.
22144 (defun org-toggle-fixed-width-section (arg)
22145 "Toggle the fixed-width export.
22146 If there is no active region, the QUOTE keyword at the current headline is
22147 inserted or removed. When present, it causes the text between this headline
22148 and the next to be exported as fixed-width text, and unmodified.
22149 If there is an active region, this command adds or removes a colon as the
22150 first character of this line. If the first character of a line is a colon,
22151 this line is also exported in fixed-width font."
22152 (interactive "P")
22153 (let* ((cc 0)
22154 (regionp (org-region-active-p))
22155 (beg (if regionp (region-beginning) (point)))
22156 (end (if regionp (region-end)))
22157 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22158 (case-fold-search nil)
22159 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22160 off)
22161 (if regionp
22162 (save-excursion
22163 (goto-char beg)
22164 (setq cc (current-column))
22165 (beginning-of-line 1)
22166 (setq off (looking-at re))
22167 (while (> nlines 0)
22168 (setq nlines (1- nlines))
22169 (beginning-of-line 1)
22170 (cond
22171 (arg
22172 (org-move-to-column cc t)
22173 (insert ": \n")
22174 (forward-line -1))
22175 ((and off (looking-at re))
22176 (replace-match "" t t nil 1))
22177 ((not off) (org-move-to-column cc t) (insert ": ")))
22178 (forward-line 1)))
22179 (save-excursion
22180 (org-back-to-heading)
22181 (cond
22182 ((looking-at (format org-heading-keyword-regexp-format
22183 org-quote-string))
22184 (goto-char (match-end 1))
22185 (looking-at (concat " +" org-quote-string))
22186 (replace-match "" t t)
22187 (when (eolp) (insert " ")))
22188 ((looking-at org-outline-regexp)
22189 (goto-char (match-end 0))
22190 (insert org-quote-string " ")))))))
22192 (defun org-reftex-citation ()
22193 "Use reftex-citation to insert a citation into the buffer.
22194 This looks for a line like
22196 #+BIBLIOGRAPHY: foo plain option:-d
22198 and derives from it that foo.bib is the bibliography file relevant
22199 for this document. It then installs the necessary environment for RefTeX
22200 to work in this buffer and calls `reftex-citation' to insert a citation
22201 into the buffer.
22203 Export of such citations to both LaTeX and HTML is handled by the contributed
22204 package org-exp-bibtex by Taru Karttunen."
22205 (interactive)
22206 (let ((reftex-docstruct-symbol 'rds)
22207 (reftex-cite-format "\\cite{%l}")
22208 rds bib)
22209 (save-excursion
22210 (save-restriction
22211 (widen)
22212 (let ((case-fold-search t)
22213 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22214 (if (not (save-excursion
22215 (or (re-search-forward re nil t)
22216 (re-search-backward re nil t))))
22217 (error "No bibliography defined in file")
22218 (setq bib (concat (match-string 1) ".bib")
22219 rds (list (list 'bib bib)))))))
22220 (call-interactively 'reftex-citation)))
22222 ;;;; Functions extending outline functionality
22224 (defun org-beginning-of-line (&optional arg)
22225 "Go to the beginning of the current line. If that is invisible, continue
22226 to a visible line beginning. This makes the function of C-a more intuitive.
22227 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22228 first attempt, and only move to after the tags when the cursor is already
22229 beyond the end of the headline."
22230 (interactive "P")
22231 (let ((pos (point))
22232 (special (if (consp org-special-ctrl-a/e)
22233 (car org-special-ctrl-a/e)
22234 org-special-ctrl-a/e))
22235 refpos)
22236 (if (org-bound-and-true-p visual-line-mode)
22237 (beginning-of-visual-line 1)
22238 (beginning-of-line 1))
22239 (if (and arg (fboundp 'move-beginning-of-line))
22240 (call-interactively 'move-beginning-of-line)
22241 (if (bobp)
22243 (backward-char 1)
22244 (if (org-truely-invisible-p)
22245 (while (and (not (bobp)) (org-truely-invisible-p))
22246 (backward-char 1)
22247 (beginning-of-line 1))
22248 (forward-char 1))))
22249 (when special
22250 (cond
22251 ((and (looking-at org-complex-heading-regexp)
22252 (= (char-after (match-end 1)) ?\ ))
22253 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22254 (point-at-eol)))
22255 (goto-char
22256 (if (eq special t)
22257 (cond ((> pos refpos) refpos)
22258 ((= pos (point)) refpos)
22259 (t (point)))
22260 (cond ((> pos (point)) (point))
22261 ((not (eq last-command this-command)) (point))
22262 (t refpos)))))
22263 ((org-at-item-p)
22264 ;; Being at an item and not looking at an the item means point
22265 ;; was previously moved to beginning of a visual line, which
22266 ;; doesn't contain the item. Therefore, do nothing special,
22267 ;; just stay here.
22268 (when (looking-at org-list-full-item-re)
22269 ;; Set special position at first white space character after
22270 ;; bullet, and check-box, if any.
22271 (let ((after-bullet
22272 (let ((box (match-end 3)))
22273 (if (not box) (match-end 1)
22274 (let ((after (char-after box)))
22275 (if (and after (= after ? )) (1+ box) box))))))
22276 ;; Special case: Move point to special position when
22277 ;; currently after it or at beginning of line.
22278 (if (eq special t)
22279 (when (or (> pos after-bullet) (= (point) pos))
22280 (goto-char after-bullet))
22281 ;; Reversed case: Move point to special position when
22282 ;; point was already at beginning of line and command is
22283 ;; repeated.
22284 (when (and (= (point) pos) (eq last-command this-command))
22285 (goto-char after-bullet))))))))
22286 (org-no-warnings
22287 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22289 (defun org-end-of-line (&optional arg)
22290 "Go to the end of the line.
22291 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22292 tags on the first attempt, and only move to after the tags when
22293 the cursor is already beyond the end of the headline."
22294 (interactive "P")
22295 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22296 org-special-ctrl-a/e))
22297 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22298 'end-of-visual-line)
22299 ((fboundp 'move-end-of-line) 'move-end-of-line)
22300 (t 'end-of-line))))
22301 (if (or (not special) arg) (call-interactively move-fun)
22302 (let* ((element (save-excursion (beginning-of-line)
22303 (org-element-at-point)))
22304 (type (org-element-type element)))
22305 (cond
22306 ((memq type '(headline inlinetask))
22307 (let ((pos (point)))
22308 (beginning-of-line 1)
22309 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22310 (if (eq special t)
22311 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22312 (goto-char (match-beginning 1))
22313 (goto-char (match-end 0)))
22314 (if (or (< pos (match-end 0))
22315 (not (eq this-command last-command)))
22316 (goto-char (match-end 0))
22317 (goto-char (match-beginning 1))))
22318 (call-interactively move-fun))))
22319 ((org-element-property :hiddenp element)
22320 ;; If element is hidden, `move-end-of-line' would put point
22321 ;; after it. Use `end-of-line' to stay on current line.
22322 (call-interactively 'end-of-line))
22323 (t (call-interactively move-fun)))))
22324 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22326 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22327 (define-key org-mode-map "\C-e" 'org-end-of-line)
22329 (defun org-backward-sentence (&optional arg)
22330 "Go to beginning of sentence, or beginning of table field.
22331 This will call `backward-sentence' or `org-table-beginning-of-field',
22332 depending on context."
22333 (interactive "P")
22334 (cond
22335 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22336 (t (call-interactively 'backward-sentence))))
22338 (defun org-forward-sentence (&optional arg)
22339 "Go to end of sentence, or end of table field.
22340 This will call `forward-sentence' or `org-table-end-of-field',
22341 depending on context."
22342 (interactive "P")
22343 (cond
22344 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22345 (t (call-interactively 'forward-sentence))))
22347 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22348 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22350 (defun org-kill-line (&optional arg)
22351 "Kill line, to tags or end of line."
22352 (interactive "P")
22353 (cond
22354 ((or (not org-special-ctrl-k)
22355 (bolp)
22356 (not (org-at-heading-p)))
22357 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22358 org-ctrl-k-protect-subtree)
22359 (if (or (eq org-ctrl-k-protect-subtree 'error)
22360 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22361 (error "C-k aborted - would kill hidden subtree")))
22362 (call-interactively
22363 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22364 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22365 (kill-region (point) (match-beginning 1))
22366 (org-set-tags nil t))
22367 (t (kill-region (point) (point-at-eol)))))
22369 (define-key org-mode-map "\C-k" 'org-kill-line)
22371 (defun org-yank (&optional arg)
22372 "Yank. If the kill is a subtree, treat it specially.
22373 This command will look at the current kill and check if is a single
22374 subtree, or a series of subtrees[1]. If it passes the test, and if the
22375 cursor is at the beginning of a line or after the stars of a currently
22376 empty headline, then the yank is handled specially. How exactly depends
22377 on the value of the following variables, both set by default.
22379 org-yank-folded-subtrees
22380 When set, the subtree(s) will be folded after insertion, but only
22381 if doing so would now swallow text after the yanked text.
22383 org-yank-adjusted-subtrees
22384 When set, the subtree will be promoted or demoted in order to
22385 fit into the local outline tree structure, which means that the level
22386 will be adjusted so that it becomes the smaller one of the two
22387 *visible* surrounding headings.
22389 Any prefix to this command will cause `yank' to be called directly with
22390 no special treatment. In particular, a simple \\[universal-argument] prefix \
22391 will just
22392 plainly yank the text as it is.
22394 \[1] The test checks if the first non-white line is a heading
22395 and if there are no other headings with fewer stars."
22396 (interactive "P")
22397 (org-yank-generic 'yank arg))
22399 (defun org-yank-generic (command arg)
22400 "Perform some yank-like command.
22402 This function implements the behavior described in the `org-yank'
22403 documentation. However, it has been generalized to work for any
22404 interactive command with similar behavior."
22406 ;; pretend to be command COMMAND
22407 (setq this-command command)
22409 (if arg
22410 (call-interactively command)
22412 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22413 (and (org-kill-is-subtree-p)
22414 (or (bolp)
22415 (and (looking-at "[ \t]*$")
22416 (string-match
22417 "\\`\\*+\\'"
22418 (buffer-substring (point-at-bol) (point)))))))
22419 swallowp)
22420 (cond
22421 ((and subtreep org-yank-folded-subtrees)
22422 (let ((beg (point))
22423 end)
22424 (if (and subtreep org-yank-adjusted-subtrees)
22425 (org-paste-subtree nil nil 'for-yank)
22426 (call-interactively command))
22428 (setq end (point))
22429 (goto-char beg)
22430 (when (and (bolp) subtreep
22431 (not (setq swallowp
22432 (org-yank-folding-would-swallow-text beg end))))
22433 (org-with-limited-levels
22434 (or (looking-at org-outline-regexp)
22435 (re-search-forward org-outline-regexp-bol end t))
22436 (while (and (< (point) end) (looking-at org-outline-regexp))
22437 (hide-subtree)
22438 (org-cycle-show-empty-lines 'folded)
22439 (condition-case nil
22440 (outline-forward-same-level 1)
22441 (error (goto-char end))))))
22442 (when swallowp
22443 (message
22444 "Inserted text not folded because that would swallow text"))
22446 (goto-char end)
22447 (skip-chars-forward " \t\n\r")
22448 (beginning-of-line 1)
22449 (push-mark beg 'nomsg)))
22450 ((and subtreep org-yank-adjusted-subtrees)
22451 (let ((beg (point-at-bol)))
22452 (org-paste-subtree nil nil 'for-yank)
22453 (push-mark beg 'nomsg)))
22455 (call-interactively command))))))
22457 (defun org-yank-folding-would-swallow-text (beg end)
22458 "Would hide-subtree at BEG swallow any text after END?"
22459 (let (level)
22460 (org-with-limited-levels
22461 (save-excursion
22462 (goto-char beg)
22463 (when (or (looking-at org-outline-regexp)
22464 (re-search-forward org-outline-regexp-bol end t))
22465 (setq level (org-outline-level)))
22466 (goto-char end)
22467 (skip-chars-forward " \t\r\n\v\f")
22468 (if (or (eobp)
22469 (and (bolp) (looking-at org-outline-regexp)
22470 (<= (org-outline-level) level)))
22471 nil ; Nothing would be swallowed
22472 t))))) ; something would swallow
22474 (define-key org-mode-map "\C-y" 'org-yank)
22476 (defun org-truely-invisible-p ()
22477 "Check if point is at a character currently not visible.
22478 This version does not only check the character property, but also
22479 `visible-mode'."
22480 ;; Early versions of noutline don't have `outline-invisible-p'.
22481 (if (org-bound-and-true-p visible-mode)
22483 (outline-invisible-p)))
22485 (defun org-invisible-p2 ()
22486 "Check if point is at a character currently not visible."
22487 (save-excursion
22488 (if (and (eolp) (not (bobp))) (backward-char 1))
22489 ;; Early versions of noutline don't have `outline-invisible-p'.
22490 (outline-invisible-p)))
22492 (defun org-back-to-heading (&optional invisible-ok)
22493 "Call `outline-back-to-heading', but provide a better error message."
22494 (condition-case nil
22495 (outline-back-to-heading invisible-ok)
22496 (error (error "Before first headline at position %d in buffer %s"
22497 (point) (current-buffer)))))
22499 (defun org-before-first-heading-p ()
22500 "Before first heading?"
22501 (save-excursion
22502 (end-of-line)
22503 (null (re-search-backward org-outline-regexp-bol nil t))))
22505 (defun org-at-heading-p (&optional ignored)
22506 (outline-on-heading-p t))
22507 ;; Compatibility alias with Org versions < 7.8.03
22508 (defalias 'org-on-heading-p 'org-at-heading-p)
22510 (defun org-at-comment-p nil
22511 "Is cursor in a line starting with a # character?"
22512 (save-excursion
22513 (beginning-of-line)
22514 (looking-at "^#")))
22516 (defun org-at-drawer-p nil
22517 "Is cursor at a drawer keyword?"
22518 (save-excursion
22519 (move-beginning-of-line 1)
22520 (looking-at org-drawer-regexp)))
22522 (defun org-at-block-p nil
22523 "Is cursor at a block keyword?"
22524 (save-excursion
22525 (move-beginning-of-line 1)
22526 (looking-at org-block-regexp)))
22528 (defun org-point-at-end-of-empty-headline ()
22529 "If point is at the end of an empty headline, return t, else nil.
22530 If the heading only contains a TODO keyword, it is still still considered
22531 empty."
22532 (and (looking-at "[ \t]*$")
22533 (when org-todo-line-regexp
22534 (save-excursion
22535 (beginning-of-line 1)
22536 (let ((case-fold-search nil))
22537 (looking-at org-todo-line-regexp)
22538 (string= (match-string 3) ""))))))
22540 (defun org-at-heading-or-item-p ()
22541 (or (org-at-heading-p) (org-at-item-p)))
22543 (defun org-at-target-p ()
22544 (or (org-in-regexp org-radio-target-regexp)
22545 (org-in-regexp org-target-regexp)))
22546 ;; Compatibility alias with Org versions < 7.8.03
22547 (defalias 'org-on-target-p 'org-at-target-p)
22549 (defun org-up-heading-all (arg)
22550 "Move to the heading line of which the present line is a subheading.
22551 This function considers both visible and invisible heading lines.
22552 With argument, move up ARG levels."
22553 (if (fboundp 'outline-up-heading-all)
22554 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22555 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22557 (defun org-up-heading-safe ()
22558 "Move to the heading line of which the present line is a subheading.
22559 This version will not throw an error. It will return the level of the
22560 headline found, or nil if no higher level is found.
22562 Also, this function will be a lot faster than `outline-up-heading',
22563 because it relies on stars being the outline starters. This can really
22564 make a significant difference in outlines with very many siblings."
22565 (let (start-level re)
22566 (org-back-to-heading t)
22567 (setq start-level (funcall outline-level))
22568 (if (equal start-level 1)
22570 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22571 (if (re-search-backward re nil t)
22572 (funcall outline-level)))))
22574 (defun org-first-sibling-p ()
22575 "Is this heading the first child of its parents?"
22576 (interactive)
22577 (let ((re org-outline-regexp-bol)
22578 level l)
22579 (unless (org-at-heading-p t)
22580 (error "Not at a heading"))
22581 (setq level (funcall outline-level))
22582 (save-excursion
22583 (if (not (re-search-backward re nil t))
22585 (setq l (funcall outline-level))
22586 (< l level)))))
22588 (defun org-goto-sibling (&optional previous)
22589 "Goto the next sibling, even if it is invisible.
22590 When PREVIOUS is set, go to the previous sibling instead. Returns t
22591 when a sibling was found. When none is found, return nil and don't
22592 move point."
22593 (let ((fun (if previous 're-search-backward 're-search-forward))
22594 (pos (point))
22595 (re org-outline-regexp-bol)
22596 level l)
22597 (when (condition-case nil (org-back-to-heading t) (error nil))
22598 (setq level (funcall outline-level))
22599 (catch 'exit
22600 (or previous (forward-char 1))
22601 (while (funcall fun re nil t)
22602 (setq l (funcall outline-level))
22603 (when (< l level) (goto-char pos) (throw 'exit nil))
22604 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22605 (goto-char pos)
22606 nil))))
22608 (defun org-show-siblings ()
22609 "Show all siblings of the current headline."
22610 (save-excursion
22611 (while (org-goto-sibling) (org-flag-heading nil)))
22612 (save-excursion
22613 (while (org-goto-sibling 'previous)
22614 (org-flag-heading nil))))
22616 (defun org-goto-first-child ()
22617 "Goto the first child, even if it is invisible.
22618 Return t when a child was found. Otherwise don't move point and
22619 return nil."
22620 (let (level (pos (point)) (re org-outline-regexp-bol))
22621 (when (condition-case nil (org-back-to-heading t) (error nil))
22622 (setq level (outline-level))
22623 (forward-char 1)
22624 (if (and (re-search-forward re nil t) (> (outline-level) level))
22625 (progn (goto-char (match-beginning 0)) t)
22626 (goto-char pos) nil))))
22628 (defun org-show-hidden-entry ()
22629 "Show an entry where even the heading is hidden."
22630 (save-excursion
22631 (org-show-entry)))
22633 (defun org-flag-heading (flag &optional entry)
22634 "Flag the current heading. FLAG non-nil means make invisible.
22635 When ENTRY is non-nil, show the entire entry."
22636 (save-excursion
22637 (org-back-to-heading t)
22638 ;; Check if we should show the entire entry
22639 (if entry
22640 (progn
22641 (org-show-entry)
22642 (save-excursion
22643 (and (outline-next-heading)
22644 (org-flag-heading nil))))
22645 (outline-flag-region (max (point-min) (1- (point)))
22646 (save-excursion (outline-end-of-heading) (point))
22647 flag))))
22649 (defun org-get-next-sibling ()
22650 "Move to next heading of the same level, and return point.
22651 If there is no such heading, return nil.
22652 This is like outline-next-sibling, but invisible headings are ok."
22653 (let ((level (funcall outline-level)))
22654 (outline-next-heading)
22655 (while (and (not (eobp)) (> (funcall outline-level) level))
22656 (outline-next-heading))
22657 (if (or (eobp) (< (funcall outline-level) level))
22659 (point))))
22661 (defun org-get-last-sibling ()
22662 "Move to previous heading of the same level, and return point.
22663 If there is no such heading, return nil."
22664 (let ((opoint (point))
22665 (level (funcall outline-level)))
22666 (outline-previous-heading)
22667 (when (and (/= (point) opoint) (outline-on-heading-p t))
22668 (while (and (> (funcall outline-level) level)
22669 (not (bobp)))
22670 (outline-previous-heading))
22671 (if (< (funcall outline-level) level)
22673 (point)))))
22675 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22676 "Goto to the end of a subtree."
22677 ;; This contains an exact copy of the original function, but it uses
22678 ;; `org-back-to-heading', to make it work also in invisible
22679 ;; trees. And is uses an invisible-ok argument.
22680 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22681 ;; Furthermore, when used inside Org, finding the end of a large subtree
22682 ;; with many children and grandchildren etc, this can be much faster
22683 ;; than the outline version.
22684 (org-back-to-heading invisible-ok)
22685 (let ((first t)
22686 (level (funcall outline-level)))
22687 (if (and (derived-mode-p 'org-mode) (< level 1000))
22688 ;; A true heading (not a plain list item), in Org-mode
22689 ;; This means we can easily find the end by looking
22690 ;; only for the right number of stars. Using a regexp to do
22691 ;; this is so much faster than using a Lisp loop.
22692 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22693 (forward-char 1)
22694 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22695 ;; something else, do it the slow way
22696 (while (and (not (eobp))
22697 (or first (> (funcall outline-level) level)))
22698 (setq first nil)
22699 (outline-next-heading)))
22700 (unless to-heading
22701 (if (memq (preceding-char) '(?\n ?\^M))
22702 (progn
22703 ;; Go to end of line before heading
22704 (forward-char -1)
22705 (if (memq (preceding-char) '(?\n ?\^M))
22706 ;; leave blank line before heading
22707 (forward-char -1))))))
22708 (point))
22710 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22711 "Use Org version in org-mode, for dramatic speed-up."
22712 (if (derived-mode-p 'org-mode)
22713 (progn
22714 (org-end-of-subtree nil t)
22715 (unless (eobp) (backward-char 1)))
22716 ad-do-it))
22718 (defun org-end-of-meta-data-and-drawers ()
22719 "Jump to the first text after meta data and drawers in the current entry.
22720 This will move over empty lines, lines with planning time stamps,
22721 clocking lines, and drawers."
22722 (org-back-to-heading t)
22723 (let ((end (save-excursion (outline-next-heading) (point)))
22724 (re (concat "\\(" org-drawer-regexp "\\)"
22725 "\\|" "[ \t]*" org-keyword-time-regexp)))
22726 (forward-line 1)
22727 (while (re-search-forward re end t)
22728 (if (not (match-end 1))
22729 ;; empty or planning line
22730 (forward-line 1)
22731 ;; a drawer, find the end
22732 (re-search-forward "^[ \t]*:END:" end 'move)
22733 (forward-line 1)))
22734 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22735 (point)))
22737 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22738 "Move forward to the ARG'th subheading at same level as this one.
22739 Stop at the first and last subheadings of a superior heading.
22740 Normally this only looks at visible headings, but when INVISIBLE-OK is
22741 non-nil it will also look at invisible ones."
22742 (interactive "p")
22743 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22744 (if (and arg (< arg 0))
22745 (goto-char (point-min))
22746 (outline-next-heading))
22747 (org-at-heading-p)
22748 (let ((level (- (match-end 0) (match-beginning 0) 1))
22749 (f (if (and arg (< arg 0))
22750 're-search-backward
22751 're-search-forward))
22752 (count (if arg (abs arg) 1))
22753 (result (point)))
22754 (forward-char (if (and arg (< arg 0)) -1 1))
22755 (while (and (> count 0)
22756 (funcall f org-outline-regexp-bol nil 'move))
22757 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22758 (cond ((< l level) (setq count 0))
22759 ((and (= l level)
22760 (or invisible-ok
22761 (progn
22762 (goto-char (line-beginning-position))
22763 (not (outline-invisible-p)))))
22764 (setq count (1- count))
22765 (when (eq l level)
22766 (setq result (point)))))))
22767 (goto-char result))
22768 (beginning-of-line 1)))
22770 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22771 "Move backward to the ARG'th subheading at same level as this one.
22772 Stop at the first and last subheadings of a superior heading."
22773 (interactive "p")
22774 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22776 (defun org-next-block (arg &optional backward block-regexp)
22777 "Jump to the next block.
22778 With a prefix argument ARG, jump forward ARG many source blocks.
22779 When BACKWARD is non-nil, jump to the previous block.
22780 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22781 (interactive "p")
22782 (let ((re (or block-regexp org-block-regexp))
22783 (re-search-fn (or (and backward 're-search-backward)
22784 're-search-forward)))
22785 (if (looking-at re) (forward-char 1))
22786 (condition-case nil
22787 (funcall re-search-fn re nil nil arg)
22788 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22789 (goto-char (match-beginning 0)) (org-show-context)))
22791 (defun org-previous-block (arg &optional block-regexp)
22792 "Jump to the previous block.
22793 With a prefix argument ARG, jump backward ARG many source blocks.
22794 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22795 (interactive "p")
22796 (org-next-block arg t block-regexp))
22798 (defun org-forward-element ()
22799 "Move forward by one element.
22800 Move to the next element at the same level, when possible."
22801 (interactive)
22802 (cond ((eobp) (user-error "Cannot move further down"))
22803 ((org-with-limited-levels (org-at-heading-p))
22804 (let ((origin (point)))
22805 (goto-char (org-end-of-subtree nil t))
22806 (unless (org-with-limited-levels (org-at-heading-p))
22807 (goto-char origin)
22808 (user-error "Cannot move further down"))))
22810 (let* ((elem (org-element-at-point))
22811 (end (org-element-property :end elem))
22812 (parent (org-element-property :parent elem)))
22813 (if (and parent (= (org-element-property :contents-end parent) end))
22814 (goto-char (org-element-property :end parent))
22815 (goto-char end))))))
22817 (defun org-backward-element ()
22818 "Move backward by one element.
22819 Move to the previous element at the same level, when possible."
22820 (interactive)
22821 (cond ((bobp) (user-error "Cannot move further up"))
22822 ((org-with-limited-levels (org-at-heading-p))
22823 ;; At a headline, move to the previous one, if any, or stay
22824 ;; here.
22825 (let ((origin (point)))
22826 (org-with-limited-levels (org-backward-heading-same-level 1))
22827 ;; When current headline has no sibling above, move to its
22828 ;; parent.
22829 (when (= (point) origin)
22830 (or (org-with-limited-levels (org-up-heading-safe))
22831 (progn (goto-char origin)
22832 (user-error "Cannot move further up"))))))
22834 (let* ((trail (org-element-at-point 'keep-trail))
22835 (elem (car trail))
22836 (prev-elem (nth 1 trail))
22837 (beg (org-element-property :begin elem)))
22838 (cond
22839 ;; Move to beginning of current element if point isn't
22840 ;; there already.
22841 ((/= (point) beg) (goto-char beg))
22842 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22843 ((org-before-first-heading-p) (goto-char (point-min)))
22844 (t (org-back-to-heading)))))))
22846 (defun org-up-element ()
22847 "Move to upper element."
22848 (interactive)
22849 (if (org-with-limited-levels (org-at-heading-p))
22850 (unless (org-up-heading-safe) (error "No surrounding element"))
22851 (let* ((elem (org-element-at-point))
22852 (parent (org-element-property :parent elem)))
22853 (if parent (goto-char (org-element-property :begin parent))
22854 (if (org-with-limited-levels (org-before-first-heading-p))
22855 (error "No surrounding element")
22856 (org-with-limited-levels (org-back-to-heading)))))))
22858 (defvar org-element-greater-elements)
22859 (defun org-down-element ()
22860 "Move to inner element."
22861 (interactive)
22862 (let ((element (org-element-at-point)))
22863 (cond
22864 ((memq (org-element-type element) '(plain-list table))
22865 (goto-char (org-element-property :contents-begin element))
22866 (forward-char))
22867 ((memq (org-element-type element) org-element-greater-elements)
22868 ;; If contents are hidden, first disclose them.
22869 (when (org-element-property :hiddenp element) (org-cycle))
22870 (goto-char (or (org-element-property :contents-begin element)
22871 (error "No content for this element"))))
22872 (t (error "No inner element")))))
22874 (defun org-drag-element-backward ()
22875 "Move backward element at point."
22876 (interactive)
22877 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22878 (let* ((trail (org-element-at-point 'keep-trail))
22879 (elem (car trail))
22880 (prev-elem (nth 1 trail)))
22881 ;; Error out if no previous element or previous element is
22882 ;; a parent of the current one.
22883 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22884 (error "Cannot drag element backward")
22885 (let ((pos (point)))
22886 (org-element-swap-A-B prev-elem elem)
22887 (goto-char (+ (org-element-property :begin prev-elem)
22888 (- pos (org-element-property :begin elem)))))))))
22890 (defun org-drag-element-forward ()
22891 "Move forward element at point."
22892 (interactive)
22893 (let* ((pos (point))
22894 (elem (org-element-at-point)))
22895 (when (= (point-max) (org-element-property :end elem))
22896 (error "Cannot drag element forward"))
22897 (goto-char (org-element-property :end elem))
22898 (let ((next-elem (org-element-at-point)))
22899 (when (or (org-element-nested-p elem next-elem)
22900 (and (eq (org-element-type next-elem) 'headline)
22901 (not (eq (org-element-type elem) 'headline))))
22902 (goto-char pos)
22903 (error "Cannot drag element forward"))
22904 ;; Compute new position of point: it's shifted by NEXT-ELEM
22905 ;; body's length (without final blanks) and by the length of
22906 ;; blanks between ELEM and NEXT-ELEM.
22907 (let ((size-next (- (save-excursion
22908 (goto-char (org-element-property :end next-elem))
22909 (skip-chars-backward " \r\t\n")
22910 (forward-line)
22911 ;; Small correction if buffer doesn't end
22912 ;; with a newline character.
22913 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22914 (org-element-property :begin next-elem)))
22915 (size-blank (- (org-element-property :end elem)
22916 (save-excursion
22917 (goto-char (org-element-property :end elem))
22918 (skip-chars-backward " \r\t\n")
22919 (forward-line)
22920 (point)))))
22921 (org-element-swap-A-B elem next-elem)
22922 (goto-char (+ pos size-next size-blank))))))
22924 (defun org-drag-line-forward (arg)
22925 "Drag the line at point ARG lines forward."
22926 (interactive "p")
22927 (dotimes (n (abs arg))
22928 (let ((c (current-column)))
22929 (if (< 0 arg)
22930 (progn
22931 (beginning-of-line 2)
22932 (transpose-lines 1)
22933 (beginning-of-line 0))
22934 (transpose-lines 1)
22935 (beginning-of-line -1))
22936 (org-move-to-column c))))
22938 (defun org-drag-line-backward (arg)
22939 "Drag the line at point ARG lines backward."
22940 (interactive "p")
22941 (org-drag-line-forward (- arg)))
22943 (defun org-mark-element ()
22944 "Put point at beginning of this element, mark at end.
22946 Interactively, if this command is repeated or (in Transient Mark
22947 mode) if the mark is active, it marks the next element after the
22948 ones already marked."
22949 (interactive)
22950 (let (deactivate-mark)
22951 (if (and (org-called-interactively-p 'any)
22952 (or (and (eq last-command this-command) (mark t))
22953 (and transient-mark-mode mark-active)))
22954 (set-mark
22955 (save-excursion
22956 (goto-char (mark))
22957 (goto-char (org-element-property :end (org-element-at-point)))))
22958 (let ((element (org-element-at-point)))
22959 (end-of-line)
22960 (push-mark (org-element-property :end element) t t)
22961 (goto-char (org-element-property :begin element))))))
22963 (defun org-narrow-to-element ()
22964 "Narrow buffer to current element."
22965 (interactive)
22966 (let ((elem (org-element-at-point)))
22967 (cond
22968 ((eq (car elem) 'headline)
22969 (narrow-to-region
22970 (org-element-property :begin elem)
22971 (org-element-property :end elem)))
22972 ((memq (car elem) org-element-greater-elements)
22973 (narrow-to-region
22974 (org-element-property :contents-begin elem)
22975 (org-element-property :contents-end elem)))
22977 (narrow-to-region
22978 (org-element-property :begin elem)
22979 (org-element-property :end elem))))))
22981 (defun org-transpose-element ()
22982 "Transpose current and previous elements, keeping blank lines between.
22983 Point is moved after both elements."
22984 (interactive)
22985 (org-skip-whitespace)
22986 (let ((end (org-element-property :end (org-element-at-point))))
22987 (org-drag-element-backward)
22988 (goto-char end)))
22990 (defun org-unindent-buffer ()
22991 "Un-indent the visible part of the buffer.
22992 Relative indentation (between items, inside blocks, etc.) isn't
22993 modified."
22994 (interactive)
22995 (unless (eq major-mode 'org-mode)
22996 (error "Cannot un-indent a buffer not in Org mode"))
22997 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22998 unindent-tree ; For byte-compiler.
22999 (unindent-tree
23000 (function
23001 (lambda (contents)
23002 (mapc
23003 (lambda (element)
23004 (if (memq (org-element-type element) '(headline section))
23005 (funcall unindent-tree (org-element-contents element))
23006 (save-excursion
23007 (save-restriction
23008 (narrow-to-region
23009 (org-element-property :begin element)
23010 (org-element-property :end element))
23011 (org-do-remove-indentation)))))
23012 (reverse contents))))))
23013 (funcall unindent-tree (org-element-contents parse-tree))))
23015 (defun org-show-subtree ()
23016 "Show everything after this heading at deeper levels."
23017 (interactive)
23018 (outline-flag-region
23019 (point)
23020 (save-excursion
23021 (org-end-of-subtree t t))
23022 nil))
23024 (defun org-show-entry ()
23025 "Show the body directly following this heading.
23026 Show the heading too, if it is currently invisible."
23027 (interactive)
23028 (save-excursion
23029 (condition-case nil
23030 (progn
23031 (org-back-to-heading t)
23032 (outline-flag-region
23033 (max (point-min) (1- (point)))
23034 (save-excursion
23035 (if (re-search-forward
23036 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23037 (match-beginning 1)
23038 (point-max)))
23039 nil)
23040 (org-cycle-hide-drawers 'children))
23041 (error nil))))
23043 (defun org-make-options-regexp (kwds &optional extra)
23044 "Make a regular expression for keyword lines."
23045 (concat
23046 "^#\\+\\("
23047 (mapconcat 'regexp-quote kwds "\\|")
23048 (if extra (concat "\\|" extra))
23049 "\\):[ \t]*\\(.*\\)"))
23051 ;; Make isearch reveal the necessary context
23052 (defun org-isearch-end ()
23053 "Reveal context after isearch exits."
23054 (when isearch-success ; only if search was successful
23055 (if (featurep 'xemacs)
23056 ;; Under XEmacs, the hook is run in the correct place,
23057 ;; we directly show the context.
23058 (org-show-context 'isearch)
23059 ;; In Emacs the hook runs *before* restoring the overlays.
23060 ;; So we have to use a one-time post-command-hook to do this.
23061 ;; (Emacs 22 has a special variable, see function `org-mode')
23062 (unless (and (boundp 'isearch-mode-end-hook-quit)
23063 isearch-mode-end-hook-quit)
23064 ;; Only when the isearch was not quitted.
23065 (org-add-hook 'post-command-hook 'org-isearch-post-command
23066 'append 'local)))
23067 (org-fix-ellipsis-at-bol)))
23069 (defun org-isearch-post-command ()
23070 "Remove self from hook, and show context."
23071 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23072 (org-show-context 'isearch))
23075 ;;;; Integration with and fixes for other packages
23077 ;;; Imenu support
23079 (defvar org-imenu-markers nil
23080 "All markers currently used by Imenu.")
23081 (make-variable-buffer-local 'org-imenu-markers)
23083 (defun org-imenu-new-marker (&optional pos)
23084 "Return a new marker for use by Imenu, and remember the marker."
23085 (let ((m (make-marker)))
23086 (move-marker m (or pos (point)))
23087 (push m org-imenu-markers)
23090 (defun org-imenu-get-tree ()
23091 "Produce the index for Imenu."
23092 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23093 (setq org-imenu-markers nil)
23094 (let* ((n org-imenu-depth)
23095 (re (concat "^" (org-get-limited-outline-regexp)))
23096 (subs (make-vector (1+ n) nil))
23097 (last-level 0)
23098 m level head0 head)
23099 (save-excursion
23100 (save-restriction
23101 (widen)
23102 (goto-char (point-max))
23103 (while (re-search-backward re nil t)
23104 (setq level (org-reduced-level (funcall outline-level)))
23105 (when (and (<= level n)
23106 (looking-at org-complex-heading-regexp)
23107 (setq head0 (org-match-string-no-properties 4)))
23108 (setq head (org-link-display-format head0)
23109 m (org-imenu-new-marker))
23110 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23111 (if (>= level last-level)
23112 (push (cons head m) (aref subs level))
23113 (push (cons head (aref subs (1+ level))) (aref subs level))
23114 (loop for i from (1+ level) to n do (aset subs i nil)))
23115 (setq last-level level)))))
23116 (aref subs 1)))
23118 (eval-after-load "imenu"
23119 '(progn
23120 (add-hook 'imenu-after-jump-hook
23121 (lambda ()
23122 (if (derived-mode-p 'org-mode)
23123 (org-show-context 'org-goto))))))
23125 (defun org-link-display-format (link)
23126 "Replace a link with either the description, or the link target
23127 if no description is present"
23128 (save-match-data
23129 (if (string-match org-bracket-link-analytic-regexp link)
23130 (replace-match (if (match-end 5)
23131 (match-string 5 link)
23132 (concat (match-string 1 link)
23133 (match-string 3 link)))
23134 nil t link)
23135 link)))
23137 (defun org-toggle-link-display ()
23138 "Toggle the literal or descriptive display of links."
23139 (interactive)
23140 (if org-descriptive-links
23141 (progn (org-remove-from-invisibility-spec '(org-link))
23142 (org-restart-font-lock)
23143 (setq org-descriptive-links nil))
23144 (progn (add-to-invisibility-spec '(org-link))
23145 (org-restart-font-lock)
23146 (setq org-descriptive-links t))))
23148 ;; Speedbar support
23150 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23151 "Overlay marking the agenda restriction line in speedbar.")
23152 (overlay-put org-speedbar-restriction-lock-overlay
23153 'face 'org-agenda-restriction-lock)
23154 (overlay-put org-speedbar-restriction-lock-overlay
23155 'help-echo "Agendas are currently limited to this item.")
23156 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23158 (defun org-speedbar-set-agenda-restriction ()
23159 "Restrict future agenda commands to the location at point in speedbar.
23160 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23161 (interactive)
23162 (require 'org-agenda)
23163 (let (p m tp np dir txt)
23164 (cond
23165 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23166 'org-imenu t))
23167 (setq m (get-text-property p 'org-imenu-marker))
23168 (with-current-buffer (marker-buffer m)
23169 (goto-char m)
23170 (org-agenda-set-restriction-lock 'subtree)))
23171 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23172 'speedbar-function 'speedbar-find-file))
23173 (setq tp (previous-single-property-change
23174 (1+ p) 'speedbar-function)
23175 np (next-single-property-change
23176 tp 'speedbar-function)
23177 dir (speedbar-line-directory)
23178 txt (buffer-substring-no-properties (or tp (point-min))
23179 (or np (point-max))))
23180 (with-current-buffer (find-file-noselect
23181 (let ((default-directory dir))
23182 (expand-file-name txt)))
23183 (unless (derived-mode-p 'org-mode)
23184 (error "Cannot restrict to non-Org-mode file"))
23185 (org-agenda-set-restriction-lock 'file)))
23186 (t (error "Don't know how to restrict Org-mode's agenda")))
23187 (move-overlay org-speedbar-restriction-lock-overlay
23188 (point-at-bol) (point-at-eol))
23189 (setq current-prefix-arg nil)
23190 (org-agenda-maybe-redo)))
23192 (eval-after-load "speedbar"
23193 '(progn
23194 (speedbar-add-supported-extension ".org")
23195 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23196 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23197 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23198 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23199 (add-hook 'speedbar-visiting-tag-hook
23200 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23202 ;;; Fixes and Hacks for problems with other packages
23204 ;; Make flyspell not check words in links, to not mess up our keymap
23205 (defvar org-element-affiliated-keywords) ; From org-element.el
23206 (defvar org-element-block-name-alist) ; From org-element.el
23207 (defun org-mode-flyspell-verify ()
23208 "Don't let flyspell put overlays at active buttons, or on
23209 {todo,all-time,additional-option-like}-keywords."
23210 (let ((pos (max (1- (point)) (point-min)))
23211 (word (thing-at-point 'word)))
23212 (and (not (get-text-property pos 'keymap))
23213 (not (get-text-property pos 'org-no-flyspell))
23214 (not (member word org-todo-keywords-1))
23215 (not (member word org-all-time-keywords))
23216 (not (member word org-options-keywords))
23217 (not (member word (mapcar 'car org-startup-options)))
23218 (not (member-ignore-case word org-element-affiliated-keywords))
23219 (not (member-ignore-case word (org-get-export-keywords)))
23220 (not (member-ignore-case
23221 word (mapcar 'car org-element-block-name-alist)))
23222 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23224 (defun org-remove-flyspell-overlays-in (beg end)
23225 "Remove flyspell overlays in region."
23226 (and (org-bound-and-true-p flyspell-mode)
23227 (fboundp 'flyspell-delete-region-overlays)
23228 (flyspell-delete-region-overlays beg end))
23229 (add-text-properties beg end '(org-no-flyspell t)))
23231 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23232 (eval-after-load "bookmark"
23233 '(if (boundp 'bookmark-after-jump-hook)
23234 ;; We can use the hook
23235 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23236 ;; Hook not available, use advice
23237 (defadvice bookmark-jump (after org-make-visible activate)
23238 "Make the position visible."
23239 (org-bookmark-jump-unhide))))
23241 ;; Make sure saveplace shows the location if it was hidden
23242 (eval-after-load "saveplace"
23243 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23244 "Make the position visible."
23245 (org-bookmark-jump-unhide)))
23247 ;; Make sure ecb shows the location if it was hidden
23248 (eval-after-load "ecb"
23249 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23250 "Make hierarchy visible when jumping into location from ECB tree buffer."
23251 (if (derived-mode-p 'org-mode)
23252 (org-show-context))))
23254 (defun org-bookmark-jump-unhide ()
23255 "Unhide the current position, to show the bookmark location."
23256 (and (derived-mode-p 'org-mode)
23257 (or (outline-invisible-p)
23258 (save-excursion (goto-char (max (point-min) (1- (point))))
23259 (outline-invisible-p)))
23260 (org-show-context 'bookmark-jump)))
23262 ;; Make session.el ignore our circular variable
23263 (eval-after-load "session"
23264 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23266 ;;;; Experimental code
23268 (defun org-closed-in-range ()
23269 "Sparse tree of items closed in a certain time range.
23270 Still experimental, may disappear in the future."
23271 (interactive)
23272 ;; Get the time interval from the user.
23273 (let* ((time1 (org-float-time
23274 (org-read-date nil 'to-time nil "Starting date: ")))
23275 (time2 (org-float-time
23276 (org-read-date nil 'to-time nil "End date:")))
23277 ;; callback function
23278 (callback (lambda ()
23279 (let ((time
23280 (org-float-time
23281 (apply 'encode-time
23282 (org-parse-time-string
23283 (match-string 1))))))
23284 ;; check if time in interval
23285 (and (>= time time1) (<= time time2))))))
23286 ;; make tree, check each match with the callback
23287 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23289 ;;;; Finish up
23291 (provide 'org)
23293 (run-hooks 'org-load-hook)
23295 ;;; org.el ends here